texts:
I have a function which sets the text to a label displaying current active "products" and current active pages. The label displays "X products, Y pages/page" depending on the amount of products active in the template. Products is the same as rows really, the client wants to call it products.

The template consists of a number of tags, activeTags, which holds the tags that are not deleted. One row consists of a number of tags, perhaps 2 or 3, in the property _selectedTemplateConfiguration.TemplateConfigurationTagsPerRow. Every template page can hold a number of products/rows, _selectedTemplateConfiguration.TemplateConfigurationRowsPerPage.

Let's say I have 41 rows and the template takes 20 rows on each page. This means I have 3 pages active. When I made the function I could not get it to work without the use of the divisionRestvariable, ie. when I had 40 rows it still said it was 3 active pages, due to Math.Ceiling.

The _currentTagCollectionconsists really of a number of Telerik RadDocks with a text input, the idea with the whole template is that the client can enter textvalues into a template online, which is the printed.

I probably missed something, but this is a function that I feel could be made different. Feel free to ask if I need to clarify anything. I'm using .NET 4.0.

private string displayTemplateNumbers()
{
  int totalPagesActive;
  var activeTags = _currentTagCollection.Count - totalAmountOfDeletedTags();

  var divisionRest = (Convert.ToDouble(activeTags / _selectedTemplateConfiguration.TemplateConfigurationTagsPerRow) % _selectedTemplateConfiguration.TemplateConfigurationRowsPerPage);

  if (divisionRest == 0) //Math.Ceiling thinks it's 3 pages when it's only 2, have to check divisionRest like this
  {
       totalPagesActive = Convert.ToInt32((activeTags / _selectedTemplateConfiguration.TemplateConfigurationRowsPerPage) / _selectedTemplateConfiguration.TemplateConfigurationTagsPerRow);
  }
  else
  {
       totalPagesActive = Convert.ToInt32(Math.Ceiling((Convert.ToDouble(activeTags) / Convert.ToDouble(_selectedTemplateConfiguration.TemplateConfigurationRowsPerPage)) / Convert.ToDouble(_selectedTemplateConfiguration.TemplateConfigurationTagsPerRow)).ToString());
  }
  var pages =  totalPagesActive > 1 ? string.Format("{0} pages", totalPagesActive) : string.Format("{0} page", 1);
  return string.Format("{0} products, {1}", activeTags / _selectedTemplateConfiguration.TemplateConfigurationTagsPerRow, pages);
}

private int totalAmountOfDeletedTags()
{
 int counter = 0;
 foreach (var tag in _currentTagCollection)
 {
   if (tag.Deleted)
   {
      counter++;
   }
 }
 return counter;
}


texts:
I really appreciate the way filtering is applied to queries in Django. I have a list of items (each item is an Item instance which contains a few attributes) that I would like to provide a similar API for filtering.

For reference, the Item class contains the following attributes:

Name
Description
Price
Stock

Currently, Item instances are stored in a list contained inside an Inventory instance. The end-goal is to have code like the following:

>>> inv = Inventory('some id')
>>> inv.load()
>>> inv.find(name='Tomato Paste')
[Item <Tomato Paste>]
>>> inv.find(name__startswith = 'T', name__contains='paste')
[Item <Tomato Paste>]
>>> inv.find(price__gt=200)
[Item <Some Expensive Item>, Item <Some Other Expensive Item>]

Here is an excerpt from my Inventory class with my attempt at accomplishing this:

def find(self, **kwargs):
    matches = []

    for item in self.data:
        match = 0
        for key in kwargs.keys():
            try:
                # Determine if this query has extra arguments
                if '__' in key:
                    arg = key.split('__')[1]
                    atrib = key.split('__')[0]
                    value = getattr(item, atrib)

                    if arg not in self.query_types:
                        continue

                    if arg == 'contains' and type(value) is str:
                        if kwargs[key].lower() in value.lower():
                            match += 1
                    elif arg == 'startswith' and type(value) is str:
                        if value.lower().startswith(kwargs[key].lower()):
                            match += 1
                    elif arg == 'endswith' and type(value) is str:
                        if value.lower().endswith(kwargs[key].lower()):
                            match += 1
                    elif arg == 'gt' and self._is_int(value):
                        if int(value) > int(kwargs[key]):
                            match += 1
                    elif arg == 'lt' and self._is_init(value):
                        if int(value) < int(kwargs[key]):
                            match += 1
                else:
                    value = getattr(item, key)
                    if type(kwargs[key]) is str:
                        if kwargs[key].lower() == value.lower():
                            match += 1
                    else:
                        if kwargs[key] == value:
                            match += 1
            except Exception:
                continue

        if match == len(kwargs.keys()):
            matches.append(item)
    return matches

A few notes:

self._is_init does what it implies
self.data is the list of Item instances

The above code does what I need it to, but it seems to have a serious boilerplate issue. I feel like there's a much more efficient and easier to understand solution. Optimization and feedback is welcomed.


texts:
#include <stdio.h>
#include <stdlib.h>
#define RED     "\x1b[31m"
#define GREEN   "\x1b[32m"
#define YELLOW  "\x1b[33m"
#define BLUE    "\x1b[34m"
#define MAGENTA "\x1b[35m"
#define CYAN    "\x1b[36m"
#define RESET   "\x1b[0m"

int main () {

  int n1 = 1, n2 = 0, i = 0, limit = 0, neg = 0, pos = 0;
        printf("Enter first number > ");
  scanf("%d",&n1);
        printf("Enter the seconed number > ");
  scanf("%d",&n2);
        printf("Enter the number of terms > ");
  scanf("%d",&limit);

  for (i; i < limit; i++ ) {
                if (n2 >=1) { pos ++; printf( RESET "%i\n" RESET, n2); }
                if (n2 <=0) { neg ++; printf( MAGENTA   "%i\n" MAGENTA,  n2); }
    int temp = n2;

    n2 += n1;
    n1 = temp;
  }

        printf(RESET"\n***************************************************"RESET);
        printf("\nPositive numbers in range %i : %i\n",limit,pos);
        printf("Negitive : %i",neg);
  printf("\n***************************************************");
}


texts:
By applying the get_name and get_mac functions to the specified IP address, it is possible to estimate the network availability of a segment:

#include <Winsock2.h>
#include <iphlpapi.h>
#include <cstdio>

#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")

bool get_name(unsigned char* name, char dest[32])
{
  struct in_addr destip;
  struct hostent* info;

  destip.s_addr = inet_addr(dest);

  info = gethostbyaddr((char*)&destip, 4, AF_INET);

  if (info != NULL)
{
  strcpy((char*)name, info->h_name);
}
else
{
return false;
}

return true;
}

bool get_mac(unsigned char* mac, char dest[32])
{
  struct in_addr destip;
  ULONG mac_address[2];
  ULONG mac_address_len = 6;

  destip.s_addr = inet_addr(dest);

  SendARP((IPAddr)destip.S_un.S_addr, 0, mac_address, &mac_address_len);

  if (mac_address_len)
  {
   BYTE* mac_address_buffer = (BYTE*)&mac_address;
   for (int i = 0; i < (int)mac_address_len; i++)
    {
    mac[i] = (char)mac_address_buffer[i];
    }
   }
   else
   {
     return false;
   }

    return true;
   }

   int main()
   {
     char address[][32] = { { "192.168.14.101" },{ "192.168.14.102" },
                     {"192.168.14.103" },{ "192.168.14.106 "} };
     WSADATA sock;

     if (WSAStartup(MAKEWORD(2, 2), &sock) != 0)
   {
     printf("Failed to initialise winsock. (%d)\n", WSAGetLastError());
     return 1;
   }

    for (int i = 0; i < (int)sizeof(address) / 32; i++)
    {
     unsigned char mac[6] = { '\0' };
     unsigned char name[100] = { '\0' };

     if (get_mac(mac, address[i]))
    {
      printf("%s : %s : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n", address[i],
     (get_name(name, address[i])) ? (char*)name : "-",
     mac[0],mac[1],mac[2],mac[3], mac[4], mac[5]);
     fflush(stdout);
    }
    }

    printf("\nDone.\n");
    fflush(stdout);
    system("PAUSE");

   return 0;
   }

An attempt to implement a program that scans the subnet and displays IP address, host name, and MAC of machines on the network.


texts: Project Euler Problem 10 - Sum of primes < 2mil

texts:
/*The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.
*/
#include <iostream>
#include <vector>

using namespace std;

int main(){
//We will be storing the primes as bool in a vector.
    vector<bool>primes(2000000,true);

// This is the Sieve of Eratosthenes. It is not perfect, but It solve's the problem.

    primes[1] = false;
    for(int a = 2; a*a < primes.size(); ++a){
        if(primes[a]==true){
            for(int b = 0; a*a+b*a < primes.size(); ++b){
                    primes[a*a+b*a] = false;
            }
        }
    }
//This simply add's all the prime numbers
    long long total = 0;
    for(int c = 1; c < primes.size(); c++){
        if(primes[c] == true)
            total +=c;
    }
    std::cout << total;

return 0;
}

This works well. I'm trying to improve my C++ and was wondering if there is a way to improve on it. I'm just learning, and would welcome any advice.


texts:
\0
   / \
  a   b-a-t-s
 /|\
m s t

which contains [am, as, at, bat, bats]

The goal I'm trying to reach is to iterate through the trie to find if there's a next word or not, then if so get that word.

I would like to know your opinion on my approach.

The goal for this is that, at any point in the trie if there is a node that hasn't been visited, there's another word.

public boolean hasNext() {
    if (position < this.trie.nodeCount()) return true;
    return false;
}

What I'm trying to go for here is to check to see if the trie is not empty, then at the first trienode in the trie traverse it's children and descendants to find the next word in the trie. so for the trie above it would would go to a then first to m then back to a to s, then t. then eventually go onto b and it's children. then on the way, if it passes a full word, it will repeat that. so in this case, since bat is part of bats it would return 'bat' first then on the next iteration return bats

The logic in plain words is

string temp = null
  if has next
  while current != null
     look at current nodes children
     keep track of nodes visited
            (temp += char at that node)
            current = current nodes next node in trie (so a step down the trie)
     if fullword at that node found return next
  return false;

I also thought of trying a pre-order traversal but couldn't figure out how to do it with the arrays.

Current implementation:

public String next() {
    String next = null;
    if(hasNext()){
        current = trie.root.children[position];
        while(!current.children[position].isEndOfWord()){
            position++;
            current = current.children[position];
            next += current.letter;
            if (current.isEndOfWord()) return next;
        }
    }
    return null;
}

Here's the declaration of the trienodes:

    protected char letter = ' ';
    protected TrieNode parentNode = null;
    protected boolean fullWord = false;
    protected TrieNode[] children = new TrieNode[26];
    protected int prefixes = 0;

    public TrieNode(char letter, TrieNode parentNode){
        this.letter = letter;
        this.parentNode = parentNode;
    }

How the trie is built:

public void addWord(String s) {
        if (hasWord(s)) return;

        int index = 0;
        TrieNode current = root;
        char[] letters = s.toCharArray();

        while(index < s.length()){
            TrieNode child = current.children[letters[index] - 97];
            if(child == null){
                child = new TrieNode(letters[index], current);
                child.prefixes++;
                numOfNodes++;
            }

            current = child;
            index++;

            if(index == s.length()){
                current.fullWord = true;
                numOfWords++;
            }
        }
    }


texts: Extracting coordinates file that are inside a bounding box

texts:
I'm scanning a CSV file to see which values fit inside of a given box. The CSV file has X and Y coordinates, and the arguments to the function are the perimeters of a box (i.e, top, bottom, left side, right side). I don't want to use any external libraries; part of the purpose of this is to learn how to speed up code manually.

I'm fairly new to Java, so any input would be helpful. I'm trying to get this down to 100ms if possible, but right now it's taking about 1000ms.

Scanner dataStream = new Scanner(fileMain);
while (dataStream.hasNext()){
    String data = dataStream.next();
    String[] values = data.split(",", 3);
    if(Double.parseDouble(values[0]) > lowX && Double.parseDouble(values[0]) < highX){
            if(Double.parseDouble(values[1]) < highY && Double.parseDouble(values[1]) > lowY){
                System.out.println(data);

    }

dataStream.close();

Data is formatted like so:

90.92, 102.3
40.28, 82.32
13.02, 80
72, 104.82


texts:
I have a WPF/MVVM form that contains sections for managing Recipient Contacts, CC Contacts and BCC Contacts.

Each of the three sections has buttons/ICommands for 'Add', 'Clear', 'Previous' and 'Next' that move through the collection of objects.

I'm trying to work out how I can remove the repeated code.

I wire up the commands in my constructor:

        this.AddressBookRecipientCommand = new GenericCommand(AddressBookRecipientPressed);
        this.ClearRecipientCommand = new GenericCommand(ClearRecipientPressed, CanClearRecipient);
        this.NextRecipientCommand = new GenericCommand(NextRecipientPressed, CanPressNextRecipient);
        this.PrevRecipientCommand = new GenericCommand(PrevRecipientPressed, CanPressPrevRecipient);
        this.AddressBookCCCommand = new GenericCommand(AddressBookCCPressed);
        this.ClearCCCommand = new GenericCommand(ClearCCPressed, CanClearCC);
        this.NextCCCommand = new GenericCommand(NextCCPressed, CanPressNextCC);
        this.PrevCCCommand = new GenericCommand(PrevCCPressed, CanPressPrevCC);
        this.AddressBookBCCCommand = new GenericCommand(AddressBookBCCPressed);
        this.ClearBCCCommand = new GenericCommand(ClearBCCPressed, CanClearBCC);
        this.NextBCCCommand = new GenericCommand(NextBCCPressed, CanPressNextBCC);
        this.PrevBCCCommand = new GenericCommand(PrevBCCPressed, CanPressPrevBCC);

Then I have the various command code:

    public ICommand AddressBookRecipientCommand { get; set; }
    public void AddressBookRecipientPressed()
    {
        this.Recipient = this.Details.Recipients.ReplaceAndReturn(this.Recipient, this.Outlook.GetContact());
    }

    public ICommand PrevRecipientCommand { get; set; }
    public bool CanPressPrevRecipient()
    {
        return Details.Recipients.IndexOf(Recipient) != 0;
    }
    public void PrevRecipientPressed()
    {
        int i = Details.Recipients.IndexOf(Recipient);
        Recipient = Details.Recipients[i - 1];
    }

    public ICommand NextRecipientCommand { get; set; }
    public bool CanPressNextRecipient()
    {
        return !Recipient.IsNullOrEmpty() && Details.Recipients.IndexOf(Recipient) != MaxRecipients;
    }
    public void NextRecipientPressed()
    {
        if (Details.Recipients.IndexOf(Recipient) + 1 == Details.Recipients.Count)
        {
            Recipient = new Contact();
            Details.Recipients.Add(Recipient);
        }
        else
        {
            int i = Details.Recipients.IndexOf(Recipient);
            Recipient = Details.Recipients[i + 1];
        }
    }

    public ICommand ClearRecipientCommand { get; set; }
    public bool CanClearRecipient()
    {
        return !Recipient.IsNullOrEmpty();
    }
    public void ClearRecipientPressed()
    {
        int i = this.Details.Recipients.IndexOf(this.Recipient);
        if (i + 1 == this.Details.Recipients.Count)
            this.Recipient.Clear();
        else
        {
            this.Details.Recipients.Remove(this.Recipient);
            this.Recipient = this.Details.Recipients[i];
        }
    }

This code is repeated for CC and BCC.


texts: Concurrent programming with a simple server

texts:
I am creating a simple server that accepts a int and returns the value received twice:

public class MyServer{

    private static int port = 1234;

    public static void main(String args[]){
        try{
            ServerSocket serversock=new ServerSocket(port);
            while(true){
                Socket  socket=serversock.accept();
                new Thread(new MyClass(socket)).start();
            }
        }catch(IOException e){}
        }
    }

    class MyClass implements Runnable{

        Socket socket;

        public MyClass(Socket s){socket = s;}

        public void run(){
            try{
                DataInputStream in = new DataInputStream(socket.getInputStream());
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                int x = in.readInt();
                out.write(2*x);
                socket.close();
            }
            catch(IOException e){}
    }
}

My question is about redesigning the code. Are there any weaknesses in the design?
If yes, then what changes would make the code better?


texts: JavaScript - Given a list of integers, return the first two values that adds up to form sum. sum = x + y

texts:
The following function sum_pairs takes two arguments one array and another number, It should return the first two values (parse from the left please) in order of appearance that adds up to form the sum. Negative numbers and duplicate numbers can and appear.

For example

sum_pairs([10, 5, 2, 3, 7, 5],         10)
#              ^-----------^   5 + 5 = 10, indices: 1, 5
#                    ^--^      3 + 7 = 10, indices: 3, 4 *
#  * entire pair is earlier, and therefore is the correct answer
== [3, 7]

My following code works but takes time. I know it can be optimized but can't think how can I replace any of the loops.

var sum_pairs=function(ints, s){
  var result = [];
  var finalResult = undefined

  for(let i = 0; i < ints.length; i++){
    var anotherArray = ints.slice()
    anotherArray[i] = 0
    for(let j = 0; j < anotherArray.length; j++){
      var sum = ints[i] + anotherArray[j]
      if(sum === s){
        var tempResult = []
        tempResult.push(i)
        tempResult.push(j)
        result.push(tempResult)
      }
    }
  }

  var resultArray = []
  result.map((array, index) => {
    array.map((number, idx) => {
      array[idx] === array[idx+1] ? result.splice(index, 1) : false
      array.every((num, i) => i === array.length - 1 || num < array[i + 1]) ? resultArray = array : false
    })
  })

  s === 0 ?
  finalResult = [0, 0] : resultArray.length === 0 ?
  finalResult = undefined : finalResult = [ints[resultArray[0]], ints[resultArray[1]]]

  return finalResult
}

Any suggestion to optimize further?


texts:
I've written binary search with only my own efforts  without glancing at anywhere. I stuck on finding base case. At final, I think that if last checking is less than first index or first checking is greater than last index, it stops.  But, I'm still  suspicious of its performance and righness. I could return Integer.MAX_VALUE or Integer.MIN_VALUE if the searched number is not in the array but I assumed that all numbers are positive.

In the beginning times of writing recursion, I had difficulty in thinking recursively. But, now I have difficulty in finding base case(s).

public static int binarySearch(int[] arr, int key, int low, int high) {
        if (high < 0 || low > high )
            return -1;

        int middleIndex = (low + high) / 2;

        if (arr[middleIndex] == key)
            return middleIndex;
        else if (key > arr[middleIndex])
            return binarySearch(arr, key, middleIndex + 1, high);
        else
            return binarySearch(arr, key, low, middleIndex - 1);

}


texts: Python/Sklearn code optimization (New at Python)

texts:
I am trying to optimize the following code, as you may see I am quite new to python but I am trying to improve, any kind of tip or code changes is welcome. I am trying to optimise this module by keeping it as short as possible but still understandable for everyone.

from copy import deepcopy

import pandas as pd

from sklearn import ensemble
from sklearn.externals import joblib
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

from draw_benchmark_graphs import draw_benchmark_graphs

def preparate_dataset():
    # Load the dataset.
    dataframe = pd.read_csv('datasets/eggs_data_set.csv')
    features_df = deepcopy(dataframe)

    # Remove the wanted dataset output from the features-list.
    del features_df['days_remaning']

    # Create the Features(X) & Output(Y) arrays.
    features = features_df.as_matrix()
    output = dataframe['days_remaning'].as_matrix()

    # Split the data in a 70% to 30% ratio,the 30% will be kept hidden for testing porpuses.
    x_train, x_test, y_train, y_test = train_test_split(
        features, output, test_size=0.3)

    return [x_train, y_train, x_test, y_test]

def generate_new_model():
    dataset = preparate_dataset()
    x_train = dataset[0]
    y_train = dataset[1]
    x_test = dataset[2]
    y_test = dataset[3]

    # Create & fit a GB model using GridSearch optimised parameters.
    params = {
        'learning_rate': 0.01,
        'loss': 'ls',
        'max_depth': 4,
        'max_features': 0.3,
        'min_samples_leaf': 9,
        'n_estimators': 500
    }
    model = ensemble.GradientBoostingRegressor(**params)
    model.fit(x_train, y_train)

    # Find the error rate on the training set.
    mae_train = mean_absolute_error(y_train, model.predict(x_train))
    print('Training Set Mean Absolute Error: %.4f' % mae_train)

    # Find the error rate on the test set.
    mae_test = mean_absolute_error(y_test, model.predict(x_test))
    print('Test Set Mean Absolute Error: %.4f' % mae_test)

    # Save the trained model to a file for later use,
    # otherwise we will need to train a new model everytime we want to use it.
    joblib.dump(model, 'models/trained_eggs_classifier_model.pkl')

    draw_benchmark_graphs(model, params, x_test, y_test, mae_train, mae_test)
    return (model, (mae_train, mae_test))

generate_new_model()


texts: Using exceptions inside CakePHP controller actions to simplify flow

texts:
I'm looking to simplify controller logic where multiple validation steps will either result in redirecting the browser or re-rendering the current view.
Overall I'm looking to:

Avoid excessive nested if statements
Avoid multiple calls to Controller::redirect with the same arguments
Avoid using "return $this->render();"
Set view data that depends on the actions arguments (excludes using Controller::beforeRender)
Avoid generating/setting additional view data (ie dropdown list data) unless the view will render

The sample below is CakePHP 2 but I assume this idea could apply to versions 3 or 4 as well.
Are there any potential issues or downsides with the generic sample I've provided below?
<?php
class MyController extends Controller {
    public function my_action($id = null) {
        try {
            //test controller args
            if (!$id) {
                throw new RedirectException('Invalid id selected');
            }

            //form submitted
            if ($this->request->is('post')) {

                //check various things
                if (!$this->validationStep1()) {
                    throw new AlertException('Please check something for step 1');
                }

                if (!$this->validationStep2()) {
                    throw new AlertException('Please check something for step 2');
                }

                //situation where the validation may throw
                try {
                    $this->validateStep3MayThrowSomething();
                }
                catch (Exception $e) {
                    throw new AlertException('Please check something for step 3');
                }

                //more checks here

                if (!$this->Model->save()) {
                    throw new AlertException('Error saving');
                }

                //successful completed if we are here
                throw new RedirectException('Action completed successfully');
            }
        }
        catch (RedirectException $e) {
            if ($e->hasMessage()) {
                $this->alert($e->getMessage());
            }
            $this->redirect(array('action' => 'index'));
        }
        catch (AlertException $e) {
            $this->alert($e->getMessage());
        }

        //set any data needed to render this view
        $this->set('someData', $this->Model->getSomeData());
        $this->set('someSpecifcData', $this->Model->getDataById($id));

    }
}


texts:
I'm working on a simple method that would censor emails (GPDR stuff) so they won't show the full name of a user, with 1st character, optional dot, 1st character after the dot and whatever is left after the @ to be left uncensored. So, the intent is like this:
Email to be censored: name.lastname@email.com
Desired effect: n***.l*******@email.com
I've written this:
public static String getCensoredUsername(String username) {
    if (username.contains("@")) {
        char[] chars = username.toCharArray();
        for (int i = 1; i < chars.length; i++) {
            boolean isCurrentCharacterADot = chars[i] == '.';
            boolean isPreviousCharacterADot = chars[i - 1] == '.';

            if (chars[i] == '@') {
                break;
            }
            if (chars[i] == '.') {
                chars[i] = '.';
            } else if (!isCurrentCharacterADot && !isPreviousCharacterADot) {
                chars[i] = '*';
            }
        }
        return String.valueOf(chars);
    }
    return username;
}

It feels to me very Java 6. What would make it look better?


texts:
I just finished this Merge Sort in Clojure, structured according to ex. 22-26 of this workshop.

The main question I have can be answered without spending time understanding the code: halve is called twice in merge-sort, is this still \$\mathcal{O}(n \log n)\$? (last lines in the code sample) Since it's functional programming, I can't think of a way to avoid calculating halve twice (can't stash the result into a variable).

I followed the structure set out in the exercises, but I think this code is bloated and hard to read. How would you improve the individual functions while maintaining the general structure?

(defn my-take-r [a-list n coll]
  (if (or
        (= 1 n)
        (singleton? coll))
     (concat
      a-list
      (list (first coll)))
     (recur
      (concat a-list (list (first coll)))
      (dec n)
      (rest coll))))

(defn my-take [n coll]
   (if (empty? coll)
    `()
    (my-take-r `() n coll)))

(defn my-drop [n coll]
  (if (or (zero? n) (empty? coll))
    (concat `() coll)
    (my-drop (dec n) (rest coll))))

(defn halve [a-seq]
  (let [i (int (/(count a-seq) 2))]
     (vec (list
           (concat `() (seq (subvec (vec a-seq) 0 i)))
           (concat `() (seq (subvec (vec a-seq) i)))))))

(defn seq-merge-r [output a-seq b-seq]
  (cond (and
          (empty? a-seq)
          (empty? b-seq)) output
        (empty? a-seq) (concat output b-seq)
        (empty? b-seq) (concat output a-seq)
        (<
          (first a-seq)
          (first b-seq)) (seq-merge-r (conj output (first a-seq)) (rest a-seq) b-seq)
        :else            (seq-merge-r (conj output (first b-seq)) a-seq (rest b-seq))))

(defn seq-merge [a-seq b-seq]
  (seq-merge-r [] (seq a-seq) (seq b-seq)))

(defn merge-sort [a-seq]
  (cond
    (empty? a-seq) a-seq
    (singleton? a-seq) a-seq
    :else (seq-merge
            (merge-sort (first  (halve a-seq)))
            (merge-sort (second (halve a-seq))))))


texts:
I've written this class that downloads an images, the URLs for which are read from a local .txt file. I'm keen to make sure my code is safe and efficient.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include<cassert>
#include <algorithm>
#include <numeric>
#include <functional>
#include <curl/curl.h>

class DownloadTesting
{
  private:
    CURL *curl;
    FILE *file;
    CURLcode response;
    char outfilename[FILENAME_MAX];
    int count {0};
    std::vector<char*> URLS; //Stores the urls
    auto DownloadImage(const char *url) -> void;
    auto Convert(const std::string &s) -> char*;
    auto ReadDataStore() -> void;
    static auto WriteData(void *ptr, size_t size, size_t nmemb, FILE *stream) -> size_t;
  public:
    DownloadTesting();
    ~DownloadTesting();
    auto Interface() -> void;
};

DownloadTesting::DownloadTesting(){};

DownloadTesting::~DownloadTesting()
{
   if(!URLS.empty()) //Delete raw pointers
   {
     std::for_each(URLS.begin(),URLS.end(),[](char* url){delete url;});
   }
}

auto DownloadTesting::WriteData(void *ptr, size_t size, size_t nmemb, FILE *stream) -> size_t //Write data into file
{
   size_t written {fwrite(ptr, size, nmemb, stream)};
   return written;
}

auto DownloadTesting::Convert(const std::string &s) -> char* //Convert url from std::string to raw char pointer
{
  char *pc {new char[s.size()+1]};
  std::strcpy(pc,s.c_str());
  return pc;
}

auto DownloadTesting::ReadDataStore() -> void
{
  std::vector<std::string> storage_vector;
  std::string storage_string;
  std::ifstream storage_file {"./imagestore/urlstore.txt"};
  if(storage_file.is_open()) //Open local file
  {
     while(getline (storage_file,storage_string)) //Read each line
     {
       storage_vector.push_back(storage_string); //Storage each line in vector
     }
     storage_file.close();
  }
  std::transform(storage_vector.begin(), storage_vector.end(), std::back_inserter(URLS), [this](const std::string url){return this->Convert(url);}); //Perform conversion function on each url
}

auto DownloadTesting::DownloadImage(const char *url) -> void
{
  count++; //Use a counter to name each downloaded file
  std::string name {std::to_string(count)}; //Convert int to string
  strcpy(outfilename, name.c_str()); //Convert std::string to [char]

  curl = curl_easy_init(); //Initialise curl
  if(curl)
  {
    file = fopen(outfilename,"wb");
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &DownloadTesting::WriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
    response = curl_easy_perform(curl);
    curl_easy_cleanup(curl); //Clean up curl
    fclose(file); //Close file
  }
}

auto DownloadTesting::Interface() -> void
{
  this -> ReadDataStore(); //Read in the data
  assert(!URLS.empty()); //Ensure data is not empty
  std::for_each(URLS.begin(),URLS.end(), [this](const char* url){return this -> DownloadImage(url);}); //Perform download for each url
}

int main()
{
  DownloadTesting DTO;
  DTO.Interface();
}


texts:
I am trying to write a human-readable tester for a functioning program.

There are four methods in the class Polynomial: public Polynomial(int[] coefficients), public int getDegree(), public int getCoefficient(int k), public long evaluate(int x).

Where coefficients is an immutable array of elements that represent a polynomial. For example, the polynomial 6x^3 + 4x + 3 would be represented by its coefficients as [3, 4, 0, 6]. The method getDegree() determines the highest order term that has a non-zero coefficient. For example, the degree would equal 3 in the previous example. getCoefficient(int k) returns the coefficient of element k. For example, in the previous example, if k = 2 the returned value is 0. The method evaluate(int x) evaluates the polynomial with the value of x. In the previous example, the value returned when x = 2 would be 59.

This is the tester I've written so far:

@Test public void testPolynomial()
    {
        int [] c1 = {0, 0, 0, 1};
        Polynomial p1 = new Polynomial(c1);
        c1[2] = 1;
        assertEquals("Degree error", 3, p1.getDegree());
        assertEquals("Polynomial must compute coefficients out of range", 0, p1.getCoefficient(-1));
        assertEquals("Polynomial must compute coefficients out of range", 0, p1.getCoefficient(4));
        assertEquals("Array is not immutable", 0, p1.getCoefficient(2));
        assertEquals("Coefficient error near boundary", 1, p1.getCoefficient(3));
        assertEquals("Coefficient error near boundary", 0, p1.getCoefficient(0));
        assertEquals("Coeffificent error", 0, p1.getCoefficient(1));
        assertEquals("Evaluation error", 0, p1.evaluate(0));
        assertEquals("Evaluation error of negative x", -27, p1.evaluate(-3));

        int[] c2 = {-1, 0, 0, 0};
        Polynomial p2 = new Polynomial(c2);
        c2[2] = 4;
        assertEquals("Degree error", 0, p2.getDegree());
        assertEquals("Polynomial must compute coefficients out of range", 0, p2.getCoefficient(-1));
        assertEquals("Polynomial must compute coefficients out of range", 0, p2.getCoefficient(4));
        assertEquals("Array is not immutable", 0, p2.getCoefficient(2));
        assertEquals("Coefficient error near noundary", 0, p2.getCoefficient(3));
        assertEquals("Coefficient error near noundary", -1, p2.getCoefficient(0));
        assertEquals("Evaluation error", -1, p2.evaluate(0));
        assertEquals("Evaluation error of negative x", -1, p2.evaluate(-3));

    }

Are there any other test cases that anyone can think of that I could include into my tester or that I'm missing?


texts: Python 3: Finding common patterns in pairs of strings

texts:
I have written a piece of code that finds common patterns in two strings. These patterns have to be in the same order, so for example "I am a person" and "A person I am" would only match "person". The code is crude, all characters, including whitespace and punctuation marks, receive the same treatment. The longest patterns are matched first.

The main function then returns two lists (one per string) of tuples with two elements. The first element is 1 if a substring has been matched, else 0. The second element is the substring.

So the format of returned lists will be like this:

[(1, 'I '), (0, 'am a person\n')]
[(1, 'I '), (0, 'can see\n')]

Now to the question -- what do you think about my code? I somehow feel that it's not quite top-notch, and I'm not an experienced coder. Any suggestions on coding style or the algorithms? I hope the code is reasonably clear.

The find_raw_patterns function returns lists with alternating integers and strings, so the only thing find_common_patterns does in addition to calling find_raw_patterns, is to arrange the lists' elements in two-element-tuples.

The function longest_common_substring is copied directly from Wikibooks, and I'm not very concerned about that function.

Code:

def longest_common_substring(S1, S2):
    M = [[0]*(1+len(S2)) for i in range(1+len(S1))]
    longest, x_longest = 0, 0
    for x in range(1,1+len(S1)):
        for y in range(1,1+len(S2)):
            if S1[x-1] == S2[y-1]:
                M[x][y] = M[x-1][y-1] + 1
                if M[x][y]>longest:
                    longest = M[x][y]
                    x_longest  = x
            else:
                M[x][y] = 0
    return S1[x_longest-longest: x_longest]

def find_common_patterns(s1, s2):
    arranged1 = []
    arranged2 = []
    (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern
    for i in range(len(ptr1) - 1):
        if type(ptr1[i]) == int:
            arranged1.append((ptr1[i], ptr1[i+1]))
    for i in range(len(ptr2) - 1):
        if type(ptr2[i]) == int:
            arranged2.append((ptr2[i], ptr2[i+1]))
    return (arranged1, arranged2)

def find_raw_patterns(s1, s2): # used recursively
    one = [] # used to reassemble strings, but with patterns and integer showing whether it's been matched or not
    two = [] # same, but for the second string
    com = longest_common_substring(s1, s2)
    if len(com) < 2:
        return ((0, s1), (0, s2))
    elif len(com) >= 2:
        i1 = s1.index(com)
        i2 = s2.index(com)
        s1_bef = s1[:i1] #part of string before the matched pattern
        s1_aft = s1[i1 + len(com) : ] # -//- after matched pattern
        s2_bef = s2[:i2]
        s2_aft = s2[i2 + len(com) : ]
        if len(s1_bef) > 0 and len(s2_bef) > 0: # find patterns in first parts of strings
            res = find_raw_patterns(s1_bef, s2_bef)
            one.extend(res[0])
            two.extend(res[1])
        one.extend((1, com)) # add current pattern
        two.extend((1, com))
        if len(s1_aft) > 0 and len(s2_aft) > 0: # find patterns from second parts
            res = find_raw_patterns(s1_aft, s2_aft)
            one.extend(res[0])
            two.extend(res[1])
        return (one, two)


texts: Add neighboring stones of the same color to form chains, with logging for isolated stones

texts:
I'm trying to check four things, one of those things might happen, maybe two, three or four things, but if none of them occur, then I want to run some code. I can't do an else statement because that only applies to one and I can't do else if because more than one can happen.

At the moment I've resorted to this:

function checkChains(x, y, color, array)
{
    var count = 0;

    if ((x + 1) != (boardSize) && (stones[x + 1][y] == color))
    {
        addToChain(x, y, x + 1, y, array);
    }
    else
    {
        count++;
    }

    if ((x != 0) && (stones[x - 1][y] == color))
    {
        addToChain(x, y, x - 1, y, array);
    }
    else
    {
        count++;
    }

    if ((y + 1) != (boardSize) && (stones[x][y + 1] == color))
    {
        addToChain(x, y, x, y + 1, array);
    }
        else
    {
        count++;
    }

    if ((y != 0) && (stones[x][y - 1] == color))
    {
        addToChain(x, y, x, y - 1, array);
    }
    else
    {
        count++;
    }

    if (count == 4)
    {
        console.log("none!");
    }
}

It's pretty ugly, can this be tidied?


texts: Sending a file over a socket with AES encryption

texts:
I'm not sure what's the best way to deal with streams that need to be closed whenever I'm done using them? Usually the need to also catch the exception inside the finally statement is very, very annoying. Am I doing this right?

public class FileSender {

    public static final String KEY = "00000000000000000000000000000000";
    public static final String ALGORITHM = "AES";
    public static final String FILE = "C:\\Users\\Andres\\Desktop\\file.txt";
    public static final String HASH_ALG = "MD5";

    private String filePath;
    private String serverMachine;
    private int serverPort;

    public FileSender(String filePath, String serverMachine, int serverPort){
        this.filePath = filePath;
        this.serverMachine = serverMachine;
        this.serverPort = serverPort;
    }

    public void sendFile(){
        CipherOutputStream cipherOut = null;
        Socket client = null;
        String checkSum;
        try {
            System.out.println("Running client ...");
            client = connectToServer();
            checkSum = getHashChecksum();
            cipherOut = initCipherStream(client);
            transferData(cipherOut, checkSum);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {

        }
    }

    private String getHashChecksum() {
        FileInputStream fis = null;
        try {
            MessageDigest md = MessageDigest.getInstance(HASH_ALG);
            fis = new FileInputStream(this.filePath);
            byte[] byteArray = new byte[1024];
            int bytesCount = 0;
            while ((bytesCount = fis.read(byteArray)) >= 0)
                md.update(byteArray, 0, bytesCount);
            byte[] hash = md.digest();
            fis.close();
            return String.format("%032x",new BigInteger(1, hash));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Error in checksum");
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException("Error in checksum. Provided file can't be closed.");
            }
        }
    }

    private Socket connectToServer() throws Exception{
        try {
            Socket client = new Socket(this.serverMachine, this.serverPort);
            return client;
        } catch (IOException e) {
            throw new Exception("Server can't be reached");
        }
    }

    private CipherOutputStream initCipherStream(Socket client) {
        SecretKeySpec keySpec = new SecretKeySpec(hex2byte(KEY), ALGORITHM);
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            return new CipherOutputStream(client.getOutputStream(), cipher);
        } catch (Exception  e) {
            e.printStackTrace();
            throw new RuntimeException("Error in cipher stream initialization.");
        }

    }

    private void transferData(CipherOutputStream cipherOut, String checksum) {
        FileInputStream fileReader = null;
        try {
            //Missing here: send MD5 checksum. TODO
            fileReader = new FileInputStream(this.filePath);
            byte[] fileBuffer = new byte[1024];
            int len;
            while ((len = fileReader.read(fileBuffer)) != -1)
                cipherOut.write(fileBuffer, 0, len);
        } catch (Exception e) {
            throw new RuntimeException("File " + this.filePath + " not found");
        } finally{
            try {
                if(fileReader != null) fileReader.close();
            } catch (IOException e) {
                throw new RuntimeException("Socket stream can't be closed");
            }
        }
    }

    private byte[] hex2byte(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }

    public static void main(String [] args) throws Exception {
        FileSender fileSender = new FileSender(FILE, "localhost", 8081);
        fileSender.sendFile();
    }
}


texts:
I wrote a simple Dependency Resolver in PHP that I'm hoping to get some input on.

The main problem that gave me some trouble was when it had to resolve typed arguments ( like type hinting a constructor argument with an interface, I don't remember exactly what they call it ).  The only work around was to let the DependencyResolver know about such dependencies that are not directly resolvable (instantiable).

Note: The class name of this Dependency Resolver is ObjectManager

// dependencies.php
// this is where I define all my dependencies in case if they are not directly instantiable
$deps = array(
  'DependentClass' => array(
     'depclass' => 'DependencyClass'
    )
);

ObjectManager::getInstance()->setDependencies($deps);

ObjectManager uses singleton pattern so I can use the same object throughout the flow

// mainfile.php
use DependencyClassInterface;
use AnotherClass;
Class DependentClass {
  protected $depClass;
  public function __construct(DependencyClassInterface $depclass, AnotherClass $another) {
     $this->depClass = $depClass;
  }
  public function doSomething() { echo "Something"; }
}
ObjectManager::getInstance()
     ->get('DependentClass')
     ->doSomething();

And finally the implementation of Dependency Resolver.

<?php
class ObjectManager
{
protected $dependencies;

protected static $omInstance;

public static function getInstance()
{
    if (!self::$omInstance) {
        self::$omInstance = new ObjectManager();
    }
    return self::$omInstance;
}

public function setDependencies(array $dependencies)
{
    $this->dependencies = $dependencies;
}

public function getDependencies()
{
    return $this->dependencies;
}

public function get($class)
{
    $finalizedParams = array();
    $deps = array();

    // check if deps are defined
    if (array_key_exists($class, $this->dependencies)) {
        $deps = $this->dependencies[$class];
    }

    $reflector = new ReflectionClass($class);

    if (!$reflector->isInstantiable()) {
        throw new Exception("Class {$class} is not instantiable");
    }

    $constructor = $reflector->getConstructor();
    if ($constructor == null) {
        return $reflector->newInstance();
    }

    $parameters = $constructor->getParameters();

    foreach ($parameters as $key => $parameter) {
        $parameterType = $this->getParameterType($parameter);
        $parameterName = $parameter->getName();

        if ($parameterType == null) {
            if ($parameter->isDefaultValueAvailable()) {
                $finalizedParams[$key] = $parameter->getDefaultValue();
            } else {
                throw new Exception("
                Failed resolving argument (dependency) \"$parameterName\" for class $class.
                Not directly instantiatable.
                No default value specified.");
            }
            continue;
        }

        $classReflection = new ReflectionClass($parameterType);

        // if dep is directly instantiable; save and continue
        if ($classReflection->isInstantiable()) {
            $finalizedParams[$key] = $classReflection->newInstance();
            continue;
        }

        // if defined in di.php
        if (array_key_exists($parameterName, $deps)) {
            $argName = $deps[$parameterName];
            $finalizedParams[$key] = ObjectManager::getInstance()->get($argName);
            continue;
        }
    }

    return $reflector->newInstanceArgs($finalizedParams);
}

protected function getParameterType(ReflectionParameter $parameter)
{
    $export = ReflectionParameter::export(
        array(
            $parameter->getDeclaringClass()->name,
            $parameter->getDeclaringFunction()->name,
        ),
        $parameter->name,
        true
    );
    return preg_match('/[>] ([A-z]+) /', $export, $matches)
    ? $matches[1] : null;
}
}

Hopefully, you got the idea. It might be an overkill to resolve dependencies this way, but I like the option of an Object Manager being able to do that.


texts:
I have written this Java snippet to generate all permutations of a given array of integers. Can somebody review it and give some pointers as to how to make it more generic? I.e. instead of dealing with only ints, it should be able to handle a collection of any data type.

import java.util.Arrays;
public class PrintPermutations{
        private int[] taperedArray(int[] arr,int idx){
                int nArray[] = new int[arr.length-1];
                for(int i=0,j=0;i<nArray.length;i++,j++){
                  if(j == idx){j+=1;}
                  nArray[i] = arr[j];
                }
                return nArray;
        }

        public void printPermutations(String prefix,int[] arr){
                if(arr.length == 1){
                  System.out.println(prefix + arr[0]);
                }else{
                 for(int i=0;i<arr.length;i++){
                   printPermutations(prefix+arr[i]+",",taperedArray(arr,i));
                 }
                }
        }

        public static void main(String[] args){
                PrintPermutations pp = new PrintPermutations();
                int data[] = new int[]{1,2,3};
                pp.printPermutations("",data);
        }
}


texts: Database schema for holding game save files

texts:
I have a database schema for a game to hold save files where some tables have a one-to-one relationship to classes.  I was wondering if I should split up some tables.

Example: troop_class table. It could have a PK of

{ GameID,PostionX,PostionY,PostionZ,Team }

but then team don't really rely on the positions and could be split to two new tables

game_units Keys{GameID, troop_id} PK{GameID}

and

troop_team{troop_id, Team} PK{troop_id}.

I am wondering if I should break up the one-to-one mapping for table-class and start to normalize and create proper PK instead of using id.

CREATE TABLE accounts(
    AccountName VARCHAR(50) UNIQUE NOT NULL,
    Password BLOB NOT NULL,
    PRIMARY KEY(AccountName)
) Engine=InnoDB;

CREATE TABLE maps(
    maps_id INT NOT NULL UNIQUE,
    MapName VARCHAR(30) NOT NULL,
    PRIMARY KEY (maps_id),
    INDEX(maps_id)
) ENGINE=InnoDB;

CREATE TABLE game_searching_player(
    AccountName VARCHAR(50) NOT NULL,
    MapID INT NOT NULL,
    PRIMARY KEY (AccountName, MapID),
    FOREIGN KEY (AccountName) REFERENCES accounts(AccountName)
                      ON DELETE CASCADE ,
    FOREIGN KEY (MapID) REFERENCES maps(maps_id)
                      ON DELETE CASCADE ,
    INDEX(AccountName)
) ENGINE=InnoDB;

CREATE TABLE games(
    games_id INT NOT NULL AUTO_INCREMENT UNIQUE,
    Player1 VARCHAR(50) NOT NULL,
    Player2 VARCHAR(50) NOT NULL,
    WhosTurn INT NOT NULL,
    TurnHasEnded BOOL NOT NULL,
    HaveWon BOOL NOT NULL,
    TurnNumber INT NOT NULL,
    MapID INT NOT NULL,
    Type VARCHAR(30) NOT NULL,
    PRIMARY KEY (games_id),
    FOREIGN KEY (Player1) REFERENCES accounts(AccountName)
                      ON DELETE CASCADE ,
    FOREIGN KEY (Player2) REFERENCES accounts(AccountName)
                      ON DELETE CASCADE ,
    FOREIGN KEY (MapID) REFERENCES maps(maps_id)
                      ON DELETE CASCADE ,
    INDEX(games_id,Player1, Player2  )
) ENGINE=InnoDB;

CREATE TABLE player(
    GameID INT NOT NULL,
    Player VARCHAR(30) NOT NULL,
    VictoryResources INT NOT NULL,
    UniversalResources INT NOT NULL,
    Type VARCHAR(30) NOT NULL,
    PRIMARY KEY (GameID, Player),
    FOREIGN KEY (GameID) REFERENCES games(games_id)
                      ON DELETE CASCADE ,
    INDEX(GameID)

) ENGINE=InnoDB;

CREATE TABLE troop_class (
    troop_class_id INT NOT NULL AUTO_INCREMENT UNIQUE,
    GameID INT NOT NULL,
    Health INT NOT NULL,
    CombatInitiative INT NOT NULL,
    Spotted BOOL NOT NULL,
    Entrenched INT NOT NULL,
    Initiative INT NOT NULL,
    Ammo INT NOT NULL,
    Petrol INT NOT NULL,
    ActionPoints INT NOT NULL,
    IsMoving BOOL NOT NULL,
    PositionX INT NOT NULL,
    PositionY INT NOT NULL,
    PositionZ INT NOT NULL,
    Team VARCHAR(30) NOT NULL,
    Name VARCHAR(30) NOT NULL,
    Type VARCHAR(30) NOT NULL,
    PRIMARY KEY (troop_class_id),
    FOREIGN KEY (GameID) REFERENCES games(games_id)
                      ON DELETE CASCADE ,
    INDEX(GameID)
) ENGINE=InnoDB;

CREATE TABLE supply_unit(
    supply_unit_id INT NOT NULL UNIQUE,

    SupplyPetrol INT NOT NULL,
    SupplyAmmo INT NOT NULL,
    VictoryResources INT NOT NULL,
    LoadWeight INT NOT NULL,
    MaxWeight INT NOT NULL,
    PRIMARY KEY (supply_unit_id),
    FOREIGN KEY (supply_unit_id) REFERENCES troop_class(troop_class_id)
                      ON DELETE CASCADE

) ENGINE=InnoDB;

CREATE TABLE central_warehouse (
    central_warehouse_id INT NOT NULL AUTO_INCREMENT UNIQUE,
    GameID INT NOT NULL,
    SupplyPetrol INT NOT NULL,
    SupplyAmmo INT NOT NULL,
    VictoryResources INT NOT NULL,
    LoadWeight INT NOT NULL,
    MaxWeight INT NOT NULL,
    PositionX INT NOT NULL,
    PositionY INT NOT NULL,
    PositionZ INT NOT NULL,
    Team VARCHAR(30) NOT NULL,
    Name VARCHAR(30) NOT NULL,
    Type VARCHAR(30) NOT NULL,
    PRIMARY KEY (central_warehouse_id),
    FOREIGN KEY (GameID) REFERENCES games(games_id)
                      ON DELETE CASCADE ,
    INDEX(GameID)

) ENGINE=InnoDB;


texts:
I have a list of BasicDBObject that I fetch from my database. This is basically a JSON document converted into a java Object.

Let's assume that we have a BasicDBObject named result

This JSON document may or may not contain the key name. If the document doesn't contain the key, result.get("name") will return null.

Is there a difference in terms of performance between this :

BasicDBObject result = ...
Object name = result.get("name");
String nameString = (name == null ? "." : name.toString());

and

BasicDBObject result = ...
String name = (String) result.get("name");
String nameString = (name == null ? "." : name);

Even if this part of the code is called 100 000+ times within a function, I know this wil never be the bottleneck, I'm just interested in the answer.


texts: Multiplying binary numbers digit by digit and carry method in Python

texts:
I have two numbers encoded in a reversed list of digits. First I made multiplication in "Peano" way:

#from summa import summa
#from predecessor import predecessor

#def multiply(m, n):
#  def _(b):
#    return [0] if is_zero(b) else summa(m, _(predecessor(b)))
#  return [0] if is_zero(m) or is_zero(n) else summa(m, _(predecessor(n)))

but my intention is to find out, if carry method presented below is more efficient.

While the algo itself should work, I need some assistance, if the middle part of it could be optimized. At the moment it looks overly complex, but I haven't find a way to simplify it. Of course it could be an unavoidable effect of the way I have chosen to carry and pass parameters, but if someone could either confirm the case or do some optimization suggestions, I'd greatly appreciate it.

# encode int to binary list
def bn(n):
  return list(reversed(list(map(lambda x: 1 if x == "1" else 0, "{0:b}".format(n)))))

def is_zero(n):
  return not n[1:] and not n[0]

def is_one(n):
  return not n[1:] and n[0]

# multiplication
def multiply2(a, b):
    def _(c, d, f, g, e):
        if not b and not c:
            return g + (e if e[1] else e[:1])
        if c:
            # clumsy part is the formation of A and x
            A = 0 if (0 if (1 if c[0] and d else 0) == (e[1] if e else 0) else 1) == (f[0] if f else 0) else 1
            # x = [0, 0] or [1, 0] or [0, 1] or [1, 1]
            x = [A, 1 if ((e[1] if e else 0) or (f[0] if f else 0)) and c[0] and d or \
                         ((e[1] if e else 0) and (f[0] if f else 0)) and not c[0] and d else 0]
            #print(x, c, d, e, f, g)
            return _(c[1:], d, f[1:], (g + e[:1] if e else g), x)
        return g[:1] + _(a, b.pop(0), g[1:] + e, [], [])
    return [0] if is_zero(a) or is_zero(b) else \
             b if is_one(a) else \
             a if is_one(b) else _(a, b.pop(0), [], [], [])
# test cases
for i in range(101):
  for j in range(101):
    x, y = bn(i*j), multiply2(bn(i), bn(j))
    if x != y:
      print("prod %s * %s = %s:" % (i, j, (i*j)), x, "->", y)

Please note the comment: "clumsy part is the formation of A and x" which is due to required optimization.

The last double for loop iterates numbers from 0 to 100 and multiplies them, which is for checking that algo works correctly.

  Note, that I can do only simple comparison, boolean checks and list
  cut/concat operations on the algo.

Addition

In the simple sample output:

print(multiply2(bn(10), bn(10)), bn(10*10))

both lists should be same.

Also

This algo is based on the schema presented below, althought the one below is using base ten numbers, but carrying logic is same in the right part of the spreadsheet:

Left part is the common multiplication shema learnt in the elementary schools and one really could to repeated additions as on my commented "Peano" example. But my intuition says multiply2 method is faster until we really want to go to the Fast Fourier transform algorithms.


texts: Highest floor of a building from which to drop an egg without breaking it

texts:
Problem description:

You have two eggs, and need to find the maximum floor of a 100-floor building from which you can drop the eggs without them breaking. Do this with as few attempts as possible.
NB! You are passed the level of where it breaks, n, and an egg is considered broken when your compares and finds test floor is larger than n. You can try to drop the egg as many times as you want (compare test floor and n), but you can only be above twice. Returning n-1 is cheating, consider n to be unknown!

I created a function which takes an argument of the floor, and then calculates the answer (since creating the physics engine to actually simulate the gravity and all that was out of scope).
I'd like to be reviewed on style, accuracy, efficiency, bugs/edge cases, and take into account I did this in a couple minutes while running through interview sample questions that I found on Glassdoor.
def egg_drop(n):
    ''' Find the highest floor in a building that an egg can drop from without breaking '''
    t = [1,11]
    while t[0] < 100:
        if t[1] >= n:
            print 'break_an_egg on floor %d' % t[1]
            for i in range(t[0],t[1]):
                if i >= n:
                    print  'break_an_egg on floor %d' % i
                    return i - 1
        else:
            t[0] += 10
            t[1] += 10
    return 100


texts: Multithread the variant of matrix multiplication

texts:
This is matrix multiplication. Big matrix split on the submatrix and multiplication in parallel, result matrices merge to result. How i can make this code better?

public class MatrixMultiplication implements Callable<int[][]> {
private static int LENGTH_OF_SIDE = 1000;
private int taskCount = 4;
private int[][] matrixA;
private int[][] matrixB;

public MatrixMultiplication(int[][] matrixA, int[][] matrixB) {
    this.matrixA = matrixA;
    this.matrixB = matrixB;
}

public void setTaskCount(int taskCount) {
    this.taskCount = taskCount;
}

@Override
public int[][] call() {
    int n = matrixA.length;
    int m = matrixA[0].length;
    int p = matrixB[0].length;
    try {
        if (n >= LENGTH_OF_SIDE || m >= LENGTH_OF_SIDE || p >= LENGTH_OF_SIDE) {
            return splitAndMerge(matrixA, matrixB);
        } else {
            return MultiplicationMatrixSingleThread.multiplicationMatrices(matrixA, matrixB);
        }
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
        return null;
    }
}

public int[][] splitAndMerge(int[][] matrixA, int[][] matrixB) throws ExecutionException,
        InterruptedException {
    ExecutorService service = Executors.newCachedThreadPool();
    int n = matrixA.length;
    int m = matrixA[0].length;
    int k = matrixB[0].length;
    int bound = n / taskCount;
    int start;
    int end;
    Future<int[][]> future;
    List<Future<int[][]>> matrices = new ArrayList<>();
    for (int task = 0; task < taskCount; task++) {
        start = task * bound;
        end = (task + 1) * bound;
        future = service.submit(new MultiplicationSubMatrixN(matrixA, matrixB, start, end));
        matrices.add(future);
    }
    int[][] result = new int[n][k];
    int[][] currentMatrix;
    for (int st = 0; st < taskCount; st++) {
        currentMatrix = matrices.get(st).get();
        System.arraycopy(currentMatrix, 0, result, st * bound, currentMatrix.length);
    }
    if (n % taskCount != 0) {
        int begin = n - n % taskCount;
        currentMatrix = new int[n % taskCount][m];
        for (int i = 0; i < currentMatrix.length; i++) {
            System.arraycopy(matrixA[i + begin], 0, currentMatrix[i], 0, currentMatrix[0].length);
        }
        currentMatrix = MultiplicationMatrixSingleThread.multiplicationMatrices(currentMatrix, matrixB);
        System.arraycopy(currentMatrix, 0, result, begin, currentMatrix.length);
    }
    service.shutdown();
    return result;
}

private class MultiplicationSubMatrixN implements Callable<int[][]> {
    private int[][] matrixA;
    private int[][] matrixB;
    private int start;
    private int end;

    private MultiplicationSubMatrixN(int[][] matrixA, int[][] matrixB, int start, int end) {
        this.matrixA = matrixA;
        this.matrixB = matrixB;
        this.start = start;
        this.end = end;
    }

    @Override
    public int[][] call() throws Exception {
        int n = matrixA.length;
        int m = matrixA[0].length;
        int k = matrixB[0].length;
        int[][] matrixC = new int[n / taskCount][k];
        for (int i = start; i < end; i++) {
            for (int j = 0; j < k; j++) {
                for (int l = 0; l < m; l++) {
                    matrixC[i - start][j] += matrixA[i][l] * matrixB[l][j];
                }
            }
        }
        return matrixC;
    }
}
}


texts: Need help with valid knight moves in Chess

texts:
Last weekend I was writing a short PHP function that accepts a starting move and returns valid knight squares for that move.

<?php

/* get's starting move and returns valid knight moves */

echo GetValidKnightSquares('e4');

function GetValidKnightSquares($strStartingMove) {

  $cb_rows = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8);
  $valids  = array(array(-1, -2), array(-2, -1), array(-2, 1), array(-1, 2), array(1, 2), array(2, 1), array(2, -1), array(1, -2));

  $row = substr($strStartingMove, 0, 1);
  $col = substr($strStartingMove, 1, 1);

  $current_row = $cb_rows[$row];
  if(!in_array($current_row, $cb_rows)) {
    die("Hey, use chars from a to h only!");
  }

  $current_col = $col;
  if($current_col > 8) {
    die("Hey, use numbers from 1 to 8 only!");
  }

  $valid_moves = '';

  foreach ($valids as $valid) {
    $new_valid_row = $current_row + $valid[0];
    $new_valid_col = $current_col + $valid[1];

    if(($new_valid_row <= 8 && $new_valid_row > 0) && ($new_valid_col <= 8 && $new_valid_col > 0)) {
      $row_char = array_search($new_valid_row, $cb_rows);
      $valid_moves .= $row_char . "$new_valid_col ";
    }
  }

  return "Valid knight moves for knight on $strStartingMove are: $valid_moves";
}

?>

Could you please take a look at it and share your thoughts about it?  The code can also be found here.

I was kinda 'criticized' about the code. One guy said it's messy, too long and not 'clever' enough. So I needed second opinion on it, a code review if you like. I think there is a place for improvement (always), but for me this was the first time I've coded something related with Chess. I've found something like this that caught my attention:

if ((abs(newX-currentX)==1 and abs(newY-currentY)==2) or (abs(newX-currentX)==2 and abs(newY-currentY)==1)) {
  /* VALID MOVE FOR A KNIGHT */
}
else {
  /* INVALID MOVE FOR A KNIGHT */
}


texts:
I have the following query.  Its execution took 15 min and it's too much slow.  Is there a way to optimize it?

SELECT
 Id,Fees,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Fees                      ' AS FeesName
  ,@MonthName AS [MonthName]
  INTO ##TempFeesMonthly
  from
  (
SELECT DISTINCT
1 as Id,sum(((CNTI_THPAYE *(CNTI_THFACT / CNTI_THPAYE)) *
(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*@NumberOfDays)) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
      LEFT JOIN
    SCHHAYS.dbo.WTTIEINT INT
        ON (
            TAT.TIE_ID = INT.TIE_ID
        )
        AND (
            TAT.VTAT_IORDRE = INT.TIEI_ORDRE
        )
    LEFT JOIN
    SCHHAYS.dbo.PYCONTRAT CC
        ON TAT.PER_ID = CC.PER_ID
        AND TAT.CNT_ID = CC.CNT_ID
    LEFT JOIN
    SCHHAYS.dbo.CMTIERS T
        ON TAT.TIE_ID = T.TIE_ID
    LEFT JOIN
    SCHHAYS.dbo.WTMISS M
        ON CC.PER_ID = M.PER_ID
        AND CC.CNT_ID = M.CNT_ID
    LEFT JOIN
    ##WTCNTIWeek COT1
        ON M.PER_ID = COT1.PER_ID
        AND M.CNT_ID = COT1.CNT_ID
    INNER JOIN
    SCHHAYS.dbo.WTPRH AS PRH
        ON M.PER_ID = PRH.PER_ID
        AND M.CNT_ID = PRH.CNT_ID
        AND M.TIE_ID = PRH.TIE_ID
    INNER JOIN
    ##tempStartEndWeekDates AS Tsed
        ON     PRH_DTEDEBSEM>=Tsed.StartDate
        AND PRH_DTEFINSEM<=Tsed.EndDate
    LEFT JOIN
    SCHHAYS.dbo.WTSCCT C
        ON CC.RGPCNT_ID = C.RGPCNT_ID
        AND CC.PER_ID = C.PER_ID
        AND CC.CNT_ID = C.CNT_ID
    INNER JOIN
    ##TempHaysStaffWeek HF
        ON C.VAPO_CODE = HF.onetouch  COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate)t

--CREATE INDEX IDX_TempFeesMonthly ON ##TempFeesMonthly(WeekOfMonth)
--Calcul Temp Margin
UNION ALL
--INSERT INTO ##TempFeesMonthly(Id,Fees,WeekOfMonth,StartDate,EndDate,FeesName,[MonthName])
SELECT
 2,  sum(Fees) AS Fees  ,WeekOfMonth,CONVERT(NVARCHAR(MAX), StartDate, 103) AS StartDate,CONVERT(NVARCHAR(MAX), EndDate, 103) AS EndDate,'Temp Margin ' AS FeesName
  ,@MonthName AS [MonthName]
  from
  (
 SELECT DISTINCT
sum((CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*@NumberOfDays)-(CNTI_THPAYE *(CASE WHEN CNTI_DURHEBDO IS NULL THEN 1 ELSE CNTI_DURHEBDO/5 END)*1.453*1.21*@NumberOfDays) AS Fees,WeekOfMonth,StartDate,EndDate
FROM SCHHAYS.dbo.WTVTAT TAT
      LEFT JOIN
    SCHHAYS.dbo.WTTIEINT INT
        ON (
            TAT.TIE_ID = INT.TIE_ID
        )
        AND (
            TAT.VTAT_IORDRE = INT.TIEI_ORDRE
        )
    LEFT JOIN
    SCHHAYS.dbo.PYCONTRAT CC
        ON TAT.PER_ID = CC.PER_ID
        AND TAT.CNT_ID = CC.CNT_ID
    LEFT JOIN
    SCHHAYS.dbo.CMTIERS T
        ON TAT.TIE_ID = T.TIE_ID
    LEFT JOIN
    SCHHAYS.dbo.WTMISS M
        ON CC.PER_ID = M.PER_ID
        AND CC.CNT_ID = M.CNT_ID
    LEFT JOIN
    ##WTCNTIWeek COT1
        ON M.PER_ID = COT1.PER_ID
        AND M.CNT_ID = COT1.CNT_ID
    INNER JOIN
    SCHHAYS.dbo.WTPRH AS PRH
        ON M.PER_ID = PRH.PER_ID
        AND M.CNT_ID = PRH.CNT_ID
        AND M.TIE_ID = PRH.TIE_ID
    INNER JOIN
    ##tempStartEndWeekDates AS Tsed
        ON     PRH_DTEDEBSEM>=Tsed.StartDate
        AND PRH_DTEFINSEM<=Tsed.EndDate
    LEFT JOIN
    SCHHAYS.dbo.WTSCCT C
        ON CC.RGPCNT_ID = C.RGPCNT_ID
        AND CC.PER_ID = C.PER_ID
        AND CC.CNT_ID = C.CNT_ID
    INNER JOIN
    ##TempHaysStaffWeek HF
        ON C.VAPO_CODE = HF.onetouch  COLLATE Latin1_General_CI_AS
group by
WeekOfMonth,StartDate,EndDate,CNTI_THPAYE,CNTI_DURHEBDO)t
GROUP BY WeekOfMonth,StartDate,EndDate


texts: Computing the probability of rolling a given total with five dice

texts:
I'm trying to compute the probability of rolling a certain dice total with an unknown number of dice.  Below is a brute force example for 5 dice, hence the 5 loops.  I feel like there is a recursive answer here that I can't put my finger on that would work for different numbers of dice.

function computeDiceOdds(dice, desired_result, sides = 6) {
    var successes = 0;
    for (let a = 1; a <= sides; a++ ) {
        for (let b = 1; b <= sides; b++) {
            for (let c = 1; c <= sides; c++) {
                for (let d = 1; d <= sides; d++) {
                    for (let e = 1; e <= sides; e++) {
                        if ((a + b + c + d + e) == desired_result) {
                            successes++;
                        }
                    }
                }
            }
        }
    }
    return successes.toString() + " / " + Math.pow(sides, dice).toString();
}

console.log(computeDiceOdds(5, 21)); // "540 / 7776"


texts: Using a cronjob on node for storing a json file, parsing it and update a database

texts:
I need to retrieve a file from a website every minute that contains boats location.

Then, I parse the file, delete all the boats from my database and re-create all of them at the new position indicated in the file.

Here's my code so far - in the server.js of my loopbackjs app:

var CronJob = require('cron').CronJob;
var exec = require("child_process").exec;
var reload = require('require-reload')(require);
var app = module.exports = loopback();

// Bootstrap the application, configure models, datasources and middleware.(loopbackjs mandatory code)
boot(app, __dirname, function (err) {
    if (err)
        throw err;

    var Boat = app.models.Boat;
    var ais_url_france = 'http://data.aishub.net/ws.php?username=XXXXXXXXX&format=1&output=json&compress=0&latmin=40&latmax=52&lonmin=-5&lonmax=10';

    //start the cronjob on a node env every min
    new CronJob('* * * * *', function () {
                // get the file and save as a .json
                exec('wget "' + ais_url_france + '" -O aishub_france.json', function (error, stdout, stderr) {
                    // I need to use reload here because the file is stored in memory otherwise and only read once after the first download...
                    var file = reload('../aishub_france.json');
                    if (file[0].ERROR === false) {
                        var boats = file[1];
                        if (boats.length > 0) {
                            Boat.destroyAll({typeId: 'aishub_boats'}, function (err, info) {
                                for (var i = 0; i < boats.length; i++) {
                                    Boat.create({
                                        name: boats[i].NAME,
                                        latlng: {
                                            lat: boats[i].LATITUDE,
                                            lng: boats[i].LONGITUDE
                                        },
                                        typeId: 'aishub_boats'
                                    });
                                }
                            });
                        }
                    }
                });
            }, null, true, null);
});

I'm not sure the code here is so great but here are my troubles:

The downloaded file is huge (1,3Mo)
I need to remove and re-add all the boats because they change location and some might appear/disappear (maybe there is a better solution)
Not sure using require-reload is the best solution, but if I don't the file is read only once in the cronjob even if the donwloaded file changed each time...
I think I might have some memory leak because I'm having strange stacks trace recently after I added this code. Here is the trace:

33503717 ms: Mark-sweep 1288.0 (1403.6) -> 1288.0 (1404.6) MB, 672.5 / 0.0 ms [allocation failure] [GC in old space requested].

33504750 ms: Mark-sweep 1288.0 (1404.6) -> 1288.0 (1404.6) MB, 847.3 / 0.0 ms [allocation failure] [GC in old space requested].

33505597 ms: Mark-sweep 1288.0 (1404.6) -> 1288.0 (1403.6) MB, 846.4 / 0.0 ms [last resort gc].

33506438 ms: Mark-sweep 1288.0 (1403.6) -> 1288.0 (1403.6) MB, 841.4 / 0.0 ms [last resort gc].


texts:
I made a fairly simple template engine (if I could call it that). Basically my server returns something like

string "This text should be [color:red;font-weight:bold; red and bold]"

Then on the client side I have my parser, for HTML in this case

function parse(str){
    return str.replace(/\[(.+?) (.+?)\]/g,'$2');
}

I was wondering, however, do HTML tags make a difference? If I were to use font instead of span, would I win/lose anything?

P.S.: I am aware that this regex may pick up something that wasn't meant to be parsed, but my application doesn't use these braces in texts it returns, so it is alright.


texts:
I wrote a bot for a Programming Puzzles & Code Gold King of the Hill type of challenge called "Spacewar!". The challenge was written by @El'endiaStarman. The bot is called "Spy".

The controller is hosted here, so take a look for the feel. The API is a bit long, so here's a link.

The bot's logic:

  It runs away from the other bot with a 70% chance of firing a missile and hyperspaces when it's close to the sun.

It's not online yet at a seperate bot; so you can copy-paste the code here into the KotH controller's text area at the bottom to test it out.

I sorta just monkey-patched this bot together without an IDE, so the code isn't that great. Seriously, there's even an extra function I didn't use.

The code

function Spy_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function Spy_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn right");
        } else {
            actions.push("turn left");
        };
        actions.push("fire engine");
        if (Math.random() > 0.3) {
            actions.push("fire missile")
        }
    }
}


texts: Configuration for Embedded Broker ActiveMQ

texts:
This is my configuration for sending messages to an embedded broker. Also, the first bean method is used to just create and start the broker. It doesn't return any instance.

Please a take a look at the 3 methods and tell me if there is an issue. Don't worry about inner details such as pub/sub domain. I am mostly worried about broker service and whether I am starting it right, so that the broker can be used to publish messages into.

@Configuration
@EnableJms
public class JMSConfig {

    public static final String DEFAULT_BROKER_URL = "tcp://localhost:61616";
    public static final String COMMENT_QUEUE = "comment-queue";

    @Bean
    public void createBrokerService() throws Exception {
        BrokerService broker = new BrokerService();
        TransportConnector connector = new TransportConnector();
        connector.setUri(new URI("tcp://localhost:61616"));
        broker.addConnector(connector);
        broker.start();
    }

    @Bean
    public ActiveMQConnectionFactory connectionFactory(){
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
        connectionFactory.setBrokerURL(DEFAULT_BROKER_URL);
        return connectionFactory;
    }

    @Bean
    public JmsTemplate jmsTemplate(){
        JmsTemplate template = new JmsTemplate();
        template.setConnectionFactory(connectionFactory());
        template.setDefaultDestinationName(COMMENT_QUEUE);
        template.setPubSubDomain(true);
        template.setSessionTransacted(true);
        return template;
    }


texts: Excel VBA code that displays a 14 day weather forecast

texts:
I am trying to see if anyone can help me in making this Excel VBA code a little faster in rendering the data from the weather site I am using.  Maybe instead of getting all 14 days it includes in the site, could I get help in getting just 10 days? Any help is much appreciated. Thanks!
Sub MiamiWeather()

   Dim HTTP As Object, HTML As Object, i As Integer, j As Integer

    Set HTML = CreateObject("HTMLFILE")
    Set HTTP = CreateObject("MSXML2.XMLHTTP")

    myURL = "https://weather.com/weather/tenday/l/3881cd527264bc7c99b6b541473c0085e75aa026b6bd99658c56ad9bb55bd96e"

    HTTP.Open "GET", myURL, False
    HTTP.send

    HTML.body.innerHTML = HTTP.responseText

    Set objCollection = HTML.getElementsByTagName("p")
    i = 0

    Do While i < objCollection.Length And j < 20
        If objCollection(i).getAttribute("data-testid") = "wxPhrase" Then
            j = j + 1
            Range("A" & j) = objCollection(i).PreviousSibling.PreviousSibling.FirstChild.innerText
            Range("B" & j) = objCollection(i).PreviousSibling.FirstChild.innerText

        End If
        i = i + 1
    Loop

    Set HTML = Nothing
    Set HTTP = Nothing
End Sub


texts: Batch file-download script - is it necessary to re-phrase commands?

texts:
I run a script to download a file and unzip it. An import process then runs and leaves the files in their source location. I wrote the fully functioning code below to clean up that directory to be ready to use the next night.

I streamlined as much as I believe possible. I realize ~15 lines of code isn't exactly verbose or complicated and I've included the full script for reference. I feel, however, that specifically the second block - line SET DATE= through line DIR - can be better written but I don't know in what way. Am I simply seeing messy code where none exists?  It just doesn't seem to 'read' well.

A note - the index.txt file is the same despite having two paths and is located in one or the other depending on the outcome (errors or not) of the import.

SET PATH="\\server\path\path2"
IF NOT EXIST %PATH%\Upload.zip GOTO Done

SET DATE=%date:~4,2%-%date:~7,2%-%date:~10,4%
MKDIR %PATH%\Archives\%date%
SET ARCHIVE=%PATH%\Archives\%date%\
DIR %PATH% /B > %ARCHIVE%log-%date%.txt

MOVE %PATH%\Upload.zip %ARCHIVE%Upload-%date%.zip
MOVE %PATH%\index.txt %ARCHIVE%index-%date%.txt ||(
MOVE %PATH%\error_files\index.txt %ARCHIVE%index-%date%.txt
)
DEL %PATH%\*.tif
RMDIR %PATH%\error_files

PUSHD %PATH%\Archives &&(
FORFILES /S /D -15 /C "CMD /C IF @isdir == TRUE RD /S /Q @path"
) & POPD

:Done


texts:
I wrote this script for a proof of concept JavaScript password cracker:

var charset = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
function crack(value){
    function toRadix(N,radix) {
        var HexN = "",
            Q = Math.floor(Math.abs(N)),
            R,
            strv = charset,
            radix = strv.length;
        while (true) {
            R = Q % radix;
            HexN = strv.charAt(R) + HexN;
            Q = (Q - R) / radix;
            if (Q == 0)
                break;
        };
        return ((N < 0) ? "-" + HexN : HexN);
    };
    var start = (new Date()) * 1,
        cracked = false,
        index = 0;
    while(!cracked){
        if(toRadix(index) == value)
            cracked = true;
        else
            index++;
    };
    alert(((new Date()) * 1) - start);
};

This script works fine, but it is slow.

What would be the best way to speed up this algorithm?


texts:
I am working on a code to see if a video already exists. The problem is that I have to check multiple sections. The code is working but it should not be this big, I think, and it takes a long time to load.

Is there an easier way to do this?

$xmlurl7b = 'http://mysite.me/library/sections/2/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl1b = 'http://mysite.me/library/sections/5/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl2b = 'http://mysite.me/library/sections/7/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl3b = 'http://mysite.me/library/sections/9/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl4b = 'http://mysite.me/library/sections/10/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl5b = 'http://mysite.me/library/sections/11/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl6b = 'http://mysite.me/library/sections/13/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl8 = 'http://mysite.me/library/sections/3/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl9 = 'http://mysite.me/library/sections/8/all?title=' . $movie->title() . '&HndJk7Sd';
$xmlurl7 = 'http://mysite.me/library/sections/2/all?guid=movieid' . $movieid . '%3Flang%3Dnl&HndJk7Sd';
$xmlurl1 = 'http://mysite.me/library/sections/5/all?guid=movieid' . $movieid . '%3Flang%3Dnl&HndJk7Sd';
$xmlurl2 = 'http://mysite.me/library/sections/7/all?guid=movieid' . $movieid . '%3Flang%3Dnl&HndJk7Sd';
$xmlurl3 = 'http://mysite.me/library/sections/9/all?guid=movieid' . $movieid . '%3Flang%3Dnl&HndJk7Sd';
$xmlurl4 = 'http://mysite.me/library/sections/10/all?guid=movieid' . $movieid . '%3Flang%3Dnl&HndJk7Sd';
$xmlurl5 = 'http://mysite.me/library/sections/11/all?guid=movieid' . $movieid . '%3Flang%3Dnl&HndJk7Sd';
$xmlurl6 = 'http://mysite.me/library/sections/13/all?guid=movieid' . $movieid . '%3Flang%3Dnl&HndJk7Sd';
$achxml8 = simplexml_load_file($xmlurl8);
$achxml9 = simplexml_load_file($xmlurl9);
$achxml1 = simplexml_load_file($xmlurl1);
$achxml2 = simplexml_load_file($xmlurl2);
$achxml3 = simplexml_load_file($xmlurl3);
$achxml4 = simplexml_load_file($xmlurl4);
$achxml5 = simplexml_load_file($xmlurl5);
$achxml6 = simplexml_load_file($xmlurl6);
$achxml7 = simplexml_load_file($xmlurl7);
$achxml1b = simplexml_load_file($xmlurl1b);
$achxml2b = simplexml_load_file($xmlurl2b);
$achxml3b = simplexml_load_file($xmlurl3b);
$achxml4b = simplexml_load_file($xmlurl4b);
$achxml5b = simplexml_load_file($xmlurl5b);
$achxml6b = simplexml_load_file($xmlurl6b);
$achxml7b = simplexml_load_file($xmlurl7b);
if( $achxml1->Video && ($achxml1->Video != '')
OR $achxml2->Video && ($achxml2->Video != '')
OR $achxml3->Video && ($achxml3->Video != '')
OR $achxml4->Video && ($achxml4->Video != '')
OR $achxml5->Video && ($achxml5->Video != '')
OR $achxml6->Video && ($achxml6->Video != '')
OR $achxml7->Video && ($achxml7->Video != '')
OR $achxml8->Directory && ($achxml8->Directory != '')
OR $achxml9->Directory && ($achxml9->Directory != '')
OR $achxml1b->Video && ($achxml1b->Video != '')
OR $achxml2b->Video && ($achxml2b->Video != '')
OR $achxml3b->Video && ($achxml3b->Video != '')
OR $achxml4b->Video && ($achxml4b->Video != '')
OR $achxml5b->Video && ($achxml5b->Video != '')
OR $achxml6b->Video && ($achxml6b->Video != '')
OR $achxml7b->Video && ($achxml7b->Video != '')
 ) {
echo 'Exists';
} else {
echo 'New';
}


texts: Oneliner to extract External IP from IFCONFIG.CO

texts:
I wrote a small function in powershell that works fine, however I feel its extremely hacky and I'm sure there must be a smarter way to do this. In the interests of learning, what can I do to improve on this?

function WhatsMyIP
{
return ((Invoke-RestMethod -Uri http://ifconfig.co).split("`n") | where {$_ -match "`"ip`""}).split("<").split(">")[4]
}

I tried this with Invoke-WebRequest but the returned data is the same, except you need to expand the .content property to get at it, making this slightly more clunky than before.

I'd like to do this natively, I realise I can just invoke CURL or what ever but the point is that I am very likely to be on systems where CURL isn't available when I need this.


texts: Non-recursive method for finding \$a^n\$

texts:
I am working on an interview question from Amazon Software. The particular question I am working on is "to write a program to find \$a^n\$."

Here is my recursive solution to this problem (in Java):

int pow(int a, int n) {
     if(n == 0) {
          return 1;
     } else {
          return a * pow(a, n -1 );
     }
}

I did some runtime analysis and found that this solution runs in \$O(n)\$ time - recurrence relation with \$T(n) = 3 + T(n-1)\$, \$T(0)=1\$, and \$O(n)\$ space - depth of memory stack is \$n\$, with two local variables at each call, \$2n\$ total.

We are always taught to optimize our code in terms of space complexity and time complexity, so here is another solution that I came up with:

int pow(int a, int n) {
     int result = 1;
     for(int count=0;count<n;count++) {
           result *= a;
     }
     return result;
}

Would this solution be more efficient than the first one? This one runs in \$O(n)\$ time-loop until \$n\$ and \$O(1)\$ space - four units of space - one for a, n, result, and count.


texts:
The below code is working uses formula to concatenate the result from Range("K:M") and write the result in column H.

Is there a better way to write the below code that can concatenate the result to the exact location as per below table? Please note that data in the before table is discontinued but sometimes will be from row 4 to 1000 rows down or the below example.

Sub GenerateStyleFabricColourV4()
    Dim srcData As Range
    Dim rowNum As Long, lastRow As Long

    With Worksheets(2)
        lastRow = Application.Max(4, _
                    .Cells(.Rows.Count, "K").End(xlUp).Row, _
                    .Cells(.Rows.Count, "L").End(xlUp).Row, _
                    .Cells(.Rows.Count, "M").End(xlUp).Row)
        With .Cells(4, "H").Resize(lastRow - 4 + 1, 1)
            .FormulaR1C1 = "=rc[3]&rc[4]&rc[5]"
            .Value = .Value2
        End With
    End With
End Sub

Sub ClearAllData()

Rows("4:" & Rows.Count).ClearContents

End Sub


texts: Removing duplicate characters from a string

texts:
I implemented a function removeDuplicates which takes 1 parameter, a std::string, and returns a std::string without the duplicate characters.

Example I/O might look like this:

removeDuplicates("hello"); //--> "helo"
removeDuplicates("this is easy"); //--> "this eay"

Here is the function:

std::string removeDuplicates(const std::string& str)
{
    //Map for storing character count
    std::map<char, unsigned int> ctable{};

    //Count characters
    std::for_each(str.begin(), str.end(), [&ctable](const auto& value) {
        ++ctable[value];
    });

    std::string newstring = "";
    newstring.resize(str.size());

    //Only copy one character of each type to the new string
    std::copy_if(str.begin(), str.end(), newstring.begin(), [&ctable](const auto& value) {
        return ctable.erase(value) > 0;
    });

    //newstring is bigger than necessary if it has duplicates
    newstring.shrink_to_fit();

    return newstring;
}

Is there a more efficient way to do it?

And what can be improved about the actual code of the function (like variable names/comments, ...).


texts:
I'm looking for feedback on the following code which checks if a number is prime using Swift 2.

 import UIKit

 var number:Int = 1123

 var isPrime:Bool = true

 switch number {

 case 1:
     isPrime = false

 case 2:
     isPrime = true

 case 3:
     isPrime = true

 default:
     primeCheck:for i in 2...Int(sqrt(Double(number))) {

         if number % i == 0 {

             isPrime = false
             break primeCheck

         }
   }

}

if isPrime {

    print("The number \(number) is prime!")

} else {

    print("The number \(number) is composite!")
}


texts:
I face a problem I think I am not approaching appropiately.

I have two independent enumerators that both will contain the same members, the only difference being the values given.

I have to be able to parse from one enum type to the other on the fly and I've seen the following code works as intended:

(enumType)Enum.Parse(typeof(enumType), enum1.ToString());

But I feel like there's something I am doing wrong, I believe this code is prone to errors and I feel like I need some help approaching this problem.

The code involved is the following:

public enum AdjustCircuitsCurrent
{
    _2V = 0x0001,
    _1_28V = 0x0002,
    _333mV = 0x0003,
    _0_25A = 0x0004,
    _0_01V = 0x0005,
    _0_1V = 0x006,
    _1V = 0x0007,
}

public enum VerificacionCircuitsCurrent
{
    _2V = 0x000B,
    _1_28V = 0x000C,
    _333mV = 0x000D,
    _0_25A = 0x000E,
    _0_1V = 0x00F,
    _0_01V = 0x0011,
    _1V = 0x0012,
}

public VerificacionCircuitsCurrent ConvertToVerificationCircuit(AdjustCircuitsCurrent circuit)
{
    return (VerificacionCircuitsCurrent)Enum.Parse(typeof(VerificacionCircuitsCurrent), circuit.ToString());
}

Again, this code works as intended, I can convert from one enum to the other, but I feel there's something wrong with it.


texts: Using RouteValueDictionary to convert anonymous type to query string

texts:
I am trying to take advantage of the reflection built into RouteValueDictionary to add values to the query string of a URL. This is what I came up with. It seems to work, but I thought I would post it to see if anyone has any suggestions. It also uses the super-secret HttpValueCollection returned by ParseQueryString(), which automatically generates a URL-encoded query string.

So far the only negative is that it only works on URLs that can be parsed by UriBuilder (i.e. absolute URLs). So, relative URLs (i.e. "/Home/Index") will throw an exception. Maybe I should try the UriBuilder, and if that fails then try to extract/append the query string manually.

public static string AppendQueryValues(this string absoluteUrl, object queryValues)
{
    if (absoluteUrl == null)
        throw new ArgumentNullException("absoluteUrl");
    if (queryValues == null)
        throw new ArgumentNullException("queryValues");

    // Parse URL so we can modify the query string
    var uriBuilder = new UriBuilder(absoluteUrl);

    // Parse query string into an HttpValueCollection
    var queryItems = HttpUtility.ParseQueryString(uriBuilder.Query);

    // Parse & filter queryValues (using reflection) into key/value pairs
    var newQueryItems = new RouteValueDictionary(queryValues)
        .Where(x => !queryItems.AllKeys.Contains(x.Key));

    // Add new items to original collection
    foreach (var newQueryItem in newQueryItems)
    {
        queryItems.Add(newQueryItem.Key, newQueryItem.Value.ToString());
    }

    // Save new query string (HttpValueCollection automatically URL encodes)
    uriBuilder.Query = queryItems.ToString();

    return uriBuilder.Uri.AbsoluteUri;
}


texts:
I'm using the rolling curl library to fire HTTP requests for content-length headers of images (we need to know their size to weed out placeholders and low res images). The image URLs are stored in a database so I need to loop over the data in our products table (approx 1 million rows but will grow bigger, potentially much bigger).

I'm using PHP and the Laravel framework (the artisan CLI component). The operation seems to slow down as time progresses e.g. it starts processing 100 requests in less than a second and later the time to process 100 rows/requests is logged at over 20 seconds. Can anyone explain this and / or offer any performance improvement suggestions? The task is running on an Amazon EC2 micro instance so processing power / memory is limited.

public function fire()
{
    $dt = new DateTime();
    Log::info("started: ".$dt->format('Y-m-d H:i:s'));
    $counter = 1;
    Item2::where('img_size', '=', NULL)->chunk(1000, function($items) use ( &$counter)
    {
        $results = array();
        $filePath = storage_path().'/imports/new/new_img_sizes_'.$counter.'.csv';

        if (!File::exists($filePath)) {
            File::put($filePath, '');
        }
        $start = microtime(true);
        $rollingCurl = new \RollingCurl\RollingCurl();
        $rollingCurl->setOptions($this->curlOptions);

        foreach ($items as $item)
        {
            if ($item->img !== '') {

                $results[$item->id] = array('url' => $item->img, 'size' => null);
                $rollingCurl->get($item->img);
            }

        }
        //callback runs on each curl request
        $rollingCurl->setCallback(function(\RollingCurl\Request $request, \RollingCurl\RollingCurl $rollingCurl) use (&$results, $filePath) {
            $responseInfo = $request->getResponseInfo();
            //var_dump($responseInfo);exit;
            $length = $responseInfo['download_content_length'];

            foreach ($results as $key => $value) {
                if (array_search($request->getURL(),$value)) {
                    $idKey = $key;
                    $results[$idKey]['size'] = $length;
                    File::append($filePath,$idKey.','.$results[$idKey]['size']."\r\n");
                    break;
                }
            }

        })

            ->setSimultaneousLimit(10)
            ->execute();

        $counter++;
        echo 'done in...'.(microtime(true) - $start).PHP_EOL;
        Log::info('1000 records: '.(microtime(true) - $start));
        Log::info('Last url was: '.json_encode(end($results)));
        exit;
    }); // end item chunk

Some benchmarks:

done in...3.8803641796112
done in...7.4326379299164
done in...8.1860301494598
done in...8.5088090896606
done in...10.606615781784
done in...10.655412912369
done in...10.804574966431
done in...14.004528045654
done in...10.903785943985
done in...11.905344009399
done in...13.763195991516
done in...14.723680019379
done in...15.823812961578
done in...17.972007989883
done in...31.734715938568
done in...20.509822845459
done in...22.924754858017
done in...34.274693012238
done in...39.217702865601
done in...29.883662939072
done in...24.094554901123
done in...25.726534128189
done in...31.788655996323
done in...24.713880062103
done in...25.855134963989
done in...23.161122083664
done in...32.380167007446
done in...36.53077507019
done in...31.859884023666
done in...71.458341121674


texts: Picking the desired one between two links

texts:
I've written a script in python to scrape the link within contact us or about us from few webpages. The challenge here is to prioritize contact us over about us. For example, if any site contains both of them then my scraper should pick the link within contact us. However, if contact us is not present then only the scraper go for parsing the link within about us. My first attempt used the logic if "contact" in item.text.lower() or "about" in item.text.lower() but I could notice that in every cases while dealing with the below links the scraper picks the link within about us whereas my first priority is to get the link within contact us. I next rewrote it with the following approach (using two for loops to get the job done) and found it working.

This is what I've tried to get the links complying with the above criteria:

import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

links = (
    "http://www.innovaprint.com.sg/",
    "https://www.richardsonproperties.com/",
    "http://www.innovaprint.com.sg/",
    "http://www.cityscape.com.sg/"
    )

def Get_Link(site):
    res = requests.get(site)
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.select("a[href]"):
        if "contact" in item.text.lower():
            abslink = urljoin(site,item['href'])
            print(abslink)
            return

    for item in soup.select("a[href]"):
        if "about" in item.text.lower():
            abslink = urljoin(site,item['href'])
            print(abslink)
            return

if __name__ == '__main__':
    for link in links:
        Get_Link(link)

The two for loops defined within the above function look awkward so I suppose there is any better idea to do the same. Thanks in advance for any betterment of this existing code.


texts: Python program for fibonacci sequence using a recursive function

texts:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.....

The first two terms are 0 and 1. All the other terms are obtained by adding the preceding two terms.

Here is my code:

def recur_fibonacci(n):
   if n <= 1:
       return n
   else:
       return(recur_fibonacci(n - 1) + recur_fibonacci(n - 2))

nterms = int(input("How many terms? "))

if nterms <= 0:
   print("Please enter a positive integer!")
else:
   print("Fibonacci sequence:")
   for i in range(nterms):
       print(recur_fibonacci(i))

So I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts:
The function below converts a time code into seconds, while maintaining the decimal value (fractions of seconds). The time code fed to this function will always contain microseconds. This currently works, but I'd be interested to see how it could be improved/simplified.

def Second_Conversion(x): #Takes a string such as "2:22:04.996304"
    HMS = x.split(':')
    SF = x.split('.')
    Full_HMS = x[0:7]
    Split_HMS = Full_HMS.split(':')

    Full_Units = int(Split_HMS[0]) * 3600 + int(Split_HMS[1]) * 60 + int(Split_HMS[2])

    Second_Fractions = int(SF[1])
    Converted_Seconds_Fractions = Second_Fractions /1000000
    print(Converted_Seconds_Fractions)

    Final_Time = Full_Units + Converted_Seconds_Fractions
    print(Final_Time)


texts:
I have written the following get/set for a username which is stored in local Storage.  Do you think this "buys" me anything or even perhaps has major disadvantages?  I have never liked relying on global variables so I figured the getter and setter would be tidier and more maintainable.

var namespace = {};

namespace.username = {
        key: "Username",
        get: function() { return localStorage.getItem(this.key)},
        set: function(value) {localStorage.setItem(this.key, value)}
    };

before the code had "constants" (I know they arent real in JS)

LOCAL_STORAGE = {
    USERNAME: "Username"
}

and everywhere I need access to the username I would write:

localStorage.getItem(LOCAL_STORAGE.USERNAME);


texts:
I'm new to programming, and I would like to know if this is the right way to layout code. If anyone has any tips, please share them.

import random
import time

def displayIntro():
    print("You are in a land full of dragons. In front of")
    print("you are two caves. In one cave the dragon is")
    print("friendly and will give you his treasure. In the")
    print("other, the dragon is greedy and hungry and will")
    print("eat you on sight")
    print()

def chooseCave():
    cave = ""
    while cave != "1" and cave != "2":
        print("Which cave will you choose? (1 or 2)")
        cave = input()
   return cave

def checkCave(chosenCave):
    print("You approach the cave...")
    time.sleep(2)
    print("It is dark and spooky...")
    time.sleep(2)
    print("A large dragon jumps out in front of you. He opens his jaws and...")
    print()
    time.sleep(2)

    friendlyCave = random.randint(1,2)

    if chosenCave == str(friendlyCave):
        print("gives you his treasure")
    else:
        print("gobbles you down in one bite")

playAgain = "yes"
while playAgain =="yes" or playAgain == "y":

    displayIntro()

    caveNumber = chooseCave()

    checkCave(caveNumber)

    print("Would you like to play again? (yes or no)")
    playAgain = input()