texts:
The following is some code I just wrote.  I keep wondering as always what I can do to make this more efficient. Please help me make this code object oriented and if anyone could help me write automated or even non automated tests for my widget...

Also is this considered a closure? I don't think it is but I would love to know how to produce better quality/reusable code.  Oh- bonus points for any corrections to my techniques used as well.  I'm really trying to step my JS game up and I know it needs work...

var ExplodedContentWidget = $('[data-widget~="exploded-content"]');
// search for existance of the exploded widget in DOM
if (ExplodedContentWidget[0]){
    var ExplodedDefaultEl = $('[data-function~="default-state"]');
    var ExplodedEl = $('[data-function~="exploded-state-1"]');
    var ExplodedEl2 = $('[data-function~="exploded-state-2"]');
    var CloseButton = $('.button-close');
    ExplodedEl.hide(); // default exploded content is hidden
    ExplodedEl2.hide();
    CloseButton.hide();
    ExplodedContentWidget.on('click',function(){
            ExplodedEl.slideToggle('slow');
    });
    var FullScreenViewButton = $('button');
        FullScreenViewButton.on('click',function(){
            ExplodedDefaultEl.hide();
            ExplodedContentWidget.addClass('exploded-fullscreen-state');
            ExplodedEl2.slideToggle('slow');
            CloseButton.fadeIn();
                ExplodedEl2.on('click',function(){
                    ExplodedContentWidget.removeClass('exploded-fullscreen-state');
                    ExplodedDefaultEl.show();
                    ExplodedEl.toggle();
                    ExplodedEl2.toggle();
                    CloseButton.hide();
        });
     });
    }

PS: Here is the fiddle


texts: Java to Beanshell: validate an attribute for each record of a spreadsheet

texts:
Suppose this Java code is converted to Beanshell and called by an application which reads a spreadsheet and validates the department of each employee at a university.

My primary concern is if there is a more efficient, standard, or otherwise better way to go about validating an employee's department rather than how I have done so below.  Null should be returned if the department is invalid.

import java.util.HashSet;
import java.util.Arrays;

public class Test{

    public static final String VALID_DEPARTMENTS[] = {
            "Computer Science", "Biology"
    };

    public static final HashSet<String> set = new HashSet<String>( Arrays.asList(VALID_DEPARTMENTS) );

    public String validate(String dep) {
        if( set.contains(dep) )
            return dep;
        return null;
    }

    public static void main(String[] args){
        Test t = new Test();
        System.out.println( t.validate("CS") );
    }
}


texts:
I have implemented a binary search tree with the methods search, insert, and delete. I want to know if this is the best way to code them or if there are any other way by which I can reduce the code size or redundancies in code, if any.

#include <bits/stdc++.h>
using namespace std;

struct node{
    int val;
    node* left;
    node* right;
    node(){
        left=right=NULL;
    };
    node(int val){
        this->val = val;
        left=right=NULL;
    }
};

struct bTree{
    node* root;
    void insert(int val);
    node* search(int val);
    void deleteVal(int val);
    node* getParent(int val);
    bTree(){
        root = NULL;
    }
    bTree(int val){
        root = new node(val);
    }
};

void bTree::insert(int val){
    if(!root){
        root = new node(val);
        return;
    }
    node* temp = root;
    node* parent = root;
    while(temp){
        parent = temp;
        if(val >= temp->val){temp = temp->right;}
        else{ temp = temp->left;}
    }
    if(val >= parent->val){parent->right = new node(val);}
    else{parent->left = new node(val);}
    return;
}

node* bTree::search(int val){
    node* temp = root;
    while(temp && (temp->val!=val)){
        if(val > temp->val){temp = temp->right;}
        else if(val < temp->val){temp = temp-> left;}
    }
    return temp;
}

node* bTree::getParent(int val){
    if(!root || (root->val == val)){return NULL;}
    node* temp = root;
    node* parent = NULL;
    while(temp){
        if(temp->val == val) return parent;
        if(val < temp->val) {parent = temp; temp= temp->left;}
        if(val > temp->val) {parent = temp; temp= temp->right;}
    }
    return NULL;
}

void bTree::deleteVal(int val){
    node* temp = search(val);
    if(!temp){return;}
    if(!(temp->left) && !(temp->right)){
        if(temp==root){
            root = NULL;
            delete temp;
        }
        else{
            node* parent = getParent(val);
            if(parent->right==temp){parent->right=NULL; delete temp;}
            else{parent->left=NULL; delete temp;}
        }
    }
    else if(!(temp->left) && (temp->right)){
        if(temp==root){
            root = root->right;
            delete temp;
        }
        else{
            node* parent = getParent(val);
            if(parent->right==temp){parent->right=temp->right; delete temp;}
            else{parent->left = temp->right; delete temp;}
        }
    }
    else if((temp->left) && !(temp->right)){
        if(temp==root){
            root = root->left;
            delete temp;
        }
        else{
            node* parent = getParent(val);
            if(parent->right==temp){parent->right = temp->left; delete temp;}
            else{parent->left = temp->left; delete temp;}
        }
    }
    else{
        node* minNode =temp->right;
        while(minNode->left){
            minNode = minNode->left;
        }
        int valStoring = minNode->val;
        deleteVal(minNode->val);
        temp->val = valStoring;
    }
    return;
}

int main(){
    bTree a;
}


texts: Check if more engineers are happy than not happy

texts:
I wish to use this sample to make my code more readable. Could you share with me your ideas on method naming, variable naming, if-statements etc.

It would be great if you have any URLs.

private boolean areEngineersHappy (List<Engineer> engineers) {
  int notHappyEngineers = 0;
  int happyEngineers = 0;
  for (Engineer engineer : engineers) {
    boolean notHappy = !engineer.isHappy();
    if (!notHappy) {
      happyEngineers++;
    }
    if (notHappy) {
      notHappyEngineers++;
    }
  }
  return happyEngineers > notHappyEngineers;
}


texts: Function for adding a tag to the first row of a table is running slowly

texts:
I have a jQuery function which adds a tag to the first row of a table. I previously tried using append, however that didn't work. I now have the following solution which is very slow and it gives this warning:

  A script on this page is causing Internet Explorer to run slowly

Function:

jQuery.fn.fixGridView = function () {
    "use strict";
   // var start = +new Date();  // log start timestamp
    if (jQuery(this).is('table') && this.find('thead').length === 0) {

        var theadv = "

" + this.find('tbody tr:first').html(); +"

";

        this.find('tbody tr:first').remove();
        var htmlv = this.html();
        this.html(theadv + htmlv);
    }
    //var end = +new Date();  // log end timestamp
   // var diff = end - start;
   // alert(diff);
    return this;
};

I have to use IE8, it is client's requirement.
I have also created a jsfiddle.


texts: Reading, echoing, and returning integers in an array

texts:
I was wanting some clarification on my code, as I am new to pointers in C. I am trying to return an array from a simple function just so I can understand exactly what it is that I'm doing.

Here is the code I have so far and, to me, it seems as if I haven't even used the pointers correctly.

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

int *myFunction(int size)
{
    int i;
    int *myArray = malloc(sizeof(int)*size);
    for(i=0;i<size;i++)
    {
        printf("Enter a number: ");
        scanf("%d",&myArray[i]);
    }
    for(i=0;i<size;i++)
    {
        printf("%d\n",myArray[i]);
    }
    return myArray;
}
int main()
{
    int *p;
    int size;
    printf("Enter the size: ");
    scanf("%d",&size);
    p = myFunction(size);
    return 0;
}


texts: Extracting attribute value from multiple XML nodes in golang?

texts:
I'm attempting to parse an SVG file to get all of the colors that are present in the file.  SVGs are XML based and their structure can vary a bit.  For example:

<svg viewBox="-80 -80 160 160">
  <g stroke="black" fill="none">
    <path d='...' fill='#0FF'/>
    <path d='...' fill='#F0F'/>
    ...
  </g>
</svg>

and

<svg viewBox="0 0 100 100">
  <a>
    <path d="..." stroke="black" fill="red"/>
    <ellipse stroke="black" fill="white" cx="50" cy="40" rx="22" ry="35"/>
    <circle cx="50" cy="40" r="5" stroke="black" fill="red"/>
  </a>
</svg>

and

<svg viewBox="0 0 80 120">
  <rect id="background-rect" x="0%" y="0%" width="100%" height="100%" fill="#aaaaaa"/>
</svg>

Are all examples of valid SVGs. At first I attempted to create the underlying structs that would allow me to represent all of these structures but then I decided to take a more generic approach that would focus soley on the fill attribute which is all I care about:

type GenericNode struct {
    XMLName xml.Name
    Fill    string        `xml:"fill,attr"`
    Nodes   []GenericNode `xml:",any"`
}

func (s *SVGController) GetColorsFromXML() []string {
    xmlFile, _ := os.Open(s.Path)
    byteValue, _ := ioutil.ReadAll(xmlFile)
    var svg GenericNode
    xml.Unmarshal(byteValue, &svg)

    // Using a map here to avoid having to worry about having
    // duplicate colors in the color slice
    colorMap := make(map[string]struct{})
    colorMap = getSVGColors(svg, colorMap)

    // Once we have a complete color map extract all the keys
    // to an array and return it.
    colors := make([]string, len(colorMap))
    i := 0
    for k := range colorMap {
        colors[i] = k
        i++
    }
    return colors
}

func getSVGColors(svg GenericNode, colors map[string]struct{}) map[string]struct{} {
    if svg.Fill != "" && strings.ToLower(svg.Fill) != "none" {
        colors[svg.Fill] = struct{}{}
    }
    for _, node := range svg.Nodes {
        colors = getSVGColors(node, colors)
    }
    return colors
}

Is this a reasonable approach to take?  Am I doing anything here that should be avoided?


texts:
I was presented with an interview question described as follows:

Receiving an int[] A of cities, where each A[i] has an appeal value. We want to plan our trip based on the highest appeal possible, taking in mind that is calculated as follows A[i] + A[j] + (i - j). This means the appeal values of 2 cities summed, plus their distance.

Function signature:

public static int solution(int[] A);

The constraints were the following:

N is an integer within [1, 100,000]
A[i] is an integer within [-1,000,000,000, 1,000,000,000]

Using the same value is a possible valid solution, so for example, if we have A = {1, 3, -3}; this should return 6 as visiting city A[0] twice gives the max appeal value A[0] + A[0] + (0 - 0) = 6.

So given that, a possible solution is the same value twice, I did not found other solution than:

int highestAppeal = 0;

for (int i = 0; i < A.length; i++) {
    for (int j = 0; j < A.length; j++) {
        int currentAppeal = A[i] + A[j] + (i - j);
        highestAppeal = currentAppeal > highestAppeal ? currentAppeal : highestAppeal;
    }
}

return highestAppeal;

This solution was marked as pretty bad. I realize that a \$O(n^2)\$ solution is far from efficient, but in this case, I did not see how to improve it. Later on, I thought about sorting A values in descending order and, for repeated values, using indexes in ascending order. But I don't see that going forward.

What would be a better and more efficient solution for this?


texts: Rock Paper Scissors in one single method in Java - Good or bad?

texts:
I'm new to programming and have created a simple Rock, Paper, Scissors game. The entire program is under a single class and the main method.  I hear that's probably not the best way to code.

How should I have written this to utilize multiple classes or to adhere to best practice?

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

public class RPS {
    public static void main(String args[]){

    String choice, choice1;
    int num = 0;
    Random r = new Random();
    num = r.nextInt(3);

    System.out.println("Choose: Rock, Paper or Scissors.");
    Scanner userChoice = new Scanner(System.in);
    choice1 = userChoice.next();
    choice = choice1.toLowerCase();

    switch (num){
    case 0:
        String num1 = "rock";
        System.out.println("System chose Rock");
        if (choice.matches(num1)){
            System.out.println("Its a tie!");

            }
        else if (choice.matches("paper")){
            System.out.println("You win!");

        }
        else if (choice.matches("scissors")){
            System.out.println("You lose!");
        }
        else {
            System.out.println();
            System.out.println("ERROR: Please choose Rock, Paper or Scissors");
        }
    break;
    case 1:
        String num2 = "paper";
        System.out.println("System chose Paper");
        if (choice.matches(num2)){
            System.out.println("Its a tie!");

        }
        else if (choice.matches("scissors")){
            System.out.println("You win!");

        }
        else if (choice.matches("rock")){
            System.out.println("You lose!");
        }
        else {
            System.out.println();
            System.out.println("ERROR: Please choose Rock, Paper or Scissors");
        }
    break;
    case 2:
        String num3 = "scissors";
        System.out.println("System chose Scissors");
        if (choice.matches(num3)){
            System.out.println("Its a tie!");

        }
        else if (choice.matches("rock")){
            System.out.println("You win!");

        }
        else if (choice.matches("paper")){
            System.out.println("You lose!");
        }
        else {
            System.out.println();
            System.out.println("ERROR: Please choose Rock, Paper or Scissors");
        }
    break;

    }

}
}


texts: Passing Node objects into insert routine of linked list

texts:
I've created a linked list class in Python, but I'm not sure how to enforce only passing Node objects into the insert routine.

# linked list in Python

class Node:
    """linked list node"""
    def __init__(self, data):
        self.next = None
        self.data = data
    def insert(self, n):
        n.next = self.next
        self.next = n
        return n
    def showall(self):
        print self.data
        if self.next != None:
            self.next.showall()

ll = Node("one")
ll.insert(Node("two")).insert(Node("three"))
ll.showall()


texts:
I had heard about sorting for a while, but never actually gave it a try. So I decided to make an algorithm that would sort the members of a vector from least to greatest. Though this may seem pretty simple and/or silly, I actually put a lot of thought into it and wrote out tables/diagrams.

#include <iostream>
#include <vector>

namespace{
    typedef unsigned int uint;
}

std::vector<int> sort(std::vector<int>a)
{
    for (int i = 1; i < a.size(); ++i){
        for (int j = 0; j < a.size() - 1; ++j){
            if (a[j] > a[i]) std::swap(a[j], a[i]);
        }
    }

    return a;
}

int main()
{
    std::vector<int> a = { 17, 12, 1, 20, 4, 6, 94 };

    for (uint i = 0; i < a.size(); ++i){
        std::cout << sort(a)[i] << std::endl;
    }
}

I know there's probably some sort function part of the standard C++ library, but for a sort function from scratch, how efficient is this? What could I do to improve it?


texts:
I am a beginner to JavaScript and I know about jQuery Validations however I do not want to use a foundation like jQuery just yet.

I am wondering if what I have done its good or if there is another way to do it other then jQuery?

I won't post the html just the JS. It does work by the way! Just wondering if there is a better way!

function validateForm() {
  var userName = document.forms["register"]["username"].value;
  var passWord = document.forms["register"]["password"].value;
  var c_passWord = document.forms["register"]["c_password"].value;

  if (userName == null || userName == "") {
    alert("Your username can not be empty!");
    return false;
  } else if (userName.length < 3) {
    alert("Your username must be atleast 3 characters long!");
    return false;
  }

  if (passWord == null || passWord == "") {
    alert("Your password can not be empty");
    return false;
  } else if (passWord.length < 5) {
    alert("Your password must be more the 5 characters");
    return false;
  }
}


texts: Appropriate separation of concerns for this case?

texts:
This is a method that calls a web service, it uploads an audio file and fetches metadata back.

While the advantage is that there is only one method to call there are a few concerns about it :

There is some UI-related code (upload progress)
Some audio-related code (format detection)
Web-service related code (first purpose)

In the end, while it tries to be smart, it's completely tied to a particular audio library, it will report progress anyway and well, it doesn't only upload ...

How would you apply separation of concerns to this current method ?

Would transforming the fileFormat to a parameter be acceptable ?
What about handler, how can it be used without being tied to the upload process ?

I'm not necessarily asking for code, directions to some documentation on the subject is fine too.

public class TrackUpload
{
    public async Task<string> Upload(string apiKey, string path, ProgressEventHandler handler)
    {
        if (apiKey == null) throw new ArgumentNullException("apiKey");
        if (path == null) throw new ArgumentNullException("path");
        using (var stream = new ReadOnlyFileStream(path))
        {
            if (handler != null)
            {
                stream.ProgressChanging += handler;
            }

            string fileFormat = TrackFormatDetector.Detect(path);
            if (fileFormat == null)
            {
                throw new InvalidAudioFormatException();
            }

            var dataContent = new MultipartFormDataContent();
            dataContent.Add(new StringContent(apiKey), "api_key");
            dataContent.Add(new StringContent(fileFormat), "filetype");
            dataContent.Add(new StreamContent(stream), "track");
            var client = new HttpClient();
            client.DefaultRequestHeaders.UserAgent.Add(
                new ProductInfoHeaderValue(new ProductHeaderValue("xxxx", "1.0")));
            HttpResponseMessage response =
                await client.PostAsync(@"http://developer.echonest.com/api/v4/track/upload", dataContent);
            response.EnsureSuccessStatusCode();
            HttpContent content = response.Content;

            if (handler != null)
            {
                stream.ProgressChanging -= handler;
            }

            using (var reader = new StreamReader(await content.ReadAsStreamAsync()))
            {
                string s = await reader.ReadToEndAsync();
                return s;
            }
        }
    }
}


texts: Calculating the squares dominated by a queen on a chessboard

texts:
I have a JavaScript function that increments a counter for each square on the chessboard as it becomes dominated by a queen and decrements it if one of the dominating queens are removed (only queens, this isn't actually a chess game with all of the pieces, it's essentially the 8 queens puzzle). If a square is dominated by at least one queen, (e.g. square.dominatedBy > 0), a CSS class is later applied to change the color of the square.

The function seems far longer than it needs to be though, and there has to be a better way to DRY it up.

(chessBoardSquares is an array of an array of Squares on the board, which are objects with properties such as row, column, and dominatedBy)

function setDominatedSquares(queenPosition, remove = false) {
    // handle squares in the same row as the queen
    for (var column = 0; column < boardSizeX; column++) {
        if (remove) {
            chessBoardSquares[queenPosition.row][column].dominatedBy--;
        } else {
            chessBoardSquares[queenPosition.row][column].dominatedBy++;
        }
    }
    // handle squares in the same column as the queen
    for (var row = 0; row < boardSizeY; row++) {
        if (remove) {
            chessBoardSquares[row][queenPosition.column].dominatedBy--;
        } else {
            chessBoardSquares[row][queenPosition.column].dominatedBy++;
        }
    }
    // handle diagonals down and to right
    var row = queenPosition.row;
    var column = queenPosition.column;
    while (row < boardSizeY && column < boardSizeX) {
        if (remove) {
            chessBoardSquares[row][column].dominatedBy--;
        } else {
            chessBoardSquares[row][column].dominatedBy++;
        }
        row++;
        column++;
    }
    // handle diagonals up and to left
    row = queenPosition.row;
    column = queenPosition.column;
    while (row >= 0 && column >= 0) {
        if (remove) {
            chessBoardSquares[row][column].dominatedBy--;
        } else {
            chessBoardSquares[row][column].dominatedBy++;
        }
        row--;
        column--;
    }

    // handle diagonals down and to left
    row = queenPosition.row;
    column = queenPosition.column;
    while (row >= 0 && column < boardSizeX) {
        if (remove) {
            chessBoardSquares[row][column].dominatedBy--;
        } else {
            chessBoardSquares[row][column].dominatedBy++;
        }
        row--;
        column++;
    }

    // handle diagonals up and to right
    row = queenPosition.row;
    column = queenPosition.column;
    while (row < boardSizeY && column >= 0) {
        if (remove) {
            chessBoardSquares[row][column].dominatedBy--;
        } else {
            chessBoardSquares[row][column].dominatedBy++;
        }
        row++;
        column--;
    }
    // update the UI
    updateDominatedSquares();
}

Update: For anyone interested, this code is now running live at queensoptimization.azurewebsites.net


texts: HTML parser written in JavaScript that takes in strings and output a DOM tree object

texts:
I wrote an HTML parser in JavaScript, where it takes an a string that represents the HTML
const html =
`

foo

bar

`

And it should output an object like this
{
    children: [
      { children: ['foo'], value: 'div' },
      { children: ['bar'], value: 'div' },
    ],
    value: 'div',
  }

here is my attempt
function parser(html) {
  const tokens = html.split('\n')
  const stack = []
  tokens.forEach((token) => {
    if (token === '
') {
      const children = []
      while (stack[stack.length - 1] !== '
') {
        children.unshift(stack.pop())
      }
      stack.pop()
      stack.push({
        children,
        value: 'div',
      })
    } else {
      stack.push(token)
    }
  })
  return stack.pop()
}

const html =
`

foo

bar

`

function parser(html) {
  const tokens = html.split('\n')
  const stack = []
  tokens.forEach((token) => {
    if (token === '
') {
      const children = []
      while (stack[stack.length - 1] !== '
') {
        children.unshift(stack.pop())
      }
      stack.pop()
      stack.push({
        children,
        value: 'div',
      })
    } else {
      stack.push(token)
    }
  })
  return stack.pop()
}

console.log(parser(html))

My questions are:

How can I modify the code so it can become easily expandable for other HTML tag body, div, span etc.
Right now the HTML string it takes has to be valid. How can I modify the code so it can detect invalid HTML
Right now the HTML string it takes doesn't have any indentation. How can I modify the code so it can allow indentations in the input strings?


texts:
I am developing a Python script that will process large amounts of data from an experiment. Files are read in, calculations are made, images are plotted and saved as .pngs, and calculated parameters are outputted to a .txt file.

When I save a file, the user is prompted if they want to overwrite any existing files. If yes, a file overwrite is attempted. If the file is locked/open in another program, a number is appended to the filename and then saved. If they do not want to overwrite, a number is appended to the filename.

In order to not have redundant code, I wrote a generic "save" method:

def _handle_file_save(path, save, overwrite, *args):
    """
    Handles file collisions when saving files. If "overwrite" is true,
    overwrites file, if "overwrite" is false or the file to be overwritten
    is locked from editing, appends a number on end of filename to avoid
    file collision.

    Args:
        path (str): the path to the file to be saved
        save(): The save function used to save file
        overwrite (bool): true if user wants to overwrite file
        args: generic tuple of arguments used for different save functions

    """
    if os.path.isfile(path):
        if overwrite:
            try:
                print "Saving \"" + path + "\""
                save(path, args)
            # Signifies problem writing file (lack of permissions, open
            # in another program, etc.)
            except EnvironmentError:
                # save as incremented file number
                print "Whoops! Looks like %s is locked!" % path
                path = gen_alt_filename(path)
                save(path, args)
        else:
            # save as incremented file number
            path = gen_alt_filename(path)
            print "Saving as \"" + path + "\" instead"
            save(path, args)
    else:
        print "Saving \"" + path + "\""
        save(path, args)
    print "\n"

I pass in a generic save function and any arguments that save function needs if any. Some file outputs don't require any arguments.

Flaws:

The client could pass in any arbitrary function as "save" and execute it. Is this a security risk?
The variable args gets passed to the save function regardless of whether that method actually takes any args (i.e. args could be empty, but gets passed anyway.
Doesn't check if appended filepath is also a locked/open file (could fix this with a while loop I suppose).

Possible improvements:

Use Python's functools.partial to reduce the function call's signature to one without "args" if args is empty.

Alternative:

Instead of passing a generic save function, I could replace "save(path, args)" with "new_file = open(path, 'w')" (i.e. test file write, if successful, return the path to that file and write there).
Don't merge code, let every save method handle its own collisions separately.

Nothing about any of this seems elegant. I'd greatly appreciate some advice on this, and how I can improve my coding strategies.


texts:
I wrote this code a while back and I have recently been rewriting most of my code. I just to know if these methods can be improved. The ones that pop out to me are listed below; others don't matter as much.

Methods that need improving:

FilterInjectionChars
IsValidAlphaNumeric
FilterFigure

namespace Apple.Application.Core
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class AppleFunctions
    {
        private readonly HashSet<char> _allowedCharacters;

        public AppleFunctions()
        {
            _allowedCharacters = new HashSet<char>(new[] { '-', '.', ' ', 'Ã', '©', '¡', '', 'º', '³', 'Ã', '‰', '_' });
        }

        public bool GetBoolFromEnum(string EnumValue)
        {
            return Convert.ToBoolean(EnumValue);
        }

        public bool GetBoolFromEnum(int EnumValue)
        {
            return Convert.ToBoolean(EnumValue);
        }

        public int GetEnumFromBool(bool BoolValue)
        {
            return BoolValue ? 1 : 2;
        }

        public bool IsNumber(string StringValue)
        {
            int Number;
            return int.TryParse(StringValue, out Number);
        }

        public int CompareMilleseconds(DateTime time, DateTime from)
        {
            DateTime DateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return Convert.ToInt32((from.Subtract(DateTime).TotalMilliseconds - time.Subtract(DateTime).TotalMilliseconds));
        }

        public int GetUnixTimestamp()
        {
            return (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
        }

        public DateTime GetUnixToDate(int unixTimeStamp)
        {
            DateTime Datetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            return Datetime.AddSeconds(unixTimeStamp).ToLocalTime();
        }

        public DateTime GetUnixToDate(double unixTimeStamp)
        {
            DateTime Datetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            return Datetime.AddSeconds(unixTimeStamp).ToLocalTime();
        }

        public int GetDateToUnix(DateTime time)
        {
            DateTime Datetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            return Convert.ToInt32((time - Datetime).TotalSeconds);
        }

        public string GetDateJoinString(long timeStamp) // MOVE THIS TO GROUP
        {
            string[] time = GetUnixToDate(timeStamp).ToString("MMMM/dd/yyyy").Split('/');
            return String.Format("{0} {1}, {2}", time[0].Substring(0, 3), time[1], time[2]);
        }

        public long GetNow()
        {
            double totalMilliseconds = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
            return ((long)totalMilliseconds);
        }

        private bool IsValidCharacter(char c)
        {
            return char.IsLetterOrDigit(c) || _allowedCharacters.Contains(c);
        }

        /* METHODS TO IMPROOVE ARE BELOW */

        public string FilterFigure(string FigureCode)
        {
            return FigureCode.Any(character => !IsValidCharacter(character)) ? "lg-3023-1335.hr-828-45.sh-295-1332.hd-180-4.ea-3168-89.ca-1813-62.ch-235-1332" : FigureCode;
        }

        public bool IsValidAlphaNumeric(string inputStr)
        {
            inputStr = inputStr.ToLower();
            if (string.IsNullOrEmpty(inputStr))
                return false;
            return inputStr.All(IsValidCharacter);
        }

        public string FilterInjectionChars(string input)
        {
            input = input.Replace('\u0001', ' ');
            input = input.Replace('\u0002', ' ');
            input = input.Replace('\u0003', ' ');
            input = input.Replace('\t', ' ');
            return input;
        }
    }
}


texts: Dynamically call lambda based on stream input: Try 3

texts:
Based on Dynamically call lambda based on stream input: Try 2

This fixes most of the points pointed out by @Morwenn.

It has been generalized so anybody can call it.
The only extra part needed by the code is a function to retrieve values from a stream. This is passed as a template argument to  callFunctor() see the example below.

An example of how to use it:
Here I use std::stringstream as the input to be used for this example. In my own version I have a DB socket streaming rows from a MySQL DB and the lambda is called for each row. The point is the current version of callFunctor() can be used in any general environment (I hope somebody finds it useful).

main.cpp

#include "detail_caller.h"
#include <iostream>
#include <sstream>

struct GetStreamValue
{
    // The input type to this method must match
    // the type of the first argument to `callFunctor`
    // As you will be passed the stream and asked to pull
    // a specific type from it.
    template<typename R>
    static R get(std::istream& stream)
    {
        R   result;
        stream >> result;
        return result;
    }
};

int main()
{
    std::stringstream       data("10 13 Loki 4.5");

    callFunctor<GetStreamValue>(
        data,
        [](int val1, int val2, std::string const& val3, float val4)
        {
            std::cout << "Got(" << val1 << ", "
                                << val2 << ", "
                                << val3 << ", "
                                << val4 << ")\n";
        }
    );
}

detail_caller.h

#ifndef THORSANVIL_DETAIL_CALLER_H
#define THORSANVIL_DETAIL_CALLER_H

#include <utility>

template <typename T>
struct CallerTraits
    : public CallerTraits<decltype(&T::operator())>
{};

template<typename C, typename ...Args>
struct CallerTraits<void (C::*)(Args...) const>
{
    static constexpr int                                        size = sizeof...(Args);
    typedef std::make_integer_sequence<int, size>               Sequence;
    typedef std::tuple<std::decay_t<Args>...>                   AllArgs;
};

template<typename StreamValueGetter, typename Action, typename Stream, int... S>
void expandArgsAndCallFunctor(Stream& stream, Action action, std::integer_sequence<int, S...>)
{
    typedef CallerTraits<decltype(action)>  Trait;
    typedef typename Trait::AllArgs         ArgumentTuple;

    // ArgumentTuple  arguments(StreamValueGetter::template get<typename std::tuple_element<S, ArgumentTuple>::type>(stream)...);
    // action(std::get<S>(arguments)...);

    // The above two commented out lines
    // Represent the logic of the following line which retrieves
    // and calls the arguments in a single line thus avoiding temporaries.
    action(StreamValueGetter::template get<typename std::tuple_element<S, ArgumentTuple>::type>(stream)...);
}

template<typename StreamValueGetter, typename Action, typename Stream>
void callFunctor(Stream& stream, Action action)
{
    typedef CallerTraits<decltype(action)>  Trait;
    typedef typename Trait::Sequence        Sequence;

    expandArgsAndCallFunctor<StreamValueGetter>(stream, action, Sequence());
}

#endif


texts: Make external js file in ASP.NET MVC with razor path

texts:
I have js code , that I decided to move to external js.

In this code I have razor syntax (url path)

Here is code of those functions

 function getStops() {
    var url = $('#map').data('request-url');
    $.getJSON(url,
        function (data) {
            var marker = [];

            $.each(data,
                function (i, item) {
                    marker.push({
                        'location': new google.maps.LatLng(item.Latitude2, item.Longitude2),
                        'map': map,
                        'weight': item.Difference,
                        'radius': 10
                    });
                });
            var pointArray = new google.maps.MVCArray(marker);

            heatmap = new google.maps.visualization.HeatmapLayer({
                data: pointArray
            });
            heatmap.setMap(map);
        });
};

// get Driving and show on layer
function getDriving() {
    var url = $('#map').data('request-url2');
    $.getJSON(url,
        function (data) {
            var marker = [];

            $.each(data,
                function (i, item) {
                    marker.push({
                        'location': new google.maps.LatLng(item.Latitude2, item.Longitude2),
                        'map': map,
                        'weight': item.Speed,
                        'radius': 10
                    });
                });
            var pointArray = new google.maps.MVCArray(marker);

            heatmap = new google.maps.visualization.HeatmapLayer({
                data: pointArray
            });
            heatmap.setMap(map);
        });

I know about data-request-url that I can write in element. in my case it's div.

So I wrote it like this on font-end

<div id="map" data-request-url="@Url.Action("GetStops", "Home")" data-request-url2="@Url.Action("Driving", "Home")">

Is this right, or I can do it in other way?


texts: Sphere Online Judge, Problem 2: Prime Number Generator

texts:
I am trying to solve this problem on Sphere Online Judge. I keep getting a timeout error. Any comments or suggestions are welcome and appreciated.

package info.danforbes.sphere;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.MalformedInputException;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;

public class PrimeNumberGenerator {
  private static BufferedReader inStream;
  private static BufferedWriter outStream;
  private static List<Entry<Integer, Integer>> pairs = new ArrayList<Entry<Integer, Integer>>();
  private static HashSet<Integer> primes = new HashSet<Integer>();

  private static void getPairs(int numCases) throws MalformedInputException {
    String line;
    int spaceNdx;
    int num1, num2;
    try {
      for (int pairNdx = 0; pairNdx < numCases; ++pairNdx) {
        line = inStream.readLine();
        spaceNdx = line.indexOf(' ');
        num1 = Integer.parseInt(line.substring(0, spaceNdx));
        num2 = Integer.parseInt(line.substring(spaceNdx + 1));
        if (num1 < 1) throw new MalformedInputException(num1);
        if (num1 > num2) throw new MalformedInputException(num2 - num1);
        if (num2 > 1000000000) throw new MalformedInputException(num2);
        if (num2 - num1 > 100000) throw new MalformedInputException(num2 - num1);
        pairs.add(new SimpleEntry<Integer, Integer>(num1, num2));
      }
      inStream.close();
    } catch (IOException e) {
      System.out.println("IOException encounterd!");
      e.printStackTrace();
      System.exit(-1);
    }
  }

  private static boolean isPrime(int num) {
    boolean isPrime = true;
    if (num < 2) isPrime = false;
    else if (num > 3) {
      if (num % 2 == 0 || num % 3 == 0) isPrime = false;
      else if (!primes.contains(num)){
        int sqrRoot = (int)Math.sqrt(num);
        for (int factorNdx = 1; 6 * factorNdx - 1 <= sqrRoot; ++factorNdx) {
          if (num % (6 * factorNdx + 1) == 0 || num % (6 * factorNdx - 1) == 0) {
            isPrime = false;
            break;
          }
        }
      }
    }

    if (isPrime) primes.add(num);
    return isPrime;
  }

  public static void main(String[] args) {
    if (args.length == 0) {
      inStream = new BufferedReader(new InputStreamReader(System.in));
      outStream = new BufferedWriter(new OutputStreamWriter(System.out));
    }

    StringBuilder resultBuilder = new StringBuilder();

    try {
      if (inStream == null && outStream == null) {
        inStream = new BufferedReader(new FileReader(args[0]));
        outStream = new BufferedWriter(new FileWriter(args[1]));
      }

      int numCases = Integer.parseInt(inStream.readLine());
      if (numCases > 10) throw new MalformedInputException(numCases);
      getPairs(numCases);
      int beg, end;
      for (Entry<Integer, Integer> anEntry : pairs) {
        beg = anEntry.getKey();
        end = anEntry.getValue();
        for (int rangeNdx = beg; rangeNdx <= end; ++rangeNdx) {
          if (isPrime(rangeNdx)) resultBuilder.append(Integer.toString(rangeNdx) + "\n");
        }

        resultBuilder.append("\n");
      }

      resultBuilder.delete(resultBuilder.length() - 2, resultBuilder.length());
      outStream.write(resultBuilder.toString());
      outStream.close();
    } catch (IOException e) {
      System.out.println("IOException encountered!");
      e.printStackTrace();
      System.exit(-1);
    }
  }
}


texts: HTML 5 form validation and form handling

texts:
Problem Statement

  Create one form having following fields

  1) Email ( with html5 email validation).

  2) Password (It should take minimum 6 charactors ).

  3) Your project URL ( with html5 url validation).

  4) Project completion date ( with html5 date validation).

  5) Current month ( with html5 month validation).

  6) Current week (with html5 week validation).

  7) Current time (with html5 time validation).

  8) Select color (with html5 color features).

  9) Age (with html5 range features and also show the selected age ).

  10) Your hobbies (with html5 data list ).

  Expected output

Solution

        <title>Form validation</title>
        <meta charset="UTF-8">

Fill The Form

        <form method="POST" action="javascript:void(0)" enctype="multipart/form-data">
                <input type="email" name="email_id" placeholder="Email" required autocomplete="off" autofocus="on" pattern="^[A-Za-z0-9_-.]+@[A-Za-z-]{3, 4}\.[A-Za-z]{2, 3}$">

                <input type="password" name="password" placeholder="Password" required autocomplete="on" pattern="^[A-Za-z0-9_.-]{6, 10}$">

                <input type="url" name="url" placeholder="your project URL" required autocomplete="on">

                <input type="date" name="projectCompletionDate" placeholder="Project completion date" required autocomplete="off">

                <input type="month" placeholder="Current month" required autocomplete="on">

                <input type="week" placeholder="Current week" required autocomplete="on">

                <input type="time" placeholder="Current time" required autocomplete="on">

                Select color:<input type="color" required autocomplete="on">

                Age:<input type="range" required autocomplete="on">

                Hobbies:<input list="hobbies" name="hobby">
                                          <datalist id="hobbies">
                                            <option value="Soccer">
                                            <option value="Reading">
                                            <option value="Golf">
                                            <option value="Swimming">
                                            <option value="Tennis">
                                          </datalist>
                <input type="submit" value="Submit Query">
        </form>

1) Can this solution be improved?

2) Can regex patterns be avoided?


texts:
My context is a very simple filter-like program that streams lines from an input file into an output file, filtering out lines the user (well, me) doesn't want. The filter is rather easy, simply requiring a particular value for some 'column' in the input file. Options are easily expressed with argparse:

parser.add_argument('-e', '--example', type=int, metavar='EXAMPLE',
    help='require a value of %(metavar)s for column "example"')

There's a few of these, all typed. As the actual filter gets a line at some point, the question whether to include such a line is simple: split the line and check all the required filters:

c1, c2, c3, *_ = line.split('\t')
c1, c2, c3 = int(c1), int(c2), int(c3) # ← this line bugs me

if args.c1 and args.c1 != c1:
    return False

The second line of which bugs me a bit: as the values are initially strings and I need them to be something else, the types need to be changed. Although short, I'm not entirely convinced this is the best solution. Some other options:

create a separate function to hide the thing that bugs me;
remove the type= declarations from the options (also removes automatic user input validation);
coerce the arguments back to strs and do the comparison with strs (would lead to about the same as what I've got).

Which of the options available would be the 'best', 'most pythonic', 'prettiest'? Or am I just overthinking this...


texts: Solution to Project Euler #1 - multiples of 3 and 5

texts:
I have been programming for about ~2 years, and mostly wrote OOP and structural code. Recently, I have decided to pick up a functional programming language, and Haskell being too alien for me, looked to Racket (since it is high time I learned a LISP anyways) and am loving it. Since this is a new area of programming for me, I would appreciate any feedback you could give me on this program. It is the solution to the first Project Euler program.

;If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
;Find the sum of all the multiples of 3 or 5 below 1000.

#lang racket

(define max 1000)

(define (multiple_of base test)
    (equal? (remainder test base) 0))

(define (primes current total)
    (if (< current max)
        (primes
            (+ current 1)
            (+ total (if
                (or (multiple_of 5 current) (multiple_of 3 current)) current 0)))
        total))

(primes 1 0)

; Output: 233168
; Success


texts:
Challenge Description:

  If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.
  Source

I want to receive advice on my code.

total_sum = 0
for i in range(1000):
    if (i%3 == 0 or i%5 == 0):
        total_sum = total_sum+i
print total_sum


texts:
I wrote a memory bus struct in golang to allow systems to interact with each other without knowing anything about the receiver.

This is for a game engine. I know it's not good to write games in garbage collected languages like golang, but I enjoy writing in golang so whatever. But since golang has a garbage collector and can cause the game to freeze I want to make sure that the message bus is optimized and not the cause of any freezes. (Besides the obvious overhead to using a message bus)

When looking up what causes the gc to struggle I learned that pointers are a major killer bc it requires the gc to go searching for the pointer. I'd like to know if there is a better way of adding receivers and sending messages that don't require pointers to the message bus.

Here is the MessageBus:

type Message string

type MessageBus struct {
    recievers []func(Message)
    messages  chan Message
}

var (
    WaitGroup sync.WaitGroup
)

func (mb *MessageBus) AddReceiver(r func(Message)) {
    mb.recievers = append(mb.recievers, r)
}

func (mb *MessageBus) GetMessageChan() chan Message {
    return mb.messages
}

func (mb *MessageBus) Shutdown() {
    close(mb.messages)
}

func (mb *MessageBus) Start() {
    for msg := range mb.messages {
        fmt.Println(msg)
        for _, f := range mb.recievers {
            WaitGroup.Add(1)
            go f(msg)
        }
        WaitGroup.Wait()
    }
}

func New() MessageBus {
    return MessageBus{[]func(Message){}, make(chan Message, 1000)}
}

Here is an example of a handler:

type Input struct {
    mb chan<- messagebus.Message
}

func New(mb chan<- messagebus.Message) Input {
    r := Input{mb}
    return r
}

func (r Input) HandleMessage(m messagebus.Message) {
    defer messagebus.WaitGroup.Done()

    time.Sleep(time.Second)
    switch m {
    case "HI":
        r.mb <- "A_PRESSED"
    case "BYE":
        r.mb <- "B_PRESSED"
    }
}

func (r Input) Update() {}

Any help to speed up the transfers or prepare for garbage collection would be much appreciated!


texts:
Following from this question

I created a Image cache of sorts (let's call it version 1.0) that used WeakReference as "cache" items. And this comes from the accepted answer:

  It looks like weak reference would serve the purpose of what you are trying to achieve [IF] those images will go out of scope (not being directly referenced in any execution path) after handing them back to the caller of that method then they will be collected by GC at some point.

Here is the code that references on any way the images:

Note: cardBaseId and level are used to identify unambiguously a card, and thereby its image.

On the XAML:

<Image x:Name="Portrait" Style="{StaticResource Portrait}">
    <Image.Source>
        <MultiBinding Converter="{StaticResource PortraitConv}">
            <Binding Path="CardBaseId" />
            <Binding Path="MaxLevel" />
        </MultiBinding>
    </Image.Source>
</Image>

On the IValueConverter:

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int cardBaseId = (int)values[0];
        int level = (int)values[1];
        return ImageManagerInstance.GetImage(cardBaseId, level);
    }

On ImageManager.cs:

    public BitmapImage GetImage(int cardBaseId, int level)
    {
        Debug.Assert(FilepathManagerInstance != null);

        string filepath = FilepathManagerInstance.GetImageFilepath(cardBaseId, level);
        return new BitmapImage(new Uri(filepath));
    }

So I'd say that the images are not on the scope of my code anymore once they are sent to the XAML.

Still, I've changed the implementation to use MemoryCache as sugested for the reason above, and because this way I have more control of how memory is managed.

Here is the new code:

public class ImageCache
{
    private string Filepath;
    private MemoryCache Cache;
    private TimeSpan SlidingExpiration;

    public ImageCache(string filepathToStoredImages, int cacheMemoryLimitMegabytes, TimeSpan slidingExpiration)
    {
        Filepath = filepathToStoredImages;
        NameValueCollection config = new NameValueCollection();
        config.Add("CacheMemoryLimitMegabytes", cacheMemoryLimitMegabytes.ToString());
        Cache = new MemoryCache("ImageCache", config);
        SlidingExpiration = slidingExpiration;
    }

    public BitmapImage GetImage(int id)
    {
        string identifier = id.ToString();
        BitmapImage image = Cache.Get(identifier) as BitmapImage;

        if (image == null)
        {
            image = GetFromDisk(id);
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.SlidingExpiration = SlidingExpiration;
            Cache.Set(identifier, image, policy);
        }

        return image;
    }

    private BitmapImage GetFromDisk(int id)
    {
        Uri uri = new Uri(Filepath + id + ".png");
        return new BitmapImage(uri);
    }
}

Is the first time I use the MemoryCache class so any insight if this code is correct or something should be changed or improved?


texts:
Would love some feedback on this.  I'm coming from a Java background and kinda feel like I've just done exactly what I would do in Java. Is there a better way?

for (i <- 1 to 100) {
  if ( i % 3 == 0 && i% 5 == 0)
    println(i +" = FizzBuzz")
  else if (i % 3 == 0)
    println(i +" = Fizz")
  else if (i % 5 == 0)
    println(i +" = Buzz")
}


texts:
Here is a very handy subclass of Operation that allows to do asynchronous tasks inside an OperationQueue:

public class ManuallyCompletableOperation: Operation {
    var debugLabel: String?

    // Override read-only superclass property as read-write.
    private(set) override public var isExecuting: Bool {
        get { return _isExecuting }
        set {
            willChangeValue(forKey: "isExecuting")
            _isExecuting = newValue
            didChangeValue(forKey: "isExecuting")
        }
    }

    // Override read-only superclass property as read-write.
    private(set) override public var isFinished: Bool {
        get { return _isFinished }
        set {
            willChangeValue(forKey: "isFinished")
            _isFinished = newValue
            didChangeValue(forKey: "isFinished")
        }
    }

    private var _isFinished = false
    private var _isExecuting = false

    /**
     - Important: Never put strong reference to the operation inside the block.
     */
    var block: (()->())?

    override public func start() {
        if isCancelled {
            isFinished = true
            return
        }

        isExecuting = true

        if let existingBlock = block {
            existingBlock()
        } else {
            complete()
        }
    }

    public override func cancel() {
        block = nil
        super.cancel()
    }

    /**
     This must be called somewhere inside the block
     in order to complete the operation.
     */
    func complete() {
        block = nil
        isExecuting = false
        isFinished = true
    }
}

Usage:

let op = ManuallyCompletableOperation()
op.block = { [weak op] in
    // ...
    doAsyncStuffWithCompletion({
        // ...
        op?.complete()
    })
}

I understand that this class is vulnerable.

1)
If complete() isn't called the entire queue will get stuck.

2)
Putting strong reference to the operation inside the block will lead to retain cycle.

How can I improve ManuallyCompletableOperation design to reduce risks of wrong usage? May be there are exist some patterns or best practices applicable to this case?


texts:
I started learning Python and wrote my first program. This is a console game based on guessing the number. Can you take a look and tell me if I'm doing it right or give me any advice? Here is the code: https://github.com/theriseq/GuessTheNumber

Is it a good way of doing this or can I simplify it?

Thank you.

main.py

from can_convert import check
import random

welcome_msg = """Welcome to GuessTheNumber Game!
I\'m thinking of a number between 1 and 100.
Can you guess this number?

[?] Type \'pass\' to exit game.
"""
print(welcome_msg)

number_to_guess = random.randrange(1, 101)
attemps = 0

while True:
    user_inp = str(input("Your choice: "))
    if user_inp != "pass":
        if check(user_inp):
            attemps += 1
            # print('is int')
            if int(user_inp) < number_to_guess:
                print("Your guess is too small.")
            elif int(user_inp) > number_to_guess:
                print("Your guess is too high.")
            else:
                print("Correct! You won the game!")
                print(f"Attemps: {attemps}")
                break
        else:
            print('Enter numbers only!')
    else:
        break

can_convert.py

def check(to_check):
    try:
        int(to_check)
        return True
    except ValueError:
        return False


texts: Using deque for composing a string from 2 alternating stacks

texts:
We have 2 strings, say "JACK" and "DANIELS". We create two stacks from these strings, and then loop over them comparing first elements: whichever of the 2 goes first in lexicographic order gets popped from its stack and added to a string (the second value is left alone). So it goes, until we end up with a string containing all the elements from both stacks. In this example it would be "DAJACKNIELS"

My solution takes advantage of the fact that min function, when applied to deque() objects, returns the one whose first element goes lexicographically first. As it happens, it works well enough for small testcases, but fails large ones, for it takes all the memory it can get and then some.

Perhaps, something can be improved in my code, or there's a better solution altogether (like, without a while loop).

def morgan(a, b):
    string = ""
    stack_a = deque()
    stack_b = deque()

    stack_a.extend(a)
    stack_b.extend(b)
    while True:
        if len(stack_a) != 0 and len(stack_b) != 0:
            if stack_a == min(stack_a, stack_b):
                string += stack_a.popleft()
            else:
                string += stack_b.popleft()
        elif len(stack_a) == 0 and len(stack_b) == 0:
            break
        elif len(stack_a) == 0:
            string += stack_b.popleft()
        elif len(stack_b) == 0:
            string += stack_a.popleft()
    return(string)

Example of a large testcase:

string a: https://pastebin.com/raw/pebMbcA6
string b: https://pastebin.com/raw/bwNEqJcr


texts: Refactor 2 regular expressions in Javascript into 1 statement

texts:
I have the following code, which replaces " " <-- Spaces with "-" <-- Dash.
Because some of the title text will be returned with more spaces, it converts it into 3 dashes.

Examples of Possible Titles:

"Hello  World  From  Jquery"  <--- Notice 2 Spaces between the words, not 1
"Main Title - Sub-Title or description here"

I would like the above titles to be turned into:

"Hello-World-From-Jquery" <---- (Not "Hello--World--From--Jquery")
"Main-Title-Sub-Title-or-description-here" <--- (Not "Main-Title---Sub-Title-or-desc...")

This is what I got so far, but its not ideal as you can see.
Example:

var dirty_url = ui.item.label;
var url = dirty_url.replace(/\s+/g,"-");
var url = url.replace(/---/g,"-");

So basically, I want to convert all spaces and illegal characters (Its for a url) to "-" to be used in a url. I only want a maximum of 1 dash between charactors.


texts:
I am solving this question:

  It's not the rivers that you might be thinking about. The question
  revolves around the concept of digital rivers. A digital river is a
  sequence of numbers where the number following n is n plus the sum of
  its digits.

  FOR EXAMPLE

  12345 is followed by 12360 since 1+2+3+4+5=15 and so 12345 + 15 gives
  12360. similarly 145 is followed by 155. If the unit's digit of a digital river is 'M' we will call it river 'M'. For example, 231 would
  be called river 1.

  river 480 is the sequence beginning {480,492,507,519....} river 483 is
  the sequence beginning {483,498,519,....}. normal streams and rivers
  can meet, and the same is true for digital rivers. This happens when
  two digital rivers share some of the same values.

  FOR EXAMPLE:

  River 480 meets river 483 at 519. river 480 meets river 507 at 507 and
  never meets river 481. Every digital river will eventually meet river
  1, river 3 or river 9.

  Write a program that can determine for a given integer n the value
  where river n first meets one of these three rivers.

  Input

  The input may contain multiple test cases. Each test case occupies a
  separate line and contains an integer \$n\$ (\$1 \le n \le 16384\$). A test case with value of 0 for n terminates the input and this test case must not
  be processed.

  Output

  For each test case in the input first output the test case
  number (starting from 1) as shown in the sample output. Then on a
  separate line output the line "first meets river x at y". Here y is the
  lowest value where river n first meets river x (x = 1 or 3 or 9).If
  river n meets river x at y for more than one value of x, output the
  lowest value. Print a blank line between two consecutive test cases.

  Input:

    86

    12345

    0

  Output:

    Case #1

    first meets river 1 at 101

    Case #2

    first meets river 3 at 12423

Here is the code to solve it:

#include<iostream>
using namespace std;
int sum_of_digits(int);
int connect(int start_number, int chk_number)
{
    while (true)
    {
        if (start_number>chk_number) break;
        else if (start_number == chk_number) return chk_number;
        else start_number += sum_of_digits(start_number);
    }
    return -1;
}
int sum_of_digits(int number)
{
    int sum_of_digit = 0;
    while (number>0)
    {
        sum_of_digit += number % 10;
        number /= 10;
    }
    return sum_of_digit;
}

int main()
{
    int x, temp;
    int m = 1;
    while (x != 0)
    {
        cin >> x;
        temp = x;
        bool flag = false;
        while (true)
        {
            for (int i = 1; i < 10;)
            {
                if (connect(i, temp) != -1)
                {
                    cout << "Case #" << m << endl;
                    cout << "first meets river of " << i << " at " << temp;
                    flag = true;
                    break;
                }
                if (i == 1) i = 3;
                else if (i == 3) i = 9;
                else break;
            }
            if (flag) break;
            temp += sum_of_digits(temp);

        }
    }
    return 0;
}

And I'm stuck because it takes more than 1 sec on some inputs. Please help me optimize it to below 1 second on any inputs.

Don't tell anything on using namespace std; and look at it as C code not C++ code. As it was in a competition I was in a hurry. It worked in the competition but now I want to make it fast.


texts: Eigenvector calculation involving three matrices

texts:
Code performs well for small matrices, but gives memory error for large matrices of size 63000x93000, even when I am using server with memory of 64GB, space 100GB, swap 40GB.

# -*- coding: utf-8 -*-
from numpy import array, argmax, concatenate
import csv

def uread(Filename):
    UFILE = open(Filename, 'r')
    with UFILE:
        READER = csv.reader(UFILE)
        for i in READER:
            yield i

ufinal = uread('U.csv')
U = []
for k in ufinal:
    TEMP = []
    for j in k:
        TEMP.append(eval(j))
    U.append(TEMP)
    del TEMP
    del k

sfinal = uread('s.csv')
S = []
for s in sfinal:
    for t in s:
        S.append(eval(t))
    del t

EIGVALfinal = uread('EIGVAL.csv')
EIGVAL = []
for e in EIGVALfinal:
    for l in e:
        EIGVAL.append(eval(l))
    del l

EIGVECfinal = uread('EIGVEC.csv')
EIGVEC = []
for e in EIGVECfinal:
    for l in e:
        EIGVEC.append(eval(l))
    del l

NEW_U = []
NEW_EIGVAL = []
NEW_EIGVEC = []
for i in range(len(S)):
    if S[i] > 0.001:
        NEW_U.append(U[i])
        NEW_EIGVAL.append(EIGVAL[i])
        NEW_EIGVEC.append(EIGVEC[i])
del EIGVAL
del EIGVEC
# Select the first r columns of u corresponding to the r principle Eigenvector of
# MatrixForEigenvalues
TRANSPOSE_NEW_EIGVEC = array(NEW_EIGVEC).real.T   # Done for easy accesiblity of matrix
TRANSPOSE_MATRIX_U = array(NEW_U).real.T  # Done for easy accesiblity of matrix
FINAL_ARRAY_EIGVAL = []
FINAL_ARRAY_EIGVEC = []
FINAL_MATRIX_U = []
for i in range(len(array(NEW_EIGVAL).real)):
    j = argmax(array(NEW_EIGVAL).real)
    FINAL_ARRAY_EIGVAL.append((array(NEW_EIGVAL).real)[j])
    FINAL_ARRAY_EIGVEC.append(TRANSPOSE_NEW_EIGVEC[j])
    FINAL_MATRIX_U.append(TRANSPOSE_MATRIX_U[j])
    TRANSPOSE_NEW_EIGVEC = concatenate((TRANSPOSE_NEW_EIGVEC[:j], TRANSPOSE_NEW_EIGVEC[j+1:]))
    TRANSPOSE_MATRIX_U = concatenate((TRANSPOSE_MATRIX_U[:j], TRANSPOSE_MATRIX_U[j+1:]))
RESULT_MATRIX_U = array(FINAL_MATRIX_U).T     # This is the actual R
r_file = open('r.csv', 'w')
with r_file:
    WRITER = csv.writer(r_file)
    WRITER.writerows(RESULT_MATRIX_U)
print(RESULT_MATRIX_U)
del FINAL_MATRIX_U


texts: Query for searching for the best transportation

texts:
I made a website where is possible to search for the best transportation from a place to another. For instance, if I need to go from Berlin to Bremen, the website will search in its internal database for all the trains and buses that will cover that distance.

To give the results, the websites look for all the trains which have Berlin or Bremen in their stops and will also match trains which have only one of the stations as stop.

For example, I look for Berlin-Bremen, the website will also find a solution which includes a train that cover the track Milan-Dresden and stops also in Berlin, after 20 minutes a bus leave from Berlin and goes to Paris but stops in Bremen.

As you can imagine the query is quite complicated and it might take a lot of time to find the results.

This is the main query I've done:

SELECT DISTINCT

line.id                             AS line_id,
line.type                           AS line_type,
TIME_TO_SEC(stop.timeDeparture)     AS time_departure,
stop.id_station                     AS departure_id

FROM        `stops`     AS stop
INNER JOIN  `days`      AS day      ON ( day.id_line    = stop.id_line )
INNER JOIN  `lines`     AS line     ON ( line.id        = stop.id_line )
INNER JOIN  `stations`  AS station  ON ( station.id     = stop.id_station )
WHERE (
    line.status = 1
    AND
    day.day = ' . $this->day_of_the_week . '
    AND
    line.type IN (' . $this->type_of_transport . ')
    AND
    stop.id_station IN (' . $stations_in_departure_location . ')
    AND
    time_departure > ' . $min_time_plus_walk_time . '
) OR (
    line.status = 1
    AND
    day.day = ' . $day_of_the_week_tomorrow . '
    AND
    line.type IN (' . $this->type_of_transport . ')
    AND
    stop.id_station IN (' . $stations_in_departure_location . ')
    AND
    time_departure > ' . $night_min_time_plus_walk_time . '
    AND
    time_departure < ' . $night_max_time . '
)

ORDER BY
    stop.timeDeparture,
    stop.timeArrival

This is the database structure:

I made a recursive search function that uses this same query to find every train/bus that you could take from any of the cities where any of the trains/buses found in the iteration before stops.

Every time it finds a combination of lines that reach the chosen destination, it adds it to an array which will be then sorted and filtered depending on the users preferences.

I had to limit the iteration count to 2, otherwise it gets too slow.

Can you please suggest best practices, a better solution or a way to improve it?


texts:
I'm new to Python and want to develop good habits at the beginning. This class takes a string, and then counts the number of vowels and consonants in the word(s).  Any advice on how to improve?

class CntVowels:

    def __init__(self,string):
        self.string = string
        self.vowels = [ "a", "e", "i", "o", "u"]

    def vowel_count(self):
        strings = self.string.lower()
        vowels = self.vowels

        counter = 0
        for letter in strings:
            for vowel in vowels:
                if letter == vowel:
                    counter += 1
        print("There are {} vowels in this string.".format(counter))

    def constant_count(self):
        strings = self.string.lower()
        vowels = self.vowels
        length = len(strings)
        counter = 0
        for letter in self.string:
            for vowel in vowels:
                if letter == vowel:
                    counter += 1

        results = length - counter
        print("There are {} constants in this string.".format(results))

a = input("enter a string")

CntVowels(a).vowel_count()

CntVowels(a).constant_count()


texts: What do you think of my EventAggregator implementation in C#?

texts:
I was looking for a simple Event Aggregator to use in my app, but I found people get very complicated very quickly, so I thought this was easy enough to write myself. It seems to work, but I was wondering what you think and if you would change or add anything. (I know some of them raise events back on the same thread that it was registered, but for what I was planning I don't need this.)

public class EventAggregator
{
    private Dictionary<Type, List<WeakReference>> _listeners;

    private object _syncLock;

    public EventAggregator()
    {
        _listeners = new Dictionary<Type, List<WeakReference>>();
        _syncLock = new object();
    }

    public EventAggregator Register<TEvent>(Action<TEvent> eventAction)
    {
        LockAround(() =>
            {
                var listeners = GetListeners(typeof(TEvent));
                listeners.RemoveAll(wr => !wr.IsAlive || (Action<TEvent>)wr.Target == eventAction);
                listeners.Add(new WeakReference(eventAction));
            });
        return this;
    }

    public void Raise<TEvent>(TEvent ev)
    {
        List<WeakReference> targets = null;
        LockAround(() =>
            {
                var listeners = GetListeners(typeof(TEvent));
                targets = listeners
                    .Where(wr => wr.IsAlive)
                    .ToList();
            });

        targets.ForEach(wr => ((Action<TEvent>)wr.Target)(ev));
    }

    private void LockAround(Action action)
    {
        lock (_syncLock)
        {
            action();
        }
    }

    private List<WeakReference> GetListeners(Type type)
    {
        List<WeakReference> result;
        if (_listeners.TryGetValue(type, out result))
        {
            return result;
        }
        result = new List<WeakReference>();
        _listeners[type] = result;
        return result;
    }
}

This is how I plan to use it:

class Program
{
    static void Main(string[] args)
    {
        var ea = new EventAggregator();

        var view = new View(ea);
        var p = new Presenter(ea);

        view.Name = "Name1";
        view.Name = "Name2";

        Console.ReadKey();
    }
}

interface INameChangeEvent
{
    string OldName { get; set; }

    string NewName { get; set; }
}

public class NameChangeEvent : EventArgs, INameChangeEvent
{
    public NameChangeEvent(string oldName, string newName)
    {
        this.OldName = oldName;
        this.NewName = newName;
    }

    public string OldName { get; set; }

    public string NewName { get; set; }
}

class View
{
    private string _name;
    private EventAggregator _ea;

    public View(EventAggregator ea)
    {
        _ea = ea;
    }

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _ea.Raise<INameChangeEvent>(new NameChangeEvent(_name, value));
            _name = value;
        }
    }
}

class Presenter
{
    public Presenter(EventAggregator ea)
    {
        ea.Register<INameChangeEvent>((ev) =>
            Console.WriteLine(string.Format("View name was changed from {0} to {1}",
              ev.OldName, ev.NewName)));
    }
}


texts:
Help me with code code review.
Helium is my pet project, written in Golang.
Helium is a small, simple, modular constructor with some pre-built components.

https://github.com/im-kulikov/helium

Simple example how to use it

package main

import (
    "context"

    "github.com/davecgh/go-spew/spew"
    "github.com/im-kulikov/helium"
    "github.com/im-kulikov/helium/grace"
    "github.com/im-kulikov/helium/logger"
    "github.com/im-kulikov/helium/module"
    "github.com/im-kulikov/helium/settings"
    "github.com/spf13/viper"
)

var mod = module.New(newApp).
    Append(
        settings.Module,
        logger.Module,
        grace.Module)

// App struct
type App struct {
    v *viper.Viper
}

func newApp(v *viper.Viper) helium.App {
    return &App{v: v}
}

// Run application
func (a App) Run(ctx context.Context) error {
    spew.Dump(a.v.AllSettings())

    return nil
}

func main() {
    h, err := helium.New(&helium.Settings{
        Prefix:       "demo",
        Name:         "demo",
        BuildTime:    "now",
        BuildVersion: "dev",
    }, mod)
    helium.Catch(err)
    helium.Catch(h.Run())
}


texts: Decoding and Encoding packet layers using decorator pattern

texts:
I am trying to use decorator pattern to decode and encode packet layers in my application. I've supposed my packet has three layers: Header, Level2, Level3. So far I've come up with the following code. For the sake of simplicity, I've supposed that the data of each layer is the first 10 bytes of the input packet. I've also intentionally ignored memory leak problems.

#include <iostream>
#include "Decoder.h"

int main()
{
    Header* header = new Header("HeaderData");
    Level2* l2 = new Level2(header, "Level2Data");
    Level3* l3 = new Level3(l2, "Level3Data");

    std::cout << header->Encode() << std::endl;
    std::cout << l2->Encode() << std::endl;
    std::cout << l3->Encode() << std::endl;

    std::string packet = l3->Encode();

    header->Decode(packet);
    l2->Decode(header->mNextData);
    l3->Decode(l2->mNextData);

    std::cout << ((Header*)header)->mData << std::endl;
    std::cout << ((Level2*)l2)->mData << std::endl;
    std::cout << ((Level3*)l3)->mData << std::endl;
}

Decoder.h file:

#ifndef _DECODER_H_
#define _DECODER_H_

#include <string>

class DecoderBase
{
public:
    virtual void Decode(std::string &packet) = 0;
    virtual std::string Encode() = 0;
protected:
    DecoderBase* mInnerLayer;
};

class Header : public DecoderBase
{
public:
    Header(const std::string &data);
    virtual ~Header();
    virtual void Decode(std::string &packet);
    virtual std::string Encode();
    std::string mData;
    std::string mNextData;
};

class Level2 : public DecoderBase
{
public:
    Level2(DecoderBase* innerLayer, const std::string &data);
    ~Level2();
    virtual void Decode(std::string &packet);
    virtual std::string Encode();
    std::string mData;
    std::string mNextData;
};

class Level3 : public DecoderBase
{
public:
    Level3(DecoderBase* innerLayer, const std::string &data);
    ~Level3();
    virtual void Decode(std::string &packet);
    virtual std::string Encode();
    std::string mData;
    std::string mNextData;
};

#endif

Decoder.cpp file:

#include "Decoder.h"

Header::Header(const std::string &data)
{
    mData = data;
}

Header::~Header(){}

void Header::Decode(std::string &packet)
{
    mData = packet.substr(0, 10);
    mNextData = packet.substr(10);
}

std::string Header::Encode()
{
    return mData;
}

Level2::Level2(DecoderBase *innerLayer, const std::string &data)
{
    mInnerLayer = innerLayer;
    mData = data;
}

void Level2::Decode(std::string &packet)
{
    mData = packet.substr(0, 10);
    mNextData = packet.substr(10);
}

std::string Level2::Encode()
{
    return mInnerLayer->Encode() + mData;
}

Level3::Level3(DecoderBase *innerLayer, const std::string &data)
{
    mInnerLayer = innerLayer;
    mData = data;
}

void Level3::Decode(std::string &packet)
{
    mData = packet.substr(0, 10);
    mNextData = packet.substr(10);
}

std::string Level3::Encode()
{
    return mInnerLayer->Encode() + mData;
}

Output:

  HeaderData
  HeaderDataLevel2Data
  HeaderDataLevel2DataLevel3Data
  HeaderData
  Level2Data
  Level3Data

Am I using the decorator pattern correctly to decode and encode packets?
Who is responsible for calling the Decode method of the next layer? Am I calling the Decode method of each layer correctly? I thought maybe l2->Decode() should be called from within header->Decode().

Any advice on improving the above code would be appreciated!


texts:
Under sage from another CR post I'm crafting an OOP MySQL connection/query class. Nothing new, but a place to start plying OOP PHP. Here is the current design,what would aid speed and portability?

conf/config.php

<?php

//Inlcude the Data Access Layer: Db
require_once (dirname(dirname(__FILE__)) . '/inc/class/dbc.php');

//DB Constants...
define('DB_HOST','dbhost');
define('DB_USER','user');
define('DB_PASS','pass');
define('DB_NAME','dbname');

?>

inc/class/dbc.php

<?php

/**
*
*/
class Db
{
    public $mysql;

    function __construct()
    {
        $this->mysql = new mysqli (DB_HOST, DB_USER, DB_PASS, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );

//adding custom error checking:

    }// End Constructor

}//End Class Definition

index.php

<div id="todo">
<?php

                require_once(dirname(__FILE__) . '/conf/config.php');
                $db = new Db();
                $query = "SELECT * FROM todo ORDER BY id asc";
                $results = $db->mysql->query($query);

                if($results->num_rows) {
                    while($row = $results->fetch_object()) {
                        $title = $row->title;
                        $description = $row->description;
                        $id = $row->id;

    ?>

</div>


texts:
My first question relates to the first Python module that I published on Python. This is a very small and simple module, the package contains only one class. This is a port of a Perl module Locale::Wolowitz this is a module for managing translations, but uses the serialization format JSON or YAML. Below the code of my Python class, I will like to have an opinion on the code:

import glob
import re
import os.path
from collections import defaultdict

class Pylocwolowitz(object):
    '''Pylocwolitz is a very simple text localization system, meant to be used
by web applications (but can pretty much be used anywhere). Yes, another
localization system.'''

def __init__(self, path, format_deserializer='json'):

    if format_deserializer not in ('json', 'yaml'):
        raise ValueError('FormatNotSupported')

    self.path = path
    self.format_deserializer = format_deserializer
    self.locales = defaultdict(dict)
    self._find_file()

def _find_file(self):
    '''Find all json files'''
    listing = glob.glob(
        os.path.join(self.path, '*.' + self.format_deserializer))
    for infile in listing:
        self._make_loc(infile)

def _make_loc(self, infile):
    '''Store content of the file in a memory'''
    lang = os.path.basename(infile).split('.')[0]
    if self.format_deserializer == 'json':
        import json
        with open(infile) as fil:
            data = json.load(fil)
    else:
        import yaml
        with open(infile) as fil:
            data = yaml.load(fil)
    for key, value in data.items():
        if isinstance(value, dict):
            self.locales[key].update(value)
        else:
            self.locales[key].update({lang: value})

def loc(self, key, lang, values=None):
    '''Return the string key, translated to the requested language (if such
    a translation exists, otherwise no traslation occurs). Any other
    parameters passed to the method are injected to the placeholders in the
    string (if present).'''

    if self.locales[key].get(lang) is None:
        return key

    ret = self.locales[key][lang] if key in self.locales else key
    if values is None:
        return ret
    else:
        return ret % values

I get an error with Python 3.2 on travis.ci but the tests pass on Python 2.x and PyPy, if you have an idea let me know. I'm not sure, but I think as I read it was better to use format or template, rather than % with Python 3 is that I'm wrong.


texts:
I'm working on a simple superfeedr powered rails app here.

Based on the superfeedr-rack gem documentation, I'm doing this to initialize the middleware (snippet from application.rb config block):

Configuration = YAML.load_file(Rails.root.join('config', 'config.yml'))

config.middleware.use Rack::Superfeedr, { :host => Configuration["general"]["hostname"], :login => Configuration["superfeedr"]["username"], :password => Configuration["superfeedr"]["password"]} do |superfeedr|
  Superfeedr = superfeedr
  superfeedr.on_notification do |notification|
    Article.create_from_raw_notification(notification)
  end
end

I'm looking for a better way to do it - I don't like to load my configuration file there instead of in an initializer and I think the block with the article creation callback smells. Any ideas?


texts: FizzBuzz with Lambda Expressions in Java

texts:
I wanted to create a FizzBuzz in Java that is supposed to be open for extension.

So the initial problem is the good old, if divisible by 3 print fizz, if divisible by 5 print buzz, if divisible by both print fizzbuzz, otherwise print the number itself.

But I want to be able to change the numbers that we test against (3 and 5 can become 4 and 6) and the words we print (fizz and buzz may be come foo and bar). And there may be new ones added, such as 7, qux..

Here is what I came up with, any suggestions are welcome:

import java.util.*;
import java.util.function.Function;
import java.util.function.IntPredicate;

class App {
    public static void main(String[] args) {
        Function<Integer, IntPredicate> divisibilityPredicateBuilder
            = isDivisibleBy -> x -> x % isDivisibleBy == 0;

        final Map<Integer, String> fizzersBuzzers = new HashMap<>();
        fizzersBuzzers.put(3, "fizz");
        fizzersBuzzers.put(5, "buzz");

        for (int i = 1; i < 101; i++) {
            String fizzBuzz = "";

            for (Integer fizzerBuzzer : fizzersBuzzers.keySet()) {
                if (divisibilityPredicateBuilder.apply(fizzerBuzzer).test(i)) {
                    fizzBuzz += fizzersBuzzers.get(fizzerBuzzer);
                    fizzBuzz += " ";
                }
            }

            if (fizzBuzz.isEmpty()) {
                fizzBuzz = String.valueOf(i);
            }

            System.out.println(fizzBuzz.trim());
        }
    }
}


texts:
I am trying to write the simplest to undestand code possible, each function has documentation and examples and I tried to use the best style possible.

""" This programme implements a polyalphabetic cipher. """

import string

ALPHABET = string.ascii_lowercase
CHARACTERS_THAT_MUST_REMAIN_THE_SAME = string.digits + string.punctuation + string.whitespace

def cycle_get(lst,index):
    """
    If the list ends go back to the start.
    >>> cycle_get(["lorem","ipsum","dolor","sit"],8)
    "lorem"
    """
    new_index = index % len(lst)
    return(lst[new_index])

def cycle_increment_index(index,lst):
    """
    If at the end: go back to the start
    else: increment.
    >>> cycle_increment_index(0,["a","b","c"])
    1
    >>> cycle_increment_index(2,["a","b","c"])
    0
    """
    if index == len(lst) - 1:
        index = 0
    else:
        index += 1
    return(index)

def shift(letter,value):
    """
    Shifts a letter in the alphabet by the value,
    if the alphabet ends go back to the start.
    >>> shift('a',5)
    f
    >>> "".join([shift(i,20) for i in "hello"])
    'byffi'
    """
    current_letter_value = ALPHABET.find(letter)
    end_value = current_letter_value + value
    return(cycle_get(ALPHABET,end_value))

def convert_key_to_numbers(key):
    """
    Uses the alphabetic value of letters to convert a word
    to a list of numbers.
    >>> convert_key_to_numbers("abcde")
    [0,1,2,3,4]
    >>> convert_key_to_numbers("example")
    [4, 23, 0, 12, 15, 11, 4]
    """
    return([ALPHABET.find(i) for i in key])

def encrypt(text,key,reverse_operation=False):
    """
    Encrypts the text with a polyalphabetic cipher.
    >>> encrypt("lorem ipsum dolor sit amet, consectetur adipiscing elit","latine")
    'wokmz masnu qswok avx lmxb, psysxkgieuk iqmailkvrr eeqg'
    >>> encrypt("the quick brown fox jumps over the lazy dog","gvufigfwiufw")
    'zcy vcohg jltst aic rarla iaax obj tgeu lil'
    """
    text = text.lower()
    key = convert_key_to_numbers(key)
    index_of_key = 0
    result = ""
    for char in text:
        if char in CHARACTERS_THAT_MUST_REMAIN_THE_SAME:
            result += char
        else:
            if not reverse_operation:
                result += shift(char,key[index_of_key])
            else:
                result += shift(char,- key[index_of_key])
            index_of_key = cycle_increment_index(index_of_key,key)
    return(result)

def decrypt(text,key):
    """
    Decrypts the text previously encrypted with a polyalphabetic cipher.
    >>> decript('wokmz masnu qswok avx lmxb, psysxkgieuk iqmailkvrr eeqg',"latine")
    'lorem ipsum dolor sit amet, consectetur adipiscing elit'
    >>> decrypt("zcy vcohg jltst aic rarla iaax obj tgeu lil","gvufigfwiufw")
    'the quick brown fox jumps over the lazy dog'
    """
    return(encrypt(text,key,reverse_operation=True))


texts:
I am trying to calculate the print cost base on different paper size, single side or double side. So here is the detail:

A4, job type single sided:
*15 cents - black and white page
*25 cents - color page.

A4, job type double sided:
*10 cents - black and white page
*20 cents - color page.

Also need to support for other paper sizes will be added in the future.

And according to my design, developer can just create a A5 class for example to support other paper size, and add other condition in the factory class.

Could someone review my code and help me on whether I have to use interface instead of abstract class?

Here is my code:

PageBase:

public abstract class PageBase {
    abstract double GetCost(int total, int color, boolean isSingleSide);
    abstract void CalculateUnitPrice(boolean isSingleSide);
}

A4Page Class:

public class A4Page extends PageBase {
    public double blackAndWhitePrintUnitCost;
    public double colorPrintUniCost;

    @Override
    public double GetCost(int total, int color, boolean isSingleSide) {
        CalculateUnitPrice(isSingleSide);
        return color* colorPrintUniCost + (total-color)* blackAndWhitePrintUnitCost;
    }

    @Override
    public void CalculateUnitPrice(boolean isSingleSide) {
        if (isSingleSide) {
            this.blackAndWhitePrintUnitCost = 0.15;
            this.colorPrintUniCost = 0.25;
        }
        else {
            this.blackAndWhitePrintUnitCost = 0.10;
            this.colorPrintUniCost = 0.20;
        }
    }
}

PageFactory:

public class PageFactory {

    public PageBase GetPage(String pageType) {
        switch (pageType.toUpperCase()) {
            case "A4":
                return new A4Page();
            default:
                return new A4Page();
        }
    }
}

Main:

public class Main {
    public static void Main() {
        //read
        PageFactory pageFactory = new PageFactory();
        PageBase page = pageFactory.GetPage("A4");
        page.GetCost(0,0,false);
    }
}


texts: Process bunches of records in seperate threads and wait for them all to finish

texts:
I feel like there is a better way of writing this code which waits for multiple threads to finish their work (i.e. without using two loops), but my colleagues and I are drawing a blank.

private static void ProcessRecords(long[] recordIds)
{
    var threads = new List<Thread>();
    var recordsPerThread = recordIds.Length / Settings.Default.WorkerThreads + 1;

    for (var i = 0; i < Settings.Default.WorkerThreads; i++)
    {
        var t = new Thread(new ParameterizedThreadStart(Program.SetOwner));
        threads.Add(t);
        t.Start(recordIds.Skip(i * recordsPerThread).Take(recordsPerThread));
    }

    // Wait until all threads have completed
    foreach (var t in threads)
    {
        t.Join();
    }
}

private static void SetOwner(object o)
{
    var recordIds = o as IEnumerable<long>;

    using (Database d = Program.GetDatabase())
    {
        Account owner = Program.GetOwner(d);

        foreach (long id in recordIds)
        {
            try
            {
                var record = d.GetRecordById(id);
                record.Owner = owner;
                record.Save();
            }
            catch (Exception ex)
            {
                // code to log error
            }
        }
    }
}


texts: Array based Queue Implementation using Templates

texts:
This is my first code using templates and I wanted to know if the code looks good?

I have some doubts like what's the best way to report error to user (queue full/empty), I checked a link online http://www.cprogramming.com/tutorial/computersciencetheory/queuecode.html
where they use assert() so I decided to use it in my code. Also how to let user know to catch out of memory exception when using the constructor for Queue class.

EDIT: Removed assertions.

#include <iostream>
using namespace std;
template <class T>
class Queue{
private:
    T * data;
    size_t cap;
    int cnt;
    int head, tail;

public:

    Queue(size_t c){
        cap = c;
        data = new T[c];
        head = -1;
        tail = -1;
        cnt = 0;
    }

    ~Queue(){
        delete []data;
    }
    //A return value of -1 indicates failure, and 1 indicates success
    int enqueue(T val){

        if(cnt == cap)
            return -1;
        if(head==-1)
            head++;

        tail = (tail+1)%cap;
        data[tail] = val;
        cnt++;
        return 1;

    }
    //A return value of -1 indicates failure, and 1 indicates success
    int dequeue(T *res){

        if(!res || cnt==0)
            return -1;

        *res = data[head];
        head = (head+1)%cap;
        cnt--;

        return 1;

    }
    //A return value of -1 indicates failure, and 1 indicates success
    int front(T *res){

        if(cnt==0 || !res)
            return -1;

        *res = data[head];
        return 1;
    }

};


texts:
I am currently implementing pyramids in Lucas Kanade algorithm for optical flow. To be able to build pyramids, I need to pad the images (mirror edge matrix elements) for the required amount of rows/cols determined by parameter half_window.

I have written this code which works but I am new to C programming and it looks overly complex to me. How would an experienced C programmer write this?

image_t is a struct for storing image data I am required to use. Rest is my code. It first adjusts sizes of output which is a pointer to struct image_t object. Then it builds padded image row by row as follows:

skip first half_window rows
mirror first half_window columns of the row
copy original elements of that row
mirror the last half_window columns of the row
skip last half_window rows

Then

mirror first half_window rows with memcpy
mirror last half_window rows with memcpy

struct image_t {
  enum image_type type;   // The image type
  uint16_t w;             // Image width
  uint16_t h;             // Image height
  struct timeval ts;      // The timestamp of creation

  uint8_t buf_idx;        // Buffer index for V4L2 freeing
  uint32_t buf_size;      // The buffer size
  void *buf;              // Image buffer (depending on the image_type)
};

void pad_image(struct image_t *input, struct image_t *output, uint8_t half_window)
{
    uint8_t *input_buf = (uint8_t *)input->buf;

    output->h = input->h + 2*half_window;
    output->w = input->w + 2*half_window;
    output->buf_size = sizeof(uint8_t) * output->h * output->w;
    free(output->buf);
    output->buf = malloc(output->buf_size);
    uint8_t *output_buf = (uint8_t*)output->buf;

    for (int i = half_window; i != (output->h-half_window); i++){

        for (int j=0; j!=half_window; j++)
            output_buf[i*output->w + (half_window -1 - j)] = input_buf[(i-half_window)*input->w + j];

        for (int j=half_window; j!=output->w-half_window;j++)
            output_buf[i*output->w + j] = input_buf[(i-half_window)*input->w + (j - half_window)];

        for (int j=0; j!=half_window;j++)
            output_buf[i*output->w + output->w - half_window + j] = output_buf[i*output->w + output->w - half_window -1 - j];
    }

    for (int i=0; i!=half_window; i++){
        memcpy(&output_buf[(half_window-1)*output->w - i*output->w], &output_buf[half_window*output->w + i*output->w], sizeof(uint8_t)*output->w);
        memcpy(&output_buf[(output->h - half_window)*output->w + i*output->w], &output_buf[(output->h-half_window-1)*output->w - i*output->w], sizeof(uint8_t)*output->w);

    }
}

Input:

   1    2    3    4
   5    6    7    8
   9   10   11   12
  13   14   15   16

Expected output for half_window = 2:

   6    5    5    6    7    8    8    7
   2    1    1    2    3    4    4    3
   2    1    1    2    3    4    4    3
   6    5    5    6    7    8    8    7
  10    9    9   10   11   12   12   11
  14   13   13   14   15   16   16   15
  14   13   13   14   15   16   16   15
  10    9    9   10   11   12   12   11


texts: Programming Challenge from Kattis: Watchdog

texts:
I've tried to solve the kattis-challenge called Watchdog. My code works just fine, but it was too slow on the last test. I'm wondering if anyone sees any big algorithmic performance issues.

A short description of the task: First line from .in states number of test-cases.
First line in each test-case gives length of a square and number of hatches respectively. For each hatch you'll have one line giving x and y-point of hatch respectively. The mission is to find a point (x,y) where the length from (x,y) to any hatch is not greater than the length from (x,y) to any point outside of the square. If no such point, print poodle. If several such point print point with lowest x, if several points with equal x, print point with lowest y. Hatches and these points cannot overlap.

I think one issue might be extensive usage of lists, but I'm also not sure how to avoid them. Initially I started reading one and one line from stdin using the data. That way things looked way more readable, but it was also slower. And it's the speed that I'm having issues with.

Example input:

3
10 2
6 6
5 4
20 2
1 1
19 19
10 3
1 1
1 2
1 3

Example output:

3 6
poodle
2 2
2 2

My code:

import sys
from math import sqrt
import itertools

def findmaxdist(x1, y1, list):
    '''Finds the distance from x1, y1 to the most
    distant point in the list.'''
    dist = 0
    for x2, y2 in list:
        newdist = (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)
        if newdist>dist:
            dist=newdist
    return sqrt(dist)

fulltext = sys.stdin.readlines()
text = [w.rstrip('\n') for w in fulltext]

cases = int(text[0])
i = 0
j = 1
while i < cases:
    side, hatches = text[j].split()
    side = int(side)
    hatches = int(hatches)
    j += 1
    hatch_list = list()
    for k in range(hatches):
        x, y = text[j].split()
        hatch_list.append((int(x), int(y)))
        j += 1

    possibles = list()
    for x,y in itertools.product(range(side), range(side)):
        if (x, y) not in hatch_list:
            dist = findmaxdist(x, y, hatch_list)
            if x+dist<=side and x-dist>=0:
                if y+dist<=side and y-dist>=0:
                    possibles.append((x, y))

    if len(possibles)==0:
        print('poodle')
    elif len(possibles)==1:
        print(str(possibles[0][0])+' '+str(possibles[0][1]))
    elif len(possibles)>1:
        smallx = min(possibles, key = lambda t: t[0])[0]
        semifinal = list((tuple for tuple in possibles if tuple[0] == smallx))
        if len(semifinal)==1:
            x,y = semifinal[0]
            print(str(x)+' '+str(y))
        elif len(semifinal)>1:
            smally = min(semifinal, key = lambda t: t[1])[1]
            final = list((tuple for tuple in semifinal if tuple[1] == smally))
            if len(final)==1:
                x,y = final[0]
                print(str(x)+' '+str(y))
        else:
            print('Error: Wrong input-format?')
    i+=1


texts:
The code is working perfectly. I'm little bit sure this is a packet what I am sending from client to server in streams. Is this packet? Am I sending in a right way?

Another thing is that I am sending ACK from server to client. Is this right way to send ACK and NACK? Moreover, I am parsing on client side the ACK and checking again. What would you recommend? Can you share your experience?

Client:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {

public static void main(String args[]) {

    try {
        Socket client = new Socket("localhost", 2983);
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        Scanner input = new Scanner(System.in);

        int [] num = new int[]{1,2,3,4,5};
        for (int a=0;a<num.length;){
            // sending
            System.out.print("Client send packet: "+num[a]+"\t");
            oos = new ObjectOutputStream(client.getOutputStream());
            oos.writeUTF(String.valueOf(num[a]));
            oos.flush();

            // receving
            ois = new ObjectInputStream(client.getInputStream());
            String msg = ois.readUTF();
            System.out.println(msg);
            String[] flag = msg.split(":");
            if(flag[0].equals("ACK")){
                a++;
            }else{
                a--;
            }
        }
        System.out.println("By to server");

        ois.close();
        oos.close();
        client.close();
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

}

Server:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Server {

    public static void main(String args[]) {
        try {
            ServerSocket server_socket = new ServerSocket(2983);
            System.out.println("Waiting for client request");

            while (true) {
                Socket client = server_socket.accept();
                System.out.println("Accepted connection request");
                RequestHandler obj = new RequestHandler(client);
                obj.start();
            }
        } catch (Exception e) {
            System.out.println(e);
        }

        // Scanner input = new Scanner(System.in);
    }
}

RequestHandler:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class RequestHandler extends Thread{

    Scanner input = new Scanner(System.in);
    Socket client_acp;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    String packet_num;
    public RequestHandler(Socket client){
        client_acp = client;
    }

    @Override
    public void run() {

        try {
            while (true) {
                // receving
                ois = new ObjectInputStream(client_acp.getInputStream());
                String msg = ois.readUTF();
                System.out.println(msg);
                packet_num=msg;
                if(!(packet_num.equals(null))){
                //sending
                System.out.print("Server:");
                oos = new ObjectOutputStream(client_acp.getOutputStream());
                oos.writeUTF("ACK: From Server Packet = "+ packet_num );
                oos.flush();
                }else{
                    System.out.print("Server:");
                    oos = new ObjectOutputStream(client_acp.getOutputStream());
                    oos.writeUTF("NACK: From Server Packet = "+ packet_num);
                    oos.flush();
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}


texts: Is there a better way to extract a single value instead of a sequence?

texts:
The following code works, but I'd like to re-write, so that a single index is returned, rather than a sequence of indexes visited.

Here are the defs and function.

(def usage-vec-len 13)
(def read-levels [9999 3000 2000 1000 100 90 80 70 60 50 40 30 10])
(defn sel-adj-idx
"Finds the correct position at which to bin part of the reading."
[reading]
(for [idx (reverse (range 0 usage-vec-len))
     :let [out-idx idx]
     :when (and (<= reading (nth read-levels idx)) (>= idx 0))]
  out-idx))

If I run this with a reading of 5, I get what I expect

wtr-usage1.core=> (sel-adj-idx 5)
(12 11 10 9 8 7 6 5 4 3 2 1 0)
wtr-usage1.core=> (first (reverse (sel-adj-idx 5)))
0
wtr-usage1.core=>

I keep going until the first index. The value of 5 would be binned there.
I would like just to return the index, but still need to traverse read-levels to compare the reading against each of the levels.

Is there a better form to use for this purpose? I could probably write this recursively, but am trying to see if I can do it with Clojure's rich set of sequence functions.