texts: asMap-implementation for Java (based on Arrays.asList)

texts:
I am always tired of the very verbose syntax in Java for creating small maps. Arrays.asList(T... a) is very convenient, and therefore I want something similar for a map.

public class MapUtils {
    public static <K, V> MapBuilder<K, V> asMap(K key, V value) {
        return new MapBuilder<K, V>().entry(key, value);
    }

    public static class MapBuilder<K, V> extends HashMap<K, V> {
        public MapBuilder<K, V> entry(K key, V value) {
            this.put(key, value);
            return this;
        }
    }
}

/* Example of how to use asMap */
public class Example {
    public void example() {
        Map<String, String> map = MapUtil.asMap("key", "value").entry("key2", "value2");
    }
}

/* Example of how the one way to create an inline Map in Java */
public class Before {
    public void before() {
        Map<String, String> map = new HashMap<String, String>() {{
            put("key", value");
            put("key2", value2");
        }};
    }
}

Any inputs on how to improve this implementation of MapUtils? Do you consider the asMap function a good idea, or am I too lazy to write some extra characters?


texts: TinyMVC Model / Plugin how to implement?

texts:
Recently I started working with TinyMVC, wrote a simple menu model and I have few questions for those who are using it... or used before.

For the following code should I keep it as Model or as a Plugin?
How should I implement it in the view and use it on every page that is required without breaking the ideea of MVC and without rewriting again and again for each controller?
Any improvements to the code?
Need the MySQL tables?

<?php
 class Menu_Model extends TinyMVC_Model
{

    public function __construct()
    {
        parent::__construct();
    }

    public function listMenu()
    {
        return $this->db->query_all("SELECT * FROM menu_links WHERE is_deleted = 0 ORDER BY position");
    }

    public function listCategorys($menuLinkId)
    {
        return $this->db->query_all("SELECT * FROM menu_subcategorys WHERE menuLinkId = ? AND is_deleted = 0 ORDER BY position", array($menuLinkId));
    }

    public function buildMenu()
    {
        $this->listMenu = $this->listMenu();
        foreach($this->listMenu as $this->listMenuKey => $this->listMenuValue)
        {
            $this->listCategorys = $this->listCategorys($this->listMenuValue['menuLinkId']);
            if(!empty($this->listCategorys))
                $this->listMenu[$this->listMenuKey]['child'] = $this->listCategorys;
        }

        return $this->listMenu;
    }
}


texts: Laravel controller for creating payments with Mollie

texts:
I have a controller with functions to create and finish a Mollie payment. But I've got the idea that those functions are too big and do too many things. What I understand is that a function should do only 1 thing.

Any tips on how I can tidy this further up? Is it maybe a good moment to use events? Or are there any better solutions?

Note: creditBundles() returns an array with possible packages/bundles which are currently for sale.

public function __construct()
{
    $this->payment = Mollie::api()->payments();
}

public function createPayment(Request $request, $bundle)
{
    $bundles = $this->creditBundles();

    if (!array_key_exists($bundle, $bundles)) {
        return redirect()->route('order.credits');
    }

    $order_id = time();
    $bundle = $bundles[$bundle];

    $payment = $this->payment->create([
        "amount"            => $bundle['price'],
        "description"       => $bundle['credits'] . " credits",
        "redirectUrl"       => route('order.credits.finish', ['order_id' => $order_id]),
        "webhookUrl"      => route('order.credits.webhook'),
        "metadata"          => ['order' => 'credits', 'order_id' => $order_id],
    ]);

    CreditOrder::create([
        'user_id' => auth()->user()->id,
        'order_id' => $order_id,
        'payment_id' => $payment->id,
        'payment_status' => $payment->status,
        'credits' => $bundle['credits'],
    ]);

    return redirect($payment->getPaymentUrl());
}

public function finish(CreditOrder $order)
{
    $user = auth()->user();

    if ($order->user_id !== $user->id) {
        return redirect()->route('order.credits');
    }

    $payment = $this->payment->get($order->payment_id);

    if (!$payment->isPaid() || $order->payout) {
        return view('order_status', [
            'payment' => $payment,
            'order' => $order,
        ]);
    }

    $user->increment('credits', $order->credits);
    $order->payout = true;
    $order->save();

    notify()->flash('Thanks ' . escape($user->first_name) . '!', 'success', [
        'text' => 'We received your payment and added ' . $order->credits . ' credits to your account!'
    ]);

    return redirect()->route('home');
}


texts: Comparing two partition functions in Python

texts:
I have written a partition function in Python (my_partition_adv).  I have written this one after reading a similar function from a website.  The version of the partition function from the website is also given below (parititon_inplace).

As I am a beginner in Python, I want to know the following things:

My version looks certainly more readable than the  partition_in_place_with_additional_memory.
Are there any drawbacks for my version in terms of complexity that I am missing?
Are there any other drawbacks for my_partition_adv over partition_inplace?

def partition_inplace(A, start, stop, pivot_index):
    items_less_than = []
    items_greater_than_or_equal = []

    read_index = start
    while read_index <= stop:
        item = A[read_index]
        if item < pivot_value:
            items_less_than.append( item )
        else:
            items_greater_than_or_equal.append( item )
        read_index += 1

    write_index = start

    for item in items_less_than:
        A[write_index] = item
        write_index += 1

    for item in items_greater_than_or_equal:
        A[write_index] = item
        write_index += 1

    return len(items_less_than)

def my_partition_adv(A,p_val):
        less_than = []
        greater_than_or_equal = []

        for index, item in enumerate(A):
            if item < p_val:
                less_than.append(item)
            else:
                greater_than_or_equal.append(item)

        for index,item in enumerate(less_than):
            A[index] = less_than[index]

        for index,item in enumerate(greater_than_or_equal):
            A[len(less_than) + index] = greater_than_or_equal[index]

        return len(less_than)


texts: Simple function that execute an instruction every X time until Y condition is accomplished

texts:
What do you think about this implementation?

inline fun every(duration: Long, timeUnit: TimeUnit, whileCondition: () -> Boolean = { true }, function: () -> Unit) {
    while (whileCondition()) {
        function()
        Thread.sleep(timeUnit.toMillis(duration))
    }
}

This allows calling the following statement:

every(5, TimeUnit.SECONDS){
    println("Hello world")
}


texts: Int-Enum to String and vice a versa in Swift

texts:
I have a situation in my client-server app where I have to send my network strength to server and also receive other clients' strength from server.

So I created enum as:

enum NetworkType: Int {
    case none, gprs, two_g, three_g, four_g, lte, wifi
}
extension NetworkType: Comparable {
    public static func < (a: NetworkType, b: NetworkType) -> Bool {
        return a.rawValue < b.rawValue
    }
}

I can use this as:

if NetworkType.two_g < NetworkType.three_g {
    print("low network")
}

But for sending to server, I have to convert it to String and vice a versa.
So I added one more extension as:

extension NetworkType {

    static var networkDict: [String: NetworkType] = ["gprs": .gprs,
                                                     "2g": .two_g,
                                                     "3g": .three_g,
                                                     "4g": .four_g,
                                                     "lte": .lte,
                                                     "wifi": .wifi];
    init(rawString: String) {
        let loweredStr = rawString.lowercased()
        self = NetworkType.networkDict[loweredStr] ?? .none
    }

    func rawString() -> String? {
        return NetworkType.networkDict.allKeys(forValue: self).first
    }
}

//Dictionary extension for 'key for value'
extension Dictionary where Value: Equatable {
    func allKeys(forValue val: Value) -> [Key] {
        return self.filter { $1 == val }.map { $0.0 }
    }
}

let network = NetworkType(rawString: "gprs") //gprs, while receiving from server
let rawString = NetworkType.gprs.rawString() //"gprs", while sending to server

It is working fine, no issues.
Jus curious to know if theres any better way to achieve this.


texts:
I took a crack at solving the problem of finding the averages of all subarrays of length k. Here is what I came up with. I would greatly appreciate your feedback on  my code.

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

using namespace std;

vector<double> findSuseqAverages(size_t k, const vector<int>& nums) {

    vector<double> res (nums.size() - k + 1);
    auto left_it = nums.begin();
    auto right_it = next(left_it, k);
    double curr_sum = accumulate(left_it, right_it, 0);

    size_t res_index = 0;
    res.at(res_index) = curr_sum / k;

    while (right_it != nums.end()) {
        curr_sum += *right_it - *left_it;
        res.at(++res_index) = curr_sum / k;
        ++right_it;
        ++left_it;
    }

    return res;
}

int main() {
    vector<int> nums {-1, 0, 1};
    size_t k = 2;
    vector<double> averages = findSuseqAverages(k, nums);

    for (const auto& a: averages) cout << a << " ";
    cout << "\n\n";
}


texts:
How idiomatic is my code?

var Clock = function(hour, minute) {
  this.hour = hour || 0;
  this.minute = minute || 0;

  this.plus = function(minutes) {
    computed_minutes = this.minute + minutes
    if (computed_minutes > 60) {
      this.minute = computed_minutes % 60
      this.hour += computed_minutes / 60
    } else {
      this.minute = computed_minutes
    }
    if (this.hour >= 24) {
      this.hour = this.hour - 24
    }
    this.hour = Math.round(this.hour)
    this.minute = Math.round(this.minute)
    return this;
  },

  this.minus = function(minutes) {
    computed_minutes = this.minute - minutes
    if (computed_minutes < 0) {
      this.minute = 60 + computed_minutes % 60
      this.hour -= (1 + Math.abs(computed_minutes / 60))
    } else {
      this.minute = computed_minutes;
    }
    if (this.hour < 0) {
      this.hour = 24 + this.hour
    }

    this.hour = Math.round(this.hour)
    this.minute = Math.round(this.minute)

    return this;
  },

  this.equals = function(other) {
    return this.hour == other.hour && this.minute == other.minute;
  }

}

Clock.at = function(hour, minute) {
  c = new Clock(hour, minute);
  return c;
}

Clock.prototype.toString = function() {
  function format(n) {
    return n >= 10 ? n : "0" + n;
  }
  return format(this.hour) + ":" + format(this.minute)
}

module.exports = Clock;


texts: C++ number-guessing game (computer tries to guess user's chosen number)

texts:
In this program we input a number. Our PC tries to guess this number.

After every try PC asks us:"Are your number more or less than?".

We input 'l' if our number is less, and input 'h' if our number is greater?

A range of possible values is created.

I think this code is bad.  What do you think?

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int Random(int min, int max) {
    return min + rand() % (max - min);
}

int main()
{
    setlocale(LC_ALL, "rus");
    int our_num;
    srand(static_cast<unsigned int>(time(0)));
    cout << "Input a positive number: " << endl;
    cin >> our_num;
    int t = 0;  //number of attempts
    int max = rand() + our_num;  //maximum possible value
    int min = 0;  //minimum possible value
    int d = Random(min, max);
    do {
        char lh;
        cout << d << " Is this your number?(my number is greater: 'h';   less: 'l')" << endl;
        cin >> lh;
        ++t;
        if (lh == 'h') {
            min = d;
            d = Random(min, max);
        }
        else if (lh == 'l') {
            max = d;
            d = Random(min, max);
        }
    } while (d != our_num);
    cout << "I guessed thus number with " << t << " attempts. " << "This number is " << d << endl;
    return 0;
}


texts: Function to convert little endian bytes into big endian

texts:
I'm working on a little endian machine and in my program I need to convert 2,3,4,5 or 8 bytes into network order before transmitting them over the network. I've written the following function which basically just reverses the bytes. I just wanted to make sure if it's logic is correct.

 void convertLittleToBig(const uint8_t* in, uint8_t* out, const uint64_t& sizeInBytes) {
      for(int i=0;i<sizeInBytes;++i)
        out[i] = in[sizeInBytes-i-1];
    }

The function assumes that 'out' and 'in' will be pointing at 'sizeInBytes' memory.
If I'm not wrong, I can use the same function to convert from network order into little endian. Basically big endian and little endian, are mirror images of each other in terms of their byte order as per my current understanding.

Given below is a sample program:

#include <iostream>
#include <cstdint>
#include <iostream>

using std::cin;

//This function prints the raw bytes in memory.

void printBytes(const uint8_t* p, const uint64_t size) {
for(int i=0;i<size;++i)
  printf("\nbyte[%d](%x)",i+1,p[i]);
printf("\n");
}

void convertLittleToBig(const uint8_t* in, uint8_t* out, const uint64_t& sizeInBytes) {
  printf("\nCurrent representation\n");
  printBytes(in,sizeInBytes);
  for(int i=0;i<sizeInBytes;++i)
    out[i] = in[sizeInBytes-i-1];
  printf("\nRepresentation after conversion\n");
  printBytes(out,sizeInBytes);
}

int main() {
  uint64_t little;
  printf("\nEnter a number that you wish to convert into big endian: ");
  int64_t inp;
  cin>>inp;
  little=inp;
  uint64_t big;
  convertLittleToBig((uint8_t*)&little,(uint8_t*)&big,sizeof(big));
}


texts: calculate time in data processing into XML and CSV

texts:
I made a program (C#, .NET) that calculates time for XML and CSV export and please I have a question for improving my knowledge in programming. Do you think that I can improve the structure of the program? Or what do you think about code refactoring? Way of solve... Is it good? I uploaded the project to github.
Thanks for your comments.

                    t.SetupWriteStart(TestType.String); //that inicialize collection, stringreader, stringstringwriter
                    Time = CalculateTime(t.TestWriteString);
                    t.SetupWriteEnd(TestType.String); //delete this collection, close stringreader and writer

Github link


texts: Short analogue of Riffle[] accepting two blocks

texts:
I have an array of some elements that I need to loop through (i.e. execute some block A on each element) but between them I have also to "clean up" (block B) from the previous iteration and that I don't need to clean after the last iteration because B is slow and it is done somewhere further in more efficient way like process exit or whatever. If the array is [1,2,3] the flow should be like:

[1, :IN]
[1, :OUT]
[2, :IN]
[2, :OUT]
[3, :IN]

It is similar to Mathematica Riffle[] function. I already implemented it in Ruby three years ago but that implementation is complex and there is a place only for B, not for A. So I rewrote it for my current case:

riffle = lambda do |enumerable, &block|
  prev = nil
  enumerable.each_with_index do |e, i|
    block.call prev unless i.zero?
    prev = e
  end
end

riffle.call( Enumerator.new do |e|
  [1,2,3].each do |i|
    e << i

    # start block A
    p [i, :IN]
    # end

  end
end ) do |i|

  # start block B
  p [i, :OUT]
  # end

end

Is there a way to make less code and maybe not use Enumerator.new? I tried to use .to_enum and .lazy.map(&A) but had no success.


texts: Install Ruby using rbenv in a bash script

texts:
I want to write an automated bash script for installing Ruby and Rails using rbenv, but I am getting session reload issues in the terminal.

#!/bin/bash
echo "Installing rbenv.."
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc
reset
echo "Finished installing rbenv"

#!/bin/bash
rbenv -v
echo "Installing ruby.."
sudo rbenv install 2.2.3
rbenv global 2.2.3
echo "Finished installing ruby"
ruby -v

echo "gem: --no-document" > ~/.gemrc

echo "Installing rails.."
sudo apt-get install ruby-dev
sudo gem install bundler
gem install rails -v 4.2.3
rbenv rehash
echo "Finished installing rails"
rails -v
rbenv rehash


texts:
Here is my TCP socket that sends eight images per second to a connected Client.
The images are taken from a thermal camera.

static void HandleServer()
        {
            Console.WriteLine("Server is starting...");
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
        Socket newsock = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(10);
            Console.WriteLine("Waiting for a client...");

            Socket client = newsock.Accept();
            IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port {1}",
                            newclient.Address, newclient.Port);
        HandleImage(client, newsock);

    }

    private static void HandleImage(Socket client, Socket s)
    {
        int sent;
        int imageCount = 0;
        double totalSize = 0;
        try
        {
            while (true)
            {

                Image bmp = getImage();
                MemoryStream ms = new MemoryStream();
                // Save to memory using the bmp format
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                byte[] bmpBytes = ms.ToArray();
                bmp.Dispose();
                ms.Close();

                sent = SendVarData(client, bmpBytes);
                imageCount++;
                totalSize += sent;
                Console.WriteLine("Sent " + sent + " bytes");
                Thread.Sleep(125);

            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception catched, probably an interrupted connection. Restarting server...");
            s.Close();
            Console.WriteLine("Transferred {0} images with a total size of {1}", imageCount, totalSize);
            Console.WriteLine("Average JPEG size: " + totalSize / imageCount + " byte");
            HandleServer();
        }
    }
    private static int SendVarData(Socket s, byte[] data)
    {
        int total = 0;
        int size = data.Length;
        int dataleft = size;
        int sent;

        byte[] datasize = new byte[4];
        datasize = BitConverter.GetBytes(size);
        sent = s.Send(datasize);

        while (total < size)
        {
            sent = s.Send(data, total, dataleft, SocketFlags.None);
            total += sent;
            dataleft -= sent;
        }
        return total;
    }
}
}

Any feedback is appreciated:)

Update: getImage simply calls the driver DLL of the thermal camera and returns the actual Image.
I do this every 125ms because the camera is specified with 8fps and does NOT provide a method or property to check whether there is a new image available.


texts:
I need to have some static HTML pages on a project I am making with Go. I used the http.FileServer, but I noticed it was slower than rendering with html/templates, and I didn't like seeing the .html at the end of the routes. So I went with this solution:

// home.go
package pages

import "strings"

var Home string

func init() {
    html := `
        <!DOCTYPE html>

                <title>Page Title</title>

Home Page

    `

    htmlArray := strings.Fields(html)
    htmlJoined := strings.Join(htmlArray, " ")
    Home = strings.Replace(htmlJoined, "> <", "><", -1)
}

and:

// main.go
package main

import (
    "net/http"
    "io"

    "my_project/router"
    "my_project/pages"
)

func main() {
    router.On("GET", "/", home)
    http.HandleFunc("/", router.Handle)
    http.ListenAndServe(":8080", nil)
}

func home(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, pages.Home)
}

This all seems to be working well. If I understand correctly, the minification takes place when the app starts, and not on each request.

Is there anything wrong with this approach?


texts: A Priority Queue implemented using a Linked List

texts:
I'm going to write a Huffman Coding implementation, and decided to write from scratch a priority queue to help out. I've never written a priority queue before, in any language, so this was interesting.

After mulling over the design for a bit, I finally settled on a linked list design. The queue is essentially just a linked list with a size field. When a value is added, it recursively walks the list until it finds the right spot, and wedges it in as a new node. This may not be optimal, but peeks/pops are O(1), so it's sufficient. The only issue is pushes can be inefficient, as they may require walking the entire list if a low priority item is added.

This isn't my final attempt. I think I'm going to have it implement the standard protocols for consistency with the standard structures. For now though, the -queue suffixes/prefixes will do.

I'd like mainly my design critiqued here. I threw this down in only half an hour, tested it, and am fairly happy with it, but it wouldn't surprise me if I'm doing something overly roundabout. I'll welcome any critique though.

Example:

(let [q (new-priority-queue)]
  (-> q
      (push-queue 1 :hello)
      (push-queue 0 :new-root)
      (push-queue 5 :worst)
      (push-queue 3 :middle)
      (clojure.pprint/pprint)))

{:root
 {:priority 0,
  :bucket [:new-root],
  :child
  {:priority 1,
   :bucket [:hello],
   :child
   {:priority 3,
    :bucket [:middle],
    :child {:priority 5, :bucket [:worst], :child nil}}}},
 :size 4}

(ns huffman.priority-queue.attempt1)

(defrecord Priority-Queue [root size])
(defrecord Node [priority bucket child])

(defn new-node [priority value]
  (->Node priority [value] nil))

(defn- add-value-to-node [node value]
  (update node :bucket conj value))

(defn- set-child-of-node [node child]
  (assoc node :child child))

(defn new-priority-queue []
  (->Priority-Queue nil 0))

(defn queue-empty? [queue]
  ; FIXME: Just check if the root is nil?
  (zero? (:size queue)))

(defn- push-new-node [queue priority value]
  (let [node (new-node priority value)]
    (update queue :root
      (fn rec [{n-pri :priority, n-child :child :as root}]
        (cond
          (nil? root) node
          (< priority n-pri) (set-child-of-node node root)
          (= priority n-pri) (add-value-to-node root value)
          :else (set-child-of-node root (rec n-child)))))))

(defn push-queue
  "Pushes the value with a given priority into the queue."
  [queue priority value]
  (when-not value
    (throw (RuntimeException. (str "Pushed values must be truthy!: " (pr-str value)))))

  (-> queue
      (push-new-node priority value)
      (update :size inc)))

(defn peek-priority?
  "Returns either the highest priority item, or nil if the queue is empty.
  If multiple items have the same priority, the first pushed item is returned."
  [queue]
  (when-not (queue-empty? queue)
    (-> queue :root :bucket (first))))

(defn- remove-priority [queue]
  (update queue :root
    (fn [root]
      (if (= (count (:bucket root)) 1)
        (:child root)
        (update root :bucket subvec 1)))))

(defn pop-priority?
  "Returns either a pair of [highest-priority rest-queue], or nil if the queue is empty."
  [queue]
  (when-not (queue-empty? queue)
    (let [popped (peek-priority? queue)
          rest-queue (remove-priority queue)]
      [popped (update rest-queue :size dec)])))

Just a note: right now, lower valued priorities are considered higher priority (since I had Huffman Coding in mind while writing this). I'm going to add a comparator field to the queue record in the future though, and use the custom comparator in push-new-node to allow for a user-defined ordering.


texts:
I am brushing up on my Java skills by trying to solve the below assignment problem I found on the internet:

Write a Java method that accepts two strings as parameters and returns
a string that contains all unique two-character strings whose first
character comes from the first string and second character comes from
the second string. All two-character strings in your returned string
should be separated by a space. Use ordinary string concatenation in
your solution. Look at the examples below for a "hint" on how to
proceed and look at the String API for methods you can use to simplify
your solution.
Example
First string = ABCD
Second string = EFGH
Returned string > AE AF AG AH BE BF BG BH CE CF CG CH DE DF DG DH

How can I improve this code?
package com.assignments.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * This is an Assignment Program for Java
 *
 * @author SaiUpadhyayula
 *
 */

public class JavaAssignmentOne {
    public static void main(String[] args) throws IOException {
        BufferedReader bReader = new BufferedReader(new InputStreamReader(
                System.in));

        System.out.println("Enter First String");
        String firstString = bReader.readLine();

        System.out.println("Enter Second String");
        String secondString = bReader.readLine();

        String returnedString = constructCharSequence(firstString, secondString);
        System.out.println("Returned String : " + returnedString.trim());
    }

    public static String constructCharSequence(String firstString,
            String secondString) throws IOException {

        String biggerString = firstString;
        String smallerString = secondString;
        String returnedString = "";

        // Determine the smaller and bigger Strings from
        // the given two input strings
        if (firstString.length() <= secondString.length()) {
            biggerString = firstString;
            smallerString = secondString;
        } else {
            biggerString = secondString;
            smallerString = firstString;
        }

        // Construct the given required character sequence
        // by iterating over the two input strings

        for (int i = 0; i < biggerString.length(); i++) {
            for (int j = 0; j < smallerString.length(); j++) {

                // As we require unique two-character string
                // check whether the string sequence already exists
                // in the returnedString
                if (!returnedString.contains("" + biggerString.charAt(i)
                        + smallerString.charAt(j) + "")) {
                    returnedString = returnedString + biggerString.charAt(i)
                            + smallerString.charAt(j) + " ";
                }
            }
        }
        return returnedString;
    }
}


texts: Initialization of Extended class without too much overhead?

texts:
I am getting object of a class AAA from somewhere and I want to add more information in that object. So, I am creating a new class BBB which is derived from AAA. The class BBB has additional field dictionary. I am populating this dictionary in derived class constructor which is taking the Class AAA object and array of item which I want to use as keys of dictionary and values of this dictionary are elements of a field of object of class AAA. I tried to create similar scenario in blow example code:

void Main(){
     A obj = new A () ;
     obj.prop1 =  new int [] {5 ,10, 15}   ;
     obj.prop2 =  "Hello" ;
     obj.prop3 = "World" ;
//   obj.Dump () ;
     B obj2 = new B (new int [] {1,2,3}, obj)  ;
//   obj2.Dump () ;

}

// Define other methods and classes here
public class A {
    public int [] prop1 ;
    public string prop2 ;
    public string prop3 ;
}

public class B : A {
    public Dictionary <int, int> prop4 ;
    public B (int [] keys, A a) {
    prop4 = new Dictionary <int, int> () ;
        if (keys.Length == a.prop1.Length ) {
            for (int i = 0 ; i < keys.Length ; i++ ) {
                prop4.Add (keys[i], a.prop1[i]) ;
            }
            // is there a way to obsolete below lines of code???
            this.prop1 = a.prop1 ;
            this.prop2 = a.prop2 ;
            this.prop3 = a.prop3 ;
        }
        else {
            throw new Exception ("something wrong") ;
        }
    }
}

In derived class constructor, I am filling the properties manually and I do not want to do it. Is there another way to do it. I have more than 20 properties in my actual class.


texts:
I've been building a simple tool to calculate the LIX value of a text (a standard measurement of the readability of a text).

My approach was to have every step of the calculation as seperate functions. In a larger and more complex tool the total words, sentences and others would be nice to have as independent functions.

Also the functions should be able to take in any string input and do their calculations. So that I would easily be able to use this in other contexts like TinyMCE editor and so forth.

So I've tried to find a way to make the code flexible. And my ambition was to write simple and pure functions.

I'm a little in doubt as to how readable and maintainable this approach is.

The click function triggering the calculation is an example. I'd really like your thoughts about this functions inside functions approach. I found it very nice to work in this way.

jQuery(document).ready(function() {

  function getText() {
    var text = jQuery('#inputLix').val();

    return text;
  }

  function countWords(input) {
    var wordCount;
    var wordsArray;
    var splitter = /\s|\n/g;
    wordsArray = input
      .replace(/(<([^>]+)>)/ig, "")
      .replace(/,/g, "")
      .replace(/-/g, "")
      .replace(/"/g, "")
      .replace(/'/g, "")
      .split(splitter)
      .filter(Boolean);
    wordCount = wordsArray.length;
    return wordCount;
  }

  function longWordCount(input) {
    var longWordCounter = 0;
    var splitter = /\s|\n/g;
    var checkedText = input.replace(/<([^>]+)>|[\.\+\?,\(\)"'\-\!\;\:]/ig, "");
    var wordsArray = checkedText
      .split(splitter)
      .filter(Boolean);

    for (var i in wordsArray) {
      if (wordsArray[i].charAt(0) > -1) {} else if (wordsArray[i].length > 6) {
        longWordCounter++;
      }
    }
    return longWordCounter;
  }

  function getSentences(input) {
    var splitter = /\?|\!|\.|\n/g;
    var checkedText = input
      .replace(/(<([^>]+)>)/ig, "")
      .replace(/,/g, "")
      .replace(/-/g, "")
      .replace(/"/g, "")
      .replace(/'/g, "");
    var arrayOfSentences = checkedText.split(splitter);
    arrayOfSentences = arrayOfSentences.filter(Boolean);
    return arrayOfSentences;
  }

  function countSentences(input) {
    return input.length;
  }

  function calculateLix(wordCount, sentenceCount, longWordsCount) {
    var lixScore = Math.round((wordCount / sentenceCount) + ((longWordsCount * 100) / wordCount));
    return lixScore;
  }

  function outputContent(input, id) {
    jQuery(id).html(input);
  }

  jQuery("#lixButton").click(function() {
    var input = getText();
    outputContent(calculateLix(countWords(input), countSentences(getSentences(input)), longWordCount(input)), "#notification");
  });

});
.tool-wrapper {
  background: #899398;
  padding: 30px;
  border-radius: 10px;
}

textarea {
  width: 100%;
}

  <textarea id="inputLix" rows="15">This is just some basic text. Push the button to calculate the LIX value. And figure out how hard your text is to read.</textarea>

    <button id="lixButton" class="alignright" type="submit">Calculate Lix</button>

You haven't performed any calculations yet


texts:
first here is the code:

Part 1
    $('#monhpf').keyup(function()
    {
        /* General variable(s) */
        var monhpf = $('#monhpf').val();

        if(monhpf=="")
        {
            $('#monhpf').css('border-color',red);
            $('.mondayErrors').text(emptyField).show();
        }else
        if(monhpf.length > 0)
        {
            /* Verifies the charset of the zip code */
            $.post('functions/hoursCharset.php',{hoursPHP:monhpf},function(hoursCharset)
            {
                if(hoursCharset==true)
                {
                    /* Charset valid*/
                    $('#monhpf').css('border-color',green);
                    $('.mondayErrors').hide();
                    mondayErrors = false;
                }else
                {
                    /* Charset not valid */
                    $('#monhpf').css('border-color',orange);
                    $('.mondayErrors').text(invalid).show();
                    mondayErrors = true;
                }
            });
        }
    });
Part 2
    $('#monmpf').keyup(function()
    {
        /* General variable(s) */
        var monmpf = $('#monmpf').val();

        if(monmpf=="")
        {
            $('#monmpf').css('border-color',red);
            $('.mondayErrors').text(emptyField).show();
        }else
        if(monmpf.length > 0)
        {
            /* Verifies the charset of the zip code */
            $.post('functions/minutesCharset.php',{minutesPHP:monmpf},function(minutesCharset)
            {
                if(minutesCharset==true)
                {
                    /* Charset valid*/
                    $('#monmpf').css('border-color',green);
                    $('.mondayErrors').hide();
                    mondayErrors = false;
                }else
                {
                    /* Charset not valid */
                    $('#monmpf').css('border-color',orange);
                    $('.mondayErrors').text(invalid).show();
                    mondayErrors = true;
                }
            });
        }
    });

As you can see part 1 and part 2 are pretty much the same except for the #monhpf and #monmpf variables. My question is, how can I improve this code to be smaller? Like in a single function for example.


texts: boost::unordered_set intersection using templates

texts:
I wrote this function to do unordered_set intersection using templates. I have seen this answer but I thought that it was overkill. I would like the method to take in 2 sets and return a set.

class SetUtilites{
public:
    template<typename Type>
    static boost::unordered_set<Type> intersection(const boost::unordered_set<Type> &set1, const boost::unordered_set<Type> &set2){
        if(set1.size() < set2.size()){

            boost::unordered_set<Type> iSet;

            boost::unordered_set<Type>::iterator it;
            for(it = set1.begin(); it != set1.end();++it){
                if(set2.find(*it) != set2.end()){
                    iSet.insert(*it);
                }
            }
            return iSet;
        }else{
            return intersection(set2,set1);
        }
    }
};


texts: A package for outer-package communications

texts:
By outer-package, I mean outside of this package - this can be the DOM or other packages.  This package has a basic event system and a basic registry.  It also has a debugger which allows you to fiddle with the DOM by removing and adding entire sets of tags.  Later it might have things which allow it to Debug /  Configure the server via ajax.

Please review all aspects of this code.

/***************************************************************************************************
    **COMS
    **  provides registry, event system, debugger ...
    **  reduces dependencies
    ***************************************************************************************************/

    (function () {
        "use strict";
        var $A,

            // public
            $P = {};

        // require utility
        (function manageGlobal() {
            if (window.$A && window.$A.pack && window.$A.pack.utility) {
                $A = window.$A;
                $A.pack.comms = true;
            } else {
                throw "comms requires utility module";
            }
        }());
        $P.Debug = (function () {
            var publik = {},
                hold = {};
            publik.addTags = function (tag) {
                if (hold[tag]) {
                    $A.someIndex(hold[tag], function (val) {
                        if (tag === 'script' || tag === 'style') {
                            document.head.appendChild(val);
                        } else {
                            document.body.appendChild(val);
                        }
                    });
                }
            };
            publik.removeTags = function (tag) {
                var styles = document.getElementsByTagName(tag),
                    i;
                hold[tag] = [];
                for (i = styles.length; i; i--) {
                    hold[tag][i] = styles[i];
                    $A.removeElement((styles[i]));
                }
            };
            publik.removeStorage = function () {
                localStorage.clear();
                sessionStorage.clear();
            };
            return publik;
        }());

        // a basic registry pattern with get/set and getMany/setMany
        $P.Reg = (function () {
            var publik = {},
                register = {};
            publik.get = function (key) {
                return register[key];
            };
            publik.set = function (key, value) {
                register[key] = value;
            };
            publik.setMany = function (o) {
                $A.someKey(o, function (val, key) {
                    register[key] = val;
                });
            };
            publik.getMany = function () {
                return register;
            };
            return publik;
        }());

        // a basic event system using an internal bus
        $P.Event = (function () {
            var publik = {},
                events = {};
            publik.add = function (name, callback) {
                if (!events[name]) {
                    events[name] = [];
                }
                events[name].push(callback);
            };
            publik.remove = function (name, callback) {
                if (name && callback) {
                    delete events[name][callback];
                } else if (name) {
                    delete events[name];
                }
            };
            publik.trigger = function (name) {
                if (events[name]) {
                    $A.someIndex(events[name], function (val) {
                        val();
                    });
                }
            };
            return publik;
        }());
        window.$A = $A.extendSafe($A, $P);
    }());


texts: All possible lists from ups and downs between elements in python list

texts:
I have a function that compares sequential elements from a python list and returns 1 and -1:

>>> up_down([0, 2, 1, 3])
[1, -1, 1]

I need a function to return all possible lists from a '-1, 1' list using the function up_down.

>>> possible_lists([1, -1])
[[0, 2, 1], [1, 0, 2]]

I'd like to know if I can write these functions in a better way. My code is below:

import itertools

def comparison(a, b):
    if b > a:
        return 1
    if b < a:
        return -1
    else:
        return 0

def up_down(data, n=1):
    return [comparison(data[pos], data[pos + n]) for pos, value in enumerate(data[:-n])]

def possible_lists(data, n=1):
    size = len(data) + n
    all_lists = itertools.permutations(range(size), size)

    return [list(el) for el in all_lists if up_down(el, n) == data]


texts: Unit testing a servlet in a meaningful way

texts:
I have to write a unit test for the method processRequest in the servlet below and I'm wondering if:

It just shouldn't be done.
The class should be rewritten / refactored to allow easier unit testing. Suggestions as to how?
There is a meaningful way of getting the value of response.getWriter().print(result), which is all the method returns.

Method in question:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/plain;charset=UTF-8");
    session = request.getSession(false);
    User sessionUser = (User) session.getAttribute("user");
    int userId = sessionUser.getId();

    if (sessionUser != null) {
        switch (request.getParameter("function")) {
            // UPLOAD IMAGE FUNCTION
            case "uploadimg":
                // save image
                final String path = getServletContext().getRealPath("") + "/resources/img/profile/tmp/";
                String imagePath = imageService.uploadImage(request, path, userId);

                // return image path for use in frontend java script
                response.getWriter().print(getServletContext().getContextPath() + "/resources/img/profile/tmp/" + imagePath);
                break;

            // SAVE IMAGE FUNCTION
            case "save":
                // move image from temp folder to permanent storage
                final String pathOrigin = getServletContext().getRealPath("") + "/resources/img/profile/tmp/";
                final String pathDestination = getServletContext().getRealPath("") + "/resources/img/profile/";
                boolean result = imageService.moveImage(pathOrigin, pathDestination, userId);

                // Returns true whether or not the image was saved successfully
                response.getWriter().print(result);
                break;
        }

        response.getWriter().flush();
        response.getWriter().close();
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}


texts: Abstract factory pattern for a system modelisation

texts:
I've just done an exercise on the abstract factory pattern and I want someone to tell me whether or not I followed the rules of the abstract factory pattern.

Exercise 2 (Abstract Factory: GUI based OS)
The purpose of this exercise is to provide a modelisation of a system for creating different components of a graphical user interface (buttons, menu,...) depending on the operating system (Linux, Windows, ...) to which they are intended.
The model must create components without having to know their concrete classes, to be independent of how the components evolve. The Abstract Factory pattern seems well suited.

Make the UML diagram of this program. We consider that the buttons have a color, width and height, and menus just wide.

Write the Java classes d'efinies by the UML diagram.

Add back a new operating system (Mac OS X, for example)

The abstract class Composant:
package Interfaces;

public abstract class Composant {
    protected double largeur ;
    protected String color = null;
    protected double hauteur ;

    public abstract void setColor(String C);
    public abstract void setLargeur(double L);
    public abstract void setHauteur(double H);

    public abstract String getColor();
    public abstract double getLargeur();
    public abstract double getHauteur();
}

The Boutton class:
package concreteClasses;

import Interfaces.Composant;

public class Boutton extends Composant{

    @Override
    public void setColor(String C) {
        color = C;
    }

    @Override
    public void setLargeur(double L) {
        largeur = L;
    }

    @Override
    public void setHauteur(double H) {
        hauteur = H;
    }

    @Override
    public String getColor() {
        return color;
    }

    @Override
    public double getLargeur() {
        // TODO Auto-generated method stub
        return largeur;
    }

    @Override
    public double getHauteur() {
        // TODO Auto-generated method stub
        return hauteur;
    }
    public String toString(){
        return "boutton color ="+color+" boutton largeur ="+largeur+" boutton     hauteur ="+hauteur;
    }
}

The Menu class:
package concreteClasses;

import Interfaces.Composant;

public class Menu extends Composant{

    @Override
    public void setColor(String C) {
        color = null;
    }

    @Override
    public void setLargeur(double L) {
        largeur = L;
    }

    @Override
    public void setHauteur(double H) {

    }

    @Override
    public String getColor() {
        return color;
    }

    @Override
    public double getLargeur() {
        // TODO Auto-generated method stub
        return largeur;
    }

    @Override
    public double getHauteur() {
        return hauteur;
    }
    public String toString(){
        return "Menu largeur ="+largeur;
    }
}

The abstract class AbstractFatcory:
package factoryClasses;

import Interfaces.Composant;

public abstract class AbstractFactory {
    public abstract Composant getComposant(String composant);
}

The FactoryComposant class:
package factoryClasses;

import concreteClasses.*;
import Interfaces.Composant;

public class FactoryComposant extends AbstractFactory{

    @Override
    public Composant getComposant(String composant) {
        if(composant.equalsIgnoreCase("Boutton")) return new Boutton();
        else if(composant.equalsIgnoreCase("Menu")) return new Menu();
        return null;
    }
}

The Main class:
import Interfaces.Composant;
import factoryClasses.*;

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

        AbstractFactory factorycomposant = new FactoryComposant();
        Composant compo = factorycomposant.getComposant("Boutton");
        compo.setColor("Red");
        compo.setHauteur(12);
        compo.setLargeur(12);
        System.out.println(compo);

        Composant compo2 = factorycomposant.getComposant("Menu");
        compo2.setLargeur(10);
        System.out.println(compo2);
    }
}


texts:
Just implemented this Kalman Filter in Python + Numpy keeping the Wikipedia notation

It's a pretty straightforward implementation of the original algorithm, the goals were

develop skills related to implementing a scientific paper
keep it readable (so I have used private methods for intermediate results)

It includes a simple test case

import numpy as np

"""
  Kalman Filter in plain Python + Numpy
  Filter State
  - x = Updated State
  - P = Updated State Uncertainty
  - x_pred = Predicted State
  - P_pred = Predicted State Uncertainty

  Models
  - F = Prediction Model
  - H = Observation Model (Maps from State Space to Observation Space)
  - B = Evolved Forcing Term
  - Q = Evolution Noise
  - R = Observation Noise
"""
class KF:
  def __init__(self, x, P, F, B, H, Q, R):
    # Init
    self.x = x
    self.x_pred = x

    # Initial State Uncertainty
    self.P = P
    self.P_pred = P

    # Prediction Model
    self.F = F

    # Observation Model
    self.H = H

    # Process Noise
    self.Q = Q

    # Observation Noise
    self.R = R

  def predict(self, u):
    self.x_pred = F.dot(x) + B.dot(u)
    self.P_pred = F.dot(P.dot(np.transpose(F))) + Q

  def __innovation(self, y):
    return y - self.H.dot(self.x_pred)

  def __S(self):
    return self.R + self.H.dot(self.P_pred.dot(np.transpose(self.H)))

  def __K(self):
    return self.P_pred.dot(np.transpose(self.H).dot(np.linalg.inv(self.__S())))

  def __I(self, A):
    if(A.shape[0] != A.shape[1]):
      raise ValueError("[Identity] Not Square")
    return np.identity(A.shape[0])

  def update(self, y):
    self.x = self.x_pred + self.__K().dot(self.__innovation(y))
    temp = self.__K().dot(self.H)
    self.P = (self.__I(temp) - temp).dot(self.P_pred.dot(np.transpose(self.__I(temp) - temp))) + self.__K().dot(self.R.dot(np.transpose(self.__K())))

  def to_str(self):
    return "x \n" + np.array2string(self.x) + "\n P \n" + np.array2string(self.P) + "\n x_pred \n" + np.array2string(self.x_pred) + "\n P_pred \n" + np.array2string(self.P_pred)

F = np.array([[1,0], [0,1]])
P = np.array([[1,0], [0,1]])
B = np.array([[1,0], [0,1]])
H = np.array([[1,0], [0,1]])
Q = np.array([[1,0], [0,1]])
R = np.array([[1,0], [0,1]])

x = np.array([[1], [0]])
y = np.array([[3], [5]])
u = np.array([[0], [0]])

kf = KF(x, P, F, B, H, Q, R)
kf.predict(u)
kf.update(y)

print("State = " + kf.to_str())

Output

State = x
[[2.33333333]
 [6.66666667]]
 P
[[0.66666667 0.        ]
 [0.         0.66666667]]
 x_pred
[[1.]
 [0.]]
 P_pred
[[2. 0.]
 [0. 2.]]

Validation with Filterpy as suggested by @AlexV

from filterpy.kalman import KalmanFilter
my_filter = KalmanFilter(dim_x=2, dim_z=2)
my_filter.x = x   # initial state (location and velocity)

my_filter.F = F
my_filter.H = H    # Measurement function
my_filter.P = P                 # covariance matrix
my_filter.R = R                      # state uncertainty
my_filter.Q = Q

my_filter.predict()

my_filter.update(y)

print(np.array2string(my_filter.x))

Output

[[2.33333333]
 [6.66666667]]


texts: Get ruby Hash#each to return a built hash

texts:
I'm golfing some code while waiting for a coworker, and I shortened a function to this:

def get_data(dir)
  newest = get_most_recent_file_numbers(dir)

  data = {}
  $file_prefixes.each do |type, file_prefix|
    file = File.open("#{dir}/#{file_prefix}_#{newest[type]}.csv")
    file.readline
    data[type] = file.readlines
  end

  data
end

I feel like there must be some method to do away with that last line of just data. How can I get $file_prefixes.each to return data?

If it matters, $file_prefixes looks like this:

$file_prefixes = {
  :fixed_deal   => "PC2MMS_CMSS_DEALS_",
  :fixed_offer  => "PC2MMS_CMSS_OFFERS_",
  :mobile_deal  => "PC2MMS_NGBSS_DEALS_",
  :mobile_offer => "PC2MMS_NGBSS_OFFERS_"
}

and newest is pretty much identical.

My target code might look something like this:

def get_data(dir)
  newest = get_most_recent_file_numbers(dir)

  data = {} # might even be able to get rid of this with clever use of Hash.new
  data = $file_prefixes.each do |type, file_prefix|
    file = File.open("#{dir}/#{file_prefix}_#{newest[type]}.csv")
    file.readline
    ???
  end
end

Disclaimer: I'm aware I could golf more by using single letter names, but I'm just trying to get it succinct and still readable


texts:
At work, I find myself frequently crunching CSVs with headers prone to change names and location. I have a solution, but with no opportunity for code review I was hoping SE could offer a look

header_indexer was built to allow me to us the same parsing code among spreadsheets where the data is known, but it's location prone to change.

The indexer parses the header row and creates an index_calculated dictionary based on the below user generated dict, effectively translating the headers to find into their column indexes:

headers_dict = {
        # "reference":  "header to find"
        "hostname":     "DNSHostname",
        "track":        "TrackingID",
        "OS":           "OperatingSystem"
}

(Adjusting "header to find" values ensures adaptability when spreadsheet format changes)

Assuming we're using a header row like so...

spreadsheet[0] = ["Date", "Status", "TrackingID", "Title", "DNSHostname", "OperatingSystem"]

Feeding the header row and headers_dict to the below code, as arguments:
sheet_headers=spreadsheet[0], head_names=headers_dict...

from typing import List, Dict

def index_headers(sheet_headers: List[str], head_names: Dict[str, str],
                  ignore_duplicates=False, ignore_nonindexed=False) -> Dict[str, int]:
    """Builds and returns an Index calc dict based on the provided header row\n
    Provide headers row and head names dictionary"""

    # A dictionary of all header names from given CSV
    # For each column header, ndx_all[header] = header's index
    ndx_all = {}
    index = 0
    for header in sheet_headers:
        ndx_all[header] = index
        index += 1

    # Create new NEW_NDX entries based on HEAD_NAMES entries, using indexes stored in ndx_all
    ndx_calc = {}
    for key, val in head_names.items():
        try:
            ndx_calc[key] = ndx_all[val]
        # Missing or unfound header. Address in later checks
        except (IndexError, KeyError):
            ndx_calc[key] = None

    # Check for non indexed headers, if allowed
    error_string = "\n"
    nonindexed = []
    if not ignore_nonindexed:
        for key, val in ndx_calc.items():
            if val is None:
                nonindexed.append([key, val])

        # Prepare string out to display missing headers
        if nonindexed:
            error_string += "\nNon indexed headers!\n" + '\n'.join(str(x) for x in nonindexed)

    # Check for duplicate indexes, if allowed
    duplicates = []
    dup_check = {}
    if not ignore_duplicates:
        for key, val in ndx_calc.items():
            dup_check.setdefault(val, set()).add(key)
        for val in dup_check.values():
            if len(val) > 1:
                for k in val:
                    duplicates.append([k, ndx_calc[k]])

        # Prepare string out to display problem headers
        if duplicates:
            error_string += "\nDuplcate header indexes!\n" + '\n'.join(str(x) for x in duplicates)

    # Raise ValueError,
    if duplicates or nonindexed:
        raise ValueError(error_string)

    return ndx_calc

...creates and returns the following dict, corresponding to headers_dict above:

ndx_calc = {
    "hostname": 4,
    "track":    2,
    "OS":       5
}

I have some ideas of improvement, namely to prompt a query against all non-indexed headers when given values aren't found, but wanted to get some sort of feedback before I proceeded

Thank you


texts: Script that counts quarters, dimes, nickels, and pennies

texts:
I am learning Python and I wrote a script that counts how many coins you would need for an amount in dollars. I was wondering if I could make any improvements to it.

def change():
    amnt = float(input("Enter an amount in USD: "))
    quarters = divmod(amnt, 0.25)
    print("Quarters: ", quarters[0])
    amnt = round(quarters[1], 2)
    dimes = divmod(amnt, 0.10)
    print("Dimes: ", dimes[0])
    amnt = round(dimes[1], 2)
    nickels = divmod(amnt, 0.
    print("Nickels: ", nickels[0])
    amnt = round(nickels[1], 2)
    penny = divmod(amnt, 0.01)
    print("Pennies", penny[0])
change()


texts:
Problem Statement

  You are given a tree (a simple connected graph with no cycles). You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected component of the forest should contain an even number of vertices.

  To accomplish this, you will remove some edges from the tree. Find out the number of removed edges.

Input Format

  The first line of input contains two integers N and M. N is the number of vertices and M is the number of edges.
  The next M lines contain two integers ui and vi which specifies an edge of the tree. (1-based index)

Output Format

  Print the answer, a single integer.

Constraints

  \$2 \le N \le 100\$

Example input

10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 8

Example output

  2

Note: The tree in the input will be such that it can always be decomposed into components containing even number of nodes.

Solution

def parents(ar, child):
    """ Enumerates on the list of all the parents of a child."""
    parent = ar[child]
    while child != parent:
        yield parent
        child = parent
        parent = ar[child]

def update_child_count(node_parent, node_count, child):
    for parent in parents(node_parent, child):
        node_count[parent] += 1

if __name__ == '__main__':

    N, E = map(int, raw_input().split())
    node_count = [None]*N
    node_parent = [None]*N
    root = 0
    res = 0
    for child, parent in enumerate(node_parent):
        node_parent[child] = child
        node_count[child] = 1

    for node in xrange(E):
        child, parent = map(int, raw_input().split())
        node_parent[child-1] = parent-1
        update_child_count(node_parent, node_count, child-1)

    for child, parent in enumerate(node_count):
        if node_count[child] % 2 == 0 and child != root:
            res += 1

    print res

The solution is working fine, but I am more interested in a better/more efficient approach.


texts:
In looking for a bit of feedback about an Angular app I have created.

I'm new to angular I want to clean up the loose ends before I carry on and add new functionality.

Below is the code snippet of index.html which includes custom directives that includes a block of HTML and various angular elements

It also includes a $http service to fetch Json from an external file

{{store.title}}

            <product-title></product-title>

Item is not available for purchase

        <button ng-show="product.canPurchase">Add to cart</button>
        <product-panels></product-panels>

This is my app.js which contains the controllers

var app = angular.module('store', ['store-products']);

app.controller("ReviewController", function () {
// New review array slot is created and assigned blank
this.review = {};

// Form triggers function to push new review slot into array
this.addReview = function (product) {
    product.reviews.push(this.review);
    // Set the review form to blank again
    this.review = {};
}
});

app.controller('StoreController', ['$http', function ($http) {
this.title = "Angular App";
    console.log('test');
var store = this;
//store.products = [];

$http.get('/products.json').then(function (response) {
    console.log(response);
    store.products = response.data;
});
}]);

and finally here is my directives.js. with the logic being stored in external html files.

var app = angular.module('store-products', []);

app.directive('productPanels', function () {

return {
    restrict: 'E',
    templateUrl: 'product-panels.html',
    controller: function () {

        this.tab = 1;

        this.selectTab = function (setTab) {
            this.tab = setTab;
        }

        this.isSelected = function (checkTab) {
            return this.tab === checkTab;
        }

    },
    controllerAs: 'panel',
};
});

app.directive('productTitle', function () {

return {
    restrict: 'EA',
    templateUrl: 'product-title.html'
};
});


texts:
I have written a code to check if the number is prime number are not.

I pass the number from command line argument, and check if the number is prime.

I have written a function for it which returns the boolean value.

(function(){
    'use strict';

    main();

    function main(){
        var testNum = getCommandLineVariables();
        console.log("Is Number \""+testNum+"\" a prime number ? ",isPrimeNumber(testNum));
    }

    function isPrimeNumber(num){
        var halfNum = num/2;
        halfNum = parseInt(halfNum);

        // check if number is divisible by 2,
        // if yes then its not a prime number.
        if(num%2 === 0){
            return false;
        }

        do{
            // if number is divisible by its half value,
            // if yes, than its not prime number
            if(num%halfNum === 0){
                return false;
            }

        }while(--halfNum >= 2); // reduce the half-value by 1 and continue

        return true;
    } // end of isPrimeNumber

    // get the number from commandline argument
    function getCommandLineVariables(){
        var arg_array = process.argv.slice(2);

        if(arg_array.length !== 1){
            throw new Error("Pass a number");
        }

        return parseInt(arg_array[0]);
    } // end of getCommandLineVariables
})();

I run the program as follows,

E:\math>node isPrimeNum01.js 13
Is Number "13" a prime number ?  true

E:\math>node isPrimeNum01.js 16
Is Number "16" a prime number ?  false

E:\math>node isPrimeNum01.js 29
Is Number "29" a prime number ?  true

E:\math>node isPrimeNum01.js 113
Is Number "113" a prime number ?  true

E:\math>node isPrimeNum01.js 127
Is Number "127" a prime number ?  true

E:\math>node isPrimeNum01.js 566
Is Number "566" a prime number ?  false

E:\math>

Please review my code and leave your valuable comments. Also please check whether my logic for checking the prime number is efficient.


texts:
I have a list of rescues for ambulance drivers in different states that are displayed on a kanban board. My JSON object is divided by the status of the rescues, and then grouped by driver. The structure is like this:
--Status (unassigned/assigned/arrived/rescued)
----Driver group
-------Rescue list
The rescues have a datetime and lat/long associated with them, so I can use map/reduce to find the rescue that the drivers attended most recently, and show that location on a map.
One issue is that a driver group can exist in one swimlane and none of the other.
I want to: filter the list down to the arrived/rescued states only, (although logically this may not be necessary as it's not possible to have an arrival time without a driver associated, but this is out of scope) and for each driver group return their latest rescue by arrival time or rescue time. This will leave me with a distinct list of driver groups, with only the most recent rescue for that group
Here's the working code:
let groups = cases
                .filter(swimlane => parseInt(swimlane.rescueStatus) >= 3)
                .map(groups => groups.rescuerGroups)
                .map(rescuerGroups => rescuerGroups)
                .reduce((result, current) => {

                  if(result.length === 0){
                    return current;
                  }
                  else{

                    current.forEach(currentRescueGroup => {

                      let index = result.findIndex(parentRescueGroup => {

                        return parseInt(parentRescueGroup.rescuer1) == parseInt(currentRescueGroup.rescuer1) &&
                            parseInt(parentRescueGroup.rescuer2) == parseInt(currentRescueGroup.rescuer2)

                      })

                      index > -1 ?
                        result[index].rescues = result[index].rescues.concat(currentRescueGroup.rescues)
                        :
                        result.push(currentRescueGroup);

                    })

                    return result;

                  }}, [])
                .map(rescueGroup => {

                  let maxRescue = rescueGroup.rescues.reduce((current, previous) => {

                  let currentTime = new Date(current.ambulanceArrivalTime) > (new Date(current.rescueTime) || new Date(1901, 01, 01)) ? current.ambulanceArrivalTime : current.rescueTime;
                  let previousTime = new Date(previous.ambulanceArrivalTime) > (new Date(previous.rescueTime) || new Date(1901, 01, 01)) ? previous.ambulanceArrivalTime : previous.rescueTime;

              return previousTime > currentTime ? current : previous;

            })

             return {
                       rescuer1Abbreviation: rescueGroup.rescuer1Abbreviation,
                       rescuer2Abbreviation: rescueGroup.rescuer2Abbreviation,
                       latestLocation: maxRescue.latLngLiteral,
                       rescues: rescueGroup.rescues
                     }
           })

And here's a JSBin including the working code:
https://jsbin.com/hocasob/edit?js,console
Any help to make the reduce sections simpler would be much appreciated


texts:
I have a bash script that is meant to start a google search from the command line. I am also looking to implement a way of getting source code for the search page possibly through a subscript. This is what I have so far:

if [[ $1 == "-n" ]]; then
    if [[ $# -lt 2 ]]; then
        echo "Usage: google [-n] term [, term [, term...]]"
        exit 1
    fi
fi

if [[ $1 != "-n" ]]; then
    if [[ $# -lt 1 ]]; then
        echo "Usage: google [-n] term [, term [, term...]]"
        exit 2
    fi

    if [[ $(node -v) != *"v"* ]]; then
        echo "This tool uses node.js to escape url entities"
        echo "To use this tool without escapes include -n as the first agument"
        echo "(THIS IS NOT RECOMMENDED!)"
        exit 3
    fi
fi

search=""

for i in ${BASH_ARGV[*]}; do
    search="$i+$search"
done

escapedSearch=`node -e "a = escape(\"$search\"); console.log(a)"`

open "http://www.google.com/search?q=$escapedSearch"


texts: Python logging: show variable name without specifying it explicitly

texts:
A lot of the Python code that I write looks something like this:

import logging
import shlex
import subprocess

logger = logging.getLogger(__name__)

def execute(system_command, **kwargs):
    """Execute a system command, with sane defaults."""
    # Question is mainly about these two lines:
    logger.info("system_command: '%s'", system_command)
    logger.debug("kwargs: %s", kwargs)
    process = subprocess.run(
        shlex.split(system_command),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        **kwargs)
    if process.returncode != 0:
        logger.info(process.stdout.strip())
        logger.error(process.stderr.strip())
    return process

The logging statements are typically added when I am trying to debug something, but then i forget to remove them and they stay there.

My question is: "Does this code look reasonable?". Is there a way for me to write logger.debug(arg1) and the logger to automatically show the name of the variable being printed, for the sake of DRY?


texts:
Can the below foreach loop be improved?  Since I use the same method twice, maybe use continue or break?

int? index = null;
int count = 0;
foreach (Break b in breaks)
{
    if (index.HasValue)
    {
        if (index == count)
            b.Remove();
    }
    else
    {
        b.Remove();
    }
    count++;
}

So I turned it into this:

foreach (Break b in breaks)
{
    if ((index.HasValue && index == count) || !index.HasValue)
    {
        b.Remove();
    }
    count++;
}

Which is the same.  Any other optimizations possible?


texts:
I found a example of Java PostMethod here.

But I want to post several times by using for loop. I made it like this.

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PostMethodExample {

  public static void main(String args[]) {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

    BufferedReader br = null;

    PostMethod method = new PostMethod("http://search.yahoo.com/search");
    method.addParameter("p", "\"java2s\"");

    try{
            String[] parameters = { "Google", "Yahoo", "MSN" };

            for (String s in parameters){
                int returnCode = client.executeMethod(method);
                method.addParameter("p", s);
                if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                    System.err.println("The Post method is not implemented by this URI");
                    // still consume the response body
                    method.getResponseBodyAsString();
                } else {
                    br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
                    String readLine;
                    while(((readLine = br.readLine()) != null)) {
                        System.err.println(readLine);
                    }
                }
                method.releaseConnection();
                method = new PostMethod("http://search.yahoo.com/search");
            }
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      method.releaseConnection();
      if(br != null) try { br.close(); } catch (Exception fe) {}
    }
  }
}

I modified code just inside of try block. I don't think this is the best way. Help me to improve this code.


texts: Which one of the two enum implementation is better?

texts:
First Implementation

public enum ReviewFlowExample {

    Draft {

        @Override
        public ReviewFlowExample getNext() {
            return Review;
        }

        @Override
        public ReviewFlowExample getPrevious() {
            return null;
        }

    },
    Review {
        @Override
        public ReviewFlowExample getNext() {
            return Final;
        }

        @Override
        public ReviewFlowExample getPrevious() {
            return Draft;
        }

    },
    Final {
        @Override
        public ReviewFlowExample getNext() {
            return null;
        }

        @Override
        public ReviewFlowExample getPrevious() {
            return Review;
        }

    };

    public abstract ReviewFlowExample getNext();

    public abstract ReviewFlowExample getPrevious();

    public boolean isDraft() {
        return this.equals(Draft);
    }
}

Second Implemenation

public enum ReviewFlowExample {
    Draft,
    Review,
    Final;
    private ReviewFlowExample next;
    private ReviewFlowExample previous;

    static{
        Draft.setNext(Review);
        Review.setNext(Final);
        Review.setPrevious(Draft);
        Final.setPrevious(Review);
    }
    private ReviewFlowExample(){
    }

    public ReviewFlowExample getNext(){
        return next;
    }

    public ReviewFlowExample getPrevious(){
        return previous;
    }

    private void setNext(ReviewFlowExample next){
        this.next = next;
    }

    private void setPrevious(ReviewFlowExample previous){
        this.previous = previous;
    }

    public boolean isDraft(){
        return this == Draft;
    }

}


texts: Removing duplicate letters from list of words with Python and List Comprehensions

texts:
I'm guessing this has quadratic time complexity, \$O(n^2)\$, and \$O(2n)\$ for memory complexity. I wonder if I can do something within the list comprehension to just .pop(n) something out of the list instead of relying on a second list. Thoughts?

listx = ['cat', 'dog','rabbit']
listLettersAlreadyFound = []
[[listLettersAlreadyFound.append(letter) for letter in list(word) if letter not in listLettersAlreadyFound] for word in listx]
print listLettersAlreadyFound


texts:
I have written a couple of scripts for accessing Twitter REST API, and storing data in a Postgres DB for data extraction purposes. I know how to use django ORM, or plain SQL, but this was my first attempt at SQLalchemy. I am not sure if the way I use sessions makes sense.

There two scenarios:

The streaming API script will continuously create new Tweet objects for as long as the script runs.

There is also the refresh_tweet_data, which iterates the existing database tweets and updates some metrics. refresh_user_data operates in a similar way.

For some operations, I had to use update_session while for most db_session seems to work better. All my DB operations are specified in my models class.

Can you spot any obvious mistakes, improvements on the way I am using sessions? The current code is working, I am just not sure if I am doing something silly.

The sessions defined in database.py. db_session and update_session used in the scripts are imported from here:

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('postgresql://tweetsql:tweetsql@127.0.0.1/tweetsql')
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=True,
                                         bind=engine))

update_session = scoped_session(sessionmaker(autocommit=True,
                                         autoflush=True,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import model
    Base.metadata.create_all(bind=engine)

The stream script. on_data is called whenever a new Tweet arrives:

def on_data(self, data):
    try:
        tweet_json = json.loads(data)
        tweet = Tweet(...)
        tweet.save()
    except:
       print_exc()
       db_session.rollback()
    return True

The Tweet.save called above:

def save(self):
    db_session.add(self)
    db_session.commit()

refresh_user_data extract. This function is called once when the script is executed. Users are currently 190.000 and increasing:

def refresh_user_followers():
    api = tweepy.API(...)

    for user in User.fetch_users():
        followers_ids = api.followers_ids(user.id)
        User.update_followers(user.id, followers_ids)

The User.update_followers function:

def update_followers(cls, user_id, follower_ids):
    update_session.query(User).filter(User.id == user_id).update({
        'followers': list(follower_ids),
        'follower_count': len(follower_ids),
        'last_update':datetime.now()
    })

The function from refresh_tweet_data. This is called once when the script executes:

def refresh_tweet_data():
    tweets_to_update = batch_ids() # get tweets ids not updated within 12 hours
    api = tweepy.API(...)

    while tweets_to_update:
        print('.', end="", flush=True)
        response = api.statuses_lookup(tweets_to_update) # Returns tweets for a list of ids
        for tweet in response:
            Tweet.update_data(tweet.id, tweet)
        tweets_to_update = batch_ids()

The Tweet.update_data:

@classmethod
def update_data(cls, tweet_id, tweet):
    db_session.query(Tweet).filter(Tweet.id == tweet_id).update({
        'favorite_count': tweet.favorite_count,
        'last_update': datetime.now(),
        'json': tweet._json,
        'retweet_count': tweet.retweet_count})
    db_session.commit()

(The refresh scripts will run at the same time as the streaming script.)


texts: Python Console App | Is there a better way to go back a page?

texts:
I have a system for going back to a previously-visited page in a Python console application; it works well enough, but I feel that there could be a prettier way of doing it. Does anyone have any suggestions to improve what I have below?
def main():
    try:
        while True:
            print('Main Menu\n')

            option = input('page 1, page 2, quit\n')

            if option in ['1', 'one']:
                menu_stack.append(0)
                page_one()
            elif option in ['2', 'two']:
                menu_stack.append(0)
                page_two()
            elif option in ['q', 'quit']:
                quit()
            else:
                print('Invalid input, please try again\n')
                sleep(1)

    except KeyboardInterrupt:
        quit()

Very similar to the main menu page, below is page 1:
def page_one():
    while True:
        clear_terminal()

        print('Page One\n')

        option = input('Page 2, back\n')

        if option in ['2', 'two']:
            menu_stack.append(1)
            page_two()
        elif option in ['b', 'back']:
            menu_checker()
        else:
            print('Invalid input, please try again\n')
            sleep(1)

menu_checker() calls the other pages based on what pops from the stack:
def menu_checker():
    page = menu_stack.pop()

    if page == 1:
        page_one()
    elif page == 2:
        page_two()
    elif page == 0:
        main()
    else:
        print('Error')

Does anyone have any better ideas/solutions? Even though it doesn't cause any issues (as far as I am aware), I feel what I have is kind of clunky and could be improved.


texts: Printing a number based on a user-provided number

texts:
Is there a better way to ask for input and give answers, but without so many lines? Each input will give a specific output according to a key that I use, but this many lines seems excessive. I'm a beginner to java and could use some ideas on how to optimize this coding.

    import java.util.Scanner;
    class Test {
    public static void main (String [] args) {

    System.out.print ("Enter the day of the month - Answer: ");
    Scanner inputFigure = new Scanner (System.in);
    int i = inputFigure.nextInt ();
    if ( i==1) {
        System.out.println ("12");
    }
    else if (i==2) {
        System.out.println ("13");
    }
    else if (i==3) {
        System.out.println ("14");
    }
    else if (i==4) {
        System.out.println ("11");
    }
    else if (i==5) {
        System.out.println ("12");
    }
    else if (i==6) {
        System.out.println ("13");
    }
    else if (i==7) {
        System.out.println ("14");
    }
    else if (i==8) {
        System.out.println ("11");
    }
    else if (i==9) {
        System.out.println ("12");
    }
    else if (i==10) {
        System.out.println ("21");
    }
    else if (i==11) {
        System.out.println ("22");
    }
    else if (i==12) {
        System.out.println ("23");
    }
    else if (i==13) {
        System.out.println ("24");
    }
    else if (i==14) {
        System.out.println ("21");
    }
    else if (i==15) {
        System.out.println ("22");
    }
    else if (i==16) {
        System.out.println ("23");
    }
    else if (i==17) {
        System.out.println ("24");
    }
    else if (i==18) {
        System.out.println ("21");
    }
    else if (i==19) {
        System.out.println ("22");
    }
    else if (i==20) {
        System.out.println ("31");
    }
    else if (i==21) {
        System.out.println ("32");
    }
    else if (i==22) {
        System.out.println ("33");
    }
    else if (i==23) {
        System.out.println ("34");
    }
    else if (i==24) {
        System.out.println ("31");
    }
    else if (i==25) {
        System.out.println ("32");
    }
    else if (i==26) {
        System.out.println ("33");
    }
    else if (i==27) {
        System.out.println ("34");
    }
    else if (i==28) {
        System.out.println ("31");
    }
    else if (i==29) {
        System.out.println ("32");
    }
    else if (i==30) {
        System.out.println ("41");
    }
    else if (i==31) {
        System.out.println ("42");
    }
    else {
        System.out.println ("Invalid entry for the day. Try again.");
    }
}
}


texts: Dividing an arbitrary dollar amount into the fewest bills and coins

texts:
I am taking a class in mobile application development this fall. I have finished my first assignment of creating a class to divide an arbitrary dollar amount into the minimum number of bills and coins. I have completed the assignment and everything works as intended (outside of an occasional error I'm having with computing pennies, but I am working on that). My main reason for posting is I would like to try and make my code more Swift like. I am coming from a mostly C background so I am learning the ins and outs of Swift and OOP on the fly. So if you have any suggestions to making my code more "Swift like" I would greatly appreciate it.

public class Cash
{
    //    Denominations of monies
    let bills = [50.00, 20.00, 10.00, 5.00, 1.00, 0.25, 0.10, 0.05, 0.01]

    //    Backing variable
    var value:Double

    //    Computed Property of minimum number of bills to satisfy the value sent in
    public var minBills:[Int]? {
        var tempArray = [Int]()
        var tempValue: Double
        if value >= 0 {
            for index in 0..<bills.count {
                tempValue = value / bills[index]                  //Calculating the amount of bills
                value -= Double(Int(tempValue)) * bills[index]    //Recalculating the value
                tempArray.append(Int(tempValue))                  //Adding number of bills needed to tempArray
            }
            return tempArray                                      //Returns entire tempArray to minBills
        }
        else {
            return nil
        }
    }

    //Constructor
    public init(value: Double) {
        self.value = value
    }
}


texts:
Challenge:

  Print set intersections.

Specifications:

  Your program should accept as its first argument a path to a filename.
  Each line in the file is a test case.
  Each test case contain two semicolon delimited sorted lists of numbers in ascending order, whose numbers are separated by a comma.

  Print out the ascending order sorted intersection of the lists, one per line.
  Print empty new line in case the lists have no intersection

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;

public class SetIntersection {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));
        String[] parts;

        while (input.hasNextLine()) {
            parts = input.nextLine().split(";");

            System.out.println(
                findIntersection(
                    toIntArray(parts[0].split(",")),
                    toIntArray(parts[1].split(","))
                )
            );
        }
    }

    private static String findIntersection(int[] foo, int[] bar) {
        Set<Integer> intersection = new LinkedHashSet<>();

        for (int i = 0, j = 0; i < foo.length; i++) {
            while (foo[i] > bar[j] && j < bar.length) {
                j++;
            }
            if (foo[i] < bar[j]) {
                continue;
            } else {
                intersection.add(bar[j++]);
            }
        }

        if (intersection.isEmpty()) {
            return ""; // none found
        }

        String result = intersection.toString();
        return result.substring(1, result.length() - 1);
    }

    private static int[] toIntArray(String[] array) {
        int[] nums = new int[array.length];

        for (int i = 0; i < array.length; i++) {
            nums[i] = Integer.parseInt(array[i]);
        }

        return nums;
    }
}

Sample Input:

  9,10,11;33,34,35
  3,7,8,22;11,22
  11,12,13,14;14,15,16
  20,21,22;45,46,47
  77,78,79;78,79,80,81,82
  33,35;3,18,26,35

Sample Output:

  22
  14

  78, 79
  35

I wanted to take advantage of the fact the lists were sorted, but I fear my efforts only served to render my code convoluted and inefficient. What do you think?


texts: Ruby: refactor simple string method for aligning DSV text

texts:
GOAL:

Accept DSV strings where the delimiter may consist of more than one character
Accept DSV strings where there are no embedded delimiters
Output text with no modification to the source string other than aligning custom delimiter with optional padding

QUESTION:

Anyone have a re-factor or stylistic enhancement or two?

CODE:

module DreftymacAddon
  module String
    ### <region-fdef ddef="dsvpretty ;; lineup delims pretty print dsv text with lined up delimiters ">
    def dsvpretty(delim=';;',padd='')
      sout    =   ""
      asizes  =   []
      alines  =   self.to_s.split(/[\x0a\x0d]/)
      alines.each{|currline|
        currline.split(delim).each_with_index{|currfld,icc|
          asizes[icc] = [asizes[icc].to_i,currfld.length].max()
        }
      }
      alines.each{|currline|
        next if currline.strip == ''
        atemp   = []
        currline.split(delim).each_with_index{|currfld,icc|
          atemp << sprintf("%-#{asizes[icc]}s", currfld)
        }
        sout += atemp.join([padd , delim , padd].join(''))
        sout += "\n"
      }
      sout
    end
    alias :dsv_pretty :dsvpretty
    ### </region-fdef>
  end
end

class String
  include DreftymacAddon::String
end

### String.new().dsvpretty ;; example usage
##{
if(1000!=0);
  vout   = %Q[
    LNAME|FNAME|AMOUNT|AGE|NATION|PLATFORM
    Rodriguez|Johan|30.00|58|uk|windows_xp
    Raynor|Coty|40.00|14|uk|redhat
    Bruen|Jackie|30.00|17|uk|ubuntu
    Breitenberg|Waldo|20.00|14|canada|mac_osx
    Collier|Lucy|30.00|22|canada|windows_vista
    Blick|Emmett|30.00|59|canada|knoppix
    Schroeder|Myrtis|10.00|29|uk|knoppix
    Rodriguez|Ashtyn|20.00|22|uk|mac_osx
    Leuschke|Sigmund|40.00|21|france|redhat
    Fahey|Cassidy|40.00|29|canada|knoppix
  ]

  puts vout.dsvpretty('|','')
=begin
    LNAME      |FNAME  |AMOUNT|AGE|NATION|PLATFORM
    Rodriguez  |Johan  |30.00 |58 |uk    |windows_xp
    Raynor     |Coty   |40.00 |14 |uk    |redhat
    Bruen      |Jackie |30.00 |17 |uk    |ubuntu
    Breitenberg|Waldo  |20.00 |14 |canada|mac_osx
    Collier    |Lucy   |30.00 |22 |canada|windows_vista
    Blick      |Emmett |30.00 |59 |canada|knoppix
    Schroeder  |Myrtis |10.00 |29 |uk    |knoppix
    Rodriguez  |Ashtyn |20.00 |22 |uk    |mac_osx
    Leuschke   |Sigmund|40.00 |21 |france|redhat
    Fahey      |Cassidy|40.00 |29 |canada|knoppix
=end

  puts vout.dsvpretty('|',' ')
=begin
    LNAME       | FNAME   | AMOUNT | AGE | NATION | PLATFORM
    Rodriguez   | Johan   | 30.00  | 58  | uk     | windows_xp
    Raynor      | Coty    | 40.00  | 14  | uk     | redhat
    Bruen       | Jackie  | 30.00  | 17  | uk     | ubuntu
    Breitenberg | Waldo   | 20.00  | 14  | canada | mac_osx
    Collier     | Lucy    | 30.00  | 22  | canada | windows_vista
    Blick       | Emmett  | 30.00  | 59  | canada | knoppix
    Schroeder   | Myrtis  | 10.00  | 29  | uk     | knoppix
    Rodriguez   | Ashtyn  | 20.00  | 22  | uk     | mac_osx
    Leuschke    | Sigmund | 40.00  | 21  | france | redhat
    Fahey       | Cassidy | 40.00  | 29  | canada | knoppix
=end

end
##}


texts:
I need to create method which handle HttpResposeMessage.
Method should throw an exception if error exist, client will handle rest.
You can see my code bellow. This code is working fine and doing what I want, but still it looks quite ugly to me.

Do you have some ideas for nicer implementation?

  [Authorize]
  public abstract class BaseController : Controller
    {
        protected readonly ILogger logger;
        protected readonly IHostingEnvironment env;
        private readonly IStringLocalizer localizer;

        public BaseController(ILogger logger, IHostingEnvironment env, IStringLocalizer localizer)
        {
            this.logger = logger;
            this.env = env;
            this.localizer = localizer;
        }

       protected void HandleResponseError(HttpResponseMessage response, ILogger logger)
        {
        if (!response.IsSuccessStatusCode)
        {
            var message = String.Empty;
            if (response.StatusCode.Equals(HttpStatusCode.Forbidden))
            {
                message = this.localizer["Forbidden"] + ": " + this.localizer["You have not the appropriate rights to access this page."];
            }
            else
            {
                try
                {
                    message = response.Content.ReadAsStringAsync().Result;
                    if (string.IsNullOrWhiteSpace(message))
                    {
                        message = message = this.localizer["Communication error with server"];
                    }
                }
                catch
                {
                    message = this.localizer["Communication error with server"];
                }
            }
            logger.LogError($"Client error message {message} !");
            throw new ApplicationException(message);
        }
    }
}


texts:
Learn You a Haskell presents the Caesar Cipher:

  The Caesar cipher is a primitive method of encoding messages by
  shifting each character in them by a fixed number of positions in the
  alphabet

EDIT

Since I'm not limiting this cipher to letters, it's not actually the Caesarian Cipher.
Thanks to Anonymous. This implementation is only a Substitution Cipher.

Here's my implementation:

import Data.Char (ord, chr)

encode :: Int -> String -> String
encode n = map $ shift' n
                 where shift' x =  chr . (+ x) . ord

decode :: Int -> String -> String
decode n = map $ shift' n
                 where shift' x =  chr . abs . ((-) x) . ord

Test:

*Main Data.Char> encode 1 "AAA"
"BBB"
*Main Data.Char>
*Main Data.Char> decode 1 "BBB"
"AAA"

I don't like that I'm using abs in my decode. How can I write a function (through currying) that will subtract X from it?

Also, please critique my implementation.


texts: Adding a constraint to a PFQuery on a PFRelation with objects that have already been gotten

texts:
For some background, I am learning from the following Stack Overflow question that I asked regarding creating the this code.

I was playing around with different combinations of whereKeys and queries, and I found a solution that seems to be working. I'm not really sure if this is the correct or most efficient way to handle a constraint on a query based on a relation, and any help improving or optimizing the code would be appreciated.

 let query: PFQuery
 let isNormalQuery = false
 response = objects as! [PFObject]
 var responseObjectIds = [String]()
 for x in response{
     responseObjectIds.append(x.objectId!)
 }
let query2 = PFQuery(className: query.parseClassName)
query2.whereKey("objectId", notContainedIn: responseObjectIds)
query = PFQuery(className: query.parseClassName)
query.whereKey("objectId", doesNotMatchKey: "objectId", inQuery: query2)
// query2 is then used to fetch objects from the Parse server


texts:
I have this code that creates unique passwords using the first letter of each word from the file. Before each password is created (written to a file) it is compared to all passwords that are currently in the file, so if the file has 50,000 passwords before a another is written it has to scan through all 50k.
A user can input any amount of passwords needed but the bigger the number the longer it takes. 100k will take a long time, so how can I optimize this to make the program run faster? (the password generation is not included code)

for mainLoop in range(passnum):

      user  = 0
      newpass = generatePassword() # New password generated each iteration of loop
      storePass = open("MnemPass.txt","a")
      print ("PASSWORD GENERATED ")

      #Checks if file is empty if True write first password
      fileEmpty = os.stat("MnemPass.txt").st_size == 0
      if fileEmpty == True:
          storePass.write(newpass)
          storePass.write("\n")
          storePass.close()
          print ("FIRST PASSWORD WRITTEN")

      #IF file is not empty Read line by line and compare each with new password generated returns boolean value
      elif  fileEmpty == False:
            storePass = open("MnemPass.txt","r")
            with open("MnemPass.txt") as f:
                fileData = f.read().splitlines()
                linelength = len(fileData).__int__()
                filemax = linelength
                num = linelength    #Number used to cycle through array set to size of list
                #print(linelength+10)

                for iterate in range(linelength):
                    num = num - 1 #Number decreases each pass
                    #print num
                    if fileData[num] != newpass: # The last element in the array is checked first decrementing each pass
                       go = True

                    if fileData[num]==newpass: #changed
                        print ("match found: PASSWORD : "+fileData[num])
                        passMatch = open("Matchpassword.txt","a")
                        passMatch.write(newpass)
                        passMatch.write("\n")
                        passMatch.close()
                        go = False
                        break

                    #places new password once it does not match and all elements prev passwords are compared
                    if go == True and num == 0:
                      storePass = open("MnemPass.txt","a")
                      storePass.write(newpass)
                      storePass.write("\n")
                      storePass.close()
                      print ("NEW WRITTEN")

            if linelength == filemax:

                num = num -1


texts: Validating username fields and showing CAPTCHA

texts:
I'm new to coding, and especially to OOP PHP. I'll highly appreciate if you expert programmers could review following code and give me your opinion to make it better. Also, how you see this code, is it too horrible and ugly?

<?php
include_once("config.inc.php");

class user{

    var $mysqli;
    var $username;
    var $userid;

     function __construct($mysqli) {
         session_start();
         $this->mysqli = $mysqli;
    }

    function valid_length($input){
        if ((strlen($input) > 4 ) AND (strlen ($input) < 16) ){
            return true;
        } else {
            return false;
        }
    }

    function valid_email($email){
        if (preg_match("/^[0-9a-z]+(([\.\-_])[0-9a-z]+)*@[0-9a-z]+(([\.\-])[0-9a-z-]+)*\.[a-z]{2,4}$/i" , $email)) {
            return true;
        } else {
            return false;
        }
    }

    function alpha_numeric($input){
        if (eregi("^([0-9a-z])+$", $input)){
            return true;
        }else{
            return false;
        }
    }

    function username_exists($username){

        if ($stmt = $this->mysqli->prepare("SELECT username FROM users WHERE username=?")) {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $stmt->store_result();
            $count=$stmt->num_rows;
            $stmt->close();
        }
        return ($count > 0 ? true : false);
    }

    function signup($username, $password, $email, $capt_error){

    //validate username.
    if(!$this->valid_length($username)){
            $this->signup_error = "Username should be 5 - 15 characters.
";
    }else if(!$this->alpha_numeric($username)){
            $this -> signup_error ="Only letters, numbers";
    } else if($this->username_unallowed($username)){
            $this -> signup_error ="Not allowed.";
    } else if ($this->username_exists($username)){
            $this -> signup_error ="Username already exists.
";
    }

    //validate password.
   if (!$this->valid_length($password) ){
            $this -> signup_error .="Password should be 5 - 15 characters.
";
        }

    //validate email.
    if (!$this->valid_email($email) ){
            $this -> signup_error .="Invalid email.";
    }else if($this->email_exists($email)) {
            $this -> signup_error .="Email exists.
";
        }

    //captcha error
    if($capt_error == 1){
    $this -> signup_error .="Invalid captcha.
";
    }

    //no any error, proceed.
    if ($this->signup_error == ""){
        $hashed_password = $this->hash_password($password);
        if ($this->insert_new_user($username, $enc_password, $email)){
        $_SESSION['username']=$username;
        header("Location: welcome.php");
        }else {
        $this->signup_error = "Unknown error.
";
        }
    }

  }

}
?>


texts:
I'm a beginner in Java and I tried to create a program that will perform basic arithmetic operations on binary numbers.

BinaryOperations class:

package binaryoperations;

import java.io.IOException;
import static java.lang.System.in;
import java.util.Scanner;

public class BinaryOperations {
    public static void main(String[] args) throws IOException {
        try(Scanner in = new Scanner(System.in)) {
            Operations operation = new Operations();
            System.out.print("First Binary:  ");
                String binOne = in.next();
            System.out.print("Second Binary: ");
                String binTwo = in.next();
            System.out.println("Sum:        " + operation.GetBinarySum(binOne, binTwo));
            System.out.println("Difference: " + operation.GetBinaryDiff(binOne, binTwo));
            System.out.println("Product:    " + operation.GetBinaryProd(binOne, binTwo));
            System.out.println("Quotient:   " + operation.GetBinaryQuotient(binOne, binTwo));
        } catch(NumberFormatException e) {
            System.out.println("Looks like you entered a non Binary digit.");
        } finally {
                in.close();
            }
        }
    }

Operations class:

package binaryoperations;

public class Operations {

    public String GetBinarySum(String a, String b){
        int left = Integer.parseInt(a, 2);
        int right = Integer.parseInt(b, 2);
        int sum = left + right;
        return Integer.toBinaryString(sum);
    }

    public String GetBinaryDiff(String a, String b){
        int left = Integer.parseInt(a, 2);
        int right = Integer.parseInt(b, 2);
        int diff = left - right;
        return Integer.toBinaryString(diff);
    }

    public String GetBinaryProd(String a, String b){
        int left = Integer.parseInt(a, 2);
        int right = Integer.parseInt(b, 2);
        int prod = left * right;
        return Integer.toBinaryString(prod);
    }

    public String GetBinaryQuotient(String a, String b){
        int left = Integer.parseInt(a, 2);
        int right = Integer.parseInt(b, 2);
        int quotient = left / right;
        return Integer.toBinaryString(quotient);
    }
}

To get the result I used Integer.parseInt(String, radix 2) because it's binary.

Did I do something wrong? Is it okay to use radix then converting the result to Binary to get the answer? Or is it better to apply the large amount of code to get the answer? Any suggestions is appreciated.


texts:
I'm trying to improve the portability of a file format converter, specifically to POSIX platforms other than Linux. I'd appreciate a review of the following functions used for converting between little endian and host endian 32bit unsigned integers and back. This is basically to replace le32toh and htole32 on platforms where they are not available. I'd particularly appreciate comments on whether this violates strict aliasing, I believe accessing integers through a char pointer is allowed but I'm not 100% sure.

I am intentionally writing endian-neutral code, performance is not so critical and simplicity, reusability and portability are more important to me. Determining endianness at compile time is difficult across compilers and operating systems, runtime checks either incur their own overhead if they need to be run on each function call or require a global variable.

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

uint32_t
le_u32_to_cpu(uint32_t le32)
{
    unsigned char   *b = (unsigned char *)&le32;
    uint32_t    cpu_u32 = b[0] | \
          (b[1] << 8) | \
          (b[2] << 16) | \
          (b[3] << 24);

    return (cpu_u32);
}

uint32_t
cpu_to_le_u32(uint32_t cpu_u32)
{
    uint32_t    le_u32;
    unsigned char   *b = (unsigned char *)&le_u32;

    b[0] = cpu_u32 & 0xff;
    b[1] = (cpu_u32 >> 8) & 0xff;
    b[2] = (cpu_u32 >> 16) & 0xff;
    b[3] = (cpu_u32 >> 24) & 0xff;

    return (le_u32);
}

int
main(void)
{
    uint32_t    x;
    unsigned char   *b = (unsigned char *)&x;

    b[0] = 0x11;
    b[1] = 0x22;
    b[2] = 0x33;
    b[3] = 0x44;

    puts("little endian");
    for (size_t i = 0; i < 4; i++) {
        printf("%02x\n", b[i]);
    }
    printf("0x%" PRIx32 "\n", x);

    puts("cpu endianness");
    x = le_u32_to_cpu(x);
    for (size_t i = 0; i < 4; i++) {
        printf("%02x\n", b[i]);
    }
    printf("0x%" PRIx32 "\n", x);

    puts("back to little endian");
    x = cpu_to_le_u32(x);
    for (size_t i = 0; i < 4; i++) {
        printf("%02x\n", b[i]);
    }
    printf("0x%" PRIx32 "\n", x);

    return (0);
}