texts:
Introduction

This problem is essentially equivalent to this HackerRank problem.

The task is to remove all duplicate characters that are adjacent to each other in a given String, until no adjacent characters are the same. If a String only contains adjacent duplicate characters then return an empty String.

Examples:

baab => bb => "" (return an empty String)
aabcd => bcd

Implementation

The core implementation logic uses Stacks to do most of the work.

Translate the input String to a Stack made up of Characters
Create a new Stack that will contain the non-duplicate Characters which will be outputted
pop through the input Stack

If the output Stack is empty, add the character
If the first element of the output Stack is the same Character as the popped Character then
pop the output Stack because this indicates that the two adjacent Characters are duplicate
Else
push the popped input Stack element to the output Stack

Feedback

I'm looking for general feedback as I'm still pretty green to Java. So if I have some serious design pattern issues, or if I'm missing something very obvious, I'd love to get feedback around that.

A couple thoughts on my mind:

Initially I tried implementing logic that iterated through Lists which worked but isn't as efficient as this implementation. One thing that I do like about this implementation is that it identifies the duplicate characters in one iteration, which you could achieve through Lists, I think, but the logic is more intuitive when using Stacks (I think).
Naming

I think the name AdjacentDuplicateCharactersRemover is relatively appropriate, but what are good names for the underlying methods? I struggled with this for a while because they are both doing similar things (removing / filtering characters).

Actual Implementation

public class AdjacentDuplicateCharactersRemover {

  public static String removeAdjacentDuplicateCharacters(final String candidate) {
    if (candidate.length() < 2) {
      return candidate;
    }

    final Stack<Character> originalCharacters = new Stack<>();
    for (char c : candidate.toCharArray()) {
      originalCharacters.push(c);
    }
    final Stack<Character> filteredCharacters = AdjacentDuplicateCharactersRemover.filterAdjacentDuplicateCharacters(originalCharacters);
    final StringBuilder stringBuilder = new StringBuilder();
    while (!filteredCharacters.empty()) {
      stringBuilder.append(filteredCharacters.pop());
    }
    return stringBuilder.toString();
  }

  public static Stack<Character> filterAdjacentDuplicateCharacters(final Stack<Character> characters) {
    if (characters.size() < 2) {
      return characters;
    }

    final Stack<Character> filteredCharacters = new Stack<>();
    while (!characters.empty()) {
      final char poppedChar = characters.pop();
      if (filteredCharacters.empty() || poppedChar != filteredCharacters.peek()) {
        filteredCharacters.push(poppedChar);
      } else {
        filteredCharacters.pop();
      }
    }

    return filteredCharacters;
  }
}


texts: Find sum of K largest elements in an array

texts:
The problem statement is to write code that returns the sum of the K largest elements in a given array. The array is not sorted already.

My solution is based on the idea of quicksort, by finding pivot elements until the pivot is actually the kth element. Thus, all elements left of the pivot will be larger than the pivot.

public class Solution {

    public int getKthSum(int[] a, int k) {
        int kthIdx = getKthLargestIndex(a, k);
        int sum = 0;
        for (int i = 0; i <= kthIdx; i ++) {
            sum += a[i];
        }
        return sum;
    }

    private int getKthLargestIndex(int[] a, int k) {
        return getKthLargestIndex(a, k, 0 , a.length - 1);
    }

    private int getKthLargestIndex(int[] a, int k, int l, int h) {
        int p = partition(a, l, h);
        int rank = p - l +1;
        if (rank == k) {
            return p;
        }
        else if ( k < rank) {
            return getKthLargestIndex(a, k, l, p - 1);
        }
        else {
            return getKthLargestIndex(a, k - rank, p +1 , h);
        }
    }

    private int partition(int[] a, int l, int h) {
        int p; //pivot;
        int firstHigh;

        p = h;
        firstHigh = l;
        for (int i = l ; i < h ; i ++) {
            if (a[i] > a[p]) {
                swap(a, i, firstHigh);
                firstHigh++;
            }
        }
        swap(a, p, firstHigh);
        return firstHigh;
    }

    private void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        int[] nums = {2,1};
        System.out.println(s.getKthSum(nums, 1));
        System.out.println(Arrays.toString(nums));
        int[] nums2 = {3,2,1,5,6,4};
        System.out.println(s.getKthSum(nums2, 2));
        System.out.println(Arrays.toString(nums2));

    }

Based on my testing, I believe that this implementation works. Is it more or less efficient compared to a maxHeap implementation?


texts: just implemented multiprocessing and queue demo, wonder if there are any improvements?

texts:
i will give a list of urls, and want to make multi processes to fetch certain url's web content, and quit if all the urls are all fetched.

here is my implementation, and not sure if it's the right way to do the stuff:

#coding=utf8

import multiprocessing
from multiprocessing import JoinableQueue
import urllib2
import logging
import os

logging.basicConfig(level=logging.DEBUG)

URLS = [
        'http://stackoverflow.com/q/2243542/94962',
        'http://docs.python.org/library/logging.html',
        'http://www.python.org/dev/peps/pep-3101/',
        'http://news.ycombinator.com/',
        'http://www.evernote.com/about/learn_more/',
        'http://news.php.net/php.internals/55293',
        ]

POOL_SIZE = multiprocessing.cpu_count()

DEST_DIR = '/tmp/pytest/'

url_q = JoinableQueue()

class Worker(multiprocessing.Process):

    def run(self):
        while True:
            try:
                url = url_q.get()
                logging.info('%(process_name)s processing %(url)s' % {
                    'process_name': multiprocessing.current_process().name,
                    'url':url,
                    })
                web_cnt = urllib2.urlopen(url).read()
                url_filename = url[7:].replace('/', '-').strip('.html') + '.html'
                with open(os.path.join(DEST_DIR, url_filename), 'w') as f:
                    f.write(web_cnt)
                url_q.task_done()
            except Exception:
                logging.exception('error')

workers = []
for i in range(POOL_SIZE):
    worker = Worker()
    worker.name = 'worker%s'%i
    workers.append(worker)
    worker.start()

for url in URLS:
    url_q.put(url)

url_q.join()

print 'workers have done stuff'

for worker in workers:
    worker.terminate()


texts: Long running in-process Publish/Subscribe class

texts:
I have a Pub/Sub class that will call Notify() when published and that Notify() could take around 10 seconds, so I need to make sure that this does not block the UI.

public static class NotificationService
{
    private static Dictionary<string, INotification> Observers { get; }

    static NotificationService()
    {
        Observers = new Dictionary<string, INotification>();
    }

    public static void Publish(string title, string requester)
    {
        foreach (var observer in Observers)
        {
            var notification = observer.Value;

            new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;
                notification.Notify(title, requester);
            }).Start();

        }
    }

    public static void Subscribe(INotification notification)
    {
        INotification notificationValue;
        if (Observers.TryGetValue(notification.NotificationName, out notificationValue))
        {
            // Observer already exists
            return;
        }

        Observers[notification.NotificationName] = notification;
    }

    public static void UnSubscribe(INotification notification)
    {
        INotification notificationValue;
        if (!Observers.TryGetValue(notification.NotificationName, out notificationValue))
        {
            // Observer doesn't exists
            return;
        }
        Observers.Remove(notification.NotificationName);
    }
}

INotification

public interface INotification
{
    string NotificationName { get; }

    bool Notify(string title, string requester);
}

Example implementation of INotification

public class EmailMessageNotification : INotification
{
    public EmailMessageNotification(EmailNotificationSettingsService settings)
    {
        EmailNotificationSettings = settings;
    }

    private EmailNotificationSettingsService EmailNotificationSettings { get; }
    public string NotificationName => "EmailMessageNotification";
    public bool Notify(string title, string requester)
    {
        var configuration = GetConfiguration();
        if (!ValidateConfiguration(configuration))
        {
            return false;
        }

        var message = new MailMessage
        {
            IsBodyHtml = true,
            To = { new MailAddress(configuration.RecipientEmail) },
            Body = $"User {requester} has requested {title}!",
            From = new MailAddress(configuration.EmailUsername),
            Subject = $"New Request for {title}!"
        };

        try
        {
            using (var smtp = new SmtpClient(configuration.EmailHost, configuration.EmailPort))
            {
                smtp.Credentials = new NetworkCredential(configuration.EmailUsername, configuration.EmailPassword);
                smtp.EnableSsl = configuration.Ssl;
                smtp.Send(message);
                return true;
            }
        }
        catch (SmtpException smtp)
        {
            Log.Fatal(smtp);
        }
        catch (Exception e)
        {
            Log.Fatal(e);
        }
        return false;
    }

    private EmailNotificationSettings GetConfiguration()
    {
        // Gets and Returns Config
    }

    private bool ValidateConfiguration(EmailNotificationSettings settings)
    {
        // Do some validation
    }

Can anyone see anything wrong with this?


texts:
I put up a simple WSGI static file handler, but I'm skeptical about its efficiency, also because I got a handful of errors while benchmarking it with Apache Benchmark.

The errors are:

IOError: [Errno 24] Too many open files: 'test.png'
Client 101 hit errno 32
Client 601 hit errno 32
Client 408 hit errno 32
Client 225 hit errno 32
Client 668 hit errno 32
Client 415 hit errno 32
Client 237 hit errno 32
Client 316 hit errno 104
...

This is what brought me to think it's inefficient.

The following is the Wsgi static file handler:

import bjoern
import os

# Get file size
size = os.path.getsize("test.png")

def app(environ, start_response):
    status = "200 OK"
    # Open image file
    the_file = open("test.png", "rb")
    response_headers = [ ('Content-Type', 'image/png'), ('Content-length', str(size)) ]

    start_response( status, response_headers )

    # return the entire file
    if 'wsgi.file_wrapper' in environ:
        # Return env[wsgi.fw](file, block size)
        return environ['wsgi.file_wrapper'](the_file , 1024)
    else:
        return iter(lambda: the_file.read(1024), '')

bjoern.run(app, "localhost", 8000)

Any advice/tips/suggestions?


texts:
int get_digits (int num)
{
   if(num < 10)
      return 1;

   if(num < 100)
      return 2;

    if(num < 1000)
      return 3;

    if(num < 10000)
      return 4;

    if(num < 100000)
      return 5;

    if(num < 1000000)
      return 6;

    if(num < 10000000)
      return 7;

    if(num < 100000000)
      return 8;

    if(num < 1000000000)
      return 9;

    return 10; /* num > 1000000000 */
}

char *itoa (int n)
{
    static char temp[10]; // MN that can be replaced by some def?
    int nDigits = 0;
    int i = 0;

    if(n == 0)
    {
        temp[0] = '0';
        temp[1] = '\0';

       return temp; // or just return "0"; ?
    }

    nDigits = get_digits(n); // fast function to count digits..

    temp[nDigits] = '\0'; // ..needed just here

   for(i = n; i >= 1; i /= 10) // whole method stinks
    {
        temp[--nDigits] = ((i % 10) + '0'); // modulo is quite slow
    }

    return temp;
}

This is my implementation of the infamous function itoa(), which isn't available everywhere and more importantly not available in my environment. Generally, the implementation of this function is ought to be different anyway. Performance and memory optimization is important.
This function converts an integer to a string. The function owns the reference to the returned string, which is statically allocated and the caller is responsible to make a copy of the returned string if he plans on changing it or preserving it across subsequent calls.


texts:
I made very simple interpreter in C and now, I want to make my code better.
Here is my code:
#define size_t unsigned long long

int printf(const char *format, ...);
int scanf(const char *format, ...);
void *memmove(void *str1, const void *str2, size_t n);
size_t strlen(const char *str);

int main()
{
    char ch[50];
    do
    {
        printf(">>> ");
        scanf("%s", ch);
        if (ch[0] == '"' & ch[strlen(ch) - 1] == '"')
        {
            memmove(ch, ch + 1, strlen(ch));
            ch[strlen(ch) - 1] = '\0';
            printf("%s\n", ch);
        }
    }
    while(1);
}

GitHub Link
(I don't want to include standard libraries)


texts:
I have an array and must fill another one.

Depending of a boolean I copy first or second element and the rest must be as is...

Currently I do it like this (data has the desired info):

const newArray = [];
newArray[0] = theBoolean ? data[0] : data[1];
for (let i = 2; i < data.length; i += 1) {
  newArray[i - 1] = data[i];
}

I've tried with shift and slice but no success...

¿how can I beautify this snippet?


texts:
Thinking about form validation, I just wanted something simple that works and is extensible.

I came up with the following code, which expects a list of selectors that maps to one or more functions performing validation. On success, a validator function returns a "falsey" value (empty string or false, preferably) and on success, it returns the error text. The final result is a map from all inputs to one or more errors they produced.

Any comments on style and good practices, and also good use of ES-6 functionality, are welcome.

export default function validateForm(form, rules, baseSelector = 'input,textarea') {
  let inputs = form.querySelectorAll(baseSelector);
  let errorMap = new Map();
  for (let input of inputs) {
    errorMap.set(input, validateInput(input, rules));
  }
  return errorMap;
}

function validateInput(input, rules) {
  let errors = [];
  for (let rule of Object.keys(rules)) {
    if (input.matches(rule)) {
      let e = validateRule(input, rules[rule]);
      errors.push(...e);
    }
  }
  return errors;
}

function validateRule(input, validators) {
  // In case only a single function is provided instead of an array
  if (typeof validators === 'function') {
    validators = [validators];
  }

  return validators
    .map(validate => validate(input))
    .filter(result => !!result);
}

Sample call:

function ensureRequired(input) {
  if (!input.required || input.value) {
    return '';
  }
  return 'required field not set';
}

function ensureNumber(input) {
  if (Number.isInteger(input.value)) {
    return '';
  }
  return 'field must be number';
}

let myForm = document.getElementById('myForm');
let validationResult = validateForm(myForm, {
  'input': ensureRequired,
  'input.phoneField': [ensureNumber]
};

Disclaimer: I'm aware HTML5 has built-in form validation - I was purposely trying to avoid using it.


texts: Is there anyway to use less if statements in my function?

texts:
I have made a random password generator using a class called password and a method called generate.
My program works as it should. It generates a random password determined by the users preferences for length, upper or lowercase, numbers and special characters.
I was just wondering if there was a way to refactor the numerous if statements I have used to determine what sort of password the program would generate.
Any other suggestions for improvements I could make would also be helpful. Thanks a ton :D
Code:
import random
import string

class password:
    def __init__(self, length, string_method, numbers=True, special_chars=False):
        self.length = length
        self.string_method = string_method
        self.numbers = numbers
        self.special_chars = special_chars

    def generate(self, iterations):

        # Checking what type of string method the user has asked for

        if self.string_method == 'upper':
            stringMethod = string.ascii_uppercase
        elif self.string_method == 'lower':
            stringMethod = string.ascii_lowercase
        elif self.string_method == 'both':
            stringMethod = string.ascii_letters

        # Checking if the user has asked for numbers or not

        if self.numbers == True:
            stringNumbers = string.digits
        elif self.numbers == False:
            stringNumbers = ''

        # Checking if the user has asked for special characters or not

        if self.special_chars == True:
            stringSpecial = string.punctuation
        elif self.special_chars == False:
            stringSpecial = ''

        characters = stringMethod + stringNumbers + stringSpecial

        # Generating the password

        for p in range(iterations):
            output_password = ''
            for c in range(self.length):
                output_password += random.choice(characters)
            print(output_password)

# Test

password1 = password(20, 'lower', True, False) # password length = 20, string method is lowercase, numbers are true and special characters are false
password1.generate(3) # generate the random password 3 times```


texts: Triaging items according to a time threshold

texts:
I'm having this part of code which I want to make smaller, more readable and easy to manage. Any thoughts? I tried linq but got lost.

foreach (var o in state.s)
        {
            TimeSpan timeDiff = (DateTime.Now - o.time);
            if (timeDiff.TotalSeconds < 300)
            {
                richTextBox.AppendColoredText(o.name + " ", Color.Green);
            }
            else
            {
                richTextBox.AppendColoredText(o.name + " ", Color.Red);
                if (f == false)
                {
                    listA.Add(o.name);
                    listA_clone.Add(o.name);
                }
                else
                {
                    listA.Add(o._name);
                }
            }
        }


texts:
I've worked out a functioning Vigenère encryption in Scala, and while it doesn't seem like my code is too hideous, I'm sure I could make it more functional and Scala-esque. Primarily, it seems like:

I've made the full key with a for-expression / zipWithIndex, I'm wondering if this is the best way to do this though. Would it be better to do this inside the encipher() function? Using an anonymous function? The way I have it now works, but I'm curious if there's a way to do so that'd be more in line with Scala best practices.
The actual encryption portion, specifically the output for case (c, i), is sort of messy/convoluted, and it seems like there might be a better way to do it.

Of course, I'll be grateful for any feedback. Definitely still getting my feet wet with Scala, and any help getting into a more functional state of mind would be appreciated.

object Vigenere {

// alphabet for use throughout object
private val alphabet = ('A' to 'Z').toList
//empty array to be filled with fillTabula() function
private var tabulaRecta = Array.ofDim[Char](26, 26)

/* fills the tabula recta array
** creates 26 rows of alphabets, each alphabet shifted
** left by one letter each iteration */
def fillTabula() = {
    for (row <- 0 to 25) {
        for (col <- 0 to 25) {
            tabulaRecta(row)(col) = alphabet((row + col) % 26)
        }
    }
}

/* create the full key by repeating the key until its as long
** as the plaintext. */
def makeFullkey(key: String, text:String): String = {
    val fkey = for (c <- text.zipWithIndex) yield c match {
            case (c, i) => key(i % key.length)
        }
        return fkey.mkString
}

def encipher(key: String, text:String): String = {
    // fill the tabula recta
    fillTabula()
    val fkey = makeFullkey(key, text)

    /* to encipher, zip the plaintext to return each letter with
    ** its index. if it's a space, just add space to ciphertext.
    ** if it's not a space, find the corresponding row in the
    ** tabula recta, then go to the appropriate column to
    ** return the ciphertext character.
    ** the second case here is a mess, there's got to be a nicer way. */

    val ciphertext = for (c <- text.zipWithIndex) yield c match {
        case (' ', _) => ' '
        case (c, i)   => tabulaRecta(alphabet.indexOf(fkey(i)))(alphabet.indexOf(c))
    }
    return ciphertext.mkString
}

def main(args: Array[String]) {
    val Array(text, key) = args

    println("Plaintext: " + text)
    println("Key: " + key)
    println("Ciphertext: " + encipher(key.toUpperCase, text.toUpperCase))

}
}

Edit: I realized that I could make the fullkey using zipWithIndex as well, and also found a better place to use toUpperCase. I've changed the code and updated my question accordingly.


texts: Chi Square Independence Test for Two Pandas DF columns

texts:
I want to calculate the scipy.stats.chi2_contingency() for two columns of a pandas DataFrame. The data is categorical, like this:

var1    var2
0       1
1       0
0       2
0       1
0       2

Here is the example data: TU Berlin Server

The task is to build the crosstable sums (contingency table) of each category-relationship. Example:

         var1
         0    1
---------------------
     0 | 0    1
var2 1 | 2    0
     2 | 2    0

I'm not really a coder, but this is what I got (working):

def create_list_sum_of_categories(df, var, cat, var2):
    list1 = []
    for cat2 in range(int(df[var2].min()), int(df[var2].max())+1):
            list1.append( len(df[ (df[var] == cat) & (df[var2] == cat2) ]))
    return list1

def chi_square_of_df_cols(df,col1,col2):
    ''' for each category of col1 create list with sums of each category of col2'''
    result_list = []
    for cat in range(int(df[col1].min()), int(df[col1].max())+1):
        result_list.append(create_list_sum_of_categories(df,col1,cat,col2))

    return scs.chi2_contingency(result_list)

test_df = pd.read_csv('test_data_for_chi_square.csv')
print(chi_square_of_df_cols(test_df,'var1','var2'))

My question gears towards two things:

Can you confirm that this actually does what I want?
If you have suggestions to make this code more beautiful (e.g. include everything in one function), please go ahead!


texts: Finding perimeters of right triangles with integer-length legs, up to a limit

texts:
I have a nested for-loop that populates a list with elements:

a = []
for i in range(1, limit+1):
    for j in range(1, limit+1):
        p = i + j + (i**2 + j**2)**0.5
        if p <= limit:
            a.append(p)

I could refactor it into list comprehension:

a = [i + j + (i**2 + j**2)**0.5
     for i in range(1, limit+1)
     for j in range(1, limit+1)
     if i + j + (i**2 + j**2)**0.5 <= limit]

But now the same complex expression is in both parts of it, which is unacceptable. Is there any way to create a list in a functional way, but more elegantly?

I guess in Lisp I would use recursion with let. How it is done in more functional languages like Clojure, Scala, Haskell?

In Racket it's possible to bind expressions inside a for/list comprehension. I've found one solution to my problem:

[k
 for i in range(1, limit+1)
 for j in range(1, limit+1)
 for k in [i + j + (i**2 + j**2)**0.5]
 k <= limit]

I'm not sure how pythonic it is.


texts: Undocumented API client / wrapper in Python

texts:
Got the go ahead to make an API wrapper for an undocumented web API.
Hoping to get some feedback on my code and design choice.

I've been going back and forth and haven't been able to really feel satisfied with any of my design choices.

There's a lot of placeholders but I think the base of what I am going for should make sense, at this point it would be a matter of adding the endpoints and do the error catching if I were to continue with it as-is.

Tips, alternative design choices, really anything is welcome and I appreciate it all.

from uuid import uuid4
from time import strftime, gmtime

from hashlib import md5

import requests

class Wrapper:

    endpoints = ['sign_in', 'sign_up']

    def __init__(self):
        # Details
        self.prv_key = ''  # private_key
        self.pub_key = ''  # token
        self.member_id = 0
        self.device_id = uuid4()

        # 'X-Device' header
        self.device_header = \
            '{0},{1},{2}:{2}'.format('android', self.device_id, '845')

    @property
    def auth_token(self):
        auth_token = ','.join((

            # MD5 of auth and time stamp
            md5(self.prv_key + self.pub_key).hexdigest(),
            md5(strftime('%Y-%m-%dT%H:%M,mobile', gmtime())).hexdigest(),

            # Member ID can't be int(0)
            str(self.member_id or '')

        ))

        return auth_token

    def request(self, url, method, **kwargs):
        # Default headers
        kwargs['headers'] = {
            'X-AuthToken':     self.auth_token,
            'X-Device':        self.device_header,
            'Accept':          'application/json',
            'Accept-Language': 'en-US',
            'User-Agent':      'okhttp/3.6.0'
        }
        # Proxy settings
        kwargs['proxies'] = {
            'https':           '192.168.178.27:8085',  # TODO: DEBUG
            'http':            '192.168.178.27:8085'   # TODO: DEBUG
        }
        # SSL verification
        kwargs['verify'] = False  # TODO: DEBUG

        r = requests.request(method, url, **kwargs)

        # TODO: CATCH ERRORS
        # TODO: CORRECT RESPONSE
        response = r.content

        return response

    def sign_in(self):
        return self.request('http://httpbin.org/get', 'GET')  # TODO: DEBUG

    def sign_up(self):
        return ''

if __name__ == '__main__':

    test = Wrapper()
    print test.sign_in()


texts: Unit testing for Python function that checks whether a value is in a range

texts:
This is the first time I've ever tried to write unit tests before, so I wanted to post here to see if I'm doing it "right". I read a couple of articles on the subject, but I work alone so I want to ensure that I fully understand the standard ideas before continuing. Could you please take a look at this and let me know what you think?

Here's an example method:

def is_in_range(value: float,
                allowed_range: (float, float),
                inclusive: bool = True) -> bool:
    """Checks if the given value falls within the allowed range.

    Raises:
        ValueError: If value or range are non numeric.
    """
    if float(allowed_range[0]) != allowed_range[0] or float(
            allowed_range[1]) != allowed_range[1] or float(value) != value:
        raise ValueError("Inputs must be numeric.")

    if inclusive:
        return min(allowed_range) <= value <= max(allowed_range)
    else:
        return min(allowed_range) < value < max(allowed_range)

And here are the unit tests I wrote:

class Test_IsInRange(object):
    def test_in_range(self):
        value = 4
        surrounding_range = (value-1, value+1)
        assert utilities.is_in_range(value, surrounding_range)

    def test_out_range(self):
        value = 76
        not_surrounding_range = (value+1, value+2)
        assert not utilities.is_in_range(value, not_surrounding_range)

    def test_exclusive_range(self):
        value = 23
        inclusive_range = (value, value+10)
        assert not utilities.is_in_range(value, inclusive_range, inclusive=False)

    def test_inclusive_range(self):
        value = 1003
        inclusive_range = (value-500, value)
        assert utilities.is_in_range(value, inclusive_range, inclusive=True)

    def test_string(self):
        string_input = "tt"
        with pytest.raises(ValueError):
            utilities.is_in_range(string_input, ("a","zzz"))

Am I testing properly? Am I testing too many different cases? Too few? Should I combine or separate any tests?


texts:
I tried to write a nullptr_t class based on the official proposal to be used in C++03 only. The only differences with the proposal are that we can compare two nullptr_t instances and that it is convertible to bool via an overload to void* to avoid unwanted behaviour such as int a = nullptr; for example. Here is the class:

const class nullptr_t
{
    public:

        // Return 0 for any class pointer
        template<typename T>
        operator T*() const
        {
            return 0;
        }

        // Return 0 for any member pointer
        template<typename T, typename U>
        operator T U::*() const
        {
            return 0;
        }

        // Used for bool conversion
        operator void*() const
        {
            return 0;
        }

        // Comparisons with nullptr
        bool operator==(const nullptr_t&) const
        {
            return true;
        }
        bool operator!=(const nullptr_t&) const
        {
            return false;
        }

    private:

        // Not allowed to get the address
        void operator&() const;

} nullptr = {};

I would like to know if there is any actual flaw in this completed implementation or if there is a difference in the behaviour compared to the C++11 type std::nullptr_t besides the namespace that I can't see.


texts: Thoughts on this conversion of code from Step.js to Q promise library?

texts:
I have some code that I'd written using this pattern with Step.js.  In this case, talking to MongoDB in Node:

Step(
    function connectToDatabaseWithAuthorization() {
        mongodb.connect(mongoConnectURI, this);
    },

    function getCommitCollection(err, conn) {
        if (err) handleResErr(res, err);

        conn.collection('commits', this);
    },

    function addCommitToCollection(err, coll) {
        if (err) handleResErr(res, err);

        var commit = JSON.parse(req.param('commit', null));
        commit.commit_date = requestTime;
        commit.commit_id = common.makeIdFromCommit(commit);
        coll.insert(commit, {safe: true}, this);
    },

    function respondWithShowAndVerifyUrlsInJson(err, records) {
        if (err) handleResErr(res, err);

        res.json({
            commit_date: records[0].commit_date
        });
    }
)

When I went to update my Node libraries, I noticed Step wasn't getting much attention or undergoing much development.  And I wasn't happy about the error handling being spread into each function in the steps.

So I went to research modern alternatives, and Async.js seemed more popular.  But when I asked about how to convert it, someone suggested I look into Q Promises instead.

I came up with this transformation, which seems to work:

Q.try(function() {

    return Q.ninvoke(mongodb, 'connect', mongoConnectURI);

}).then(function (conn) {

    return Q.ninvoke(conn, 'collection', 'commits');

}).then(function (coll) {

    var commit = JSON.parse(req.param('commit', null));
    commit.commit_date = requestTime;
    commit.commit_id = common.makeIdFromCommit(commit);
    return Q.ninvoke(coll, 'insert', commit, {safe: true});

}).then(function (records) {

    res.json({
        commit_date: records[0].commit_date
    });

}).catch(function (err) {

    handleResErr(res, err);

});

Not a large piece of code, but I could use a sanity check.  I was having problems with figuring out if I should be using .done() in there somewhere, and also I couldn't get .finally to work.  If I put it on the end of the chain, it ran after the first promise and not after all of them.  :-/

While I mostly think the generality makes it an improvement, it does really obscure the method calls.  Q.ninvoke(mongodb, 'connect' mongoConnectURI) is quite a bit uglier than mongodb.connect(mongoConnectURI).  Have people made some better way to do mongodb calls with promises than this?


texts:
The task:

  Given a pivot x, and a list lst, partition the list into three parts.

  The first part contains all elements in lst that are less than x The
  second part contains all elements in lst that are equal to x The third
  part contains all elements in lst that are larger than x Ordering
  within a part can be arbitrary.

  For example, given x = 10 and lst = [9, 12, 3, 5, 14, 10, 10], one
  partition may be `[9, 3, 5, 10, 10, 12, 14].

My solution:

const createPartitionOf = (lst, pivot) => {
  const lessLst = lst.filter(x => x < pivot);
  const equalLst = lst.filter(x => x === pivot);
  const largerLst = lst.filter(x => x > pivot);
  return [...lessLst, ...equalLst, ...largerLst];
};

console.log(createPartitionOf([9, 12, 3, 5, 14, 10, 10], 10));

My solution2:

const createPartitionOf2 = (lst, pivot) => {
  const lessLst = [];
  const equalLst = [];
  const largerLst = [];
  for (let i = 0; i < lst.length; i++) {
    if (lst[i] < pivot) {
      lessLst.push(lst[i]);
    } else if (lst[i] > pivot) {
      largerLst.push(lst[i]);
    } else {
      equalLst.push(lst[i]);
    }
  }
  return [...lessLst, ...equalLst, ...largerLst];
};

console.log(createPartitionOf2([9, 12, 3, 5, 14, 10, 10], 10));


texts:
I've been working for a program over the last few days which should download a range of pages from the webcomic Homestuck. I've created a working version in python 3, but it is horribly inefficient. Can anyone see ways to improve and shorten this code?

import urllib.request
range1 = int(input("Enter the 1st page you want: "))
range2 = int(input("Enter the last page you want: ")) + 1
current = range1 + 1900
final = range2 + 1900
page = ''
nextPage = ''
while current != final:
    page = str(current)
    nextPage = str(current+1)
    while len(page) != 6:
        page = '0'+ page
    while len(nextPage) != 6:
        nextPage = '0'+ nextPage
    html = 'http://www.mspaintadventures.com/?s=6&p='+page
    site = urllib.request.urlopen(html)
    s = site.read()
    s = s.decode("utf8")
    s = s.replace("<!-- end comic content -->", "<!-- begin comic content -->")
    s = s.replace("http://cdn.mspaintadventures.com/storyfiles/hs2/", "")
    s = s.replace("?s=6&p=" + str(nextPage), str(int(nextPage))+".html")
    s = s.replace(page+"/"+page, page)
    a,b,c = s.split('<!-- begin comic content -->')
    b = "<title> Page " + page + "</title>" + b
    t = open(str(current)+".html", 'w+')
    t.write(b)
    t.close()
    page = str((int(page)-1900))
    while len(page) != 5:
        page = '0'+ page

    t = open(str(current)+".html", 'a')
    swfname=page+".swf"
    t.write("<object width='1000' height='1000'> <param name='movie' value='"+swfname+"'>")
    t.write("<embed src="+swfname+" width=650 height=450>")
    t.write("</embed>")
    t.write("</object>")
    t.close()
    try:
        img = "http://cdn.mspaintadventures.com/storyfiles/hs2/"+page+".gif"
        urllib.request.urlretrieve(img, page+".gif")
    except:
        try:
            img = "http://cdn.mspaintadventures.com/storyfiles/hs2/"+page+"_1.gif"
            urllib.request.urlretrieve(img, page+"_1.gif")
            img = "http://cdn.mspaintadventures.com/storyfiles/hs2/"+page+"_2.gif"
            urllib.request.urlretrieve(img, page+"_2.gif")
        except:
            try:
                img = "http://cdn.mspaintadventures.com/storyfiles/hs2/"+page+"/"+page+".swf"
                urllib.request.urlretrieve(img, page+".swf")
            except:
                print("Image "+img+" failed to download")
    print ("Page " + str(page) + " of " + str(final-1901) + " downloaded")
    current+=1
    print("DONE")


texts:
You're a blind adventurer (bad luck eh). To go through the maze that'll lead you to freedom, you must first find the maze's wall, then follow this wall to find the maze's entry. Then, to get an idea about the size of the maze, you want to see how large is the said entry, so you walk until you touch another wall, which is the other border of the entrance. Still following? If not, here's a boolean[][] that'll show my example :

  1,1,1,1,1,0,0,0,1,1,1,1,1

  0,0,0,1,1,0,0,0,1,1,0,0,0

Zeros implies there is no wall
Ones implies there is a wall.

The entry of the maze can be found on the last index of the array, meaning :

maze[x,maze.length-1]

In my example, the entrance is found at [6,1]. As it is a first iteration, the maze is expected to have only one entry, which is valid, which will be situated on the last row of the array. @DoubleDouble already pointed out a flaw of my algorithm in his answer.

If the maze contained an even number of "columns", the entrance could be either the "left" or "right", it doesn't matter.

To find the entrance to my maze, I wrote the function guessEntry, in my Maze class :

package com.mazr.domain;

import java.awt.Point;

public class Maze {
    private boolean[][] content;

    public Maze(boolean[][] content) {
        this.content = content;
    }

    public Point guessEntry() throws InvalidMazeException {

        int openingBorder, closingBorder;
        int xIndex = 0;
        final int bottomYIndex = content[0].length-1;

        try {
            //Find the wall
            while (!content[xIndex][bottomYIndex])
                xIndex++;

            //Follow the wall to the entry
            while (content[xIndex][bottomYIndex])
                xIndex++;

            openingBorder = xIndex;

            //Follow the entry until the end of it
            while (!content[xIndex][bottomYIndex])
                xIndex++;

            closingBorder = xIndex;

            return new Point((closingBorder - openingBorder) / 2, bottomYIndex);
        }
        catch(IndexOutOfBoundsException e){
            throw new InvalidMazeException("The maze has no guessable entry", e);
        }
    }
}

To make the example even clearer, I will show how the algorithm behaves to find an entrance (Don't forget that it only works on the bottom row of the array, which is assumed to contain some walls.):

//Find the wall
while (!content[xIndex][bottomYIndex])
    xIndex++;

  0,0,0,1,1,0,0,0,1,1,0,0,0

  ------^
  xIndex is now at this position, since it went through all the left zeroes.

//Follow the wall to the entry
while (content[xIndex][bottomYIndex])
    xIndex++;

  0,0,0,1,1,0,0,0,1,1,0,0,0

  ----------^
  xIndex is now there, since it went through the first wall.
  We set openingBorder to xIndex since this is the beginning of the entrance "hall".

//Follow the entry until the end of it
while (!content[xIndex][bottomYIndex])
    xIndex++;

  0,0,0,1,1,0,0,0,1,1,0,0,0

  ----------------^
  xIndex went to the next wall, which marks the end of the entrance "hall".
  We set the closingBorder to xIndex so we can know where is the hall situated.

Then, averaging (sorry if that's not a word) the closing and opening border, we can figure out where is the middle of the hall, so we can start solving it (in an upcoming question).

The jagged array is rectangular, meaning that wether we talk about index 0 or 1732, the jagged array will have the same length.

Now, it is easy to seek why I need a review. The function works, it is arguably easy to understand. But I can't stand these following while loops..

I'm using Java 1.8.

I know I'm providing only one method, but I feel like it is already hard to explain briefly and to be clear about the cases.


texts:
I've made some unethical code giving HTML responses at random and masking what is there for fun. It targets mainly crawlers and scripts that run through your website that are looking for vulnerabilities AKA dem script kiddies.

Function TarPit() {
/* Send to Tarpit */
    $responce = array(200,204,300,301,302,303,304,404,410,409,406,418,500);
    $array_select = array_rand($responce,1);
    http_response_code($responce[$array_select]);
    Print(http_response_code());
    Exit(Require_once './CUSTERR/en.php');
}

/CUSTERR/en.php
Make for different languages

<?php
if(isset($_SESSION['authenticated_user'])){exit(header('refresh:0; ../index.php', false));} //You do not want your Logged in users seeing this
$http_response_code = array(200,204,300,301,302,303,304,404,406,409,410,418,500);
$http_response_name = array('Accepted','No Content','Multiple Choices','Moved Permanently','Found','See Other','Not Modified','Not Found','Not Acceptable','Conflict','Gone','I am a Teapot','Internal Server Error');
$http_response_discription = array('Accepted your connection','','Just letting you know this is actually a questionnaire?','Moved permanently somewhere else. Definitely not here although','Don\'t Panic! The monkeys have found it','Go see the other guy.','This page is Definitely not modified in anyway.',' The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found by the monkeys on this server.','This is Unacceptable','Just couldn\'t decide on what to give you','It\'s Gone. Just Gone?','I am a Teapot','Internal Server Error');

$name = str_replace(http_response_code(),$http_response_code,$http_response_name);
$description = str_replace(http_response_code(),$http_response_code,$http_response_discription);

Print('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>' . http_response_code() . $name .'</title>

' . http_response_code() . $name .'

' . $description . '

');
?>


texts:
These are some utility functions that I use for building error messages:
SQLUtil.h
#ifndef THORS_ANVIL_SQL_SQL_UTIL_H
#define THORS_ANVIL_SQL_SQL_UTIL_H

#include <map>
#include <string>
#include <sstream>

namespace ThorsAnvil
{
    namespace SQL
    {

using Options=std::map<std::string, std::string>;

    }

/* The following is generic to all ThorsAnvil Code */

/* Build error message or bug report for exceptions */
template<typename T>
void printItem(std::ostream& str, T const& msg)
{
    str << msg;
}

template<typename... Args>
std::string stringBuild(Args const& ...a)
{
    std::stringstream msg;
    auto list = {0, (printItem(msg, a), 0) ...};
    (void)list;

    return msg.str();
}

template<typename... Args>
std::string errorMsg(Args const& ...a)
{
    return stringBuild(a...);
}

template<typename... Args>
std::string bugReport(Args const& ...a)
{
    return stringBuild(a..., "\nPlease File a Bug Report: ");
}

}

#endif


texts: Travelling salesman using brute-force and heuristics

texts:
I have implemented both a brute-force and a heuristic algorithm to solve the travelling salesman problem.

import doctest
from itertools import permutations

def distance(point1, point2):
    """
    Returns the Euclidean distance of two points in the Cartesian Plane.

    >>> distance([3,4],[0,0])
    5.0
    >>> distance([3,6],[10,6])
    7.0
    """
    return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5

def total_distance(points):
    """
    Returns the length of the path passing throught
    all the points in the given order.

    >>> total_distance([[1,2],[4,6]])
    5.0
    >>> total_distance([[3,6],[7,6],[12,6]])
    9.0
    """
    return sum([distance(point, points[index + 1]) for index, point in enumerate(points[:-1])])

def travelling_salesman(points, start=None):
    """
    Finds the shortest route to visit all the cities by bruteforce.
    Time complexity is O(N!), so never use on long lists.

    >>> travelling_salesman([[0,0],[10,0],[6,0]])
    ([0, 0], [6, 0], [10, 0])
    >>> travelling_salesman([[0,0],[6,0],[2,3],[3,7],[0.5,9],[3,5],[9,1]])
    ([0, 0], [6, 0], [9, 1], [2, 3], [3, 5], [3, 7], [0.5, 9])
    """
    if start is None:
        start = points[0]
    return min([perm for perm in permutations(points) if perm[0] == start], key=total_distance)

def optimized_travelling_salesman(points, start=None):
    """
    As solving the problem in the brute force way is too slow,
    this function implements a simple heuristic: always
    go to the nearest city.

    Even if this algoritmh is extremely simple, it works pretty well
    giving a solution only about 25% longer than the optimal one (cit. Wikipedia),
    and runs very fast in O(N^2) time complexity.

    >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
    [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
    >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
    [[0, 0], [6, 0], [10, 0]]
    """
    if start is None:
        start = points[0]
    must_visit = points
    path = [start]
    must_visit.remove(start)
    while must_visit:
        nearest = min(must_visit, key=lambda x: distance(path[-1], x))
        path.append(nearest)
        must_visit.remove(nearest)
    return path

def main():
    doctest.testmod()
    points = [[0, 0], [1, 5.7], [2, 3], [3, 7],
              [0.5, 9], [3, 5], [9, 1], [10, 5]]
    print("""The minimum distance to visit all the following points: {}
starting at {} is {}.

The optimized algoritmh yields a path long {}.""".format(
        tuple(points),
        points[0],
        total_distance(travelling_salesman(points)),
        total_distance(optimized_travelling_salesman(points))))

if __name__ == "__main__":
    main()


texts:
I have a DataGrid that I filter when the user inputs text into a search box. The column that is filtered is based upon which radio button the user selects (Name, Town or Post Code). Although initially nothing happens until the user has started typing into the searchbox, for some reason there is a noticeable delay in selecting the different radio buttons.

Intuitively I thought that something was happening when the radio button is clicked, but there is (as far as I can tell) nothing being called. The C# program is relatively long, so I'll include the XAML for the radio buttons and the methods that they are being used but not the whole program, unless nothing is found originally.

SearchGrid

    private void SearchGrid(object sender, TextChangedEventArgs e)
    {
        if (!string.IsNullOrEmpty(searchBox.Text))
        {
            var view = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
            var searchText = CharactersOnly(searchBox.Text.ToLower());
            view.Filter = (obj =>
            {
                CompanyModel compDetails = obj as CompanyModel;
                if (compDetails == null)
                    return true;

                if (compNameRad.IsChecked == true)
                {
                    return compDetails.CompanyName != null && CharactersOnly(compDetails.CompanyName.ToLower()).Contains(searchText);
                }
                if (compTownRad.IsChecked == true)
                {
                    return compDetails.CompanyTown != null && CharactersOnly(compDetails.CompanyTown.ToLower()).Contains(searchText);
                }
                if (compPcodeRad.IsChecked == true)
                {
                    return compDetails.CompanyPcode != null && CharactersOnly(compDetails.CompanyPcode.ToLower()).Contains(searchText);
                }
                return false;
            });
        }
        else
        {
            FillDataGrid();
        }
    }

ClearFilter

    private void ClearFilter(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Escape)
        {
            searchBox.Text = string.Empty;
            compNameRad.IsChecked = false;
            compTownRad.IsChecked = false;
            compPcodeRad.IsChecked = false;
            FillDataGrid();
        }
    }

XAML

                <StackPanel Margin="0" Grid.Row="1">
                    <Label Content="Search" HorizontalAlignment="Center" Margin="0,10,0,5" VerticalAlignment="Center" FontSize="21.333" FontWeight="Bold"/>
                    <RadioButton x:Name="compNameRad" Content="Name" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="18.667" GroupName="RadSearch" Margin="7,0,0,5"/>
                    <RadioButton x:Name="compTownRad" Content="Town" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="18.667" GroupName="RadSearch" Margin="7,5,0,5"/>
                    <RadioButton x:Name="compPcodeRad" Content="Pcode" HorizontalAlignment="Left" Margin="7,5,0,5" VerticalAlignment="Top" FontSize="18.667" GroupName="RadSearch"/>
                    <TextBox x:Name="searchBox" TextWrapping="Wrap" Margin="20,5" FontSize="18.667" VerticalAlignment="Center" TextChanged="SearchGrid"/>
                    <Label Content="Press Esc to clear filter" Margin="5,10,5,5" FontSize="16"/>
                </StackPanel>

I really see no reason for anything to slow down purely based on the selection of the radio button, is there a way to improve this code?


texts: Interop between C++ and C# via C++/CLI with callbacks

texts:
I want to use an existing C++ library in a C# app. The C++ library will have async callbacks for things like OnConnect and user updates so I want to reflect this in the eventual C# code. I would appreciate thoughts on the following implementation particularly in the area of memory leaks in the CLI part.

To begin, I have a simple C++ class:

#include <string>

class CppClass
{
public:

    typedef void(*Callback)(int);

    CppClass(){};
    ~CppClass(){};

    void Connect(std::string conn_info)
    {
        OnConnect();
    };

    void OnConnect()
    {
        m_callback(42);
    };

    void SetOnCallback(Callback callback)
    {
        m_callback = callback;
    };

private:
    Callback m_callback;
};

To communicate with this, I have a C++/CLI wrapper:

using namespace System;
using namespace System::Runtime::InteropServices;

namespace CliCpp {

    public delegate void OnConnectDelegate(int);

    public ref class WrapperClass
    {
    public:

        // C# callback delegates
        CliCpp::OnConnectDelegate^ OnConnectHandler;

        // Ctor / dtor
        WrapperClass()
        {
            m_native = new CppClass();

            // Set OnConnect callback
            CliCpp::OnConnectDelegate^ managed_on_connect = gcnew CliCpp::OnConnectDelegate(this, &WrapperClass::OnConnect);
            IntPtr stub_ptr = Marshal::GetFunctionPointerForDelegate(managed_on_connect);
            CppClass::Callback fptr = static_cast<CppClass::Callback>(stub_ptr.ToPointer());
            m_native->SetOnCallback(fptr);
            GC::KeepAlive(managed_on_connect);
        };

        ~WrapperClass()
        {
            this->!WrapperClass();
        };

        !WrapperClass()
        {
            if (m_native != nullptr)
                delete m_native;
        };

        // Methods
        void Connect(String^ conn_info)
        {
            m_native->Connect(msclr::interop::marshal_as<std::string>(conn_info));
        };

        // Event handler from C++ code
        void OnConnect(int i)
        {
            // Call C# code:
            OnConnectHandler(i);
        };

    private:
        CppClass* m_native;
    };
}

And finally, I have some C# calling code:

using CliCpp;

namespace Caller
{
    class Program
    {
        static void Main(string[] args)
        {
            using (WrapperClass cls = new WrapperClass())
            {
                // Set up the C# callback
                cls.on_connect_handler = OnConnect;
                cls.Connect("Hello");
                Console.ReadLine();
            }
        }

        // Callback Function
        static void OnConnect(int i)
        {
            Console.WriteLine("C# handler called!");
        }

    }
}

So, what I would like an opinion on is:

Is this implementation of callbacks good practice?
In the C++/CLI constructor where I set up the callback, am I using gcnew and 'GC::KeepAlive(x)' correctly so as not to leak (do I need a corresponding delete etc.)?

Any input appreciated!


texts: Javascript objects listening to their own events

texts:
I have been playing with event driven javascript lately, and have wondered if it's a good/bad thing for objects listening for their own events as a way of abstracting and simplifying internal logic.

Consider the following:

function MyModule(options) {
    this.options = options;
    this.data    = {};

    this.setListeners();
    //...
}

MyModule.prototype = new EventEmitter;
MyModule.prototype.constructor = MyModule;

MyModule.prototype.updateBasket = function() {
    var self = this,
        url  = this.options.url;

    $.ajax(url)
        .done(function(data) {
            self.emit('basketupdate:success', data);
        })
        .fail(function(jqxhr, textStatus, err) {
            self.emit('basketupdate:error', err);
        })
        .complete(function() {
            self.emit('basketupdate:complete');
        });
};

MyModule.prototype.setListeners = function() {
    var self = this;

    this.on('basketupdate:success', function(data) {
        // ... do something on success
        self.data = data;
    });

    this.on('basketupdate:success', function(data) {
        // ... do something else on success
        console.dir(data);
    });

    this.on('basketupdate:error', function() {
        // ... do something to handle the error
    });
};

var module = new MyModule({
    url: '/path/to/request'
});

module.updateBasket();

A simple module with an ajax request. I could quite easily put all the logic in the corresponding callback, or even map callbacks to internal methods. However I'm quite liking this approach to simplifying the code.

Are there downsides or potential problems to structuring the code in the way that I haven't considered. Or would this be seen as an anti-pattern with events only intended to be listened to from elsewhere?


texts: On form submission, upload an image if there is one, then start update event

texts:
What is the expected behavior?

If there is a file in the state (file != null), then startUploadImage(file) should be executed, followed by startUpdateEvent(eventId, state).
If there is no file (file === null) then only the startUpdateEvent(eventId, state) should be executed.

What is the problem I am encountering right now?

Currently I am struggling with writing a good piece of code, especially when it comes to conditional promises. In the code below you can see that I use some if / else (nested) methodology which leads to tremendously long code.

onSubmit = event => {
        event.preventDefault();
        if (
          (this.state,
          eventNameRegex.test(this.state.event_name) &&
            eventDescriptionRegex.test(this.state.event_description) &&
            priceRegex.test(this.state.ticket_price) &&
            eventDateRegex.test(this.state.event_date))
        ) {
          // check if image changed or not then continue
          this.props.handleLoading(true);

          if (this.state.file != null) {
            startUploadImage(this.state.file).then(response => {
              this.setState({ event_image: response.data });
              return this.props
                .startUpdateEvent(this.props.event.id, this.state)
                .then(() => {
                  this.props.handleLoading(false);
                  this.props.history.push("/events");
                })
                .catch(error => {
                  this.props.handleLoading(false);
                  this.setState({
                    error: error.status,
                    errorMessage: error.data
                  });
                });
            });
          } else {
            return this.props
              .startUpdateEvent(this.props.event.id, this.state)
              .then(() => {
                this.props.handleLoading(false);
                this.props.history.push("/events");
              })
              .catch(error => {
                console.log("error");
                this.props.handleLoading(false);
                this.setState({
                  error: error.status,
                  errorMessage: error.data
                });
              });
          }
        } else {
          this.setState({
            error: 400,
            errorMessage:
              "Please fill in all required fields with correct data. Please try again."
          });
        }
      };


texts:
As part of a project I'm working on, I've implemented a class that encapsulates the syntax for a vb6/vba Dim statement.
Given a line of code, the Parse method uses a regular expression to match the keyword's syntax and extract the relevant parts.
As it stands there's no support for some valid syntaxes, the following aren't currently supported:

'multiple declarations on the same line:
Dim foo As String, bar As String

'multiple instructions on the same line:
Dim foo As String: Dim bar As String

But this question isn't about the code that's not yet implemented, it's about the approach taken; the regular expression works (for the so-far supported use cases), but it's quickly going to become a problem (read: mess), especially since DimSyntax isn't going to be the only ISyntax implementation in the code.
On the other hand, vb6 isn't likely to ever change in the future, so perhaps a well-crafted regex can do the job, if it won't need to be maintained?
public class DimSyntax : ISyntax
{
    // todo: ditch regex
    private static readonly string _syntaxPattern =
        @"^((?<keyword>Dim)\s(?<name>\w{1,30})\s?(As\s(?<type>\w{1,30})))?";

    private static readonly Regex _regex = new Regex(_syntaxPattern);

    private readonly IVBTypeFactory _typeFactory;

    public DimSyntax(IVBTypeFactory typeFactory, IIdentifier identifier)
    {
        _typeFactory = typeFactory;
        _identifier = identifier;
    }

    private readonly IIdentifier _identifier;
    public IIdentifier Identifier { get { return _identifier; } }

    public string Keyword { get { return Keywords.Dim; } }

    public ISyntax Parse(string line)
    {
        var code = line.Trim();

        var match = _regex.Match(code);
        if (!match.Success)
        {
            return null;
        }

        var nameGroup = match.Groups["name"];
        var typeGroup = match.Groups["type"];
        if (nameGroup == null || typeGroup == null)
        {
            return null;
        }

        var type = _typeFactory.Parse(nameGroup.Value);
        var identifier = new Identifier(nameGroup.Value, type);

        return new DimSyntax(_typeFactory, identifier);
    }

    public override string ToString()
    {
        if (_identifier.Type != null)
        {
            // explicit type
            return string.Format("{0} {1} {2} {3}", Keyword, _identifier.Name,
                                                  Keywords.As, _identifier.Type.TypeName);
        }
        else
        {
            // implicit type - Variant
            return string.Format("{0} {1}", Keyword, _identifier.Name);
        }
    }
}

Keywords is just a .resx resource file that contains a list of vb6/vba keywords. I was going to make a public static class with a bunch of public static readonly string members, but I find it's cleaner to use a .resx file. Other suggestions?
I have mixed feelings about the IVBTypeFactory being a dependency of the type, when it's really a dependency of the Parse method - would it make sense to just take the abstract factory in as a method parameter instead?

For reference & context, here's the Identifier implementation:
public class Identifier : IIdentifier
{
    public Identifier(string name, IVBType type)
    {
        _name = name;
        _type = type;
    }

    private readonly string _name;
    public string Name { get { return _name; } }

    private readonly IVBType _type;
    public IVBType Type { get { return _type; } }
}

Pretty much all types are immutable, which means any number of threads can safely access the parsed ISyntax objects - am I making my life harder than it needs to be here?
If you need more context, or are curious to see more, the rest of the code can be found on GitHub.


texts: Sending data to an API with Retrofit 2.0

texts:
In my application, I want to post the version name and manufacturer name to a server using retrofit. Are there any bad parts in the code below?

POJO:

public class InitPost {

    @SerializedName("appVersion")
    @Expose
    private String versionName;

    @SerializedName("deviceName")
    @Expose
    private String manufacturer;

     public String getVersionName() {
        return versionName;
    }

    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }
}

Service interface:

public interface ApiService {

    @POST("postsInit")
    @FormUrlEncoded
    Call<InitPost> postInit(
           @Field("versionName") String versionName,
           @Field("deviceName") String manufacturer
 );
}

API Utils class:

public class ApiUtils {

  private static final String BASE_URL = "https://***.****.com/";

  private ApiUtils() {
  }

  public static ApiService getAPIService() {

    return RetrofitClient.getClient(BASE_URL).create(ApiService.class);
  }
}

Retrofit client:

class RetrofitClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient(String baseUrl) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

Activity:

public class SplashActivity extends BaseActivity {

.....

String versionName;
String manufacturer;
private ApiService apiService;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        versionName = getVersionName();
        manufacturer = getManufacturer();

        apiService = ApiUtils.getAPIService();

        sendInit(versionName, manufacturer);

    }

private String getVersionName() {

        .....
        return versionName;

    }

private String getManufacturer() {

        manufacturer = Build.MANUFACTURER;
        Timber.d("MANUFACTURER: %s", manufacturer);
        return manufacturer;
    }

public void sendInit(String versionName, String manufacturer) {

        apiService.postInit(versionName, manufacturer).enqueue(new Callback<InitPost>() {
            @Override
            public void onResponse(@NonNull Call<InitPost> call, @NonNull Response<InitPost> response) {

                if (response.isSuccessful()) {
                    Timber.d("post submitted to API");
                    getInitResponse();
                }
            }

            @Override
            public void onFailure(@NonNull Call<InitPost> call, @NonNull Throwable t) {

                if (call.isCanceled()) {
                    Timber.e("Request was aborted");
                } else {
                    Timber.e("Unable to submit post to API.");
                }

            }
        });
    }

}


texts:
I'm trying to build an iterator (enumerator) that can select specific elements in an Expression tree by traversing the tree and deferring further iteration until needed.

My following implementation intends to keep it simple by leveraging the ExpressionVisitor. But since a visitor-pattern uses recursive stack calls to keep its place, I am using a Task thread in a synchronous manner to store the position of the IEnumerator between calls to MoveNext.

/// <summary>
/// Iterates through an expression tree collecting only expression elements that match the predicate.
/// </summary>
internal sealed class ExpressionCollector : IEnumerable<Expression>
{
    private ExpressionCollector(Expression root, Func<Expression, bool> predicate)
    {
        this.Root = root;
        this.Predicate = predicate;
    }

    private Expression Root { get; }
    private Func<Expression, bool> Predicate { get; }

    public static IEnumerable<Expression> Collect(Expression root, Func<Expression, bool> predicate)
        => new ExpressionCollector(root, predicate);

    public IEnumerator<Expression> GetEnumerator() => new Iterator(this);
    IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();

    private class Iterator : ExpressionVisitor, IEnumerator<Expression>
    {
        private Task itr;
        private CancellationTokenSource cancel;
        private TaskCompletionSource<Expression> found;
        private TaskCompletionSource<bool> isReady;

        public Iterator(ExpressionCollector owner) { this.Owner = owner; }

        public ExpressionCollector Owner { get; }

        public Expression Current { get; private set; }
        object IEnumerator.Current => this.Current;

        public void Dispose() => this.Reset();
        public bool MoveNext()
        {
            if (this.found is null || this.found.Task.IsCompleted)
                this.found = new TaskCompletionSource<Expression>();

            if (this.itr is null)
                this.itr = Task.Run(Iterate, (cancel = new CancellationTokenSource()).Token);

            this.isReady?.SetResult(true);
            switch (Task.WaitAny(itr, found.Task))
            {
                case 0:
                    this.Current = null;
                    this.found = null;
                    return false;
                case 1:
                    this.Current = found.Task.Result;
                    this.found = null;
                    return true;
                default: throw new NotSupportedException();
            }
        }
        public void Reset()
        {
            if (this.itr != null)
            {
                this.cancel.Cancel();
                this.itr.Wait();

                this.itr.Dispose();
                this.itr = null;

                this.cancel.Dispose();
                this.cancel = null;

                this.Current = null;
            }
        }

        private void Iterate() => this.Visit(this.Owner.Root);
        public override Expression Visit(Expression node)
        {
            if (cancel.IsCancellationRequested)
                cancel.Token.ThrowIfCancellationRequested();

            if (this.Owner.Predicate(node))
            {
                this.isReady = new TaskCompletionSource<bool>();
                this.found.SetResult(node);
                this.isReady.Task.Wait();
            }

            return base.Visit(node);
        }
    }
}

My concern stems from whether or not I am using the Task properly.
Any thoughts?


texts: Sending an SMS message using zenoss and python

texts:
I have just finished a simple python script which uses this module to call Zenoss API for getting live events. What the script does:

connects to zenoss
reads a file which has one phone number on each line
sends a message to each number by POSTing some data(first of all it authenticates) to a specific URL with the following parameters: phonenr, smstxt, Submit

The script speaks for itself and it doesn't need comments. What I'm looking for is some logic in the script / cases that I didn't covered / coding standards that are wrong / design patterns and maybe some advices on how I can improve the code ( in a way that will make each number receive the message at the same time - maybe using multithreading will help )

The file that contains the phone numbers looks like this:

phone_no1
phone_no2
..
phone_non

The code is:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import urllib2 as urllib
from urllib import urlencode
from os.path import join as joinPath
from traceback import print_tb
from os.path import isfile
from sys import exc_info

import myzenoss

zenoss = myzenoss.Zenoss('ip_of_zenoss', 'admin', 'pass')
hdrs = {'User-Agent': "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
gh_url = 'http://ip-for-post/txsms.cgi'  # basically this is an IP for a Mobilink which sends the SMS

APPLICATION_PATH = '/srv/sms_alert/'
ALERT_POINT_PATH = joinPath(APPLICATION_PATH, 'alert_contact')

try:
    isInProduction = False
    for evt in zenoss.get_events():
        if evt['prodState'] == 'Production':
            isInProduction = True

            if isInProduction and isfile(ALERT_POINT_PATH):
                alertContactContent = None
                with open(ALERT_POINT_PATH, 'r') as alertContactFile:
                    alertContactContent = alertContactFile.read()
                alertContactContent = alertContactContent.splitlines()

                if alertContactContent:
                    evt['summary'] = ':zenoss]\n\nError: {0}'.format(evt['summary'])
                    evt['device']['text'] = '{0}'.format(evt['device']['text'])

                    final_message = '{0}\nName: {1}\n\n'.format(evt['summary'], evt['device']['text'])

                    for alertContactContentLine in alertContactContent:
                        data = {'phonenr': alertContactContentLine, 'smstxt': str(final_message), 'Submit': 'SendSms'}
                        data = urlencode(data)

                        req = urllib.Request(gh_url, data, headers=hdrs)
                        password_manager = urllib.HTTPPasswordMgrWithDefaultRealm()
                        password_manager.add_password(None, gh_url, 'admin', 'password')

                        auth_manager = urllib.HTTPBasicAuthHandler(password_manager)
                        opener = urllib.build_opener(auth_manager)

                        urllib.install_opener(opener)
                        handler = urllib.urlopen(req)
                break  # used this to only get the last event
            else:
                evt['summary'] = '#[ERROR: SMS ALERT NO CONTACT]# {0}'.format(evt['summary'])

except Exception as e:
    ex_type, ex, tb = exc_info()
    print('\n #[ERROR]#  TRANSFORM: exception: {ex}\n'.format(ex=e))
    print('\n #[ERROR]#  TRANSFORM: exception traceback: {trace}\n'.format(trace=print_tb(tb)))


texts: Least common ancestor for binary search tree

texts:
I want you to pick my code apart and give me some feedback on how I could make it better or more simple. This code finds a common ancestor for binary search tree.  This code accounts duplicates as well as incomplete tree, and also throws an exception if input element is not in the tree.

public class LeastCommonAncestorBST {

 private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        TreeNode (TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void makeBinarySearchTree(Integer[] a) {
        for (int i : a) {
            addElement(i);
        }
    }

    public void addElement(int element) {
        if (root == null) {
            root = new TreeNode(null, null, element);
        } else {
            TreeNode prevNode = null;
            TreeNode node = root;

            while (node != null) {
                prevNode = node;
                if (element <= node.item) {
                    node = node.left;
                } else {
                    node = node.right;
                }
            }

            if (element <= prevNode.item) {
                prevNode.left = new TreeNode(null, null, element);
            } else {
                prevNode.right = new TreeNode(null, null, element);
            }
        }
    }

    public int leastCommonAncestor(int n1, int n2) {
        TreeNode node  = findLCA(root, n1, n2);
        if (node != null) {
            return node.item;
        } else {
            throw new IllegalArgumentException(" Input was not valid ");
        }
    }

    private TreeNode findLCA(TreeNode node, int n1, int n2) {

        if (node == null) return null;

        if (node.item > n1 && node.item > n2) {
            return findLCA(node.left, n1, n2);
        }

        if (node.item < n1 && node.item < n2) {
            return findLCA(node.right, n1, n2);
        }

        boolean bothExist = doesExist(node, n1) && doesExist(node, n2);

        return bothExist ? node : null;
    }

    private boolean doesExist(TreeNode node, int n) {
        if (node == null) {
            return false;
        }
        if (n < node.item) {
            return doesExist(node.left, n);
        }

        if (n > node.item ) {
            return doesExist(node.right, n);
        }
        return true;
    }
}


texts: Optimizing variadic template pack subsequence matching algorithm

texts:
I'm building a small MPL module in one of my utility libraries for fun and learning experience.

One of the problems I'm trying to solve is getting a list of all indices where a sequence of types appears inside another sequence of types.

Example:

static_assert(is_same
<
    List<int, char, int, int, char, int, double, int, char>
        ::IdxsOfSeq<int, char>,
    ListInt<0, 3, 7>
>());

The above code is valid and works as intended. However, finding out the indices of a subsequence in a long type sequence becomes very slow very fast.

Searching in a list with 20 or 30 elements can take up to 30 seconds of compilation time.

That would rarely be useful, but I'm also experimenting with compile-time strings implemented as character lists.

The current implementation of IdxsOfSeq basically uses std::index_sequence to perform a naive string matching algorithm over the type sequence.

The naive algorithm requires no preprocessing time, but the execution of the type matching requires a lot of computation time.

This is my current implementation of the string matching algorithm.

// Matches<bool, int> returns a ListInt<TStart> is the boolean
// is true, otherwise an empty ListInt<>
template<bool TAllTrue, int TStart>
struct Matches;

template<int TStart>
struct Matches<true, TStart>
{
    using Type = ListInt<TStart>;
};

template<int TStart>
struct Matches<false, TStart>
{
    using Type = ListInt<>;
};

// GetMatch<TS, TM, TStart, TMIdxs>::Type checks if every type
// of TS (the source type sequence) starting from the index TStart
// matches every type in TM (the subsequence to find)
template<typename TS, typename TM, int TStart, typename TMIdxs>
struct GetMatch;

template<typename TS, typename TM, int TStart, SizeT... TMIdxs>
struct GetMatch<TS, TM, TStart, IdxSeq<TMIdxs...>>
{
    using Type = typename Matches
    <
        // True if all the types inside AreAllTrue are std::true_type
        AreAllTrue
        <
            // Type checking with index sequence expansion
            std::is_same_t
            <
                typename TS::template At<TStart + TMIdxs>,
                typename TM::template At<TMIdxs>
            >...
        >{}(),
        TStart
    >::Type;
};

// Main helper template
// Finds every occurrence of the list TM inside TS and returns its index
template<typename TS, typename TM, typename TSIdxs, typename TMIdxs>
struct IdxsOfSeqHlpr;

template<typename TS, typename TM, SizeT... TSIdxs, typename TMIdxs>
struct IdxsOfSeqHlpr<TS, TM, IdxSeq<TSIdxs...>, TMIdxs>
{
    // ConcatLists (obviously) concatenates the contents of the
    // lists passed as template parameters in a single list
    using Type = typename ConcatLists
    <
        ListInt<>,
        typename GetMatch<TS, TM, TSIdxs, TMIdxs>::Type...
    >::Type;
};

// If the subsequence to match is empty, return an empty ListInt<>
template<typename TS, SizeT... TSIdxs, typename TMIdxs>
struct IdxsOfSeqHlpr<TS, List<>, IdxSeq<TSIdxs...>, TMIdxs>
{
    using Type = ListInt<>;
};

// Main typedef
//
template<typename TS, typename TM>
using IdxsOfSeq = typename IdxsOfSeqHlpr
<
    // Source list
    TS,

    // Subsequence to match
    TM,

    // Index sequence of the source list
    // Starts from 0, ends at (source_list_size - matching_list_size + 1)
    std::make_index_sequence
    <
        getClampedMin(int(TS::size - TM::size + 1), 0)
    >,

    // Index sequence of the subsequence to match
    std::make_index_sequence<TM::size>
>::Type;

Is there any part of the algorithm that can easily be optimized?

Or is it better to rewrite the solution from scratch, using another algorithm?


texts:
Can you review my F# code and point out some insights about it?

What I want to know, in order of relevance:

Avoid so much common code between DFA and NFA. I want to make something more generic, there is much code in common there.
Make it more F# idiomatic

Performance is not a concern. Readability is.

module DFA =
    type DeterministicFiniteAutomaton = {
        InitialState: string
        FinalStates: Set<string>
        Transitions: Map<string * char, string>
    }

    let private nextState (symbol:char) (state:string) (transitions:Map<string * char, string>) =
        transitions |> Map.tryFind (state, symbol)

    let rec private haltState (input:string) (index:int) (state:string) (transitions:Map<string * char, string>) =
        match index with
        | i when i = input.Length -> state
        | _ ->
            match nextState input.[index] state transitions with
            | None -> null
            | Some state -> haltState input (index+1) state transitions

    let accepts (input:string) (dfa:DeterministicFiniteAutomaton) =
        dfa.FinalStates |> Set.contains (haltState input 0 dfa.InitialState dfa.Transitions)

module NFA =
    type NondeterministicFiniteAutomaton = {
        InitialState: string
        FinalStates: Set<string>
        Transitions: Map<string * char, string List>
    }

    let private nextState (symbol:char) (state:string) (transitions:Map<string * char, string List>) =
        transitions |> Map.tryFind (state, symbol)

    let rec private haltStates (input:string) (index:int) (state:string) (transitions:Map<string * char, string List>) =
        match index with
        | i when i = input.Length -> Seq.singleton state
        | _ ->
            match nextState input.[index] state transitions with
            | None -> Seq.empty
            | Some states ->
                states |> Seq.collect (fun state ->
                    haltStates input (index+1) state transitions)

    let accepts (input:string) (nfa:NondeterministicFiniteAutomaton) =
        haltStates input 0 nfa.InitialState nfa.Transitions
        |> Set.ofSeq
        |> Set.intersect nfa.FinalStates
        |> Set.count > 0


texts: Checks user level and limit the data before saving it to mongoDB

texts:
I have a function that checks user level and limits the data before saving it to mongoDB database (pre 'save' middleware for mongoose).
It have been getting complexity warnings and tried to rewrite it, and came up with the second version. I think now it's really not human readable! Anyone has any suggestions?

Before:

providerSchema.pre('save', function(next) {

    if(this.level === 4){
        if(this.description.length >= 80 || this.certifications.length > 5){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else if(this.level === 3){
        if(this.description.length >= 50 || this.certifications.length > 3){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else if(this.level === 2){
        if(this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else if(this.level === 1){
        if(this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else {
        if(this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
});

After:

providerSchema.pre('save', function(next) {

    if(((this.level === 4) && (this.description.length >= 80 || this.certifications.length > 5)) ||
       ((this.level === 3) && (this.description.length >= 50 || this.certifications.length > 3)) ||
       ((this.level === 2) && (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0)) ||
       ((this.level === 1 || this.level === 0) && (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart))){
         next(new Error('your current plan does not have this feature'));
    } else {
         next()
    }
});
```


texts: Automate the Boring Stuff Chapter 8 Sandwich Maker

texts:
I am currently learning Python by working my way through Automate the Boring Stuff with Python. This project is from Chapter 8 which is focused on validating input by using the PyInputPlus module. Whenever I finish, I like to look the problem up and compare to other's solutions to see what I could have done better. However, I can only find a couple of links to this problem. Here is the problem:

Sandwich Maker
Write a program that asks users for their sandwich preferences. The program should use PyInputPlus to ensure that they enter valid input, such as:

Using inputMenu() for a bread type: wheat, white, or sourdough.
Using inputMenu() for a protein type: chicken, turkey, ham, or tofu.
Using inputYesNo() to ask if they want cheese. If so, using inputMenu() to ask for a cheese type: cheddar, Swiss, or mozzarella.
Using inputYesNo() to ask if they want mayo, mustard, lettuce, or tomato.
Using inputInt() to ask how many sandwiches they want. Make sure this number is 1 or more.

Come up with prices for each of these options, and have your program display a total cost after the user enters their selection.

That being said, I'd like to hear what I can do better and how I can improve this code:
import pyinputplus as pyip

# store a dictionary of ingredients and their respective prices
optionPrices = {'white' : 2.00,
                'wheat' : 2.50,
                'sour dough' : 3.00,
                'chicken' : 2.50,
                'turkey' : 2.25,
                'ham' : 1.75,
                'tofu' : 4.00,
                'cheddar' : 1.00,
                'swiss' : 1.25,
                'mozzarella' : 2.00,
                'mayo' : 0.25,
                'mustard' : 0.25,
                'lettuce' : 0.30,
                'tomato' : 0.50
                }

customerOrder = [] # a list to store the current order
extras = ['mayo', 'mustard', 'lettuce', 'tomato']
sandwichTotal = 0.0

# ask the user for bread choice and append to order list
breadChoice = pyip.inputMenu(['white', 'wheat', 'sour dough'], 'Please choose your bread:\n', lettered=True)
customerOrder.append(breadChoice)

# ask the user for protein choice and append to order list
proteinChoice = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'], 'Please choose your protein:\n', lettered=True)
customerOrder.append(proteinChoice)

# ask if the user wants cheese, and if so, record cheese choice
cheeseResponse = pyip.inputYesNo('Would you like cheese?\n')
if cheeseResponse == 'yes':
    cheeseChoice = pyip.inputMenu(['cheddar', 'swiss', 'mozzarella'], 'Please choose your cheese:\n', lettered=True)
    customerOrder.append(cheeseChoice)
else:
    cheeseChoice = ''

# loop through 'extras' and ask if customer wants each one. If so, append it the order
choice = ''
for i in extras:
    choice = pyip.inputYesNo('Would you like ' + i +'?\n')
    if choice == 'yes':
        customerOrder.append(i)
    else:
        choice = ''

# get the number of sandwiches from the customer
numSandwiches = pyip.inputInt('How many sandwiches would you like?\n', min=1)

print('\nYour order: ')
# check if the item exists in the options, and get the price for each sandwich
for item in customerOrder:
    if item in optionPrices.keys():
        sandwichTotal += optionPrices.get(item)
        print('\t' + item + ' - $' + str(optionPrices.get(item)))

print('Total for your sandwich: $' + str('{:0.2f}'.format(sandwichTotal))) # per sandwhich total
print('Total for your order: (' + str(numSandwiches) + ' sandwiches @ $' +
      str('{:0.2f}'.format(sandwichTotal)) + ' each): ')
print('$' + str('{:0.2f}'.format(sandwichTotal * numSandwiches))) # give the total price of sandwiches

I know that there are likely a lot of things I could do better to optimize or make the code easier to read, but there are some things I just haven't learned yet. I realize this probably isn't the most efficient way to solve this problem and that is why I'd like to get some feedback.


texts: Array-based queue implementation using C

texts:
I wrote this header for generic use of a queue. The one thing I'm wondering is if I understood the usage of void*. I hope that if somebody teach me some conventions when coding in C.

/*
*   array-based queue implementation by using void*
*   written by kidkkr
*   May 6 '16
*/

#ifndef QUEUE_H
#define QUEUE_H
#define QUEUE_CAPACITY 10
#include <stdio.h>

typedef struct {
    void* data[QUEUE_CAPACITY];
    int head;
    int tail;
    int size;
} Queue;

void initQueue(Queue* pQueue)
{
    pQueue->head = 0;
    pQueue->tail = -1;
    pQueue->size = 0;
}

void enqueue(Queue* pQueue, void* item)
{
    if (pQueue->size == QUEUE_CAPACITY) // when queue is full
    {
        printf("Queue is full\n");
        return;
    }
    else
    {
        (pQueue->tail)++;
        (pQueue->tail) %= QUEUE_CAPACITY;
        (pQueue->data)[pQueue->tail] = item;
        (pQueue->size)++;
    }
}

void* dequeue(Queue* pQueue)
{
    // Return NULL when queue is empty
    // Return (void*)item at the head otherwise.
    void* item = NULL;
    if (isEmpty(&pQueue))
    {
        printf("Queue is empty\n");
    }
    else
    {
        item = (pQueue->data)[pQueue->head];
        (pQueue->head)++;
        (pQueue->head) %= QUEUE_CAPACITY;
        (pQueue->size)--;
    }
    return item;
}

int isEmpty(Queue* pQueue)
{
    return pQueue->size == 0;
}

#endif


texts:
Here is an attempt to code a specific kind of Singleton - the one geared for our configuration needs. It needs to be initialized with a configuration location, do not allow copies or other instances, and provide feedback or fail in case of problems. Prefer graceful feedback from violated workflows. While not performance-critical (especially initialization), the correct behavior and thread safety are needed.

Configuration location differs in production/testing/development scenarios - or may be acquired via a network broadcast in the future. Getting location is outside of this class scope.

So, here is the Config.h header:

class Config {

public:
  typedef std::function<void(std::string)> DupInitCB;

  static void init(std::string loc, DupInitCB err_cb);
  static Config& instance();

private:
  static std::unique_ptr<Config> cfg;
  static std::mutex init_mutex;

  std::string url;

  Config(std::string loc);
  Config(const Config& src);              // not implemented
  Config& operator=(const Config& right); // not implemented

public:
  std::string val(std::string key);
};

The implementation Config.cpp:

#include "Config.h"

std::unique_ptr<Config> Config::cfg;
std::mutex Config::init_mutex;

void Config::init(std::string loc, DupInitCB err_cb) {
  std::lock_guard<std::mutex> lock(init_mutex);
  if (cfg != nullptr) {
    err_cb(loc);
  } else {
    cfg.reset(new Config(loc));
  };
};

Config& Config::instance() {
  if (cfg == nullptr) throw std::logic_error("Requested uninitialized Config");
  return *cfg.get();
}

Config::Config(std::string loc) : url(loc) {};

std::string Config::val(std::string key) {
  return key + " key requested at the location " + url;
}

Finally, a usage example:

#include "Config.h"

int _tmain(int argc, _TCHAR* argv[])
{

  try {
    std::cout << Config::instance().val("Upstream") << std::endl;
    std::cerr << "Did not trow an exception when called an uninitialized Config." << std::endl;
    return 1;
  }
  catch (std::logic_error e) {
    std::cout << "Properly thrown an error when called an uninitialized Config." << std::endl;
  }
  catch (...) {
    std::cerr << "Thrown an unexpected exception when called an uninitialized Config." << std::endl;
    return 1;
  }

  Config::init(
    "http://cnf.local/dev",
    [](std::string loc){ std::cout << "Duplicate Config init (" << loc << ")" << std::endl; }
  );

  Config::init(
    "http://cnf.local/prod",
    [](std::string loc){ std::cout << "Duplicate Config init (" << loc << ")" << std::endl; }
  );

  std::cout << Config::instance().val("Upstream") << std::endl;
  return 0;
}

A buildable VC++ 2012 solution is posted at the GitHub repo.

The specific questions I have are:

Does the instance() method need to be synchronized?
Is there a better way to handle violated workflow from the instance() method than throwing an exception?
What are the dangers of call-back from under the lock?


texts:
To begin, I have an XML file at /Users/gaze/lab/lab/gpib_lib/out.xml that contains lines like...

<MemberCall method_name="setFastCoupleMode" callee_name="GPIB_7280" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="394" colno="9" />

<MemberCall method_name="setInputLineFilter" callee_name="GPIB_7280" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="395" colno="9" />

<MemberCall method_name="setFrequency" callee_name="capacitanceBridge" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="526" colno="5" />

<MemberCall method_name="getFrequency" callee_name="capacitanceBridge" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="528" colno="10" />

<MemberCall method_name="setupBandpass" callee_name="Stream_SR560" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="531" colno="9" />

<MemberCall method_name="thr" callee_name="listOutputFilter" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="540" colno="5" />

<MemberCall method_name="setBias" callee_name="capacitanceBridge" fname="/Users/gaze/lab/lab/gpib_lib/../apps/capbridge/capbridge.C" lineno="546" colno="5" />

To process it into a list of unique class.method() invocations I use the following code. I filter out all calls that occur outside my codebase, which is located at fpath.

filename←'/Users/gaze/lab/lab/gpib_lib/out.xml'
fpath←'/Users/gaze/lab/lab'

getxml←{⎕XML ⊃⎕NGET ⍵}
doc←getxml filename
attrib←↑doc[;4]

colnames ← attrib[1;;1]
col ← {attrib[;(attrib[1;;1]⍳⊂⍵);2]}
oot ← ((⍴fpath)↑¨col'fname')∊⊂fpath

fn ← (1+⍴fpath)↓¨oot/(col'fname')
cn ← oot/(col'callee_name')
mn ← oot/(col'method_name')

allUsed ← ∪(⍉↑(cn mn))[⍋cn;]

OOT denotes "out of tree." I'm curious if you might have suggestions about how to structure this in a larger application. I'm mostly curious how one should set fpath, should it change from invocation to invocation of allUsed, if this code is factored such that you can change filename. I don't exactly want to make allUsed a dyad s.t. fpath is on the right and filename is on the left, since that seems a bit wrong, should there be a more general allUsed that should indeed be a dyad. Should fpath be a global variable which is changed throughout the execution of a larger program? What's the right structure here? If you have any little details you'd improve upon here, I'd love to know as well.


texts: Scraper for downloading and saving images from web page

texts:
I've written some code using Python 3 to scrape movie names, links to the movie posters, and finally save the pictures on the local drive after downloading them from a web page.

I have used two functions to accomplish the whole task. I've tried my best to make the process clean. It is working great now. Any suggestion as to the betterment of this script will be very helpful for me. Thanks in advance. Here is the working code:

import requests
from lxml import html
import os

url = "https://www.yify-torrent.org/search/1080p/"

def ImageScraper(link):

    response = requests.session().get(link).text
    tree = html.fromstring(response)
    for title in tree.xpath('//div[@class="mv"]'):
        movie_title = title.findtext('.//h3/a')
        image_url = title.xpath('.//img/@src')[0]
        image_url = "https:" + image_url
        image_name = image_url.split('/')[-1]
        SavingImages(movie_title, image_name, image_url)

def SavingImages(movie_name, item_name, item_link):

    response = requests.session().get(item_link, stream = True)
    if response.status_code == 200:
        os.chdir(r"C:\Users\ar\Desktop\mth")
        with open(item_name, 'wb') as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)

    print(movie_name, item_link)

ImageScraper(url)


texts:
I have a mesh generation script which initialises a mesh with vertices that represent my map tiles as quads. Then I pass the tiles that I wish to display on the mesh by setting my triangles for the vertices related to the tile.

I was wondering if there is a more optimised way to approach this for Unity. I'm still learning about mesh generation but am unsure if I have designed it efficiently.

This is my initial generation of the mesh before I create any tiles:

private void Awake(){
  Generate();
}
private void Generate ()
{
    vertices = new Vector3[mapLength * mapWidth * 4];
    int v = -1;

    for (int j = 0; j < mapLength; j++)
    {
        for (int i = 0; i < mapWidth; i++)
        {
            vertices[++v] = new Vector3(i * gridSize, 0, j * gridSize); // bottom left
            vertices[++v] = new Vector3(i * gridSize + gridSize, 0, j * gridSize); // bottom right
            vertices[++v] = new Vector3(i * gridSize, 0, j * gridSize + gridSize); // top left
            vertices[++v] = new Vector3(i * gridSize + gridSize, 0, j * gridSize + gridSize); //top right
        }
    }
    GetComponent<MeshFilter>().mesh = mesh = new Mesh();
    mesh.name = "Floor Grid";
    mesh.MarkDynamic();
    mesh.vertices = vertices;
}

So, now I have created the mesh with the vertices for my quads. I now apply triangles to it when the user wishes to draw tiles I obtain the triangles array and add to it like so:

private void Add(List<Vector3> tiles)
{
    int[] triangles;
    if (mesh.triangles.Length == 0)
    {
        // there are currently no tiles so create new array match tile count
        triangles = new int[tiles.Count * 6];
    }
    else
    {
        // we already have some tiles so expand the existing array
        triangles = new int[mesh.triangles.Length + (tiles.Count * 6)];
    }

    // get the triangle indices from mesh.triangle and apply them to new array
    int index = 0;
    for (int i = 0; i < mesh.triangles.Length; i++)
    {
        trianglesList.AddRange(mesh.triangles);
        triangles[i] = mesh.triangles[i];
        index = i+1;
    }

    //apply the new triangles for the tiles the user wants
    for (int i = 0; i < tiles.Count; i++)
    {
        tri = (int)(tiles[i].z * mapWidth + tiles[i].x) * 4;
        triangles[index++] = tri;
        triangles[index++] = tri + 2;
        triangles[index++] = tri + 1;

        triangles[index++] = tri + 2;
        triangles[index++] = tri + 3;
        triangles[index++] = tri + 1;
    }

    mesh.triangles = triangles;
    mesh.RecalculateNormals();
}

This code works, but I am no expert at mesh generation and have basically picked up knowledge from others and example scripts over time.

I was wondering if there is any optimising I can do here. Or have I understood how it is done and this is pretty much as good at it gets?


texts: Comparing and counting thousands of dates converted using moment.js

texts:
I have a very large list of users (a Mongo Collection with roughly +4000 users). Each user belongs to a site.

On the client-side I need to loop over both the sites and users to get completed and incomplete counts between a startDate and endDate. This logic must take place on the client-side.

So far I have two for loops and am using moment.js for the time conversions. I noticed that after adding moment, this page took significantly longer to load (about 3 seconds vs. 40ms originally).

Is there a way I can optimize the code below such that the moment time conversions do not drastically slow down my app?

  function getStatusCounts(sites, users, startDate = new Date(-10000000000000), endDate = new Date(2640000000000000)) {
    startDate = moment.tz(startDate, 'America/Los_Angeles').format('MM/DD/YYYY h:mm a');
    endDate   = moment.tz(endDate, 'America/Los_Angeles').format('MM/DD/YYYY h:mm a');
    var tempDate, tempUserDate;

    for (var i = 0; i < sites.length; i++) {
      for (var j = 0; j < users.length; j++) {
        tempDate = new Date(users[j].userSubmittedAt);
        tempUserDate = moment.tz(tempDate, 'America/Los_Angeles').format('MM/DD/YYYY h:mm a');

        if (sites[i].url === users[j].site_url && moment(tempUserDate).isAfter(moment(startDate)) && moment(tempUserDate).isBefore(moment(endDate))) {

          if (users[j].isCompleted === 'true') {
            completed[i]++;
          } else {
            incompleted[i]++;
          }
        }
      }
    }
  }


texts: Optimizing code: longest repeating substring

texts:
I know i have some real problems with the following code (as others said). can you please help me to optimize it a little bit? Maybe some example of how to do it.

(find the longest repeating substring with length between x and y)

    public static String longestDuplicate(String text, int x, int y)
{
    String longest = "";
    for (int i = 0; i < text.length() - 2 * longest.length() * 2; i++)
    {
        OUTER: for (int j = Math.min((text.length() - i -1)/2, y) ; j > longest.length() && j >=x; j--)
        {
            String find = text.substring(i, i + j);
            for (int k = i + j; k <= text.length() - j; k++)
            {
                if (text.substring(k, k + j).equals(find))
                {
                    longest = find;
                    continue OUTER;
                }
            }
            break;
        }
    }
    return longest;
}