texts: Windows forms set saved groupbox location settings

texts:
I have a Windows form that when a user moves some groupboxes around, before the application exits, it saves those X and Y coordinates into a MySQL database (with a bit of added text to identify which groupbox those settings belong to).  This all works fine.  When they log back into the application, I can pull those settings too.

Is this the most efficient way to accomplish parse & apply saved settings from a string?

Here's the working function that's grabbing this text string and parses it:

private void apply_GUI_settings(string settings)
{
    // The string below, GUI_settings, will evaluate to: "[1:{X=7,Y=29}][2:{X=52,Y=433}]"
    string GUI_settings = settings;
    bool startFound = false;

    for (int c = 0; c < GUI_settings.Length; c++)
    {
        switch (GUI_settings[c])
        {
            case '[':
                {
                    startFound = true;
                }
                break;
            case '1': // groupBox_AccountInfo.Location settings
            case '2': // groupBox_YourCharacters.Location settings
                {
                    string which_groupBox = GUI_settings[c].ToString();

                    if (startFound)
                    {
                        c++; // Iterate over the "1"
                        if (GUI_settings[c] == ':')
                        {
                            int n = 0;
                            string X = "";
                            string Y = "";

                            c += 4; // Iterate over the ":{X="
                            while (int.TryParse(GUI_settings[c].ToString(), out n))
                            {
                                c++;
                                X += n.ToString();
                            }
                            n = 0;

                            c += 3; // Iterate over the ",Y="
                            while (int.TryParse(GUI_settings[c].ToString(), out n))
                            {
                                c++;
                                Y += n.ToString();
                            }
                            n = 0;

                            if (which_groupBox == "1")
                                groupBox_AccountInfo.Location = new Point(int.Parse(X), int.Parse(Y));
                            else if (which_groupBox == "2")
                                groupBox_YourCharacters.Location = new Point(int.Parse(X), int.Parse(Y));

                            // Might as well cycle thru the rest of this string until ']'
                            while (GUI_settings[c] != ']')
                                c++;
                        }
                        else
                        {
                            MessageBox.Show("[ERROR:53928]");
                        }

                        startFound = false;
                    }
                    else
                    {
                        continue;
                    }
                }
                break;
        }
    }
}


texts: Evaluator for adding and subtracting algebraic expressions

texts:
I wrote a little program that adds and subtracts some algebraic expressions.

In my code (2 x 3) represents \$2x^3\$.

The purpose of this post is to get some feedback; moreover, I would like to know how to make it perform better and improve it.

I ran this program on a Mac with SBCL + Emacs.

(defun compute (exp)
  (cond ((term? exp) exp)
    ((expression? exp)
     (make (compute (first-expression exp))
           (compute (second-expression exp))
           (operator exp)))
    (t (error "Unknown Expression Type --COMPUTE" exp))))

(defun term? (exp)
  (or (numberp exp)
      (monomial? exp)))

(defun monomial? (exp)
  (and (consp exp)
       (numberp (car exp))
       (symbolp (car (cdr exp)))
       (numberp (car (cdr (cdr exp))))))

(defun expression? (exp)
  (or (eql (car exp) '+)
      (eql (car exp) '*)
      (eql (car exp) '-)))

(defun first-expression (exp) (car (cdr exp)))

(defun second-expression (exp) (car (cdr (cdr exp))))

(defun operator (exp) (car exp))

(defun make (e1 e2 op)
  (cond ((eql op '+)
     (make-addition e1 e2))
        ((eql op '-)
     (make-subtraction e1 e2))
    (t (make-product e1 e2))))

I wrote the following higher order procedures because version 1 had
a lot patterns.

(defun make-addition (e1 e2)
  (make-exp e1
        e2
        '+
        #'add-monomials))

(defun make-subtraction (e1 e2)
  (make-exp e1
        e2
        '-
        #'subtract-monomials))

(defun make-exp (e1 e2 op term)
  (cond ((eql e1 0) e2)
    ((eql e2 0) e1)
    ((&number? e1 e2) (+ e1 e2))
    ((&monomial? e1 e2)
     (funcall term e1 e2))
    (t (list op e1 e2))))

;; make-product
(defun make-product (e1 e2) (list '* e1 e2))

(defun &number? (e1 e2)
  (and (numberp e1)
       (numberp e1)))

(defun &monomial? (e1 e2)
  (and (monomial? e1)
       (monomial? e2)))

(defun add-monomials (e1 e2)
  (compute-monomials e1
             e2
             #'+
             '+))

(defun subtract-monomials (e1 e2)
  (compute-monomials e1
             e2
             #'-
             '-))

(defun compute-monomials (e1 e2 term op)
  (if (same-variable? e1 e2)
      (make-monomial (funcall term (coeff e1) (coeff e2))
             (variablex e1)
             (exponent e1))
      (list op e1 e2p)))

(defun variablex (exp) (car (cdr exp)))

(defun same-variable? (e1 e2)
  (eql (variablex e1) (variablex e2)))

(defun make-monomial (coeff var exp)
  (list coeff var exp))

(defun coeff (exp) (car exp))

(defun exponent (exp) (car (cdr (cdr exp))))


texts:
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

I'd like to know how this would be performance wise, and if there is a better way to do it.

public int solution(int N) {
    int binaryGap = 0;
    String binaryString = Integer.toBinaryString(N);
    char[] characters = binaryString.toCharArray();
    int j = 0;
    Character c;
    for (int i = 0; i < characters.length; i++) {
         c = characters[i];
        if (c.equals('0')) {
            j += 1;
        }

        if (c.equals('1')) {
            if (j > binaryGap ){
                binaryGap = j;
            }
            j = 0;
        }

    }
    System.out.println(binaryGap);
    return binaryGap;

}


texts: Scraping a table from Texas Dept. of Criminal Justice website

texts:
The script scrapes a table from the website mentioned, looks at the last 2 columns, takes that information, and then sorts it (and then returns the largest county, and the set of races and their numbers). But, basically, I just wanted to know in which ways I can make this script parallel more closely with the Zen of Python, and if there are any optimizations I could make to the script to make it a little faster. I also know that Python's goal is not to be fast, but if I can make the script faster, I don't see why not (though the main priority is to make it Pythonic).

#!/usr/bin/env python
"""Scraping information from https://www.tdcj.state.tx.us/death_row/dr_executed_offenders.html"""

import requests, time
from bs4 import BeautifulSoup
from collections import defaultdict

url = "https://www.tdcj.texas.gov/death_row/dr_executed_offenders.html"
county = {}

def counties(countyArg):
    """Fills the `county` variable"""
    f = open("counties.txt")
    for line in f.readlines():
        countyArg[line.replace('\n', '').rstrip()] = 0

def scrape(urlArg, countyArg):
    """Scrape Site Based on HTML"""
    races = defaultdict(int)

    page = requests.get(urlArg)
    html = page.content

    soup = BeautifulSoup(html, 'html.parser')
    table = soup.find('table')
    for row in table.findAll('tr')[1:]:
        if row.findAll('td')[8].text == 'Black':
            races['black'] += 1
        elif row.findAll('td')[8].text == 'White':
            races['white'] += 1
        elif row.findAll('td')[8].text == 'Hispanic':
            races['hispanic'] += 1

        countyArg[row.findAll('td')[9].text.encode('ascii').rstrip()] += 1

    return races, county

def find_largest(countyArg):
    """find largest county"""
    largestCounty = ''
    largestInmates = 0
    for key, value in countyArg.iteritems():
        if largestInmates < value:
            largestInmates = value
            largestCounty = key
    return largestCounty, largestInmates

if __name__ == '__main__':
    counties(county)
    print county
    scrape(url, county)
    print find_largest(county)


texts: Generic decorator VS generic decorators' decorator

texts:
Here is my little snippet:

def genericDecorator(*decoArgs, **decoKwargs):
    """Accept arbitrary arguments, and use them to decorate functions.
    """
    def decoWrapper(func):
        def funcWrapper(*funcArgs, **funcKwargs):
            # You can do anything else you want here
            print decoArgs, decoKwargs
            func(*funcArgs, **funcKwargs)
        return funcWrapper
    return decoWrapper

# Example:
@genericDecorator(42, 404, whatever = 1024)
def decoratedFunc(a, b, c, isAwesome = True):
    print a, b, c, isAwesome

decoratedFunc(1, 2, 3)

Output:

(42, 404) {'whatever': 1024}
1 2 3 True

The "generic" in the title and the variable name basically means two things:

It can accept an arbitrary number of arguments.
The function it decorates can accept an arbitrary number of arguments.

Some background information:

I've just learned what "decorators" are from this post today. However, the author posted a bonus snippet "to make any decorator accept generically any argument", which defines a decorators' decorator.(Search for "Let’s practice: decorating a decorator" on that page, and you can find the snippet I mean.)

IMHO a decorators' decorator makes things unnecessarily complicated, because "Flat is better than nested". So I write my own snippet, and I want to know whether my approach is better than that author's. If not, why?

Thank you for reviewing.


texts: Create a new object that excludes specified keys

texts:
I have 2 data structures with me in JS. One is an array say of length N. Let's consider N = 4.

const arr = ['a', 'b', 'c', 'd'];

The second one is an object:

const obj = {
  a: 0,
  b: 2,
  c: 3,
  z: 5
};

I wrote a code in Javascript, to create a new object out of obj which should not contain the keys which are not present in the array arr. As of now, the time complexity of the code is \$O(n*n)\$ i.e., \$O(4*4)\$.

standardizeFilter(queryParams: any, inputType: Array<string>) {
  const filter = {};

  for (const key of Object.keys(queryParams)) {
    if (inputType.indexOf(key) > -1) {
      filter[key] = this.parseValues(queryParams[key]);
    }
  }
  return filter;
}

I'm wondering if there is a much optimal way to convert this \$O(n²)\$ to \$O(n)\$.


texts: Passive FTP port assignment synchronization

texts:
I've created the following class to manage the assignment of port numbers to passive FTP server sockets. Notice that Semaphore here is to make the thread wait in case all the ports are assigned, not for Stack synchronization, which is already thread-safe.

Is this class safe assuming releasePort is always invoked when the socket is closed ? And regarding that, what would be the safest way to ensure it, that is, of detecting that the socket has been closed, either correctly or by any exception ?

import java.util.Stack;
import java.util.Vector;
import java.util.concurrent.Semaphore;

public class PassivePortStack {

    private Semaphore semaphore;
    private Stack<Integer> stack;

    public PassivePortStack(Vector<Integer> ports) {
        semaphore = new Semaphore(ports.size());
        stack = new Stack<Integer>();
        stack.setSize(ports.size());
        for (Integer port : ports) {
            stack.push(port);
        }
    }

    public int acquirePort() {
        Integer port = -1;
        try {
            semaphore.acquire();
            port = stack.pop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }

    public void releasePort(int port) {
        stack.push(port);
        semaphore.release();
    }

}


texts: Displaying the number of elements larger than the average of an array

texts:
I have to write a program in C that reads an array with n elements and then displays how many elements are bigger than the average of the elements of the vector.

Is there any other way to do this in a shorter or simpler way?

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

#define SIZE 100

void readArray(int [] , int );
double findAverage(int [] , int);
int countAboveAverage(int [] , int , double);

int main(int argc, char* argv []) {
//declare an array of size 100
int arr[SIZE];
int n;

printf("Enter a value for n: ");
scanf("%d", &n);

if(n==0) {
fprintf(stderr, "Your size of n is too big. Run the program again.\n");
exit(1);
}
//this function will do the reading
readArray(arr, n);
//this is a function to find the average
double average = findAverage(arr, n);
//this is a function that will count the number above average
int count = countAboveAverage(arr, n, average);

printf("The number of elements above the average is %d:");

return EXIT_SUCCESS;
}

void readArray(int arr[], int n) {
int i;
for(i=0; i<n; i++) {
printf("Please enter #%d: ", i+1);
scanf("%d", arr + i); /* or &arr[i] */
}
}

double findAverage(int arr[], int n) {
int sum = 0;
int i;
for(i=0; i<n; i++)
sum+=arr[i];
return (double)sum / n;
}

int countAboveAverage(int arr[], int n, double average) {
int count=0;
int i;

for(i=0; i<n; i++)
count = arr[i] > average ? count+1: count;
return count;
}


texts:
I've solved this problem: https://leetcode.com/problems/word-break

  Given a non-empty string s and a dictionary wordDict containing a list
  of non-empty words, determine if s can be segmented into a
  space-separated sequence of one or more dictionary words.

  Note:

  The same word in the dictionary may be reused multiple times in the
  segmentation. You may assume the dictionary does not contain duplicate
  words. Example 1:

impl Solution {
    fn dfs(i: usize, words: &HashSet<String>, cur_word: &str, cache: &mut HashMap<usize, bool>, n: usize, orig:&str) -> bool {

        if i == n {
            return true;
        }
        if cache.contains_key(&i) {
            return *cache.get(&i).unwrap();
        }
        if words.contains(cur_word) {
            cache.insert(i, true);
            return true;
        }
        let mut res = String::from("");
        for k in i..n {
            let s = orig.chars().nth(k).unwrap();
            res.push(s);
            if words.contains(&res) && Self::dfs(k + 1, &words, orig.get(k+ 1..).unwrap_or_default(), cache, n, orig) {
                cache.insert(i, true);
                return true;
            }
        }
        cache.insert(i, false);
        return false;
    }
    pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
        let set = word_dict.into_iter().collect::<HashSet<String>>();
        let mut cache = HashMap::new();
        Self::dfs(0, &set, "", &mut cache, s.len(), &s)
    }
}

Please ignore the  useless Solution struct -- that's part of the website's interface for solution.

I'm quite upset with how my dfs function is structured -- I am passing far too many arguments into it.

In python, I would've simply created a recursive nested function, which would have captured outer variables; rust doesn't allow for recursive closures, as a closure is an unnamed struct. So I've had to resort to creating a argument-heavy function.

How do I make my code more idiomatic?


texts:
I'm learning JavaScript and as a start I'm trying to create a calculator.

window.onload = function() {

  var numbers = document.getElementsByTagName('span');
  var result = document.querySelectorAll('.result')[0];
  var clear = document.getElementsByClassName('clear')[0];

  for (var i = 0; i < numbers.length; i += 1) {
    if (numbers[i].innerHTML === '=') {
      numbers[i].addEventListener("click", calculate(i));
    } else {
      numbers[i].addEventListener("click", addValue(i));
    }
  }

  clear.onclick = function() {
    result.innerHTML = '';
  };

  function addValue(i) {
    return function() {
      if (numbers[i].innerHTML === '÷') {
        result.innerHTML += '/';
      } else if (numbers[i].innerHTML === 'x') {
        result.innerHTML += '*';
      } else {
        result.innerHTML += numbers[i].innerHTML;
      }
    };
  }

  function calculate(i) {
    return function() {
      result.innerHTML = eval(result.innerHTML);
    };
  }
};
 * {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
   font: bold 15px Arial, sans-serif;
 }
 #calculator {
   width: 312px;
   height: auto;
   margin: 100px auto;
   padding: 10px 10px 10px 10px;
   background: #0088cc;
 }
 .top span.clear {
   float: left;
 }
 .top .result {
   height: 40px;
   width: 212px;
   float: left;
   background: rgba(0, 0, 0, 0.2);
   border-radius: 3px;
   font-size: 17px;
   line-height: 40px;
   color: white;
   text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
   text-align: right;
   letter-spacing: 1px;
 }
 .keys,
 .top {
   overflow: hidden;
 }
 .keys span,
 .top span.clear {
   float: left;
   position: relative;
   top: 0;
   cursor: pointer;
   width: 66px;
   height: 36px;
   background: white;
   border-radius: 3px;
   margin: 0 7px 11px 0;
   line-height: 36px;
   text-align: center;
   transition: all 0.2s ease;
 }
 span.equ {
   background: #00FF19;
 }
 .top span.clear {
   background: red;
   color: white;
   font-size: 17px;
 }
 .keys span:active {
   top: 3px;
 }
 .top span.clear:active {
   top: 3px;
 }

    C

    7
    8
    9
    +

    4
    5
    6
    -

    1
    2
    3
    ÷

    0
    .
    =
    x


texts:
I have two string variables site_inclusion and site_exclusion.  If site_inclusion has some values, then I don't care what values site_exclusion contains.  This means site_inclusion overrides site_exclusion if site_inclusion has some values. But if site_inclusion is null and site_exclusion has some values, then go into the site_exclusion loop.

Requirements:

If site_inclusion and site_exclusion both are null then set useTheSynthesizer as true;
If site_inclusion is not null and it matches with the regexPattern then set useTheSynthesizer as true. And I don't care what values are there in site_exclusion.
If site_inclusion is null and site_exclusion is not null and site_exclusion does not match the regexPattern, then set useTheSynthesizer to true.

I wrote the below code but somehow I think I am repeating some stuff here in the if/else loop. Any code improvements that fulfill my conditions will be appreciated.

String site_inclusion = metadata.getSiteInclusion();
String site_exclusion = metadata.getSiteExclusion();

// fix for redundant data per site issue
if(site_inclusion != null && site_inclusion.matches(regexPattern)) {
    useTheSynthesizer = true;
} else if(site_exclusion != null && !(site_exclusion.matches(regexPattern))) {
    useTheSynthesizer = true;
} else if(site_inclusion == null && site_exclusion == null ) {
    useTheSynthesizer = true;
}


texts: Using BeautifulSoup to scrape various tables and combine in a .csv file

texts:
A page contains a table of links, each link contains a table relevant to the link (a subject). Create a list of these links to pass to the function called scrapeTable which then takes the table and stores it in a CSV file. A directory of files are created for each subject which are then merged into one master file.

I'm looking for some feedback/criticism/improvements to a piece of code I've written.

import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd
import glob
import os

def scrapeTable(url):
    r = s.get(url)

    soup = BeautifulSoup(r.text,"lxml")

    #get page header
    title = soup.find('h4', 'otherTablesSubTitle')
    subject_name = title.contents[0]

   #get table with 'tablesorter' as name
    table = soup.find('table', {'class': 'tablesorter'})

    #open file using page header
    with open('C:/' + subject_name + '.csv', 'ab') as f:
        csvwriter = csv.writer(f)
        for row in table.findAll('tr'):
            headers = []
            for item in soup.find_all('th'):
                headers.append(item.contents[0])

        #because some pages don't follow exact format, rename any instances of Institution to University
        for idx, h in enumerate(headers):
            if 'Institution' in h:
                headers[idx] = 'University'

        csvwriter.writerow(headers)

        for row in table.findAll('tr'):
            cells = [c.text.encode('utf-8') for c in row.findAll('td')]

            csvwriter.writerow(cells)

    #get third index to use as id for pd.melt
    header_id = headers[2]
    #remove third index to use remaining as values for pd.melt
    headers.pop(2)

    #denormalise the table and insert subject name at beginning
    df = pd.read_csv('C:/' + subject_name + '.csv')
    a = pd.melt(df, id_vars=header_id, value_vars=headers, var_name='Measure', value_name='Value')
    a.insert(0, 'Subject', subject_name)

    a.to_csv('C:/' + subject_name + '.csv', sep=',', index=False)

#details to post to login form
payload = {
    'username': 'username',
    'password': 'password'
}

#use with to close session after finished
with requests.Session() as s:
    p = s.post('websitelogin', data=payload)
    r = s.get('website')

    soup = BeautifulSoup(r.text, "lxml")

    #get list of links (subjects)
    links = []
    for anchor in soup.findAll('a', href=True):
        if 'imported' in anchor['href']:
            links.append('link' + anchor['href'])

    #for each link, call scrapeTable and pass link through
    for item in links:
        scrapeTable(item)

#this merges all the files together into one file called final
path = 'C:/'
allCSV = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
CSVList = []
for file in allCSV:
    df = pd.read_csv(file, index_col=None, header=0)
    CSVList.append(df)

frame = pd.concat(CSVList)
frame.to_csv('C:/final.csv', sep=',', index=False)


texts:
I've written a procedure which allows serialized writing of a stream. I don't in any way consider this done, but this is the beginning of it. I know there are other implementations out there like this, but they tend to be either too primitive or too heavy. This is an attempt to simplify serializing the output stream.

The reason I cannot use the normal writing classes is due to the fact these data are written by separate threads. And, also, when writing the output, the position of that stream needs to be considered as well.

So, I tried to store the output streams in memory until all previous ones are already written into it.

Do you see anything critically wrong with it?

var
  NextPosition: Int64 = 0;

procedure HandleOutput(OutHandle: TObjectDictionary<Integer, TStream>;
  Position: Int64; Outstream, mystream2: TStream);

begin
  TMonitor.Enter(OutHandle);
  try
    if NextPosition = Position then
    begin
      mystream2.CopyFrom(Outstream, 0);
      Inc(NextPosition);
      while OutHandle.TryGetValue(NextPosition, Outstream) do
      begin
        mystream2.CopyFrom(Outstream, 0);
        OutHandle.Remove(NextPosition);
        Inc(NextPosition);
      end;
    end
    else
      OutHandle.Add(Position, Outstream);
  finally
    TMonitor.Exit(OutHandle);
  end;
end;


texts:
I've been writing a somewhat complicated service that involves a lot of API function calls in Angular. After a somewhat tortured first attempt I have tried to take more of an MVC approach rewritten the Angular in the following ways.

All data, once it's retrieved from the API, is stored in a Service with a setter or getter, i. e. (MODEL):

.service('userFirstName', function() {
  var userFirstNameProp;
  return {
    getter: function() {
      return userFirstNameProp;
    },
    setter: function(value) {
        userFirstNameProp = value;
      }
    };
  })

That way the data can be retrived from any controller via the setter or getter with a simple function call to determine whether it's already been properly set.
All API calls are pushed into factories using Angular's $resource module.  A sample call might be (CONTROLLER):

.factory("someQueryFactory", function($resource, userToken) {
  var resource = $resource(serverPath + apiPath, {}, {
    get: {
      method: "GET",
      headers: {
        'uid': function() {
          var uid= curUid.getter();
          return token;
        }
      }
    }
  });
  return resource;
})

Each "page" is given its own route, partial, and controller (VIEW):

$routeProvider
  .when('/', {
    templateUrl: '/partials/login1.html',
    controller: 'homePageController'
  })

Each controller handles the logic of each page.  I avoided using directives because the logic of the pages is not too complex and almost entirely consists of seeing if the user's last step has been completed to the satisfaction of the user's next step (i. e. has the user logged in?  Then take them to the home page.)

So far so good, but two issues:

I notice my controller headers seem fairly bloated, mostly because of the need to include the the modules, services, and factories in them.  So maybe something like:

 LSPortal.controller('portalLoginController', ['$scope', '$log', '$location', 'thingOne', 'thingTwo', 'thingThree', 'userStatus', 'userFirstName', 'userLastName', 'userPetName', 'userColor', 'userGender', 'apiQueryOne', 'apiQueryTwo', 'apiQueryThree', function($scope, $log, $location, thingOne, thingTwo, thingThree, userStatus, userFirstName, userLastName, userPetName, userColor, userGender, apiQueryOne, apiQueryTwo, apiQueryThree) { //logic }]);

I understand I could use something like RestMod or Restangular to reduce multiple query calls, but the API is complex and I want something that's going to be supported going forward in Angular that I don't have to throw out in three months.
It's also a lot of getter and setter calls, many times involving doing a bunch of setting at the end of one page only to have to do a lot of getting at the beginning of the next.  This seems like an improvement over my formerly somewhat tortured use of $scope, but is it?

I've been feeling free to mix AngularJS with regular JS but the more I read the more it seems I should try to keep things in Angular as much as possible.  Not sure if this is illustrated above but if someone needs a better example I'd be glad to provide one.

And is there anything else I'm missing?  A lot of tutorials go over certain facets of angular but very few seek to put everything together.  All help appreciated.


texts:
I'm changing the inner implementation of a project.  In order to do so, I've created an interface that will be implemented in 2 different ways.

One of this ways is by class A, which is a wrapper for an outside class (class "B") from a .dll file (a product of other team).

Class B is a private a member of class A.  Class B ctor takes an argument, which does not change during the run of my application. It needed to be created only once, and to stay available for class A everywhere in the code.

Class A is an implementation of interface.  It use the capabilities of class B in order to implement it's functions, and obviously needed to be available also everywhere in the code.

I've concluded that:

Class A has to be:

explicitly created once (hence, not static)
only once, (because I need B to be created only once.)
accessible from anywhere in the code
have a member (B) that must initialized once, and only once (private member, needed only inside class A)

Concerning condition #4, ideally I would like to initialize B in the constructor.

A bit similar to singleton pattern, with the exception of wanting to initialize a member in the constructor.

I've come to a solution, and would like to get feedback.

public sealed class A
{
   private static SomeClass B = null; // the "must initialized only once" member
   // setting B:
   private void setB(int i)
   {
      B = new SomeClass(i);
   }
   // ctor
   public A(int i)
   {
      if(B == null)
         setB(i);
      else throw new Exception("An instance of A can be created only once");
   }
}

The idea is to assign the class to static object at the beginning of the code.  It's not very neat, but it compiles and seems to do the job just right.  I don't use singleton since it won't be possible to initialize the member in the ctor.  By the way, thread safety is not a concern here.

SomeClass needed only inside class A. SomeClass comes from dll, and class A kind of wrapping it.  A does answering cross-cutting concern, it is an implementation of Interface used all over the code. I've tried to implement singleton, but as much as I tried it didn't answer my needs.


texts:
Please review my Stack implementation and let me know if you have any suggestions.

public class StackImplementation<T> {
private StackNode<T> top;
private StackNode<T> head;
private int size;

static class StackNode<T> {
    private T value;
    private StackNode<T> next;

    public StackNode(T val) {
        this.value = val;
        this.next = null;
    }

    public T getValue() {
        return value;
    }

    public StackNode<T> getNext() {
        return next;
    }

    public void setNext(StackNode<T> nextNode) {
        this.next = nextNode;
    }

    public String toString() {
        if(value == null) {
            return "null";
        }
        return value.toString();
    }
}

public StackImplementation() {
    head = new StackNode(0);
    size = 0;
    top = head;
}

public void push(T val) {
    StackNode<T> cur = new StackNode<T>(val);
    cur.setNext(top);
    top = cur;
    size++;
    return;
}

public StackNode<T> peek() {
    return top;
}

public T pop() {
    if(size == 0 || top.getNext() == null) {
        throw new java.util.NoSuchElementException();
    }

    T poppedElement = peek().getValue();
    this.top = this.top.getNext();
    size--;
    return poppedElement;
}

public void clear() {
    head.setNext(null);
    top = head;
    size = 0;
}

public int size() {
    return size;
}

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

public String toString() {
    StringBuilder sb = new StringBuilder();
    StackNode<T> cur = head.getNext();
    sb.append(cur.getValue() + "->");
    while(!cur.equals(top)) {
        sb.append(cur.getValue() + "->");
    }
    sb.append("null");
    return sb.toString();
}

public static void main(String[] args) {
    StackImplementation<Integer> st = new StackImplementation<>();
    System.out.println(st.size());
    //st.pop(); //NoSuchElementException
    st.push(1);
    st.push(10);
    st.push(100);
    System.out.println(st.size());
    System.out.println(st.peek());
    System.out.println(st.pop());
    System.out.println(st.peek());
    System.out.println(st.pop());
    System.out.println(st.isEmpty());
    st.clear();
    System.out.println(st.isEmpty());
    System.out.println(st.size());
    //st.pop(); //NoSuchElementException
}}


texts:
I'm new to RXJS and I have a working piece of code for http-request and subscribing to Observables from a shared service in Angular. This works, but I'd want to get rid of the nested subscriptions, which I know is probably very possible with RXJS operators, but I haven't figured out how. The usage of flatMap in the nested request wouldn't be necessary, as the second nested request isn't dependable on the first.

  this.sub = this.service.isPending$
    .subscribe(data => {
      if(data) { // gives boolean
        this.service.getPending()
          .subscribe((data:Offer) => this.offer = data)
      } else {
        this.sub2 = this.service.amount$
        .flatMap((data: Amount) => {
          this.amount = data;
          return this.service.getOffer()
        })
        .subscribe((data: Offer) => {
          this.offer = data;
        })
      }
    })

How would I go about cleaning this code up? I'm using RXJS: "^5.0.1"


texts:
I would like to unit test my web requests, so on top of my head I came up with the solution below.

Since it seems to be working fine, I'm posting it on this site. Though it doesn't feel very dynamic, I would like your input. For example, this solution can't simulate response headers, which I'm also interested in mocking:

public interface IWebRequest
{
    Task<string> DownloadString();
}

public class RealWebRequest : IWebRequest
{
    private readonly string url;

    public RealWebRequest(string url)
    {
        this.url = url;
    }

    public Task<string> DownloadString()
    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadStringTaskAsync(new Uri(url));
        }
    }
}

public class FakeWebRequest : IWebRequest
{
    private readonly string fakeReponse;

    public FakeWebRequest(string fakeReponse)
    {
        this.fakeReponse = fakeReponse;
    }

    public Task<string> DownloadString()
    {
        return Task.Factory.StartNew(() => fakeReponse);
    }
}

public class TestClass
{
    private readonly IWebRequest request;

    public TestClass(IWebRequest request)
    {
        this.request = request;
    }

    public async Task<string> DoStuff()
    {
        return await request.DownloadString();
    }
}

"Real" usage example:

IWebRequest realRequest = new RealWebRequest("http://www.test.com");
TestClass test = new TestClass(realRequest);
string realResult = await test.DoStuff();

Unit test usage example:

IWebRequest fakeRequest = new FakeWebRequest("fake response string");
TestClass test = new TestClass(fakeRequest);
string fakeResponse = await test.DoStuff();


texts: Frequency analysis based anagram checker

texts:
I uploaded code solutions for some problems of the book Cracking the Coding Interview, 6th Edition to GitHub, I would like to know your rating and potential improvement of the code I wrote.

Here is the first problem of chapter 1 (anagrams):

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

/*check if one string is an anagram of another, it uses an int array
 * called alphabet to store frequencies of chars in both strings, add
 * 1 for s1 and subtract 1 for s2*/
int are_anagrams(const char *s1, const char *s2) {
    int alphabet[26] = { 0 };
    int index1, index2;
    size_t l1 = strlen(s1), l2 = strlen(s2), i;

    /*if the strings have different lengths are not anagrams */
    if (l1 != l2) return 0;

    /* count the frequencies of characters */
    for (i = 0; i < l1; ++i) {
        index1 = s1[i] - 'a';
        index2 = s2[i] - 'a';
        ++alphabet[index1];
        --alphabet[index2];
    }
    /* all the alphabet letters should be 0, otherwise the strings are not
     * anagrams */
    for (i = 0; i < 26; ++i)
        if (alphabet[i] != 0) return 0;

    return 1;
}

int main() {
    char s1[] = "aaabbbccc";
    char s2[] = "aabbaccbc";
    printf("%d\n", are_anagrams(s1, s2));
    return 0;
}

Any suggestion or advice is welcome, thanks for your time.


texts:
import java.util.Scanner;

class Main {

    public static void main(String[] args) {
        int tries = 0;
        boolean iterated = false;
        String temp = "";
        String holder = "";
        System.out.println("Welcome to the guessing game! Guess one letter at a time. You have 5 incorrect guesses remaining.");

        Scanner reader = new Scanner(System.in);
        System.out.println("The Secret Word Is: ______ (6)");
        String word = "sleepy";

        do {
            System.out.print("Your Guess: ");
            String guess = reader.nextLine();

            for(int i = 0; i < word.length(); i ++) {
                if (guess.equals(Character.toString(word.charAt(i)))) {
                    if(!iterated)
                        temp += Character.toString(word.charAt(i));
                    else {
                        holder = Character.toString(temp.charAt(i)).replace("-", guess);
                        temp = temp.substring(0, i) + holder + temp.substring( i + 1, temp.length());
                    }
                } else {
                    if(!iterated) {
                        temp += "-";
                    }
                }
            }
            tries++;
            iterated = true;
            System.out.println(temp);
            if(temp.equals(word)) {
                System.out.println("You guessed correctly!");
                break;
            }
        }while (tries < 5);

    }
}

So this is the code I have so far. It works pretty well but I was wondering how I could make it so that every time you add enter a letter, it tells you whether it was right or wrong and how many tries you have remaining. Also I was wondering how i could make it so that if the user doesn't guess the word I can say something like "sorry you didn't guess it. the word was (sleepy)". Thank you!


texts: Echo in Prolog with single print (new version)

texts:
In order to learn a bit more of Prolog, I implemented the echo command for SWI-Prolog.

I want a correct implementation, that is, it satisfies the following requirements:

It makes only one I/O call so that messages will not be garbled if multiple processes write to the same file.

If it is called without arguments, it just prints an empty line (newline).
It does not print any additional spaces. Only spaces between the arguments. No leading space. No trailing space.
Here's the Prolog code that I came up with after Echo in prolog with single print

main(Argv) :-
    echo(Argv).

echo(Argv) :-
    atomic_list_concat(Argv, ' ', A),
    format('~a~n', A).

Improvements:

Use format with ~n to print the line separator string of the underlying platform (LF on Unix, CRLF on Windows)
Use atomic_list_concat to concatenate all Strings from the command line arguments in one go.

Test:

SHELL:=/bin/bash

.PHONY: all
all: echo

%: %.pl
    swipl -q -t main -o $@ -c $^

.PHONY: clean
clean::
    $(RM) echo

.PHONY: test
test: testEmpty testOne testTwo testWithWhitespace

testEmpty: ARGS:=
testOne: ARGS:=foo
testTwo: ARGS:=foo bar
testWithWhitespace: ARGS:=foo "   bar    " quux " a b  c "

.PHONY: testEmpty testOne testTwo testWithWhitespace
testEmpty testOne testTwo testWithWhitespace: echo
    diff <(echo $(ARGS)) <(./echo $(ARGS))

Anything else that can be improved?


texts: Determining if a given square is a magic square

texts:
I'm writing the following program for a school assignment. The prompt is as follows:

  A magic square is square grid filled with distinct positive integers such that each cell contains a different integer and the sum of the integers in each row, column and diagonal is equal.

My task is to make a boolean method, named magical() that is passed a 2d array, and will return true if those criteria are met. This is the code I wrote:

private static boolean magical(int[][] square) {
        int length = square.length;
        //This loop checks for duplicate values
        for (int i = 0; i < length; i++){
            for (int j = 0; j < length; j++){
                int x = square[i][j];
                for (int a = 0; a < length; a++){
                    for (int b = 0; b < length; b++){
                        if (a == i && b == j) continue;
                        if (x == square[a][b]) return false;
                    }
                }
            }
        }
        ArrayList<Integer> sums = new ArrayList<>();
        //This loop finds the sums of the rows and columns
        for (int i = 0; i < length; i++){
            int sum = 0;
            int sum2 = 0;
            for (int j = 0; j < length; j++){
                sum += square[i][j];
                sum2 += square[j][i];
            }
            sums.add(sum);
            sums.add(sum2);
        }
        //The next two loops find the sums of each diagonal.
        int x = 0;
        int y = 0;
        int sum = 0;
        while (x < length && y < length){
            sum += square[x][y];
            x++;
            y++;
        }
        sums.add(sum);
        sum = 0;
        x = 0;
        y = length - 1;
        while (x < length && y >= 0){
            sum += square[x][y];
            x++;
            y--;
        }
        sums.add(sum);
        return sums.stream().allMatch(s -> s.equals(sums.get(0)));
    }

Here are my questions:

Is there any way to confirm that there are no duplicate values in the array without having to nest four for loops? This seems like an incredibly inefficient system.
Is there any way to combine the two loops in the end that are used to make sure that the sum of values in each diagonal are the same? I am currently using two loops, but seeing as I am iterating through the same array, it seems inefficient to do it twice.

I am also open to any other suggestions you may have. Please note, it is given in the prompt that all arrays passed as parameters will be squares, and it is not required to test for this.


texts: Gathering data using sqlalchemy from database and making it available using simplified namedtuple object in an iterable class

texts:
I wrote the below code today:

class Hosts(object):
    def __init__(self):
        super(Hosts, self).__init__()
        engine, connection = _core.get_engine()
        self._engine = engine
        self._connection = connection
        self._lan_table = self.get_table()

    def _get_selected_field_value(self, table, fields, col_value=None, limit=1):
            """Performs select Operation and gets the value of field.

            Arguments:
                table (sqlalchemy.Table) : table to select data from.
                fields (list) : fields whose value to retrieve.
                col_value (dict) : where column of table has value.
            """
            col_value = col_value or {}
            stmt = db.select(fields).where(
                and_(*[
                    getattr(
                        table.columns,
                         column
                         ) == value for column, value in col_value.items()
                    ])
                ).order_by(db.desc(table.columns.id)).limit(limit)
            _log.debug(stmt)
            ResultProxy = self._connection.execute(stmt)
            ResultSet = ResultProxy.fetchall()
            for item in ResultSet:
                yield item

    def _get_user_and_hostname(self):
        """Gets the hostname of the machine from host table.
        """
        _log.debug("Using table %s", self._lan_table)
        column_value = {"ip_address": self._ip}
        return next(self._get_selected_field_value(
            self._lan_table,
            [self._lan_table.columns.name, self._lan_table.columns.user],
            col_value=column_value
            ),
        None
        )

    def _get_all(self):
        limit = self._engine.scalar(self._lan_table.count())
        columns = Host.metadata.tables['host'].columns.keys()
        columns.pop(columns.index("mac_address"))
        _host = namedtuple("Host", columns)
        select_fields = [getattr(self._lan_table.columns, column) for column in columns]
        self._rows = []
        for rows in self._get_selected_field_value(
                self._lan_table,
                select_fields,
                limit=limit
                ):
            self._rows.append(_host(*rows))
        return self._rows

    def __iter__(self):
        table_data = self._get_all()
        return iter(table_data)

Here is the self._lan_table

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(250) | NO   |     | NULL    |                |
| user        | varchar(20)  | NO   |     | root    |                |
| ip_address  | varchar(18)  | NO   | UNI | NULL    |                |
| mac_address | varchar(250) | NO   |     | NULL    |                |
| is_linux    | tinyint(1)   | NO   |     | 1       |                |
+-------------+--------------+------+-----+---------+----------------+

my question is for the intuitive and pythonic approach and correctness of sqlalchemy !

I know when I fetchall it pulls all data at once, however my table has just 12 rows.

As is understood the appraoch  in code is letting me do this:

hosts = Hosts()
for item in hosts:
    print(item)

Take the Challenge !


texts:
I tried to implement a queue using two stacks. I saw there are questions about this topic, but in my example, I used build-in stack from java. My question is, can someone give me some advice to make my code more efficient or better (in turn of class structure, for-loop, etc)?

This is for practising and understanding how the data structure works (Queue and stack). The main idea is to use two stacks and act as a single queue. The way I implement this problem is by assigning one stack to store odd number of elements and another one to store even number of elements. Example: if there are 3 elements, the first and the third element goes to the oddStack, the second element goes to evenStack.

import java.util.Stack;

public class twoStacksInOneQueue {

private Stack <Integer> oddStack;
private Stack <Integer> evenStack;
private int counter;// count added element
private int shift;//count internal movement from one stack to another.
/**
 Constructor
 */
public twoStacksInOneQueue()
{
    counter = 1;
    shift = 0;
    oddStack = new Stack<Integer>();
    evenStack = new Stack <Integer>();
}
/**
 add element to queue according to amount of elements.
 if there are 3 element, the 3rd element is put into odd stack.
 */
public void addToQueue(int num)
{
    if(counter % 2 == 0)
    {
        evenStack.push(num);
        System.out.println("evenStack: " +  num);
    }
    else
    {
        oddStack.push(num);
        System.out.println("oddStack: " +  num);
    }
    counter++;
}

/**
 remove an element from queue according to amount of elements
 */
public int removeFromQueue()
{
    int temp;
    int result = 0;

    if(counter == 0)//empty queue
    {
        System.out.println("The Queue is empty!");
    }
    else if (counter % 2 == 0) //if there are even elements
    {
        while(!evenStack.empty())//loop while not empty
        {
            //move the entire stack to another to get the bottom of the stack
            temp = evenStack.pop();
            oddStack.push(temp);
            shift++;
        }
        result = oddStack.pop();//the previous bottom of the moved stack
        System.out.println("result From even: "+result);

        while (shift-1  > 0)//move the moved stack back. -1 because of the popped element above
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift--;
        }
        counter--;
    }
    else //if there are odd elements
    {
        while(!oddStack.empty())
        {
            temp = oddStack.pop();
            evenStack.push(temp);
            shift++;
        }
        result = evenStack.pop();

        System.out.println("result from odd: "+result);
        while (shift-1 > 0)
        {
            temp = evenStack.pop();
            oddStack.push(temp);
            shift--;
        }
        counter--;
    }
    shift = 0;//reset internal moved counter.
    return result;
}

public static void main (String [] arg)
{
   twoStacksInOneQueue myQueue = new twoStacksInOneQueue();
    for (int i = 0; i< 4; i++)
    {
        myQueue.addToQueue(i+1);
    }

    myQueue.removeFromQueue();
    myQueue.removeFromQueue();
    myQueue.removeFromQueue();
    myQueue.removeFromQueue();
}


texts:
I have an exercise in my ANSI C book:

  3.3. Write a function expand(s1,s2) that expands shorthand notations like a-z in the string s1 into the equivalent complete list abc…xyz in
  s2. Allow for letters of either case and digits, and be prepared to
  handle cases like a-b-c and a-z0-9 and -a-z. Arrange that a leading or
  trailing - is taken literally.

I have attempted to solve it and here's my code:

#include <stdio.h>
#include <string.h>
#define MAXLEN 100

void expand(char * s1, char * s2);

int main(void) {
    char s1[] = "a-b-c";
    char s2[MAXLEN];
    expand(s1, s2);
    printf("%s\n", s2);
    return 0;
}

void expand(char * s1, char * s2) {
    char prev = '\0';
    char mid = '\0';
    char next = '\0';
    if (s1[0] == '-') {
        *s2 = *s1;
        s1++, s2++;
    }
    while (*s1 != '\0') {
        if (next == '\0' && mid == '-')
            *s2++ = mid;
        else if (mid == '-') {
            if (prev < next)
                for (char i = prev; i <= next; i++, s2++)
                    *s2 = i;
            else
                for (char i = prev; i >= next; i--, s2++)
                    *s2 = i;
        }
        prev = *s1;
        s1++;
        mid = *s1;
        if (*s1 != '\0')
            next = *(s1 + 1);
    }
    *s2 = *s1;
}

What do you think about this solution? Does it solve the exercise? Is it a good way to solve it?


texts: Java 8 functions to avoid try-catch repetition

texts:
I'm developing a Java 8 + JSF application, where all the view classes extend from an abstract class called Navegable.

All the methods called from the view and intended to modify the DB in any way, have to add an information message if everything goes OK or an error message otherwise. This involves wrapping many of my methods in a try-catch clause. In order to avoid that, I've tought I could use functional programming and prepare some generic function in the parent class instead. This way:

public abstract class Navegable implements Serializable {

    protected FacesUtils facesUtils;

    protected void execute(Function<Void, Void> function) {
        try {
            function.apply(null);
            facesUtils.addInfoMessage("PROPERLY_SAVED");
        } catch (Exception ex) {
            facesUtils.addErrorMessage("ERROR");
            throw ex;
        }
    }

    public Navegable(FacesUtils facesUtils) {
        super();
        this.facesUtils = facesUtils;
    }

}

Then I'd have to call it from each of my methods modifying the DB in children classes:

public class NavegableEquipment extends Navegable {
    public void assignWorker() {
        execute(new Function<Void, Void>() {

            @Override
            public Void apply(Void t) {
                assignWorker(selectedEquipment);
                reloadEquipmentById(selectedEquipment.get_Id());
                return null;
            }
        });
    }

    //More methods
}

However, the caller method still looks like a bit verbose in its implementation. Do I have any other choice or am I limited by the language itself?


texts:
I have issues with dynamically typed languages, and I tend to worry about type a lot.

Numpy has different behaviour depending on if something is a matrix or a plain ndarray, or a list.  I didn't originally have all these asserts, but I inserted them while trying to debug a type error.

from numpy import *
sigmoid = vectorize(lambda(x): 1.0/(1.0+exp(-x)))

def prob_hOn_givenV (v,b,w):
    assert isinstance(v,matrix)
    assert isinstance(w,matrix)
    assert isinstance(b,matrix)
    assert shape(v)[1]==shape(w)[0]
    #print("|v|="+str(shape(v)) +"|w|="+str(shape(w)) )
    return sigmoid(b+v*w) #sum up rows (v is a column vector)

def prob_vOn_givenH (h,a,w):
    assert isinstance(h,matrix)
    assert isinstance(a,matrix)
    assert isinstance(w,matrix)

    assert shape(h)[1]==shape(w.T)[0]

    return sigmoid(a+h*w.T) #sum up columns. (h is a row vector)

Is there a better way? Perhaps a defensive programming toolkit?  There is also duplication in the code, but I can't see a nice way of removing it while maintaining meaning.  People familiar with Restricted Boltzman Machines will recognise the conditional formula used for Gibbs sampling for contrastive divergence.


texts: Collecting a list of documents from a factory for an AngularJS controller

texts:
With this controller I'm injecting myFactory and using Array.push() to add the array response.documents to the this.documents array. I can't help feeling there's a better way without having to use _this.

function myController($route, myFactory) {
  'ngInject';

  this.$onInit = function() {
    const _this = this;
    const id = $route.current.params.someId;

    this.documents = [];

    myFactory.getData(id).then((response) => {

      console.log(response); // { "something": { "Id":1234 }, "documents":[{ "DocumentId":"2345", "DocumentName":"doc.docx" }] }
      console.log(response.documents); // [{ "DocumentId":"2345", "DocumentName":"doc.docx" }]

      response.documents.forEach((object) => {
        _this.documents.push(object);
      });
    });
  };
}


texts:
Example: 00010111 -> 11101000

public long reverse(long x) {
    long r = 0;
    int i = 0;
    while (x > 0) {
        int bit = 0x0001 & x;
        r += bit << (63 - i);
        x >>= 1;
        i++;
    }
    return r;
}

Can someone review my code and provide any comments or suggest a better way of doing this?


texts:
I have much more experience with PAWN scripting language, but I'm digging into K&R book (I think it is it), and trying some stuff on my own.

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

#define ITEMS_COUNT 16

unsigned int randr(unsigned int min, unsigned int max);
inline short randomType();
inline char* randomCompanyName();
inline char* randomPersonName();
inline char* randomPersonSurname();
void populateItems();
void dumpItems();

typedef unsigned short int DBID;

typedef struct {
    char name[64];
    char surname[64];
} Person;

typedef struct {
    char name[128];
} Company;

typedef struct {
    unsigned short int type;
    DBID dbID;
    union {
        Person PersonItem;
        Company CompanyItem;
    } chosenItem;
} Item;

enum E_TYPE {
    TYPE_PERSON,
    TYPE_COMPANY
};

Item
    itemList[ITEMS_COUNT];

int main(int argc, char* argv[]) {
    /* Init stuff */
    srand(time(NULL));

    populateItems();
    dumpItems();
    return 0;
}

void populateItems() {
    Item
        singleItem;
    size_t
        i = 0;

    for(; i != ITEMS_COUNT; ++i) {
        singleItem.dbID =   i + 1;
        singleItem.type = randomType();

        if(TYPE_PERSON == singleItem.type) {
            strncpy(singleItem.chosenItem.PersonItem.name, randomPersonName(), sizeof(singleItem.chosenItem.PersonItem.name));
            strncpy(singleItem.chosenItem.PersonItem.surname, randomPersonSurname(), sizeof(singleItem.chosenItem.PersonItem.surname));
        } else {
            strncpy(singleItem.chosenItem.CompanyItem.name, randomCompanyName(), sizeof(singleItem.chosenItem.CompanyItem.name));
        }
        memcpy(&itemList[i], &singleItem, sizeof(singleItem));
    }
}

void dumpItems() {
    Item
        *currentItem;
    size_t
        i = 0;
    char
        str[256];

    for(; i != ITEMS_COUNT; ++i) {
        currentItem = &itemList[i];

        //Not safe sprintf!
        sprintf(str, "Row %d: { dbID: %d,", i + 1, currentItem->dbID);

        if(TYPE_PERSON == currentItem->type) {
            sprintf(str, "%s name: %s, surname: %s }", str, currentItem->chosenItem.PersonItem.name, currentItem->chosenItem.PersonItem.surname);
        } else {
            sprintf(str, "%s company name: %s }", str, currentItem->chosenItem.CompanyItem.name);
        }

        printf("%s\n", str);
    }
}

inline short randomType() {
    return randr(0, 1);
}

inline char* randomCompanyName() {
    static char*
        nameList[32] = {
        "Microsoft",
        "Valve",
        "Vamonos pest",
        "Hello folks!",
        "Just a program inc"
    };
    return nameList[randr(0, 4)];
}

inline char* randomPersonName() {
    static char*
        nameList[32] = {
        "John",
        "Mike",
        "Emily",
        "Jessica",
        "Steven"
    };
    return nameList[randr(0, 4)];
}

inline char* randomPersonSurname() {
    static char*
        nameList[32]  = {
        "Ross",
        "Litt",
        "Hellyeah"
    };
    return nameList[randr(0, 2)];
}

unsigned int randr(unsigned int min, unsigned int max)
{
    double
        scaled = (double) rand() / RAND_MAX;

    return (max - min + 1) * scaled + min;
}

I'd like you to tell me if I've made any major mistakes, and how's my coding style. Additionally I have a question about unions. I thought that it simply pointed to regions, and that you didn't have to care later which one you are using, like:

//instead of
singleItem.chosenItem.PersonItem.name
//use
singleItem.chosenItem.name

which would point at either PersonItem.name, or CompanyItem.name. How to achieve somthing similar?


texts:
I'd like to have a generic way for validating user provided email with a bias toward ease of use. Does the following do so in a clear way for implementations that have the URL interface available? The sample input below is only intended to exercise the range of expected input and demonstrate it works. The UI is not in scope and varies separately--the solution is only intended to provide input validation with usable feedback for implementations.
Any feedback welcome on the style, approach, etc.
function validEmail(input=''){
    const emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i;
    let email, url, valid = false, error, same = false;
    try{
        email = input.trim();
        // handles punycode, etc using browser's own maintained implementation
        url = new URL('http://'+email);
        let urlderived = `${url.username}@${url.hostname}`;
        same = urlderived === email;
        valid = emailPatternInput.test( email );
        if(!valid) throw new Error('invalid email pattern on input:' + email);
        valid = emailPatternUrl.test( urlderived );
        if(!valid) throw new Error('invalid email pattern on url:' + urlderived);
    }catch(err){
        error = err;
    };
    return {email, url, same, valid, error};
}

[
 'user+this@はじめよう.みんな'
, 'stuff@things.eu'
, 'stuff@things'
, 'user+that@host.com'
, 'Jean+François@anydomain.museum','هيا@יאללה'
, '试@例子.测试.مثال.آزمایشی'
, 'not@@really'
, 'no'
].forEach(email=>console.log(validEmail(email), email));


texts: Finding greatest value in array smaller than x

texts:
Code review requested to make this code simpler, cleaner, and better. Input array is sorted.

This program finds the greatest number smaller than x.  So, in an array [10 20 30 40] and x = 25, the output should be 20.

public class GreatestValueLesserThanEqualToX {

    public static Integer findGreatestValueLesserThanOrEqualToX (int[] arr, int x) {
        if (arr == null) {
            throw new NullPointerException(" The input array is null. ");
        }
        if (arr.length >= 1) {
            return findGreatestValueLesserThanOrEqualToX (arr, x, 0, arr.length - 1);
        } else {
            return null;  // note the difference wrt greatest value lesser than X.
        }
    }

    private static Integer findGreatestValueLesserThanOrEqualToX (int[] arr, int x, int lb, int ub) {

        assert arr != null;

        final int mid = (lb + ub) / 2;

        /**
         *  Testing boundaries.
         */
        // testing lower boundary.
        if (mid == 0) {
            if (arr[mid] > x) {
                return null;
            }

            // single element array with value lesser than input value.
            if (arr.length == 1) {
                return arr[0];
            }
        }

        //testing higher boundary.
        if (lb == (arr.length - 1) && arr[mid] < x) {
            return arr[mid];
        }

        /**
         *  Testing equalities and duplicates.
         */
        // testing equality and duplicates. eg: consider input like: 1, 2, 2, 5
        if (arr[mid] == x || arr[mid + 1] == x) {
            return x;
        }

        /**
         *  Testing when element is in the range of array elements.
         */
        // input x in range of array elements.
        if (arr[mid] < x && arr[mid + 1] > x) {
             return arr[mid]; // note the difference wrt greatest value lesser than X.
         }

         if (arr[mid] < x) {
             return findGreatestValueLesserThanOrEqualToX (arr, x, mid + 1, ub);
         } else {
             return findGreatestValueLesserThanOrEqualToX (arr, x, lb, mid);
         }
     }
}


texts: Find best candidates in efficient way, Django

texts:
I'm beginner in django and python. I have models :
 class Employee(models.Model):
    full_name = models.CharField(max_length = 64)
    title = models.CharField(max_length = 64)

    def __str__(self):
        return f"{self.full_name} ( {self.title} )"

class Skill(models.Model):
    name = models.CharField(max_length = 64)

    def __str__(self):
        return f"{self.name}"

class Candidate(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name="employee")
    skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name="skill")

    def __str__(self):
        return f"{self.id}: {self.employee} knows - {self.skill}"

class Job(models.Model):
    title = models.CharField(max_length = 64)
    skills = models.ManyToManyField(Skill, blank=True, related_name="Jobs")

    def __str__(self):
        return f"{self.title}"

In views.py, i have 'finder' function :
def finder(job_id):
    job = Job.objects.get(id=job_id) # get the specific job
    relevant_candidates = [] # all the relevant candidates of this kob
    common = [] # number of common skills between the employee_skill and the
    relevant_employees_by_title = Employee.objects.filter(title = job.title) # first filter the candidates by the job title
    job_skills = []
    for skill in job.skills.all():
        print(skill.id)
        job_skills.append(skill.id)

    for employee in relevant_employees_by_title:
        employee_skills =[]
        candidateCorrect = Candidate.objects.filter(employee__id = employee.id).values_list('skill', flat=True)
        for skill in candidateCorrect:
            employee_skills.append(skill)

        common_skills = list(set(job_skills) & set(employee_skills))

        if (len(common_skills)>0): #if there are common skills
            relevant_candidates.append(employee)
            common.append(len(common_skills))

    candidates = zip(relevant_candidates,common)
    candidates = sorted(candidates,key = lambda t: t[1], reverse = True) # sort the candidates by the number of common skiils , descending order
    candidates = candidates[:50] # Select the best 50 candidates

    return candidates

This function get the job_id and need to find the best candidates for this job : first by matching between the job title to the employee title (for ex' : software developer), and then matching between candidate's skills to job's required skiils .
I think that my function is inefficient. Someone has any idea how to write it in efficient way?


texts: UITableView allowing some kinds of requests to be deleted with swipe gestures

texts:
I have a tableview which shows a list of objects called Requests. It has 3 segments. Namely Accepted, Received and Sent. And the objects for each segment are in 3 arrays.

I want to enable deleting rows (in turn the objects) only for Accepted and Sent segments.

This is my current implementation.

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    var deleteAction: UIContextualAction?

    switch currentShowingStatus {
    case .accepted:
        deleteAction = UIContextualAction(style: .destructive, title: "Delete") { action, view, completionHandler in
            let request = self.acceptedRequests[indexPath.row]
            completionHandler(true)
        }
    case .sent:
        deleteAction = UIContextualAction(style: .destructive, title: "Delete") { action, view, completionHandler in
            let request = self.sentRequests[indexPath.row]
            completionHandler(true)
        }
    default:
        break
    }

    if let deleteAction = deleteAction {
        let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
    } else {
        return UISwipeActionsConfiguration(actions: [])
    }
}

As you can see there is quite a bit of duplicating code. And I can't extract away the UIContextualAction declaration part because of it's completion handler. Selecting the object to be deleted happens in there.

I also can't define UISwipeActionsConfiguration as a local variable and reduce its duplicating due to that class must be initialized with UIContextualAction instances.

Note: You have to pass an empty actions array to UISwipeActionsConfiguration in order to not show the swipe actions in cell. Returning nil doesn't do it.

So all this has produced an ugly piece of code. I'm wondering if there's a better way to refactor this.

Alternative Approach

Instead of checking for segment first and then adding multiple delete actions, I put the checking for segment part inside one completion handler like this.

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    var actions = [UIContextualAction]()

    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { action, view, completionHandler in
        switch self.currentShowingStatus {
        case .accepted:
            let request = self.acceptedRequests[indexPath.row]
            self.deleteClientRequest(request)
        case .sent:
            let request = self.sentRequests[indexPath.row]
            self.deleteClientRequest(request)
        default:
            break
        }
        completionHandler(true)
    }

    switch currentShowingStatus {
    case .accepted, .sent:
        actions.append(deleteAction)
    case .received:
        actions.removeAll()
    }

    let configuration = UISwipeActionsConfiguration(actions: actions)
    configuration.performsFirstActionWithFullSwipe = false
    return configuration
}

The downside is I still have to check for segment again in order to show the swipe action for just the Accepted and Sent segments.


texts: Finding all contiguous sublists such that each member appears an even number of times

texts:
The program needs to find all contiguous sublists of numbers where the number of occurrences of every member in the contiguous sublist is divisible by 2.

The first line of input is N (the number of ai, where N ≤ 353535).  The second line of input contains the ai, delimited by spaces (where each ai < 109).

Here is an example of input and what the output should be:

# N is the user input, and a is the user input with
#numbers separated by space and converted to list with .split(" ") but
#we'll look for examles first :
N = 8
a = [3,5,3,5,9,9,5,3]

The output of this input should be 5 because there are 5 contiguous sublists that meet the conditions:

[3,5,9,9,5,3]
[3,5,3,5,9,9]
[5,9,9,5]
[3,5,3,5]
[9,9]

Here is my solution:

import time
total = 0
try:
    listlength = int(raw_input("Enter the number of list elements >> "))
    listofnumbers   = raw_input("Enter the list elements , space separated >>").split(" ")
    start = time.clock()
    for i in range(listlength,1,-1):
        for i1 in range(0,listlength + 1 - i):
            numbers = []
            countofnumbers=[]
            currentlist = listofnumbers[i1:listlength-abs(i-listlength+i1)]
            #print "I:",i,",TR nIZ ",tr_niz
            for k in currentlist:
                if k not in numbers:
                    numbers.append(k)
                    countofnumbers.append(currentlist.count(k) if currentlist.count(k)%2==0 else 0)
            if 0 not in countofnumbers:
                if sum(countofnumbers)%2==0:
                    total+=1

    print total
    print "Time: ",time.clock()-start

except ValueError:
    print "Data wrong"

My script solves small test cases really well.  However, when there are 350350 numbers, It was working all the night, and it didn't turn up with result.  How can I fix my algorithm to finish in a reasonable amount of time? Maybe implement multiprocessing because it's using 100% od my core when running , but doesn't use any of 3 other cores available  ? And maybe some enhanced algorithm you suggest :)


texts: Searching the Foursquare API with Python

texts:
I'd like some feedback on the readability, style, and potential problems or issues.

foursquare.py

import time

from api_keys import CLIENT_ID
from api_keys import CLIENT_SECRET
from api_keys import CATEGORY_ID

from business import Business
from business import make_request

def search(lat, lng, distance):
    """
    Searches the Foursquare API (Max Limit = 50)

    :param lat: Latitude of the request
    :param long: Longitude of the request
    :param distance: Distance to search (meters)
    :returns: List of retrieved venues
    """

    url = 'https://api.foursquare.com/v2/venues/explore?ll=%s,%s&intent=browse&radius=%s&limit=50&categoryId=%s&client_id=%s&client_secret=%s&v=%s' % (lat, lng, distance, CATEGORY_ID, CLIENT_ID, CLIENT_SECRET, time.strftime("%Y%m%d"))
    venue_list = []

    try:
        data = make_request(url)

        for item in data['response']['groups'][0]['items']:
            venue = item['venue']
            venue_list.append(Business(venue['name'],
                                       venue['location']['address'],
                                       venue['rating'],
                                       venue['ratingSignals'],
                                       venue['stats']['checkinsCount']))
    except Exception, e:
        print e

    return venue_list

business.py

import urllib2
import json

class Business:
    def __init__(self, name, address, rating, rating_count, checkin_count):
        self.name = name
        self.address = address
        self.rating = rating
        self.rating_count = rating_count
        self.checkin_count = checkin_count

def make_request(url):
    """
    Makes a new HTTP request to the given URL

    :param url: The URL to request
    :returns: JSON response
    """

    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    data = json.loads(response.read())
    response.close()

    return data


texts:
I use VS 2008 and .NET 3.5

I have this code using CustomChannelFactory and Proxy ServiceReference. I would like refactor using lambdas, Action, ...

any suggestions ?

ServiceDependencias.IDependencias svcDependencias = null;

public void Dependencias(List<MfaFicheroForm> listaFicherosFormXML, string entorno)
{
    CustomChannelFactory<ServiceDependencias.IDependencias> customChannelFactory = null;

    if (!string.IsNullOrEmpty(FicheroConfiguracionWCFService)
        && !string.IsNullOrEmpty(EndpointNameWCFService))
    {
        if (!File.Exists(FicheroConfiguracionWCFService))
            throw new FileNotFoundException("Fichero de configuración WCF no encontrado", FicheroConfiguracionWCFService);

        customChannelFactory = new CustomChannelFactory<ServiceDependencias.IDependencias>(EndpointNameWCFService, FicheroConfiguracionWCFService);

        var iDependencias = customChannelFactory.CreateChannel();
        svcDependencias = iDependencias;
    }

    if (svcDependencias == null)
    {
        var depClient = new DependenciasClient();
        svcDependencias = depClient;
    }

    GenerarDependenciasDeFormulariosFmb(listaFicherosFormXML, entorno);

    if (svcDependencias is DependenciasClient)
    {
        ((DependenciasClient)svcDependencias).Close();
        return;
    }

    customChannelFactory.Close();
}


texts:
I have a data stored in .mat files, each .mat contains a cell array of vectors of length ~70. I'm trying to read these .mat files in to Python with h5py, but reading just 1000 cells takes about 7 seconds, and I have in total about 10^8 cells to read...

Is there any way I could simplify this process? I'm pretty sure the bottleneck lies in reading the mat file, and all the dereferences implicit in the h5 file structure.

# normalize_mat(mat_file)
#
# takes in a .mat file containing a cell vector 'seg',
#   which contains references to vectors representing one pulse
#
# returns a matrix of equal length, 1-normaled, segment vectors
#
def normalize_mat(mat_file, RESAMPLED_LENGTH=128):
    segments = []
    # reading from .mat version 7.3 files is super weird..
    # we start off by opening the file with h5py
    with h5py.File(mat_file) as mat_file:
        # then we get the cell array 'seg'
        seg_data = mat_file['seg']
        for segment_index in xrange(1001):        #xrange(seg_data.shape[0]):
            if (segment_index%1000) == 0:
                print "Evaluating segment", segment_index

            # then we get a reference to the actual sample array for one segment
            # this is stored in [0] of the dereferenced segment_index. ([1] is the type)
            segment_ref = seg_data[segment_index][0]

            # the data is stored as [[val1],[val2],[val[3]]], so lets get rid of that
            segment = [x[0] for x in mat_file[segment_ref]]
            segment = normalize_segment(segment, RESAMPLED_LENGTH)
            # above statement provides little performance hit.
            segments.append(segment)

    return segments


texts: Alternative std::function implementation for lambdas

texts:
I was trying to implement a faster, alternative implementation of std::function. I came up with the code below:
template <typename R, typename ...Args>
struct Function {
    template <typename Lambda>
    Function(Lambda f) {
    static auto function = f;
    func = + [] (Args... args) -> R {
        return function(args...);
    };
    };
    Function(const Function& other) : func(other.func) {}
    inline auto operator() (Args... args) {
        return func(args...);
    }
    R (*func) (Args... args);
};

Now you can instantiate a Function like below:
int y = 100;
int x = 56;
auto f1 = Function<int , int>([&] (int z) {return x + y + z});
// If you need to store a generic custom functor class:
auto functor = SomeCustomFunctorClass<int, int>(); // Assuming functor takes an int as an argument and returns an int
auto f2 = Function<int , int>([functor] (int x) {return functor(x);});

Note that my implementation Function can only store lambdas, but storing a generic lambda can be achieved through the example above.
The idea here is to erase the type of the lambda in the constructor by storing it statically, which means that I can use it the function pointer func. Note that, a different static variable is instantiated each time the constructor is called because lambdas all have a unique type, so each time a new version of the constructor is instantiated with a different constructor.
I've benchmarked this implementation, and it runs significantly faster than std::function (with optimisations enabled). It is up to 6 - 7 times faster for construction, 15 times faster for copying, and calling it is as fast as calling a function pointer (though significantly slower than calling a lambda which is always inlined).
However, this almost seems too easy, with this implementation being only 15 lines of code. Are there any drawbacks to my implementation compared to the traditional implementation of std::function using heap allocation and virtual calls? Perhaps statically allocating the lambda is not a good idea?


texts: String and Date manipulation exercise using functional programming style

texts:
I was reading a question on stackoverflow recently and I became a little curious/interested in the philosophy behind Ramda (functional programming for Javascript). So I thought I would try an exercise.

I chose to write some code to parse and format ISO8601 date strings, and try to use those with the Date object. This is something that I am fairly familiar with in the usual Javascript style.

This is what I have so far, after a day of reading and experimenting.

var C = {};
C.negFour = R.always(-4);
C.negTwo = R.always(-2);
C.negOne = R.always(-1);
C.zero = R.always(0);
C.one = R.always(1);
C.two = R.always(2);
C.four = R.always(4);
C.minus = R.always('-');
C.empty = R.always('');

var L = {};
L.toNumbers = R.map(Number);
L.toStrings = R.map(String);
L.ofZeros = R.repeat(C.zero());
L.joinMinus = R.join(C.minus());
L.joinEmpty = R.join(C.empty());

var N = {};
N.add1 = R.add(R.__, C.one());
N.subtract1 = R.subtract(R.__, C.one());

var S = {};
S.splitMinus = R.split(C.minus());
S.ofZeros = R.compose(L.joinEmpty, L.ofZeros);
S.prependZeros = R.useWith(R.concat, [R.lift(S.ofZeros)(R.identity), R.identity]);
S.sliceLast = R.slice(R.__, Infinity);
S.sliceLast2 = S.sliceLast(C.negTwo());
S.sliceLast4 = S.sliceLast(C.negFour());
S.padStartZero1 = R.compose(S.sliceLast2, S.prependZeros(C.one()));
S.padStartZero4 = R.compose(S.sliceLast4, S.prependZeros(C.four()));

var D = {};
D.adjustJSMonth = R.adjust(N.subtract1, C.one());
D.adjustGregorianMonth = R.adjust(N.add1, C.one());
D.parseISODateToArgs = R.compose(D.adjustJSMonth, L.toNumbers, S.splitMinus);
D.yearLens = R.lensIndex(C.zero());
D.monthLens = R.lensIndex(C.one());
D.dayLens = R.lensIndex(C.two());
D.getYearArg = R.view(D.yearLens);
D.getISOYear = R.compose(S.padStartZero4, D.getYearArg);
D.getMonthArg = R.view(D.monthLens);
D.getISOMonth = R.compose(S.padStartZero1, D.getMonthArg);
D.getDayArg = R.view(D.dayLens);
D.getISODay = R.compose(S.padStartZero1, D.getDayArg);
D.setYearArg = R.set(D.yearLens);
D.setMonthArg = R.set(D.monthLens);
D.setDayArg = R.set(D.dayLens);
D.setISOYear = R.lift(D.setYearArg)(R.lift(D.getISOYear)(R.identity), R.identity);
D.setISOMonth = R.lift(D.setMonthArg)(R.lift(D.getISOMonth)(R.identity), R.identity);
D.setISODay = R.lift(D.setDayArg)(R.lift(D.getISODay)(R.identity), R.identity);
D.argsToISO = R.compose(D.setISOYear, D.setISOMonth, D.setISODay);
D.argsToISOString = R.compose(L.joinMinus, D.argsToISO, D.adjustGregorianMonth);
D.parse = R.useWith(R.apply(Date.UTC), [R.lift(D.parseISODateToArgs)(R.identity)]);
D.date = function(dateString) {
  return new Date(D.parse(dateString));
};
D.toArgs = function(d) {
  return [d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()];
};
D.toISODateString = R.lift(D.argsToISOString)(D.toArgs);
D.msInDay = R.always(86400000);
D.daysToMs = R.multiply(D.msInDay());
D.day = function(date, dow) {
  date.setTime(R.add(date.getTime(), D.daysToMs(R.subtract(dow, date.getDay()))));
  return date;
};
D.getPreviousSaturday = R.compose(D.toISODateString, R.lift(D.day)(R.identity, C.negOne), D.date);

var previousSaturday = D.getPreviousSaturday('2016-09-17');
console.log(previousSaturday);
<script src="//cdn.jsdelivr.net/ramda/latest/ramda.min.js"></script>

The code is working, and to me looks quite like the code I have seen in examples. But I'd really like to check that I am going in the correct direction with what I have done, it has been difficult to prevent myself coding in the usual style.

I'd like to know what improvements I could make, I still have some code which is written as functions which I don't know if it is even possible to translate. Some of the code seems, and probably is, unnecessary. It would be really great to get some feedback to further my knowledge on the subject.


texts: Fetching daylerees colour schemes for PHPStorm from Github

texts:
I wanted to download all colour schemes for phpstorm and was too lazy to do it manually so I wrote a little script for it in python, because why not.

This is my very first Python script and I'm still learning through tutorials and what not.

Things it does:

Asks to input the path where to save the files
If the destination folder does not exist, creates it
Makes sure the the path ends with '/'
Instantiates a crawler instance
Crawler fetches the initial JSON payload
It loops over the items to check whether an item is a file or a directory
If it is a file, downloads it. If a folder, instantiates a new crawler instance with that directory path
Before downloading the files, it checks if the file exists already and prints the messages accordingly.

Things I can already see that I will go back and improve:

Make passing the link dynamic, instead of hard coding.
Implement a better path checking / validation.
use try / except methods instead where applicable.

And the code:

import urllib
import json
import time
import os
import re

class Crawler:
    def __init__(self, url, path):
        self.url = url
        self.path = path
        self.counter = 0
        self.total_files = 0

    def crawl(self):
        self.get_contents()

    def get_contents(self):
        response = urllib.urlopen(self.url).read()
        collection = json.loads(response)
        self.total_files = len(collection)
        for data in collection:
            if data.get('type') == 'file':
                self.download(data.get('name'), data.get('download_url'))
            elif data.get('type') == 'dir':
                dir_crawler = Crawler(data.get('url'), self.path)
                print('\nFound a directory. Pausing the main download and crawling the directory - ' + data.get(
                    'name') + '\n')
                dir_crawler.crawl()
                print('\n' + data.get('name') + ' directory is done. Continuing from where I left off.\n')
            time.sleep(1)

    def download(self, name, link):
        if name and not os.path.exists(self.path + name):
            download = urllib.URLopener()
            download.retrieve(link, self.path + name)
            self.counter += 1
            print('Downloading ' + name + ' (' + str(self.counter) + ' out of ' + str(self.total_files) + ')')
        else:
            print('File: ' + name + ' already exists in ' + self.path)

download_location = raw_input(
    "Where would you like me to save the files? (e.g. ./ or ../ or ./themes/ or /path/to/folder): ")
if download_location and re.match(r'.+/$', download_location):
    if not os.path.exists(download_location):
        os.mkdir(download_location)
    crawler = Crawler('https://api.github.com/repos/daylerees/colour-schemes/contents/jetbrains',
                      download_location)
    crawler.crawl()
    print('\n\nAll done. Themes have been saved into ' + download_location +
          '. Thank you for your cooperation. Have a nice day.')
else:
    print('The path must end with a forward slash.')


texts: Removing repetitive code in ASP.NET MVC Controller actions?

texts:
I want to keep things DRY, so I'm trying to figure out: Is it possible to remove repetitive parameters and code from ASP.NET MVC Controller actions?  eg given these Actions:

public ActionResult List(string key, string signature) { GetSignature(key); // etc }
public ActionResult Add(string key, string signature) { GetSignature(key); // etc }
public ActionResult Update(string key, int id, string signature) { GetSignature(key, id.ToString()); // etc}
public ActionResult Delete(string key, int id, string signature) { GetSignature(key, id.ToString()); // etc}
public ActionResult Action1(string key, string x, string y, string z, string signature) { GetSignature(key, x, y, z);//etc}

Is there any way to refactor out the repetitive key and signature parameters, and the call to GetSignature()?

There are two obstacles to refactoring I can think of:

It's MVC so the Actions are the first port of call - it may not be possible to have a refactored method that is called before the Action.
The GetSignature() method is called using all of the Action's parameters, so it may be difficult to refactor.


texts: Static web server with a bit of error handling

texts:
I am looking for a review on this code, which is a simple static web server, with a small bit of error handling. It's feeling a bit "messy" / "imperative" at the moment, so advice would be welcome.

import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Network.Socket.ByteString
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString as B
import Data.List
import Control.Concurrent
import Control.Exception (SomeException, try)
import qualified Data.Map.Strict as Map
import System.FilePath.Posix
import System.Directory (doesFileExist)
import Text.Printf

port = 8080
incomingBufferSize = 16384
mimeTypes = Map.fromList [
    (".htm", "text/html"),
    (".html", "text/html"),
    (".js", "application/javascript"),
    (".css", "text/css"),
    (".png", "image/png"),
    (".jpg", "image/jpeg"),
    (".jpeg", "image/jpeg")
  ]
defaultMime = "application/octet-stream"
headerOkText = "HTTP/1.1 200 OK\r\nContent-Type: %s\r\n\r\n"
header404 = "HTTP/1.1 404\r\n\r\n"
header500 = "HTTP/1.1 500\r\n\r\n"

main = do
  sock <- socket AF_INET Stream 0
  setSocketOption sock ReuseAddr 1
  bind sock $ SockAddrInet port iNADDR_ANY
  listen sock sOMAXCONN
  mainLoop sock

mainLoop :: Socket -> IO ()
mainLoop sock = do
  (conn, _) <- accept sock
  forkIO $ handle conn
  mainLoop sock

handle :: Socket -> IO ()
handle conn = do
  incoming <- recv conn incomingBufferSize
  let unsafeLocation = extractLocation incoming
  if isSafeLocation unsafeLocation then
    do
      fileContents <- try $ response unsafeLocation
      send conn $ contentsOr500 fileContents
  else
    send conn $ C.pack header404
  close conn
  where
    extractLocation = C.unpack . C.tail . head . tail . C.split ' '
    isSafeLocation location = not $ ".." `isInfixOf` location

contentsOr500 :: Either SomeException B.ByteString -> B.ByteString
contentsOr500 (Left _) = C.pack header500
contentsOr500 (Right contents) = contents

response :: String -> IO (B.ByteString)
response requestedLocation = do
  exists <- doesFileExist requestedLocation
  if exists then
    do
      file <- B.readFile requestedLocation
      return $ fullResponse file $ takeExtension requestedLocation
    else
      return $ C.pack header404

fullResponse :: B.ByteString -> String -> B.ByteString
fullResponse contents extension = C.pack headerWithMime `B.append` contents
  where
    headerWithMime = printf headerOkText $ mimeForExtension extension
    mimeForExtension = flip (Map.findWithDefault defaultMime) mimeTypes


texts: Writing cleaner PHP code to add additional options

texts:
I have a contact form that will perform validation on the server. Right now the form checks if the fields are empty or not. My goal is to expand it following:

Check the fields for particular format, if it is a proper email format, phone number format, etc
Set the field as required or not

My form is as below, I appreciate any suggestions on how to clean it up and make it easier to adjust and overall cleaner.

<?php

ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");
error_log( "Errors" );

include "recaptcha.php";
include 'email.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'Exception.php';
require 'PHPMailer.php';
require 'SMTP.php';

$errors         = array();      // array to hold validation errors
$data           = array();         // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['firstName']))
        $errors['firstName'] = 'First Name is required.';

    if (empty($_POST['lastName']))
        $errors['lastName'] = 'Last Name is required.';

    if (empty($_POST['companyName']))
        $errors['companyName'] = 'Company Name is required.';

    if (empty($_POST['companyAddress']))
        $errors['companyAddress'] = 'Company Address is required.';

    if (empty($_POST['city']))
        $errors['city'] = 'City is required.';

    if (empty($_POST['state']))
        $errors['state'] = 'State is required.';

    if (empty($_POST['emailAddress']))
        $errors['emailAddress'] = 'Email Address is required.';

    if (empty($_POST['comment']))
        $errors['comment'] = 'Comment is required.';

    if (empty($_POST['g-recaptcha-response']))
        $errors['recaptcha'] = 'Captcha is required.';

// return a response ===========================================================

    // Check ReCaptcha Validation

    if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"]))
    {
        $errors['recaptcha'] = 'Captcha is required.';
    }

    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Success!';
    }

    // return all our data to an AJAX call
    echo json_encode($data);

//Begin of send email
$mail = new PHPMailer;

//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.server.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "user@server.com";
$mail->Password = "super_secret_password";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;

$mail->From = $emailAddress;

$mail->addAddress("name@server.com", "Recepient Name");

$mail->isHTML(true);

$mail->Subject = "Subject Text";
$mail->Body = $emailBody;

if(!$mail->send())
{
  $data['success'] = false;
  $data['errors']  =  "Mailer Error: " . $mail->ErrorInfo;
}
else
{
    $data['message'] = 'Success!';
}

?>


texts: Simplified light Serialize/Deserialize to/from JSON for .NET

texts:
Just a very simplified and stright-forward way of serialize/deserialize to/from JSON using standard .NET 4+ libs. I was trying to avoid "complexity", so get rid of 3rd part libs and heavy-infrastructured standard libs.

    #region JSON API

    public static string ObjectToJson(object o, Type t, Type[] pTypes = null)
    {
        DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));
        MemoryStream mStrm = new MemoryStream();
        serializer.WriteObject(mStrm, o);
        mStrm.Position = 0;
        using (var sr = new StreamReader(mStrm, Encoding.UTF8))
        {
            return sr.ReadToEnd();
        }
    }

    public static object JsonToObject(string json, Type t, Type[] pTypes = null)
    {
        DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            return serializer.ReadObject(stream);
        }
    }

    #endregion // JSON  API

And an example of its usage:

    public bool ListOfGames(bool pMyGames, bool pGamesITookPartIn)
    {
        this.GamesListInfo = null;
        this.LastErrorInfo = null;
        try
        {
            string formValues =
                "&playerId=" + this.LogonInfo.userId.ToString() +
                "&createdBy=" + pMyGames.ToString() +
                "&tookPartIn=" + pGamesITookPartIn.ToString() +
                "";

            WebRequest request = createRequest("myGamesList", formValues);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                string responseText = sr.ReadToEnd();

                if (responseText.Contains("\"errType\":"))
                    this.LastErrorInfo = (ErrorInfoContract)JsonToObject(responseText, typeof(ErrorInfoContract));
                else
                    this.GamesListInfo = (GamesListContract)JsonToObject(responseText, typeof(GamesListContract), new Type[] { typeof(GameInfoContract) });

                Trace.WriteLineIf(TrcLvl.TraceInfo, TrcLvl.TraceInfo ? string.Format("NewGame.ListOfGames: {0}{1}",
                    (this.LogonInfo != null ? this.LogonInfo.ToString() : ""), (this.LastErrorInfo != null ? this.LastErrorInfo.ToString() : "")) : "");
            }
        }
        catch (Exception exc)
        {
            this.LastErrorInfo = new ErrorInfoContract()
                {
                    errType = exc.GetType().ToString(),
                    message = exc.Message,
                    stackTrace = exc.StackTrace,
                    timestamp = StrUtils.NskTimestampOf(DateTime.Now)
                };
        }
        return (this.LogonInfo != null && this.LogonInfo.userId > 0 && this.LogonInfo.authKey > 0);
    }

    private WebRequest createRequest(string pAction, string pFormValues)
    {
        WebRequest request = WebRequest.Create(this.ServerUrl + "?action=" + pAction);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = pFormValues.Length;

        byte[] data = Encoding.UTF8.GetBytes(pFormValues);
        using (Stream strm = request.GetRequestStream())
        {
            strm.Write(data, 0, data.Length);
        }
        return request;
    }

Just searched where to publish a code and example (for some purposes).

I do not expect any inputs but if you would like to - welcome, would be appreciated. :)


texts:
Seeking code correctness and best practices.

I would like to re-allocate various amounts of memory (0 or more) such that on systems that may return NULL for an allocation of 0 does not falsely imply a memory allocation error.

Given:

void * (with a valid value or NULL already)
size_t (new desired size)

Receive:

void * (new pointer)
int (failure status)

#include <assert.h>
#include <stdlib.h>

int ReallocAndTest(char **Buf, size_t NewSize) {
  assert(Buf);
  char *NewBuf = realloc(*Buf, NewSize);
  if ((NewBuf == NULL) && (NewSize > 0)) {
    return 1;  // return failure
  }
  *Buf = NewBuf;
  return 0;
}

I came across the below references, which imply a realloc() return of NULL is not always a failure.  The lone special case occurs with size is 0.  The return value may or may not be NULL.

  C11dr 7.22.3.5 The realloc function 4 The realloc function returns a
  pointer to the new object (which may have the same value as a pointer
  to the old object), or a null pointer if the new object could not be
  allocated.

  C11dr §J.1 Unspecified behavior.  — The amount of storage allocated by
  a successful call to the calloc, malloc, or realloc function when 0
  bytes was requested (7.22.3).

  C11dr §J.3.12 Implementation-defined behavior.  Whether the calloc,
  malloc, and realloc functions return a null pointer or a pointer to an
  allocated object when the size requested is zero (7.22.3).

Discusses how a memory allocation of 0 is useful.
Answer: when a routine has a malloc(size), testing for size != 0 is not needed.
what's the point in malloc(0)?
Asks if realloc(ptr), 0) is the same as free(ptr).
Answer: Not necessarily.
What happens if I re-alloc and the new size is 0. Is this equivalent with a free?
Allocation wrapper set.
Answer: Does not address realloc(ptr, 0).
Are these memory-allocation wrapper functions kosher with all C compilers?

[Answer]

Use void* rather than char *.
With a 0 size, avoid returning the implementation defined
..a) NULL or
..b) ptr that cannot be referenced.
and return a pointer to insure only 1 of the 2 is ever returned.

On point #2, I only slightly favor returning NULL.


texts:
The goal is to create a Singleton and pass it a parameter that is required for the construction and initialization of the class, then preventing any changes to be made to the passed parameter (just like a readonly field being set by an argument passed to a constructor).

For instance:

Sockets
Hosts
Databases
Repositories
(Any instance that requires at least one argument in order to construct)

  I am having a tough time coming to terms with this design, and I am quite certain that there is a pitfall or a loose-end to this implementation of a Singleton combined with a Builder Pattern, to mimic readonly fields set by constructor arguments.

Example Implementation

In this example, I am trying to get a Singleton of Host, where I would like the enum EnvironmentTypes to be treated like a readonly field usually found in classes that have parameters passed into the constructor.

EnvironmentTypes Enum

public enum EnvironmentTypes
{
    Production,
    Staging,
    Development
}

IHost Interface

public interface IHost
{
    string Name { get; set; }
}

Host Class

public sealed class Host : IHost
{
    #region Singleton
    private static readonly Lazy<Host> _instance = new Lazy<Host>(() => new Host());
    public static Host Instance { get { return _instance.Value; } }
    #endregion

    private static bool _isInstantiated;
    private static EnvironmentTypes _environment;
    private string _name;

    internal static EnvironmentTypes Environment
    {
        get { return _environment; }
        internal set
        {
            if (_isInstantiated) throw new InvalidOperationException(nameof(_environment) +" cannot be set once an instance is created.");

            _environment = value;
        }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    static Host()
    {
        _isInstantiated = false;
        _environment = EnvironmentTypes.Production;
    }

    private Host()
    {
        _isInstantiated = true;
        _name = "My Server";
    }
}

HostBuilder Class

public sealed class HostBuilder
{
    private readonly EnvironmentTypes _environment;
    private string _name;

    public HostBuilder(EnvironmentTypes environment)
    {
        _environment = environment;
    }

    public HostBuilder SetName(string name)
    {
        _name = name;
        return this;
    }

    public IHost Build()
    {
        Host.Environment = _environment;
        Host host = Host.Instance;
        host.Name = _name;

        return host;
    }
}

Implementation

class Foo
{
    void UsingTheBuilder()
    {
        // probably over-kill
        HostBuilder builder = new HostBuilder(EnvironmentTypes.Development)
            .SetName("Bingo");

        IHost host = builder.Build();

        //host.Environment is not available, great!
        host.Name = "Renamed Server"; // works as expected.
    }

    void ManualConfiguration()
    {
        Host.Environment = EnvironmentTypes.Development;
        Host host = Host.Instance;
        host.Name = "Bingo";

        Host.Environment = EnvironmentTypes.Staging; // throws! Hoped to prevent
                                                     // the developer from doing this.
    }
}

Random Notes: It would be great if I could restrict access from getting to the static properties of Host, so that I can totally avoid anyone trying to set the Host.Environment static property and throwing an exception -- note how the HostBuilder shields that from happening as it is a readonly field.