texts:
Here is a simple working Java implementation of primality test for Fermat numbers. Is there something that I could change in code to achieve a better running time?

import java.math.BigInteger;

public class FPT
{
    public static void main(String[] args)
    {
        double n;
        n = Double.parseDouble(args[0]);

        int e = (int)n;

        if (e > 1)
        {
            double m = Math.pow(2,n);
            int k = (int)m;
            BigInteger F;
            F = BigInteger.valueOf(2).pow(k).add(BigInteger.ONE);
            BigInteger s = new BigInteger ("8");
            double o = 1;
            double a = n - o ;
            double b = Math.pow(2,a) - o;
            int c = (int)b;

            for (int i = 1; i <= c; i ++)
            {
                 s=s.pow(4).subtract(BigInteger.valueOf(4).multiply(s.pow(2))).add(BigInteger.valueOf(2)).mod(F);
            }

            if (s.equals(BigInteger.ZERO))
            {
                System.out.println("prime");
            }
            else
            {
                System.out.println("composite");
            }
        }
        else
        {
            System.out.println("exponent must be greater than one");
        }
    }
}


texts: I've started Tuples to LINQ and I'm not sure if it's an anti pattern

texts:
I have

public static class TupleExtensions {

    public static IEnumerable<T> SelectMany<T>(this IEnumerable<Tuple<T, T>> te)
    {
        foreach (var t in te)
        {
            yield return t.Item1;
            yield return t.Item2;
        }
    }

    public static IEnumerable<T> SelectMany<T, U>(this IEnumerable<U> source, Func<U, Tuple<T, T>> fn)
    {
        foreach (var s in source)
        {
            var t = fn(s);
            yield return t.Item1;
            yield return t.Item2;
        }

    }

    public static IEnumerable<T> SelectMany<T, U>(this IEnumerable<U> source, Func<U, Tuple<T, T, T>> fn)
    {
        foreach (var s in source)
        {
            var t = fn(s);
            yield return t.Item1;
            yield return t.Item2;
            yield return t.Item3;
        }

    }

    public static IEnumerable<T> SelectMany<T, U>(this IEnumerable<U> source, Func<U, Tuple<T, T, T,T>> fn)
    {
        foreach (var s in source)
        {
            var t = fn(s);
            yield return t.Item1;
            yield return t.Item2;
            yield return t.Item3;
            yield return t.Item4;
        }

    }
}

I can then do as a trivial example

IEnumerable<int> source = ...
source.SelectMany(i=>Tuple.Create(i, i+1, i+2))

Obviously the tuple must have the same types throughout. My use
case is where I have a mathematical solver which will always return
two solutions for a given input. Returning a list makes it unclear
how many solutions would be returned.

However in the end I would want all my solutions merged. For example

static Tuple<Point,Point> Intersect(this Shape shape, Line other);

Shape shape = ...
IEnumerable<Line> lines = ...

IEnumerable<Point> intersections = lines.SelectMany(line=>shape.Intersect(line));

Is there some good reason not to treat Tuple<T,T,T....> as a container that we can flatten?


texts: Send email from job queue, save status, acknowledge and log info

texts:
I'm writing code for a worker receiving message from a queue.

It should

send an email
save the fact that this email has been sent
acknowledge the job
log some info.

I wrote the following code, but I find it ugly!

Do you have some advice on how to refactor it ?

class MailWorker
  def initialize(logger, db, smtp)
      @logger = logger
      @db = db
      @smtp = smtp
  end

  def handle(message)
    start = Time.now.utc.to_f
    data = JSON.parse(message.body, symbolize_names: true)

    smtp_resp = send(data)
    save_as_sent(data[:id], smtp_resp['request_id'])
    message.delete

    @logger.info("Mail send #{data[:id]} start:#{start} spent:#{(Time.now.utc.to_f - start)}")

  rescue Aws::SQS::Errors::ServiceError, Smtp::Error => e
    @logger.error("Mail error for mail #{data[:id]} #{e.backtrace.join("\n")}")
  end

  private

  def send(data)
    @smtp.send(data[:to], data[:subject], data[:body])
  end

  def save_as_sent(id, request_id)
    @db.prepare('UPDATE Mail set request_id = ? WHERE id = ?')
    @db.execute(request_id, id)
  end
end


texts:
I have many html files saved to my computer.they have same  tags like this: Rpi-Cam-Web-Interface- Page 2 - forum
and the page number changes
I want to rename file to page number
I use this code:
import re
import os
pattern=re.compile('<title>RPi Cam Web Interface - Page \d*')
for i in os.listdir():
   parser=open(i,'r',encoding='utf-8')
   m=pattern.search(parser.read())
   parser.close()
   os.rename(i,m.group()[35:]+'html')

any better way?


texts:
I'm trying to determine best case round-trip times to a redis server. Particularly, I am trying to determine exactly how low I can get the latency on a local instance.
On a technical level, this is pretty easy. However, profiling is always a bit of a dark art, doubly so when network/IPC is involved.
Is this method reasonable?
Here's the numbers I am getting:
            localhost:6379:  92.42 µs  # local, bare metal on host tcp loopback
        /tmp/go/redis.sock:  49.08 µs  # local, bare metal on host unix socket
            localhost:6380: 276.26 µs  # local, docker networking

Which seems in line with my intuition.
    package main
    import (
        "context"
        "fmt"
        "github.com/go-redis/redis"
        "math"
        "strconv"
        "time"
    )

    var ctx = context.Background()

    func reduceMin(xs []float64) float64 {
        if len(xs) == 0 {
            return math.NaN()
        }
        if len(xs) == 1 {
            return xs[0]
        }
        best := math.Min(xs[0], xs[1])
        for _, v := range xs {
            best = math.Min(best, v)
        }
        return best
    }

    func runProfileN(rdb *redis.Client, N int, tries int) (timePer float64, countErrors int){
        var val string
        totalElapsed := time.Duration(0)

        for t := 0; t < tries; t++ {
            start := time.Now()
            for i := 0; i < N; i++ {

                //err := rdb.Set(ctx, "key", fmt.Sprintf("|%3d|val|%3d|", N, i), 0).Err()
                err := rdb.Set(ctx, "key", fmt.Sprintf("%d", i), 0).Err()
                if err != nil {
                    panic(err)
                }

                val, err = rdb.Get(ctx, "key").Result()
                if err != nil {
                    panic(err)
                }
                i2, err := strconv.Atoi(val)
                if err != nil {
                    panic(err)
                }
                if i != i2 {
                    countErrors++
                }
            }
            elapsed := time.Since(start)
            totalElapsed += elapsed
        }
        timePer = float64(totalElapsed.Microseconds()) / float64(N*tries)
        return
    }

    func runProfile(redisAddr string) float64 {
        rdb := redis.NewClient(&redis.Options{
            Addr:     redisAddr,
            Password: "", // no password set
            DB:       0,  // use default DB
        })
        iters := []int{3, 10, 33, 100, 333, 1000, 3333, 10000}
        times := make([]float64, 0)
        tries := 5
        for _, N := range iters {
            timePer, countErrors := runProfileN(rdb, N, tries)
            fmt.Printf("%8d: elapsed: %7.2f µs errors: %d\n", N, timePer, countErrors/tries)
            times = append(times, timePer)
        }
        best := reduceMin(times)
        fmt.Printf("\n %11s best: %7.2f µs \n", " ", best)
        return best
    }

    func main() {
        hosts := []string{"localhost:6379", "/tmp/go/redis.sock", "localhost:6380"}
        results := map[string]float64{}
        for _, redisAddr := range hosts {
            fmt.Println("client on ", redisAddr)
            results[redisAddr] = runProfile(redisAddr)
        }
        for _, redisAddr := range hosts {
            fmt.Printf("%30s: %5.2f µs\n", redisAddr, results[redisAddr])
        }
    }


texts:
I am currently writing code for a UART communication in my firmware. I am getting an interrupt every byte received (meaning I don't get a chunk of data, 1 byte at a time but, in the sample below I store them into a chunk of data for simulating my data parsing only).

I have a dynamic message length format, as shown in the code below. May I know what is the most efficient and elegant way to parse this message? I believe my current code could be further improved.

#include <stdint.h>

typedef struct {
    uint8_t header_DLE;
    uint16_t id;
    uint8_t msg_command;
    uint16_t msg_length;
    uint8_t data[400];
    uint8_t footer_DLE;
    uint8_t footer_BCC;
} Serial_Rx_Data;

Serial_Rx_Data _rx_data;
static int _rx_index;
static uint8_t _rawData[512];

int main()
{
    uint8_t data[18];

    //Message format
    data[0] = 0x10;     //DLE
    data[1] = 0x03;     //ID
    data[2] = 0;        //ID
    data[3] = 0x03;     //Command
    data[4] = 0x03;     //Length - determines the data length
    data[5] = 0;        //Length
    data[6] = 0x41;     //Data
    data[7] = 0x42;     //Data
    data[8] = 0x43;     //Data
    data[9] = 0x03;     //DLE
    data[10] = 0xfa;    //BCC

    //Simulate getting data every byte
    for (int i = 0; i <= 10; i++) {
        _rawData[_rx_index] = data[i];

        if (_rx_index == 5) {
            _rx_data.header_DLE = _rawData[0];
            _rx_data.id = _rawData[2] << 8 | _rawData[1];
            _rx_data.msg_command = _rawData[3];
            _rx_data.msg_length = _rawData[5] << 8 | _rawData[4];
        }

        //Get the length of data
        if ((_rx_index == 6) && (_rx_data.msg_length > 0)) {
            for (int j = 0; j < _rx_data.msg_length; j++) {
                _rx_data.data[j] = _rawData[6 + j];
            }
        }

        //Get the last 2 byte
        if (_rx_index == (_rx_data.msg_length + 6 + 1)) {
            _rx_data.footer_DLE = _rawData[6 + _rx_data.msg_length];
            _rx_data.footer_BCC = _rawData[6 + _rx_data.msg_length + 1];

            //Complete parsing
            //Callback to other function
        }

        _rx_index++;
    }

    return 0;
}


texts: Using multimap to match data from a stream

texts:
I am using a multimap to match requests with their pair as soon as I get them. Order matters because it's "first come first serve". However, I don't know if multimap is the optimal approach to this problem.

// Multimap insertion:
function insert(map, key, value) {
  //:=> check positive dipole in Map.
  let values = map.get(key);
  //:=> If array results :=> push item into selected postive dipole array queue.
  if (values) values.push(value);
  // else dipole does not exist
  //:=>hash dipole && set to current iteration
  else map.set(key, [value]);
}

// Multimap retrieval:
function retrieve(map, key) {
  let values = map.get(key);
  //:=> If values results from lookup
  if (values) {
    //:=> remove last to list and first to matching object in array
    let value = values.pop();
    //if empty :=> remove negative identifying dipole hash
    if (values.length === 0) map.delete(key);
    //:=> return last matching object from array
    return value;
  }
}

// Match items with first identical match:
function* match(items, identity, match, remaining) {
  for (let item of items) {
    //:=> negative dipole hashed key compliment (all passengers)
    let candidate = retrieve(remaining, match(item));
     //:=> on matching iteration retirve matching dipole
    //:=> on yield couple iterated value with last array value
    // from matching hash
    if (candidate) yield [item, candidate];
    //:=> round-robin retrieve with insert
    else insert(remaining, identity(item), item);
  }
}

// Example:
let items = [{
  type: 'driver',
  direction: 'east',
  time: '9:15',
  name: ['Archibald Trump']
}, {
  type: 'passenger',
  direction: 'east',
  time: '9:15',
  name: ['Bacon Eater']
}, {
  type: 'passenger',
  direction: 'east',
  time: '9:15',
  name: ['Banjo Barney']
}, {
  type: 'passenger',
  direction: 'east',
  time: '9:15',
  name: ['Flimsy Stick']
}, {
  type: 'passenger',
  direction: 'west',
  time: '9:30',
  name: ['Big Red']
}, {
  type: 'passenger',
  direction: 'west',
  time: '9:35',
  name: ['Hathaway Anne']
}];

let remaining = new Map();
let pairs = match(
  items,
  item => '' + (item.type == 'driver') + item.direction + item.time,
  item => '' + (item.type == 'passenger') + item.direction + item.time,
  remaining
);

console.log('pairs',...pairs);
console.log('remaining',[...remaining.values()].reduceRight((a,b)=>a.concat(b)));
.as-console-wrapper { max-height: 100% !important; top: 0; }


texts:
I found myself with a list of UTC timestamps and wanted to convert them into the local time zone.  Using this web post as a starting point, I modified the script to grab a text file containing UTC times (one per line) and loop over each one outputting the results in a nice two column format.

Is there a more efficient method for accomplishing this?  I've seen people mention the .NET method $UTC.ToLocalTime() but I didn't find details on that, so I went with my frankenstein script.

$UTCTime = GC "C:\Scripts\UTC.txt"
$results = '' | Select UTCTime,PST
Foreach ($newtime in $UTCTime){
$strCurrentTimeZone = (Get-WmiObject win32_timezone).StandardName
$TZ = [System.TimeZoneInfo]::FindSystemTimeZoneById($strCurrentTimeZone)
$LocalTime = [System.TimeZoneInfo]::ConvertTimeFromUtc($newtime, $TZ)
$results.UTCTime = $newtime
$results.PST = $LocalTime
 $results
}

Input is: (and powershell might be flexible enough to handle various input formatting, more testing is needed to determine this)

4/19/2015 4:10:03 AM
4/19/2015 9:10:03 AM

Output is:

UTCTime               PST
-------               ---
4/19/2015 4:10:03 AM  4/18/2015 9:10:03 PM
4/19/2015 9:10:03 AM  4/19/2015 2:10:03 AM


texts:
I have been trying to implement the Hash Table function in Java and here is what I came up with. I would just like to get an opinion on this work. Would there be a better way or any improvement to make to this code ?

HashTable.java : basically contains all the hastable functions to create the table, add a node and retrieve a node

import java.math.BigInteger;

public class HashMap {
      // Srtting table size to a max of 32, value used to modulus for hash value.
      private final static int TABLE_SIZE = 32;

      HashEntry[] table;

      HashMap() {
            table = new HashEntry[TABLE_SIZE];
            for (int i = 0; i < TABLE_SIZE; i++)
                  table[i] = null;
      }

      /* function to retrieve value from the table according to key */
      public int get(String key) {
            int hash = new BigInteger(toAscii(key)).mod(new BigInteger(((Integer)TABLE_SIZE).toString())).intValue();
            while (table[hash] != null && table[hash].getKey() != key)
                  hash = (hash + 1) % TABLE_SIZE;
            if (table[hash] == null)
                  return -1;
            else
                  return table[hash].getValue();
      }

      /* function to add value to the table */
      public void put(String key, int value) {
            //creating hash code using key value given as a string
            int hash = new BigInteger(toAscii(key)).mod(new BigInteger(((Integer)TABLE_SIZE).toString())).intValue();
            while (table[hash] != null && table[hash].getKey() != key)
                  hash = (hash + 1) % TABLE_SIZE;
            table[hash] = new HashEntry(key, value);
      }

      /* value to create the Hash code from he name entered, basically converting name to ASCII */
      public static String toAscii(String s){
          StringBuilder sb = new StringBuilder();
          long asciiInt;
          // loop through all values in the string, including blanks
          for (int i = 0; i < s.length(); i++){
              //getting Ascii value of character and adding it to the string.
              char c = s.charAt(i);
              asciiInt = (int)c;
              sb.append(asciiInt);
          }
          return String.valueOf(sb);
  }
}

HashEntry.java: an object taking the entry contains setter and getters

public class HashEntry {
      private String key;
      private int value;

      HashEntry(String key, int value) {
            this.key = key;
            this.value = value;
      }

      public String getKey() {
            return key;
      }

      public int getValue() {
            return value;
      }
}

HasheTable.java: just testing my implementation

import java.io.IOException;

public class HashTable {
    public static void main(String[] args) throws IOException
    {
        HashMap entry = new HashMap();
        entry.put("Wasif", 36100);
        entry.put("Stephen Hughes", 22100);
        System.out.println(entry.get("Stephen Hughes"));
    }
}


texts:
Assume that we have a .txt file that has one word per line.
Find out the word that occurs the most.

Here's what I was able to write (I used array of strings instead of a file in this example):

string[] source = { "test1", "test2", "test3", "test4", "test1", "test1", "test3" };
Dictionary<string, int> dic = source.Distinct().ToDictionary(p => p, p => 0);
var keys = new List<string>(dic.Keys);
foreach (string key in keys)
{
  dic[key]=source.Count(f => f == key);
}
int max = dic.Values.Max();
foreach (KeyValuePair<string, int> kvp in dic)
{
    if (kvp.Value == max)
    {
        Console.WriteLine(kvp.Key + " " + max);
        break;
    }
}

Questions:

Can this be done better and more efficient way (speed/ memory)?
What if file size is 10GB. How would you do it differently from my approach?


texts: Parsing root-level elements out of HTML fragment file

texts:
I have the following code written in NodeJS, using the parse5 library. It's purpose is to parse out the root-level elements in a file containing HTML fragments (Vue component files). I want the inner content of these root-level elements to remain unchanged.

I attempted several times to use cheerio/htmlparser2/parse5 to parse the file as HTML, but always with some sort of undesirable side-effect to the inner content of the root-level elements.

Finally, I decided to make an attempt at some custom parsing (but not from scratch, because that would be stupid, hence using the SAXParser in parse5. Right now it handles a few hundred test cases, but I'm afraid there are plenty more edge cases that are going to come back and bite me.

Can anyone here see any pitfalls with this code? Is there a simpler way of accomplishing this that's more robust?

var parse5 = require("parse5")

const parse = module.exports = (str) => {
  const parser = new parse5.SAXParser({ locationInfo: true })
  const elements = []
  let current = null
  parser.on('startTag', (name, attrs, selfClosing, location) => {
    const tag = { name, attrs, openingTag: location, count: 0 }
    if(current){
      if(current.name === tag.name) current.count++
      return
    }
    current = tag
  })
  parser.on('endTag', (name, location)=>{
    const tag = { name, location }
    if(!current || current.name !== tag.name) return
    if(current.count > 0) current.count--
    else{
      current.closingTag = tag.location
      elements.push(current)
      current = null
    }
  })
  parser.end(str)
  return elements.map((element)=>{
    delete element.count
    const attrs = {}
    element.attrs.forEach((attr)=>{
      attrs[attr.name] = attr.value !== '' ? attr.value : true
    })
    element.attrs = attrs
    element.content = str.substring(element.openingTag.endOffset, element.closingTag.startOffset)
    return element
  })
}

Here is an example (vue component) HTML file:

<template>

Hello World!

Lorem ipsum

</template>


texts: Java Apache Commons Net SMTP Wrapper Attachment

texts:
Can the below code be improved? Are there any major issues with it?
Thanks

Writer w = client.sendMessageData();
for (File file : myAttachments) {
    w.append("\r\n").append("--").append(bound).append("\r\n");
    w.append("Content-Type: application/octet-stream\r\n");
    w.append("Content-Transfer-Encoding: base64\r\n");
    w.append("Content-Disposition: attachment; filename=\"" + Tools.getNameForAttach(file.getName()) + "\"\r\n\r\n");
    FileInputStream fileInputStream = new FileInputStream(file);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;
    byte[] data = new byte[1024];

    while ((nRead = fileInputStream.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();

    fileInputStream.close();

    w.append(Base64.encodeBase64String(buffer.toByteArray()));
    w.append("\r\n");

}
w.close();


texts: Leetcode Finding Maximum Area of Island Solution

texts:
Given a non-empty 2D array grid of 0's and 1's, an island is a group
  of 1's (representing land) connected 4-directionally (horizontal or
  vertical.) You may assume all four edges of the grid are surrounded by
  water.  (LeetCode)

This is my code

int maxAreaOfIsland(vector<vector<int>>& grid) {
    int max_area = 0;
    int rows = grid.size();
    int columns = grid[0].size();
    vector<vector<bool>> visited(rows, vector<bool>(columns,false));

    for(int i=0 ; i < rows ; ++i){
        for(int j=0; j < columns ; ++j){
            max_area = max(max_area, area(i,j,grid,visited));
        }
    }
    return max_area;
}

int area(int row, int col, vector<vector<int>>& grid, vector<vector<bool>>& visited){
    if(row < 0 || row >= grid.size() || col < 0 || col >= grid[row].size() || visited[row][col]==true || grid[row][col] == 0)
        return 0;

    visited[row][col] = true;
    return (1 + area(row-1,col,grid,visited) + area(row,col-1,grid,visited) + area(row+1,col,grid,visited) + area(row,col+1,grid,visited));
}

It was accepted on LeetCode and worked for all test cases.  As you can see, the readability of the code is not good, so I am looking for a Code Review:

How can I improve readability in if() construct and return in area function?
Is there a better way to initialize 2D Vector in C++?
Is there a better way to maintain the visited array? I had to pass that array in every function call. If this data member is declared as as a static data member of the class then can its passing in every recursive call be avoided?


texts: Python Simple Range and Bearing Calculator using Complex Numbers

texts:
I have just written this code that takes an initial coordinate and returns a new vector depending on a user-supplied range and bearing.
The calculation of the new position is done using Complex Numbers. I am sure there are easier ways to do this, but I wanted to play around with complex numbers. Any thoughts on these would be great.
The calculator is in a file called GenGeo, as this is where I keep lots of little modules like this that may be called again in other programs.
I have used **kwargs for a_e and a_n as these may not be required by the user. However, I have never really used *args and **kwargs before, so presume that I may have messed something up here.
This is the calculator module in GenGeo:
class CmO:
    """
    This class will contain specific code that is required to run a C-O calculation
    This includes range and bearing calc
    """

    def __init__(self, *args, **kwargs):
        """
        :param a_e: initial easting
        :param a_n: initial northing
        """
        self.a_e = kwargs.get('a_e', None)
        self.a_n = kwargs.get('a_n', None)

    def complex_randb(self, r, b):
        """
        An equation that using imaginary numbers to calculate the coordinates of a new
        point from a range and bearing of an old point
        :param r: range from original coordinate to new coordinate
        :param b: bearing from original coordinate to new coordinate
        """

        # -b is required as geodetic bearings are opposite to mathematical bearings
        t = complex(cos(radians(-b)), sin(radians(-b))) * complex(0, r)
        delta_easting = t.real
        delta_northing = t.imag

        if self.a_e and self.a_n is not False:

            new_easting = self.a_e + delta_easting
            new_northing = self.a_n + delta_northing

            return new_easting, new_northing

        else:
            return delta_easting, delta_northing

and this is the program that I have used to call it:
from GenGeo import CmO

initial_E = 100
initial_N = 100
input_range = 3
input_bearing = 310

a = CmO(a_e=initial_E, a_n=initial_N)
nE, nN = a.complex_randb(input_range, input_bearing)

print(f"The delta Easting and Northing are {round(nE, 3)}mE and {round(nN, 3)}mN")

Next project is writing something to calculate the range and bearing between two points
Any thoughts or improvements would be greatly appreciated!


texts: Decrease execution time in updating rows in PHP

texts:
Any tips on how the below code can be optimised for faster execution?

I have a table in postgres called staging with the below columns;

|person|colour|sport|
|Tom   |blue  |Tennis|

and a multi dimensional associative array that contains updates for each entry of the staging table, like so:

$updateArray =  array();
$updateArray['Tom']['color']='orange';
$updateArray['Tom']['sport']='golf';

I need to loop through the updateArray and update the entries of the staging data.

Here is what I have so far, where result2 is a query to select all the rows from the staging table. For each row returned I am looping through every entry of the updateArray, and then checking if it exists as one of the keys.

while ($row2 = pg_fetch_assoc($result2))
        {
            foreach ($array as $key => $value)
            {
                if ($key == $row2['person'])
                {
                    foreach ($value as $column_name => $column_value)
                    {
                        $row2[$column_name] = $column_value;
                    }
                }

            }
            fputcsv($fp, $row2);
        }

The above example is a simplified one, I need to update about 120,000 people and about 700 columns for each person multiple times so I am trying to get the above code more efficient.


texts: Provide functional-programming style solution for 2D Array - DS challenge

texts:
Problem Statement:

  Given a 6×6 2D Array, arr:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

  We define an hourglass in A to be a subset of values with indices
  falling in this pattern in arr's graphical representation:

a b c
  d
e f g

  There are 16 hourglasses in arr, and an hourglass sum is the
  sum of an hourglass' values. Calculate the hourglass sum for every
  hourglass in arr, then print the maximum hourglass sum.

  For example, given the 2D array:

-9 -9 -9  1 1 1
 0 -9  0  4 3 2
-9 -9 -9  1 2 3
 0  0  8  6 6 0
 0  0  0 -2 0 0
 0  0  1  2 4 0

  We calculate the following 16 hourglass values:

-63, -34, -9, 12,
-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18

  Our highest hourglass value is 28 from the hourglass:

0 4 3
  1
8 6 6

  Note: If you have already solved the Java domain's Java 2D Array
  challenge, you may wish to skip this challenge.

  Function Description

  Complete the function hourglassSum in the editor below. It should
  return an integer, the maximum hourglass sum in the array.

  hourglassSum has the following parameter(s):

  arr: an array of integers

  Sample Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

  Sample Output

19

  Explanation

  arr contains the following hourglasses: ![enter image
  description here]2 The hourglass with the maximum sum (19) is:

2 4 4
  2
1 2 4

Following is my imperative style Solution:

def hourglassSum(arr: Array[Array[Int]]): Int = {
  def sum(rowNumber: Int, columnNumber: Int): Int = {
    var oneHourglassSum = 0
    for {
      i <- 0 to 2
      j <- 0 to 2
    } yield {
      val cumulativeSum = if (i == 1 && (j == 0 || j == 2)) 0
      else arr(i + rowNumber)(j + columnNumber)
      oneHourglassSum += cumulativeSum
    }
    oneHourglassSum
  }

  def max(x: Int, y: Int): Int = if (x > y) x else y

  var hourglassMaxSum = 0
  for {
    rowOffset <- 0 to 3
    columnOffset <- 0 to 3
  } yield {
    hourglassMaxSum = max(sum(rowOffset, columnOffset), hourglassMaxSum)
  }
  hourglassMaxSum
}


texts:
I am trying to find a way to convert printable data types into a string in the fastest way possible.

I originally read that a static variable of stringstream that does all of the formatting is one of the fastest ways, since constantly constructing temporary variables of stringstream is slow.

The problem with using stringstream.str() is because it creates a copy of the entire string, which may lead to performance issues, so I made this function to get rid of the need of stringstream.str().

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

#define ALL(c) (c).begin(), (c).end()

stringstream str_buffer;

string extract()
{
    streambuf& buffer = *str_buffer.rdbuf();
    vector<char> sequence(str_buffer.tellp());
    buffer.sgetn(sequence.data(), str_buffer.tellp());

    str_buffer.seekp(0);
    buffer.pubseekpos(0);
    return string(ALL(sequence));
}

To use this function, just do str_buffer << var; string as_str = extract(); to get var as a string.

However, I have not yet compared timing benchmark results of this function and simply using stringstream.str(), so I hope that my function is faster if it is in theory. Any suggestions to further improve?


texts: Retrieve and cache web SPI results, then display on page

texts:
I'm writing some code to return results from a web service and display them on screen. If the service is down I want to use Lawnchair to serve cached results.

Test

Click to load!

<button class="btn" type="button" onclick="loadData()">Load</button>

@section scripts{

}

As you can probably tell I'm very new to JavaScript and concepts of variable scope and callback functions.

I'd like some general JavaScript feedback but more specifically how to avoid globals. I understand they're evil in every language but do they seem to be unavoidable here?

While this code works and retrieves data, the approach to getting the data from my Lawnchair cache seems wrong. Is there a better way than in the method retrieveFromStore()?


texts: Listing my StackEchange communities user id

texts:
Extending this answer solution, I've wrote the following bash script to get the html of my StackExchange accounts page and parse it to a YAML file. The objective was list for each community I participate its url and my user id.

get-stackexchange-info.sh

#!/bash/bin

NETWORK_PROFILE_URL=$1 # https://stackexchange.com/users/3581081/artu-hnrq
read -r ID USER <<< \
    $( cut -d'/' -f5,6 <<< $NETWORK_PROFILE_URL \
        | sed 's/\// /g' \
    )

OUTPUT_FILE=stackexchange.yml

echo \
"user: $USER
stackexchange:
  url: http://stackexchange.com
  id: $ID" \
> $OUTPUT_FILE

parse(){
    local HTTPS="https:\/\/"
    local COMMUNITY="[^\.]*"
    local DOMAIN="[^\/]*"
    local PROFILE_ID="\d*"

    local MODEL="\1:\n  url: $HTTPS\1\2\n  id: \3"

    sed -E "s/($COMMUNITY)($DOMAIN)\/($PROFILE_ID)/$MODEL/"
}

curl "https://stackexchange.com/users/$ID/$USER?tab=accounts" \
    | grep "account-container" -A1 \
    | grep "http" \
    | cut -d"/" -f3,5 \ # stackoverflow.com/3581081
    | parse \
    >> $OUTPUT_FILE

I would like to receive some opinions about the parse process (usage of grep, cut and sed commands) and about control flow management could be improved to the script

output example:

user: artu-hnrq
stackexchange:
  url: https://stackexchange.com
  id: 3581081
askubuntu:
  url: https://askubuntu.com
  id: 689894
stackoverflow:
  url: https://stackoverflow.com
  id: 2989289
codereview:
  url: https://codereview.stackexchange.com
  id: 213097

Thanks a lot!


texts:
Purpose

Implement a Stack with push, pop, and peek methods.

The push method should add an element to the "top" of the Stack.
The pop method should remove the "top" element from the Stack.
The peek method should return the "top" element of the Stack.

Approach

I decided to create a Node class to represent the elements in a Stack. The Node class would have a data field
and a previous field that would reference another Node. By having this previous field one can "chain" Nodes together.

For my Stack class, I decided to set the head (i.e. the Node at the "top" of the Stack) value to null on initialization.
I also decided to throw Exceptions when calling peek or pop for an empty Stack (i.e. when the head value is null).

I could see an argument to not throw Exceptions but rather return null for peek or nothing for pop (since it's void).
However, null is a valid value for an Object, and since a Stack is made up of Objects, I think returning
null when calling peek for an empty Stack could be confusing.

public class Node<T> {
  T data;
  Node<T> previous;

  public Node(T data, Node<T> previous) {
    this.data = data;
    this.previous = previous;
  }

  public T getData() {
    return data;
  }

  public Node<T> getPrevious() {
    return previous;
  }
}

public class Stack<T> {
  Node<T> head = null;

  public Stack() {
  }

  public T peek() {
    if (this.head == null) {
      throw new RuntimeException("Unable to peek element for an empty stack");
    }

    return this.head.getData();
  }

  public void push(T data) {
    this.head = new Node<>(data, this.head);
  }

  public void pop() {
    if (this.head == null) {
      throw new RuntimeException("Unable to remove element from an empty stack");
    }

    this.head = this.head.getPrevious();
  }


texts:
Here's my code for the Egyptian fraction written in Python. I need your feedback if there is any room for improvement.

def eg_fr(n, d):
    ls = []
    ls_str = []
    fraction = n / d
    total = 0
    for i in range(1, 1000):
        ls.append((1/i, str(1) + '/' + str(i)))
    for i in ls:
        while i[0] + total <= fraction:
            ls_str.append(i[1])
            total += i[0]
            if total >= fraction:
                break
    print('%s/%s = ' % (n, d), end='')
    for i in range(len(ls_str) - 1):
        print('', ls_str[i], '+ ', end='')
    print(ls_str[-1], end='')
    return ls_str

if __name__ == '__main__':
    eg_fr(7, 133)


texts: Is there a better way to write these two nested loops in Erlang?

texts:
Since one month, I'm learning Erlang and I like it so much.
Today, I wrote an algorithm to solve a problem.
Some time ago, I used two nested for loops in C# to solve it but, solving the same problem in Erlang, I asked myself if there is a better way to write something similar to the two nested for loops I used before.

Let's say that the two nested for loops in C# are:

for(int i = 100; i<=999;i++)
    {
        for(int j = 100;j<=999;j++)
        {
            int prod = i*j;
              //some logic here..
        }
    }

and the respective code in Erlang is the following:

loopINumber(_,LowerLim,UpperLim,Product) when LowerLim > UpperLim -> {Product};

loopINumber(ILimit,LowerLim,UpperLim,Product) ->
    Product = loopJNumber(ILimit,UpperLim,LowerLim,Product),
    loopINumber(ILimit,LowerLim+1,UpperLim,Product).

loopJNumber(LowerLim,UpperLim,_,Product) when LowerLim > UpperLim -> Product;

loopJNumber(LowerLim,UpperLim,ILimit,Product) ->
    Product = ILimit * LowerLim,
    %% some logic here..
    loopJNumber(LowerLim+1,UpperLim,ILimit,Product).

start(ILimit,JLimit) -> loopINumber(ILimit,ILimit,JLimit,0).

I know that maybe there's something to improve. Being still a beginner in functional languages, most probably I'm still coding in a "sequential" or OOP way. How can I improve this Erlang code?


texts:
I have the following assignment:

  A program that takes four (4) inputs then using a conditional
  statement does the following:

  Display the values that are below or equal to 25.
  Multiply the values that are below 20 with each other.
  Add the values that are above 25 with each other.

I've successfully solved all of them as they're pretty easy, however I want to ask a couple of things along with getting feedback from you.

I know that using less variables is always a better choice if you can do it, it might not matter on such small scale projects but I believe it's useful to get in the habit head-on. So in this specific example code, can I use a single var instead of 4 different ones? I know I can for the second and third tasks, however what about the third? Can I still list the inputs that are less than or equal to 25?
What tips do you have to make the code readable and even more easy to understand?

Also keep in mind that using loops, arrays, functions ... is not allowed so I would be glad if we keep our discussion limited to conditionals only.

#include "stdafx.h"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    float val1, val2, val3, val4;
    float sum = 0, multiply = 1;

    cout << "Enter the first number: ";
    cin >> val1;
    if(val1 < 20) {
        multiply *= val1;
    } else if(val1 > 25) {
        sum += val1;
    }

    cout << "Enter the second number: ";
    cin >> val2;
    if(val2 < 20) {
        multiply *= val2;
    } else if(val2 > 25) {
        sum += val2;
    }

    cout << "Enter the third number: ";
    cin >> val3;
    if(val3 < 20) {
        multiply *= val3;
    } else if(val1 > 25) {
        sum += val3;
    }

    cout << "Enter the fourth number: ";
    cin >> val4;
    if(val4 < 20) {
        multiply *= val4;
    } else if(val4 > 25) {
        sum += val4;
    }

    if(val1 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val1 << endl;
    if(val2 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val2 << endl;
    if(val3 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val3 << endl;
    if(val4 <= 25) cout << "The number(s) below or equal to 25 are/is: " << val4 << endl;

    cout << "When we multiply the numbers below 20 we get: " << multiply << endl;
    cout << "When we add the numbers above 25 we get: " << sum << endl;

    return 0;
}


texts: Improving performance of VBA data validation script in Access with large data size

texts:
I work in IT compliance and one of my main duties is ensuring the integrity of employee network accounts. Partial VBA script as currently used is shown below:

Public Function validateHireDate(hireDate as String)

    If Not IsDate(hireDate) Or IsNull(hireDate) Then
        validateHireDate = "Invalid hire date"
    Else
        validateHireDate = "Hire date reviewed"
    End if
End Function

Public Function validateEmployeeManager(employeeStatus as String, employeeManager as String)

    If employeeStatus <> "Active" Then
        Exit Function
    Else
        If IsNull(employeeManager) Then
            validateEmployeeManager = "Invalid employee manager"
        Else
            validateEmployeeManager = "Employee manager reviewed"
        End If
    End If
End Function

Given that the size of the database is around 50K of records, the above code works but is slow. There are several more validation functions such as for social security numbers, email, and user account control (disabled or enabled) depending on multiple criteria. Presently, the source data report is run bimonthly from which I import the results into Microsoft Access for auditing.

Is there a more efficient manner in which the validation can be done?


texts: Checking login from associative array vulnerabilities

texts:
For a very simple databaseless website, I'm using an associative array to store logins like this:

$logins = array(
'user' => 'password',
'user2' => 'password2',
);

I check login attemps using this code:

$user = strtolower($_POST['username']);
$pass = $_POST['password'];
if(!isset($logins[$user]) or $logins[$user] != $pass){
    // failed login
}else{
    $_SESSION['username'] = $user;
}

What would the security vulnerabilities in this be?


texts:
I'm nowhere near a PHP expert, but I have dabbled a bit. I can make things work just fine, but I am terrible at figuring out what is wrong. I was informed by our server admin that we have a mail script that is being abused, and I am unsure of how to remedy the issue.

I am looking for help to see how someone is using this form to send out spam mail. The issue is that we got a bounce-back email sent from an address that doesn't exist to a hotmail address using this form. As far as I know, this form ONLY sends email to the $recipient which is neither this non-existent email or this Hotmail. I am trying to figure out a way to secure this form so that individuals cannot abuse this form and send mail to others through it.

<?php
$name = check_input($_POST['name'],"Enter your name.");
$email = check_input($_POST['email'],"Email address is required.");
$company = check_input($_POST['company']);
$phone = check_input($_POST['phone']);
$message = check_input($_POST['message'],"Please don't send us a blank message! Let us know what you're thinking.");

if (!preg_match("/([\w\-]+\@[\w\-]+.[\w\-]+)/",$email))
{
    show_error("E-mail address is not valid.");
}

$messageBody ="Hello!

Your contact form has been submitted by:

Name: $name
E-mail: $email
Company: $company
Phone: $phone

Message:
$message

End of message
";

$recipient = "someone@example.com"; // removed real email for SE
$subject = "[Contact Form - Site Name]"; // removed site name for SE

$mailheaders = "From: someone@example.com\n"; // removed real email for SE
$mailheaders .= "Reply-To:". $_POST['email']."\n\n";

mail($recipient, $subject, $messageBody, $mailheaders);

header('Location: http://www.example.com/contact/thankyou.html'); //removed real address for SE
exit();

function check_input($data, $problem='')
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    if ($problem && strlen($data) == 0)
    {
        show_error($problem);
    }
    return $data;
}

function show_error($mailError)
{
?>
// error message in here, removed for SE as unrelated to problem
<?php
exit();
}
?>

This is the message my server admin sent me:

-----Original Message-----
From: MAILER-DAEMON@ss2.site-hosts.com
[mailto:MAILER-DAEMON@ss2.site-hosts.com]
Sent: Monday, August 04, 2014 2:47 PM
To: anonymous@ssasi.site-hosts.com
Subject: failure notice

Hi. This is the qmail-send program at ss2.site-hosts.com.
I'm afraid I wasn't able to deliver your message to the following addresses.
This is a permanent error; I've given up. Sorry it didn't work out.

<wsinwjfjqxv@hotmail.com>:
65.55.37.104 does not like recipient.
Remote host said: 550 Requested action not taken: mailbox unavailable Giving up on 65.55.37.104.

--- Below this line is a copy of the message.

Return-Path: <anonymous@ssasi.site-hosts.com>
Received: (qmail 6348 invoked by uid 2523); 4 Aug 2014 14:47:01 -0500
X-Qmail-Scanner-Diagnostics: from
199.192.201.219.rdns.continuumdatacenters.com by ss2.site-hosts.com (envelope-from <anonymous@ssasi.site-hosts.com>, uid 2020) with qmail-scanner-2.10st
 (clamdscan: 0.98.4/19261. mhr: 1.0. spamassassin: 3.3.2. perlscan:
2.10st.
 Clear:RC:1(199.192.201.219):.
 Processed in 0.024127 secs); 04 Aug 2014 19:47:01 -0000
Received: from 199.192.201.219.rdns.continuumdatacenters.com (HELO
ssasi.site-hosts.com) (199.192.201.219)
  by ss2.site-hosts.com with ESMTPA; 4 Aug 2014 14:47:01 -0500
Received: (qmail 15903 invoked by uid 10024); 4 Aug 2014 14:47:00 -0500
X-Qmail-Scanner-Diagnostics: from  by ssasi.site-hosts.com (envelope-from <anonymous@ssasi.site-hosts.com>, uid 48) with qmail-scanner-2.10st
 (clamdscan: 0.98.4/19261. mhr: 1.0. spamassassin: 3.3.2. perlscan:
2.10st.
 Clear:RC:1(127.0.0.1):.
 Processed in 0.013521 secs); 04 Aug 2014 19:47:00 -0000
Date: 4 Aug 2014 14:47:00 -0500
Message-ID: <20140804194700.15894.qmail@ssasi.site-hosts.com>
From: anonymous@ssasi.site-hosts.com
To: wsinwjfjqxv@hotmail.com
Subject:
X-PHP-Originating-Script: 10021:vnbMail.php


texts: Check for whether a string contains any duplicate characters

texts:
I am a new programmer and I want to know if I'm inheriting the right styles. I don't want to pick up any bad/amateur habits. Any advice would be much appreciated.

This is an isUnique function I wrote in C.

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

int main()
{
    int x;
    char s1[] = "dog hi cobe!";
    x = isUnique(s1);
    printf("%d", x);
    return 0;
}

isUnique(char* s1)
{
    char holder;
    int i;
    int j;

    if(s1 == NULL)
        return -1;

    for(i = 0; i < (strlen(s1) -1); i++)
    {
        holder = s1[i];
        for(j = i; j < (strlen(s1)-1); j++)
        {
            if(holder == s1[j+1])
            {
                if(holder == ' ')
                    continue;
                else
                    return 0;
            }
        }
    }
    return 1;
}

And I'm going to say the run time complexity is \$O(n^2)\$, would I be correct?


texts:
I have this code:

for (int i = 0; i < lst.Count(); i++)
{
    lst[i].ColumnOrder = (short)i;
}

But I was trying to find a way to do it via LINQ or something else with better performance. I'm pretty sure that there are better ways to change the sequence of a column.  I use this code in a drag & drop context.


texts:
I am working my way into learning a bit of Scheme (actually, Racket) with the help of a few practical problems to solve. In this case, I want to split a flat list of symbols at a certain delimiter symbol, discarding it and returning the list of split chunks.

#! /usr/bin/racket

#lang racket

(define (split lst del)
    (define (split-one lst)
        (if (or (empty? lst) (equal? (car lst) del))
            '()
            (cons (car lst) (split-one (cdr lst)))))
    (let loop ((next lst))
        (if (empty? next)
            '()
            (let ((cur (split-one next)))
                (cons
                    cur
                    (loop (let ((nextpos (+ 1 (length cur))))
                        (if (< nextpos (length next))
                            (list-tail next nextpos)
                            '()))))))))

(split '(a b c x d x e x f) 'x) ; '((a b c) (d) (e) (f))
(split '(0 1 2 0 2 0 3 0) 0) ; '(() (1 2) (2) (3))

It does work, but I feel it's not the best way to accomplish the task, for a couple of reasons:

The (loop (let (... part seems a bit clunky, maybe even unnecessary.
The (list-tail ... clause entails rescanning the list for nextpos elements, which obviously is not optimal. In Python, I would have split-one return the current chunk and a reference to the head of the following, i.e. the cdr of the last element considered, and keep iterating from that. Here I'm uncertain at what to do.

In addition to that, I've start using the (if (cond) '() (...)) pattern quite a lot for recurring, so I would be grateful if any seasoned LISPer could comment on how much this is idiomatic and if there are better ways of expressing the same.

Also, the whole point of this exercise is learning, so please don't tell me I should use string-split or regex-split or the like. I am aware of their existence.


texts: Is building a test instance from a mix of both mock and real objects OK?

texts:
I am new to android testing and would like to try start off in the correct direction, so I am trying to understand if this is the correct way to test a particular method or if there is some best practice that I should be following.

Here are some snippets of the class that contains the method I would like to test.

public class MapMarker implements Target {

private Bus mBus;
private RailsMarker mMarker;
private Bitmap mBitmap;

public String getGravatarUrl() {
    return mMarker.getGravatarUrl();
}

public String getUserId() {
    return mMarker.getUserId();
}

@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom loadedFrom) {
    System.out.println(String.format("loaded bit map from gravatar url = %s, for userid = %s",getGravatarUrl(), getUserId()));
    mBitmap = bitmap;
    mBus.post(new MarkerReadyEvent(this));
    }
}

I am trying to test that when the onBitMapLoaded method is called, it posts a MarkerReadyEvent onto my eventbus.

Here is the test method I coded.

@Test
public void testOnBitMapLoaded() {
    Bus mockBus = mock(Bus.class);
    RailsMarker railsMarker = new RailsMarkerBuilder().withGravatarUrl("a_gravatar_url")
                                                      .withUserId("a_user_id")
                                                      .build();
    MapMarker androidMapMarker = new MapMarkerBuilder().withBus(mockBus)
                                                       .withMarker(railsMarker)
                                                       .build();
    androidMapMarker.onBitmapLoaded(null, null);
    verify(mockBus).post(isA(MarkerReadyEvent.class));
}

I am using Mockito to mock the eventbus.
I am creating a real instance of the MapMarker class (via https://github.com/mkarneim/pojobuilder)
I am also creating a RailsMarker instance to be included in the MapMarker instance.  (I realized this in only needed for the println statement but I did not want to remove it just to make the test easier)

Is this a good approach or is there some other pattern I should be following?
The part that seems a bit strange is that I end up building the instance I am going to test with both a mock object (the Bus) and a real object (the RailsMarker),  but I don't see anyway around this.


texts: ActiveRecord model for users who have issues or who assist with issues

texts:
I'm running into an issue while playing around with some models in a Rails app. Namely issues of the polymorphic variety. I think I may have solved it, more or less looking for an approval.

I have the following models in my app:

class Issue < ActiveRecord::Base
  belongs_to :creator, class_name: 'User', foreign_key: 'creator_id'
  has_many :user_issues
  has_many :helpers, through: :user_issues, source: :users
end

class User < ActiveRecord::Base
  has_many :issues, foreign_key: 'creator_id'
  has_many :user_issues
  has_many :issues_helped, through: :user_issues, source: :issues
end

class UserIssues < ActiveRecord::Base
  belongs_to :user
  belongs_to :issue
end

Scenario:

UserOne creates an issue and is saved as the IssueOne's creator. UserTwo decides to help UserOne and joins/follows IssueOne (has_many :issues_helped declared in the model) and is allowed to post a comment. UserTwo is a helper in this instance.

Well, UserTwo is now in need of some help and creates a new issue of his own. UserTwo is the creator of IssueTwo. UserOne decides to help out his new buddy UserTwo on his issue and joins/follows IssueTwo, and is allowed to post a comment. UserOne has now become a helper in this instance.

Is this the Rails way of doing it? This is the best solution I have come up with, so far.
Am I misusing the power of has_many :x, through: :y, source: :z?


texts:
I have a sleep function which displays the time remaining in sec, some feedback would be appreciated

use warnings;

$x=$ARGV[0];
$|++;

$n=0;
# arguments could be 1, 1s , 1m or 1h
if($x=~/([0-9]+)([a-zA-Z]?)/)
{
   $t = lc($2) ;
   if($t eq "h"){$n = $1*3600;}
   elsif( $t eq "m" ){$n = $1*60;}
   elsif( $t eq "s" || $t eq "") {$n = $1;}
   else {die;}
}
else {die;}

while($n)
{
   print $n;
   sleep 1;
   $len=length($n);
   print "\r", " "x$len, "\r"; $n--;
}

This code and updates are available at csleep


texts:
I've got this really convoluted reselect selector. It's going a few levels deep and setting a couple of attributes. What's a good way to split this up to make it more readable? Ideally in a "redux" way.

export const getFoosOrderedWithDisabledAndUsed = createSelector(
  getFoos,
  getBazs,
  (foos, bazs) => {
    let foo;
    return Object.keys(foos)
      .sort((a, b) => foos[a].sort - foos[b].sort)
      .map((key) => {
        foo = foos[key];
        return {
          [key]: {
            ...foo,
            items: foo.items.map(
              item => ({
                ...item,
                disabled: !bazs.some(
                  baz => bazMatchFilter(baz, {
                    ...foo,
                    key,
                    items: [item],
                  }),
                ),
              }),
            ),
            used: foo.items.some(item => item && item.selected),
          },
        };
      });
  },
);


texts:
This is self-explaining example with usage in doctests (it's not that fast as implementation with dict key-lookups, but it's a lot more readable, and don't require callables and lambdas):

class Switch(object):
    """
    Switch, simple implementation of switch statement for Python, eg:

    >>> def test_switch(val):
    ...   ret = []
    ...   with Switch(val) as case:
    ...     if case(1, fall_through=True):
    ...       ret.append(1)
    ...     if case(2):
    ...       ret.append(2)
    ...     if case.call(lambda v: 2 < v < 4):
    ...       ret.append(3)
    ...     if case.call(lambda v: 3 < v < 5, fall_through=True):
    ...       ret.append(4)
    ...     if case(5):
    ...       ret.append(5)
    ...     if case.default:
    ...       ret.append(6)
    ...   return ret
    ...
    >>> test_switch(1)
    [1, 2]

    >>> test_switch(2)
    [2]

    >>> test_switch(3)
    [3]

    >>> test_switch(4)
    [4, 5]

    >>> test_switch(5)
    [5]

    >>> test_switch(7)
    [6]

    >>> def test_switch_default_fall_through(val):
    ...   ret = []
    ...   with Switch(val, fall_through=True) as case:
    ...     if case(1):
    ...       ret.append(1)
    ...     if case(2):
    ...       ret.append(2)
    ...     if case.call(lambda v: 2 < v < 4):
    ...       ret.append(3)
    ...     if case.call(lambda v: 3 < v < 5, fall_through=False):
    ...       ret.append(4)
    ...     if case(5):
    ...       ret.append(5)
    ...     if case.default:
    ...       ret.append(6)
    ...   return ret
    ...
    >>> test_switch_default_fall_through(1)
    [1, 2, 3, 4]

    >>> test_switch_default_fall_through(2)
    [2, 3, 4]

    >>> test_switch_default_fall_through(3)
    [3, 4]

    >>> test_switch_default_fall_through(4)
    [4]

    >>> test_switch_default_fall_through(5)
    [5]

    >>> test_switch_default_fall_through(7)
    [6]
    """

    class StopExecution(Exception):
        pass

    def __init__(self, test_value, fall_through=False):
        self._value = test_value
        self._fall_through = None
        self._default_fall_through = fall_through
        self._use_default = True
        self._default_used = False

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is self.StopExecution:
            return True

        return False

    def __call__(self, expr, fall_through=None):
        return self.call(lambda v: v == expr, fall_through)

    def call(self, call, fall_through=None):
        if self._default_used:
            raise SyntaxError('Case after default is prohibited')

        if self._finished:
            raise self.StopExecution()
        elif call(self._value) or self._fall_through:
            self._use_default = False
            if fall_through is None:
                self._fall_through = self._default_fall_through
            else:
                self._fall_through = fall_through
            return True

        return False

    @property
    def default(self):
        if self._finished:
            raise self.StopExecution()

        self._default_used = True

        if self._use_default:
            return True

        return False

    @property
    def _finished(self):
        return self._use_default is False and self._fall_through is False

class CSwitch(Switch):
    """
    CSwitch is a shortcut to call Switch(test_value, fall_through=True)
    """
    def __init__(self, test_value):
        super(CSwitch, self).__init__(test_value, fall_through=True)


texts: Apply capitalization of one string to another

texts:
I want to take the capitalization of one string and apply it to another.

For example: take Apple and orange and turn that into Orange.

This is the solution I implemented. Is there a more efficient way of doing this?

public static String applyCapitalization(String to, String from) {
    int[] capArray = toCapitalizationArray(to);
    char[] charCap = from.toCharArray();
    for (int i = 0; i < capArray.length; i++) {
        if (capArray[i] == 1) {
            charCap[i] = Character.toUpperCase(charCap[i]);
        } else {
            charCap[i] = Character.toLowerCase(charCap[i]);
        }
    }
    return new String(charCap);
}
private static int[] toCapitalizationArray(String to) {
    int[] arr = new int[to.length()];
    for (int i = 0; i < to.length(); i++) {
        char c = to.toCharArray()[i];
        if (Character.isUpperCase(c)) {
            arr[i] = 1;
        } else {
            arr[i] = 0;
        }
    }
    return arr;
}


texts:
I was working on a syllable counting function for a text editor(this function is accurate enough). However, I would like to know if it is possible to optimize it, it already separated into another thread, but I would like to know if there is any kind of optimization that I can do with it to make it more efficient.

private static int SyllableCount(string word)
{
    word = word.ToLower().Trim();
    int count = System.Text.RegularExpressions.Regex.Matches(word, "[aeiouy]+").Count;
    if ((word.EndsWith("e") || (word.EndsWith("es") || word.EndsWith("ed"))) && !word.EndsWith("le"))
        count--;
    return count;
}

It uses regular expressions, something that this source mentions having poor performance in .net applications, is that the case? And if not, are there any other optimizations that I can perform on it?

Anyway, it does not lag much, but my application does use around four threads already, just for keeping up with various text entry statistics, so now I'm just trying to shave the fat off so to speak.


texts: VBscript XLS-to-CSV with minor transform

texts:
I have a system that only outputs reports in Excel 97-2003, and a second system (for the user to look at) that only accepts these reports in CSV format.  The reports manager was previously opening each of the fifteen XLS reports, find/replacing all the commas with semicolons, saving as CSV, and renaming each file to the specific name that the second system requires.  I heard of his plight and wanted to try my hand at automating the process, so my hamfisted attempt - after about a day of combing through SO and various other sites - follows.

It does work as intended, but I feel like I'm missing some obvious improvement.

Option Explicit

Dim objFS, objFolder, colFiles, re, objFile, intConvert, userContinue, objXL, objBook, objSheet, strBase

Set objFS = CreateObject("Scripting.FileSystemObject")

Set objFolder = objFS.GetFolder(".\")
Set colFiles = objFolder.Files

Set re = New RegExp
re.Global     = True
re.IgnoreCase = False
re.Pattern    = "\.xls$"

intConvert = 0
For Each objFile in colFiles
  If re.test(objFile.Name) Then
    intConvert = intConvert + 1
  End If
Next

If intConvert = 0 then
  MsgBox "ChangeFile found no files to convert where it was opened." & vbNewLine & "Exiting process."
Else
  userContinue = MsgBox ("ChangeFile found " & intConvert & " files to convert where it was opened." & vbNewLine & _
    "Continue conversion process?", vbYesNo, "Continue Conversion")
  If userContinue = vbYes Then
    'MsgBox "Conversion beginning."
    Set objXL = WScript.CreateObject("Excel.Application")
    objXL.Visible = False
    For Each objFile in colFiles
      If re.test(objFile.Name) Then
        Set objBook = objXL.Workbooks.Open(objFile.Path)
        Set objSheet = objBook.Worksheets(1)
        objSheet.Cells.Replace ",", ";"

        objBook.SaveAs Replace(objFile.Path, ".xls", ".csv"), 6
        objBook.Close True

        strBase = objFS.GetBaseName(objFile)
        Select Case strBase
          Case "[REDACTEDXLS1]"
            objFS.MoveFile strBase & ".csv", "[REDACTEDCSV1].csv"
          Case "[REDACTEDXLS2]"
            objFS.MoveFile strBase & ".csv", "[REDACTEDCSV2].csv"
          Case Else
            MsgBox strBase & " was not renamed - no match found"
        End Select
      End If
    Next
    objXL.Quit
    Set objSheet = nothing
    Set objBook = nothing
    Set objXL = nothing
    Set objFS = nothing
    MsgBox "If you see this message, conversion was completed successfully."
  End If
End If

Never mind the REDACTEDs.  My bosses can get a little leery of putting info out there sometimes.  There are only two specific cases listed thus far since I don't have the full list of requirements, which should get to me some time next week.  (Also they are sadly all non-uniform names on both sides of the transform, so there’s no iteration that can be done.)

Possibly more appropriate for SO: I’ve also been advised that repeatedly opening/closing Excel like this can create phantom copies of Excel in memory, but testing with Windows 7 and Excel 2013 (which is what the report manager would be using) I see the second Excel process being created (when I'm already running one) and then removed at the end, so all appears to be well.  Is this something more applicable to an earlier iteration that Office 2013 fixes, or am I justified in worrying about it still?


texts: Is this binary search in TypeScript correct?

texts:
I need your help to see if the following binary search code is correct. I did my best to cover the corner cases.  I wonder if I missed anything.

The code as it is with tests (you can play with it online here):

function binarySearch<a, r>(
    hay: a[],
    needle: a,
    compare:(one: a, another: a, oneGreaterThanAnother: () => r, oneLessThanAnother: () => r, oneEqualToAnother: () => r) => r,
    haveStaightHit: (hay: a[], index: number) => r,
    haveExpectedToBeAt: (hay: a[], index: number) => r
) {
    if (hay.length > 0) {
        return binarySearchUnsafe(hay, needle, 0, hay.length - 1, compare, haveStaightHit, haveExpectedToBeAt);
    } else {
        return haveExpectedToBeAt(hay, 0);
    }
}
function binarySearchUnsafe<a, r>(
    hay: a[],
    needle: a,
    from: number,
    to: number,
    compare:(one: a, another: a, oneGreaterThanAnother: () => r, oneLessThanAnother: () => r, oneEqualToAnother: () => r) => r,
    haveStaightHit: (hay: a[], index: number) => r,
    haveExpectedToBeAt: (hay: a[], index: number) => r
): r {
    if (from < to) {
        var at = from + (~~((to - from) / 2));
        return compare(
            needle,
            hay[at],
            function needleIsOnTheRight() {
                return binarySearchUnsafe(hay, needle, at + 1, to, compare, haveStaightHit, haveExpectedToBeAt);
            },
            function needleIsOnTheLeft() {
                return binarySearchUnsafe(hay, needle, from, at, compare, haveStaightHit, haveExpectedToBeAt);
            },
            function needleIsFound() {
                return haveStaightHit(hay, at);
            }
        );
    } else if (from > to) {
        throw new Error('From index ' + from + ' is bigger than the to index ' + to + '.');
    } else {
        var at = from /* === to */;
        return compare(
            needle,
            hay[at],
            function needleIsOnTheRight() {
                return haveExpectedToBeAt(hay, at + 1);
            },
            function needleIsOnTheLeft() {
                return haveExpectedToBeAt(hay, at);
            },
            function needleIsFound() {
                return haveStaightHit(hay, at)
            }
        );
    }
}

function areEqual(actual: any, expected: any) {
    if (actual !== expected) throw new Error('Expected: ' + expected + ', Actual: ' + actual);
}

function compareStrings<r>(one: string, another: string, oneGreaterThanAnother: () => r, oneLessThanAnother: () => r, oneEqualToAnother: () => r) : r {
    if (one > another) {
        return oneGreaterThanAnother();
    } else if (one < another) {
        return oneLessThanAnother();
    } else {
        return oneEqualToAnother();
    }
}

function failOver(message: string) : any {
    return function() {
        throw new Error(message);
    }
}

try {
    binarySearch([], 'x', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 0));
    binarySearch(['b', 'd', 'f'], 'b', compareStrings, (hay, index) => areEqual(index, 0), failOver('Direct hit is expected.'));
    binarySearch(['b', 'd', 'f'], 'd', compareStrings, (hay, index) => areEqual(index, 1), failOver('Direct hit is expected.'));
    binarySearch(['b', 'd', 'f'], 'f', compareStrings, (hay, index) => areEqual(index, 2), failOver('Direct hit is expected.'));
    binarySearch(['b', 'd', 'f'], 'g', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 3));
    binarySearch(['b', 'd', 'f'], 'a', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 0));
    binarySearch(['b', 'd', 'f'], 'c', compareStrings, failOver('Direct hit is not expected.'), (hay, index) => areEqual(index, 1));
    alert('You are all good!');
} catch (e) {
    alert(e.message);
}


texts:
I tried to help someone in Stackoverflow with a refactoring exercise. Did many changes to his original code and made a somewhat decent solution (at least in my eyes). Was thinking, whether someone can critique on my implementation.

class Theatre
  COST = { running: 3, fixed: 180 }

  attr_accessor :number_of_audience, :ticket_price

  def revenue
    @number_of_audience * @ticket_price
  end

  def total_cost
    COST[:fixed] + (@number_of_audience * COST[:running])
  end

  def net
    revenue - total_cost
  end

  def profit?
    net > 0
  end
end

class TheatreCLI
  def initialize
    @theatre = Theatre.new
  end

  def seek_number_of_attendes
    print 'Number of audience: '
    @theatre.number_of_audience = gets.chomp.to_i
  end

  def seek_ticket_price
    print 'Ticket price: '
    @theatre.ticket_price = gets.chomp.to_i
  end

  def print_revenue
    puts "Revenue for the theatre is RM #{@theatre.revenue}."
  end

  def print_profit
    message_prefix = @theatre.profit? ? 'Profit made' : 'Loss incurred'
    puts "#{message_prefix} #{@theatre.net.abs}."
  end

  def self.run
    TheatreCLI.new.instance_eval do
      seek_ticket_price
      seek_number_of_attendes

      print_revenue
      print_profit
    end
  end
end

TheatreCLI.run


texts: Euler Project 14 (Longest Collatz Sequence)

texts:
Project Euler 14 asks: Which starting number, under one million, produces the longest Collatz sequence?

I've been trying to optimize this solution to execute in less then 1s. Agenda for first 50 eulers. Currently it executes in 1,2s for me, so I guess that I want it to be 20% faster. Any tips or other methods?

from time import time

def rec_col(n, cache):
    if n in cache:
        return cache[n]
    x = (rec_col(n//2, cache) if n % 2 == 0 else rec_col(3*n+1, cache))+1
    cache[n] = x
    return x

def main():
    start = time()
    highest = 0
    ans = 1
    cache = {1: 1}
    for i in range(1, 10**6):
        temp = rec_col(i, cache)
        if temp > highest:
            ans = i
            highest = temp
    print("{0}\nTime {1:.4f} s".format(ans, time() - start))

if __name__ == '__main__':
    main()

This has the same preformance:

def rec_col(n, cache):
    cache[n] = (rec_col(n//2, cache) if n % 2 == 0 else rec_col(3*n+1, cache)) + 1 \
        if n not in cache else cache[n]
    return cache[n]


texts: Create an object when you need it! in PHP

texts:
Well Iam trying to learn OOP for a while now, My idea here is to create a simple CMS kind of thing.And I did something like this:

App Class:

namespace System;

class App {
    private $storage = [];
    private static $_instance;

    public static function getInstance()
    {

        if (is_null(self::$_instance)) {

            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __get($key)
    {
        return $this->get($key);
    }

    public function get($key){

        if (!$this->has($key)){
            if ($this->isCore($key)){
                $this->share($key,$this->createNewObj($key));
            }else{
                die($key.' was not found!');
            }
        }
        return $this->storage[$key];

    }

    private function has($key)
    {
        return array_key_exists($key, $this->storage);
    }

    public function share($key,$value)
    {
        $this->storage[$key]= $value;

    }

    private function isCore($class)
    {
        $coreClasses = $this->coreClasses();
        return isset($coreClasses[$class]);
    }

    private function coreClasses()
    {
        return [

            'db'        => 'System\\Database',
            'user'      => 'System\\User'
        ];
    }

    private function createNewObj($key)
    {
        $coreClasses = $this->coreClasses();
        $opj = $coreClasses[$key];
        return new $opj($this);
    }

}

User Class: (Every class I write in this app will take an object from App using Dependency Injection).

namespace System;

class User
{
    private $app = null;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    public function getAllUsers()
    {
        return $this->app->db->select('* FROM users')->fetchAll();

    }

}

init.php

if (!session_id()){
    session_start();
}

define('ROOT',dirname(__DIR__));
define('DS', /);

require ROOT.DS.'System/Autoload.php';
\System\Loader::reg();

$app = \System\App::getInstance();

an now when I want to get something from the database I use this: in users.php

require 'init.php';
//get the object from storage if does exist!
$User = $app->user->getAllUsers();

The idea was to get the an object from User class on the fly. rather doing it like:

$User = new User($database);
$User->getAllUsers();

Am I doing this right, or is it a bad idea?


texts: Simple Rock-Paper-Scissors to get more comfortable with OOP

texts:
I'm trying to get a little more comfortable with using classes as they're meant to be used, instead of using them to decorate my code to make it look more legitimate. Can you see anything glaringly wrong/could be improved/possibly different implementations?

import random

class Player(object):

    def __init__(self,player):
        self.name = player
        self.score = 0
        self.choice = []

class Game(object):

    player_one,player_two = Player('player_one'),Player('player_two')

    def gameplay(self):
        choices = ['rock','paper','scissors']
        self.player_one.choice,self.player_two.choice = random.choice(choices),random.choice(choices)
        if self.player_one.choice == self.player_two.choice:
            print 'Tie!'
        elif self.player_one.choice == 'rock' and self.player_two.choice == 'paper':
            print '{0} is the winner with {1}!'.format(self.player_one.name,self.player_one.choice)
            self.player_one.score += 1
        elif self.player_one.choice == 'paper' and self.player_two.choice == 'rock':
            print '{0} is the winner with {1}!'.format(self.player_two.name,self.player_two.choice)
            self.player_two.score += 1
        elif self.player_one.choice == 'scissors' and self.player_two.choice == 'rock':
            self.player_two.score += 1
        elif self.player_one.choice == 'scissors' and self.player_two.choice == 'paper':
            self.player_one.score += 1
        elif self.player_one.choice == 'paper' and self.player_two.choice == 'scissors':
            self.player_two.score += 1
        elif self.player_one.choice == 'rock' and self.player_two.choice == 'scissors':
            self.player_one.score += 1
        print '{0}\'s score is {1}, and {2}\'s score is {3}'.format(self.player_one.name,self.player_one.score,self.player_two.name,self.player_two.score)

g = Game()
for i in range(0,10000):
    g.gameplay()


texts:
I had to work in the Transport Problem and we're asked to try to make the fastest code for big matrices, so we're advised to try to avoid loops. And the only one I've got and I cannot imagine how to simplify it is this one for making an incidence matrix (with 1s, 0s and -1s) like that:

b<-diag(-1,n2)
a<-b
for (i in 1:(n1-1)) {
  a<-cbind(a,b)
}

Can this be simplified?


texts: Synchronizing billing fields with the corresponding shipping fields

texts:
How can I refactor this redundant code?

$("#txtShippingAddressFullName").change(function () {
    $("#txtBillingAddressFullName").val($(this).val());
})

$("#txtShippingAddress").change(function () {
    $("#txtBillingAddress").val($(this).val());
})

$("#txtShippingPostalCode").change(function () {
    $("#txtBillingPostalCode").val($(this).val());
})

$("#txtShippingPhoneNumber").change(function () {
    $("#txtBillingPhoneNumber").val($(this).val());
})

$("#ddlShippingCity").change(function () {
    $("#ddlBillingCity").val($(this).val());
})


texts:
I'm a beginning Scala programmer with a strong background in functional programming (ML, Haskell, Scheme) and I've just written my first Scala program. It is an implementation of a FSA (finite state automaton). Below is a simplified version that has 3 events/actions/labels (E0, E1, E2) and four states (S0, S1, S2, S3).

 sealed abstract class Event

 case object E0 extends Event
 case object E1 extends Event
 case object E2 extends Event

 abstract class State { def event ( e : Event ) : State }

 object S0 extends State {
   override def event ( e : Event ) : State = {
     e match {
       case E0 => { S1 }
       case E1 => { S0 }
       case E2 => { S2 } } } }

 object S1 extends State {
   override def event ( e : Event ) : State = {
     e match {
       case E0 => { S1 }
       case E1 => { S2 }
       case E2 => { S0 } } } }

 object S2 extends State {
   override def event ( e : Event ) : State = {
     e match {
       case E0 => { S2 }
       case E1 => { S0 }
       case E2 => { S3 } } } }

 object S3 extends State {
   override def event ( e : Event ) : State = {
     e match {
       case E0 => { S0 }
       case E1 => { S3 }
       case E2 => { S3 } } } }

 class Fsa {
   private var state : State = S0
   def event ( e : Event ) : Unit = { state = state.event ( e ) } }

A typical use of Fsa objects would be like this:

val fsa = new Fsa
while ( true ) {
   fsa.event ( ... nextEvent () ) }

I'd be interested to know if you think this is a good, or at least reasonable way
of implmenting FSAs in Scala, and if not, why. I'm particularly interested in the memory consumption of solutions like this.


texts:
I am trying to make a rake task but after completion my code i realized i need some refactorization. How could I do refactorization of the following code?

def self.transaction_type(row)
    if row['SENDER_BLZ'] == '00000000' and row['RECEIVER_BLZ'] == '00000000'
      return 'AccountTransfer'
    elsif row['SENDER_BLZ'] == '00000000' and row['UMSATZ_KEY'] == '10'
      return 'BankTransfer'
    elsif row['RECEIVER_BLZ'] == '70022200' and ['16'].include?row['UMSATZ_KEY']
      return 'Lastschrift'
    else
      return false
    end
  end

and second method is

def self.import_file_row_with_error_handling(row, validation_only, errors, dtaus)
  error_text = nil
  self.import_retry_count = 0
  5.times do
    self.import_retry_count += 1
    error_text = nil
    begin
      import_file_row(row, validation_only, errors, dtaus)
      break
    rescue => e
      error_text = "#{row['ACTIVITY_ID']}: #{e.to_s}"
      break
    end
  end
  errors << error_text if error_text

  [errors, dtaus]
end

Just need bit guid. thanks


texts:
I have a very simple webpage that contains 4 color images. When I hover over any of the images the original (xxxx1.jpg) is replaced by a black and white version (xxxxx2.jpg) of the same image, and then it reverts back to the original image after hover.

I'm declaring the same variable for both handlerIn and handlerOut:

var src = $(this).attr("src")

Can I declare the var just once somehow? I just can't seem to figure this out myself.

$(document).ready(function(){
    $( "img" ).hover(
        function() {
            var src = $(this).attr("src").replace("1.jpg", "2.jpg");
            $(this).attr("src", src);
        },
        function() {
            var src = $(this).attr("src").replace("2.jpg", "1.jpg");
            $(this).attr("src", src);
        }
    );
});


texts: Abstract classes with operator overloading

texts:
I'm following a YouTube video and am wondering if there are any other efficient ways of doing this. Is it possible to do it with an interface too?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Learning
{
    class Program
    {
        static void Main(string[] args)
        {
            Shape Rect = new Rectangle(5, 3);
            Shape Tri = new Triangle(8, 12);
            Rectangle CombinedRectangle = new Rectangle(3, 3) + new Rectangle(6, 6);
            Console.WriteLine(CombinedRectangle.Area());
        }

        abstract class Shape
        {
             public abstract double Area();

        }

        class Triangle : Shape
        {
            private double theBase { get; set; }
            private double theHeight { get; set; }

            public Triangle(double theBase, double theHeight)
            {
                this.theBase = theBase;
                this.theHeight = theHeight;
            }

            public override double Area()
            {
                return (theBase * theHeight) / 2;
            }
        }

        class Rectangle : Shape
        {
            private double Length { get; set; }
            private double Width { get; set; }

            public Rectangle(double Length, double Width)
            {
                this.Length = Length;
                this.Width = Width;
            }

            public override double Area()
            {
                return Length * Width;
            }

            public static Rectangle operator+ (Rectangle r1, Rectangle r2)
            {
                double combinedWidth = r1.Width + r2.Width;
                double combinedLength = r1.Length + r2.Length;
                return new Rectangle(combinedLength, combinedWidth);
            }
        }

    }
}


texts:
A week ago I did a three function calculator, I took the input from you guys and made it better. Overall it works fine, I didn't find any problems. But as a beginning programer I'd like some input on this calculator.

// Three function Calculator.cpp : main project file.
#include "stdafx.h"
#include<iostream>
using std::cout;
using std::cin;

long double action(long double num1, long double num2, char act) //External function to do all the calculations
{
    long double total;
    switch (act)
    {
    case '+':
        total = num1 + num2;
        break;
    case '-':
        total = num1 - num2;
        break;
    case '*':
        total = num1*num2;
        break;
    case '/':
        total = num1 / num2;
        break;
    default:
        cout << "Input not recognized\n";
    }
    return total;    //Giving the main function a number to work with.
}

int main()
{
    cout << "Enter action as # to exit program\n";
    cout << "Possible actions:+,-,*,/\n\n";
    long double num1, num2, num3, total;
    char act1, act2;
    while (1)   //inf loop
    {
        beginning:    //label, to reset the program in case of division by zero
        cin >> num1 >> act1 >> num2 >> act2 >> num3;
        if (act1 == '#' || act2 == '#')         //user wants to exit program
        {
            system("pause");
            return 0;
        }
        else if (act1 == '/' && num2 == 0 || act2 == '/' && num3 == 0)      //division by zero happens
        {
            cout << "You can't divide by zero\n";
            cout << "\n\n";
            goto beginning;              //restarting the program from the lable, to the beginning of the 'while' loop
        }
        else if ((act2 == '*' || act2 == '/') && (act1 == '-' || act1 == '+'))     //action2 happens before action1 because of order of operation
        {
            total = action(num2, num3, act2);             //sending the function reciving the total
            total = action(num1, total, act1);            //sending the total of previos function to get overall total
        }
        else      //action1 happens before action2 because of order of operation
        {
            total = action(num1, num2, act1);      //sending the function reciving the total
            total = action(total, num3, act2);     //sending the total of previos function to get overall total
        }
        cout << num1 << act1 << num2 << act2 << num3 << "=" << total;   //printing result of overall function
        cout << "\n\n";    //new line before restarting program
    }
}

Old Calculator

Example:

  Input:-6*2+4
  Output:-6*2+4=-8


texts: Autocompleting when a certain class is present

texts:
This jQuery actually autocomplete when the onkeydown class is present and load the autocomplete with corresponding variable. This is working but I want to make it shorter.

var autocomp_opt = {
    source: "<?php echo base_url();?>description/get_description",
    minLength: 1,
    select: function(evt, ui) {
        this.form.sub_description.value = ui.item.sub_description;
    }
};

var autocomp_opt1 = {
    source: "<?php echo base_url();?>description/get_description",
    minLength: 1,
    select: function(evt, ui) {
        this.form.sub_description2.value = ui.item.sub_description;
    }
};

$(document).on("keydown", ".sn", function () {
    $(this).autocomplete(autocomp_opt);
});

$(document).on("keydown", ".sn2", function () {
    $(this).autocomplete(autocomp_opt1);
});


texts:
How can I improve readability of this code? indentChar needs to be reused elsewhere.

toCoordinate = dropWhile ((||) <$> (not . indentChar) <*> (=='(')) >>> takeWhile(/= ' ')
indentChar = (||) <$> isAlpha <*> (=='(')

Desired result:

*Parse> toCoordinate " \\--(my.coordinate - from outerspace)"
"my.coordinate"


texts:
I am new to Python and I am writing my first utility as a way to learn about strings, files, etc.  I am writing a simple utility using string replacement to batch output HTML files. The program takes as inputs a CSV file and an HTML template file and will output an HTML file for each data row in the CSV file.

CSV Input File: test1.csv

The CSV file, which has  header row, contains some catalog data, one product per row, like below:

stockID,color,material,url
340,Blue and magenta,80% Wool / 20% Acrylic,http://placehold.it/400
275,Purple,100% Cotton,http://placehold.it/600
318,Blue,100% Polyester,http://placehold.it/400x600

HTML Template Input File: testTemplate.htm

The HTML template file is simply a copy of the desired output with string replace tags %s placed at the appropriate locations:

Stock ID: %s

%s

%s

The Python is pretty straight forward I think.  I open the template file and store it as a string.  I then open the CSV file using the csv.dictreader() command.  I then iterate through the rows of the CSV, build the file names and then write the output files using string replacement on the template string using the dictionary keys.

import csv

# Open template file and pass string to 'data'.  Should be in HTML format except with string replace tags.
with open('testTemplate.htm', 'r') as myTemplate:
    data = myTemplate.read()
    # print template for visual cue.
    print('Template passed:\n' + '-'*30 +'\n' + data)
    print('-'*30)

# open CSV file that contains the data and store to a dictyionary 'inputFile'.
with open('test1.csv') as csvfile:
    inputFile = csv.DictReader(csvfile)
    x = 0 # counter to display file count
    for row in inputFile:
        # create filenames for the output HTML files
        filename = 'listing'+row['stockID']+'.htm'
        # print filenames for visual cue.
        print(filename)
        x = x + 1
        # create output HTML file.
        with open(filename, 'w') as outputFile:
            # run string replace on the template file using items from the data dictionary
            # HELP--> this is where I get nervous because chaos will reign if the tags get mixed up
            # HELP--> is there a way to add identifiers to the tags?  like %s1 =row['stockID'], %s2=row['color'] ... ???
            outputFile.write(data %(row['stockID'], row['color'], row['material'], row['url']))

# print the number of files created as a cue program has finished.
print('-'*30 +'\n' + str(x) + ' files created.')

The program works as expected with the test files I have been using (which is why I am posting here and not on SO).  My concern is that it seems pretty fragile.  In 'production' the CSV file will contain many more columns (around 30-40) and the HTML will be much more complex, so the chances of one of the tags in the string replace getting mixed seems pretty high. is there a way to add identifiers to the tags?  like %s1 =row['stockID'], %s2=row['color'] ...? that could be placed either in the template file or in the write() statement (or both)?  Any method alternatives or improvements I could learn would be great (note I am well aware of the Makos and Mustaches of the world and plan to learn a couple of template packages soon.)


texts:
At the moment I'm learning Python and I made this script to workout my skills.
Since it is one of my first programs I would love some feedback and tips, like more organization, less lines of code or more optimization, anything I could improve.

print "Do you want to encrypt or decrypt the message (e/d)"
action = raw_input("> ")
while action != "e" and action != "d":
    action = raw_input( "(e/d): ")

abc_l_e = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
abc_u_e = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
abc_l_d = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba"
abc_u_d = "ZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBA"
chars = "!\"#$%&'()*+-'-./:;<=>?@[]^_{}|~1234567890"

if action == "e":
    print "\nEnter the message to encrypt"
    message = raw_input("> ")

    print "\nEnter the key"
    try:
        key = input("> ")
        while not (key >= 1 and key <= 26):
            print "Number not in range (1-26). Try again"
            key = input("> ")
    except:
        print "That's not a correct integer. Try again."
        exit()

    e_message = ""
    for char in message:
        if char in abc_l_e:
            e_message += abc_l_e[(abc_l_e.index(char) + key)]
        if char in abc_u_e:
            e_message += abc_u_e[(abc_u_e.index(char) + key)]
        elif char == " ":
            e_message += " "
        elif char in chars:
            e_message += char
    print "Your encrypted message is:\n", e_message

elif action == "d":
    print "\nEnter the message to decrypt"
    message = raw_input("> ")
    print "\nEnter the key (enter \"n\" if you don't know)"
    try:
        key = raw_input("> ")
        if key != "n":
            while not (int(key) >= 1 and int(key) <= 26):
                print "Number not in range (1-26). Try again"
                key = input("> ")
    except:
        print "That's not a correct integer nor \"n\". Try again."
        exit()

    d_message = ""
    if key != "n":
        key = int(key)
        for char in message:
            if char in abc_l_d:
                d_message += abc_l_d[(abc_l_d.index(char) + key)]
            elif char in abc_u_d:
                d_message += abc_u_d[(abc_u_d.index(char) + key)]
            elif char == " ":
                d_message += char
            elif char in chars:
                d_message += char
        print "Your decrypted message is:\n", d_message

    if key == "n":
        results = []
        for turn in range(1,26):
            d_message = ""
            for char in message:
                if char in abc_l_d:
                    d_message += abc_l_d[(abc_l_d.index(char) + turn)]
                elif char in abc_u_d:
                    d_message += abc_u_d[(abc_u_d.index(char) + turn)]
                elif char == " ":
                    d_message += char
                elif char in chars:
                    d_message += char
            results.append(d_message)

        print "\nYour decrypted message is between one of the following:"
        for result in results:
            print "%d." % (results.index(result) + 1), result


texts:
I am trying to complete this challenge. The user should enter a sequence of instructions, = to link two numbers, and ? to query whether two integers are linked. For example,

? 1 2
= 1 5
= 2 5
? 1 2

should produce

no
yes

I have tried following the algorithm given here to the letter, but I keep getting a judgment of "time limit exceeded". It's very infuriating as the difficultly rating for the problem suggests it should be quite easy. I have tried modifying the code so that redundant links (e.g. = 1 2 where 1 is never queried nor later linked to another number) are ignored, but it still isn't fast enough.

#include <iostream>
#include <vector>

using namespace std;

int root(int a, vector<int> & parent) {
    int b = parent[a];
    return b == a ? a : parent[a] = root(b, parent);
}

void link(int a1, int a2, vector<int> & parent, vector<int> & rk) {
    int root1 = root(a1, parent);
    int root2 = root(a2, parent);
    if (root1 == root2)
        return;
    int rk1 = rk[root1];
    int rk2 = rk[root2];
    if (rk1 < rk2) {
        parent[root1] = root2;
    } else if (rk2 < rk1) {
        parent[root2] = root1;
    } else {
        parent[root1] = root2;
        rk[root2]++;
    }
}

int main() {
    int n, q;
    cin >> n >> q;
    vector<int> parent;
    for (int i = 0; i < n; i++)
        parent.push_back(i);
    vector<int> rk(n, 0);
    for (int i = 0; i < q; i++) {
        string str;
        int a, b;
        cin >> str >> a >> b;
        if (str == "?")
            cout << (a == b || root(a, parent) == root(b, parent) ? "yes" : "no") << endl;
        else
            link(a, b, parent, rk);
    }
    return 0;
}


texts:
I've written JavaScript for a while, but lately I've been writing a lot of C#.  I wanted to write a method that could take the column name of a DataTable and return an average for those values.  Having never written closures in C#, but being comfortable with them in JavaScript, I came up with this:

public static double GetColumnAverage(DataTable dt,string columnName)
{
    Func<DataTable, double> getAverage = (t) => t.AsEnumerable().Where(x => x[columnName] != DBNull.Value)
                                                                        .Average(x => x.Field<dynamic>(columnName));
    bool isNumeric = true;
    foreach (DataRow row in dt.Rows)
    {
        var type = row[columnName].GetType();
        //not all numeric data types, but close enough for this
        isNumeric = type == typeof(int) || type == typeof(double) || type == typeof(float) || type == typeof(uint)
            || type == typeof(byte);
        if (isNumeric ==false)
        {
            throw new Exception();
        }
    }
    return getAverage(dt);
}

From this I learned that the parameters passed to an inner delegate are matched to the outer delegate, so Intellisense picked up the t parameter as a DataTable (not sure about implications, but neat).  Cool.  My initial thought was to create a private helper method IsNumeric that would return a bool if the value in the DataRow was something we could average.

I know that I could probably improve this a little, but I'm wondering if there's any practical reason to using a closure here, or if there are any potential pitfalls that might make it a bad idea?


texts: Simplifying if else statements in Python code snippet

texts:
How can I simplify and optimize this code?

if type(variant_list) == dict:
    style_color_if(variant_list[style_colors_main], variant_list)
else:
    for variant in variant_list:
        if type(variant[style_colors_main]) == dict:
            json_key_getter(variant[style_colors_main], variant)
        else:
            for styleColors in variant[style_colors_main]:
                if type(styleColors) == dict:
                    json_key_getter(styleColors, variant)
                else:
                    for styleColor in styleColors:
                        json_key_getter(styleColor, variant)

Example of one element of variant list, variant list can have one such thing or many:

http://pastebin.com/axuvzZnh


texts:
I have a library of news articles. Each story is unique by id.

 public String getStory(String id) throws Exception {
        Connection conn = MysqlDb.getConn(dbName);

        try {
            for(Publisher p : Publishers) {
                PreparedStatement prpStmt = conn.prepareStatement("SELECT story FROM " + p + " WHERE id='" + id + "'");
                ResultSet rs = prpStmt.executeQuery();

                while (rs.next()) {
                    String story = rs.getString(1);
                    rs.close();
                    return story;
                }
                rs.close();
            }
        } finally {
            conn.close();
        }
        return null;
    }

Come what may (like an exception, or something), I want to make sure to release the JDBC resources used by the Connection and ResultSet objects. Does finally always execute in Java?

Closing the database connection in a finally block makes sense, right? In the code I've looked at, I've not seen finally really used for anything.
Maybe making sure that the ResultSet closes is not absolutely necessary? But, the close() method must exist for some reason... But, in my method above, the scope is too narrow to be closed by the finally block. What to do? Create another finally with adequate scope for the ResultSet?


texts:
An element in an array X is called a leader if it is greater than all
  elements to the right of it in X. The best algorithm to find all
  leaders in an array.

  Solves it in linear time using a left to right pass of the array
  Solves it in linear time using a right to left pass of the array
  Solves it using divide and conquer in time \$Θ(n \log n)\$
  Solves it in time \$Θ(n^2)\$

At the start the right most element will always be a leader. If an element is greater than our current_max, it will a leader. Add this element to leaders. Set current_max to this element and carry on leftward. Time complexity would be \$O(n)\$.

Can you give an algorithm for another way or better way to find leader in an array?

#include <iostream>
using namespace std;

/* C++ Function to print leaders in an array */
void printLeaders(int arr[], int size)
{
    int max_from_right =  arr[size-1];

    /* Rightmost element is always leader */
    cout << max_from_right << " ";

    for (int i = size-2; i >= 0; i--)
    {
        if (max_from_right < arr[i])
        {
            max_from_right = arr[i];
            cout << max_from_right << " ";
        }
    }
}

/* Driver program to test above function*/
int main()
{
    int arr[] = {16, 17, 4, 3, 5, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    printLeaders(arr, n);
    return 0;
}


texts: Grouping orders by similarity (cluster) of their items

texts:
My task is to write an algorithm for grouping list of orders into batches, each batch consisting of 4 orders. Orders are grouped by similarity of their items, which means the more items from Order X sharing the same location as Order Y's items, the bigger the similarity ratio between both. Note that one order is compared only against equally sized or bigger orders. A similarity ratio of 0 would mean no items match, whereas 1 means 100% match. Also, the biggest order in a batch has ratio of 1 because it's compared only against itself.

The idea behind all this is to optimize the path for a warehouse worker who visit a location and pick the ordered items. In the best case they should pick all identical items with a single visit, then proceed to the next location.

The code below represents a custom class I created for this purpose, but something says me it's not very optimized or could be written better. I'd be very happy if you can help me out and give some advice on what could be improved.

public static class SimilarityCalculator
{
    private static double CalcSimilarityRatio(Order minOrder, Order maxOrder)
    {
        var similarities = 0;

        foreach (var item1 in minOrder.Items)
        {
            foreach (var item2 in maxOrder.Items)
            {
                if (string.Equals(item1.Cluster, item2.Cluster))
                {
                    similarities++;
                    break;
                }
            }
        }

        var ratio = (double)similarities / minOrder.Items.Count;
        ratio = Math.Round(ratio, 3);
        return ratio;
    }

    private static void CheckSimilarities(List<Order> ordersList)
    {
        foreach (var order in ordersList)
        {
            order.MatchingList.Clear();

            var equalOrGreaterOrders = ordersList
                                       .Where(o => o.Items.Count >= order.Items.Count)
                                       .ToList();

            foreach (var equalOrGreater in equalOrGreaterOrders)
            {
                var ratio = CalcSimilarityRatio(order, equalOrGreater);
                var match = new KeyValuePair<Order, double>(equalOrGreater, ratio);
                order.MatchingList.Add(match);
            }
        }
    }

    private static List<KeyValuePair<Order, double>> GetTop4Matches(Order order)
    {
        var top = (from m in order.MatchingList
                   orderby m.Value descending
                   select m)
                   .Take(4)
                   .ToList();

        return top;
    }

    /// <summary>
    /// This method is called for creating the batches. Can be used from another app.
    /// </summary>
    /// <param name="ordersList">All the orders that should be grouped into batches.</param>
    /// <returns>Generated batches consisting of 4 orders each.</returns>
    public static List<List<Order>> GenerateBatches(List<Order> ordersList)
    {
        var batches = new List<List<Order>>();
        while (ordersList.Any())
        {
            CheckSimilarities(ordersList);

            var currentOrder = ordersList.First();
            var top4Matches = GetTop4Matches(currentOrder);
            var batch = new List<Order>();

            foreach (var match in top4Matches)
            {
                batch.Add(match.Key);
                ordersList.Remove(match.Key);
            }

            batches.Add(batch);
        }

        return batches;
    }
}


texts: Using gulp + gulp-babel + browserify to work with ReactJS

texts:
This is my first attempt at setting up a local environment to build a react app. I got my code to work in the browser using this code, but I'm curious if using .pipe(babel) AND .pipe(browserify) is redundant? Is Babel capable of accomplishing the same task that Browserify does?

 const gulp = require('gulp'),
          babel = require('gulp-babel'),
          browserify = require('gulp-browserify'),

var src = './src',
app = './builds/app';

    gulp.task('js', () => {
     return gulp.src(src + '/App.js')
    .pipe(babel({
      presets: ['es2015', 'react','stage-2']
    }))
    .on('error', function (err) {
      console.error('Error!', err.message);
    })
    .pipe(browserify({
      transform: 'babelify',
      debug: true
    }))
    .pipe(gulp.dest('./builds/app/js'));
});