texts:
I'm learning Rust so as an exercise I'm trying to write a datatype wrapping the builtin BTreeMap to allow it to store duplicates. Like the STL multimap type. The functions I have:

fn insert_dup<V>(map: &mut BTreeMap<i32, Vec<V>>, k: i32, v: V)
{
    if map.contains_key(&k) {
        map.get_mut(&k).unwrap().push(v);
    } else {
        let mut vec: Vec<V> = Vec::new();
        vec.push(v);
        map.insert(k, vec);
    }
}

fn remove_dup_internal<V>(map: &mut BTreeMap<i32, Vec<V>>, k: i32) -> usize {
    if map.contains_key(&k) {
        let ref mut vec = map.get_mut(&k).unwrap();
        vec.pop();
        return vec.len();
    }
    return 10;
}

fn remove_dup<V>(map: &mut BTreeMap<i32, Vec<V>>, k: i32) {
    if remove_dup_internal(map, k) == 0 {
        map.remove(&k);
    }
}

They work, but I would like to be able to parametrize the key too and not just the value. And the remove_dup / remove_dup_internal is because there  was a strange compiler error about borrowing I couldn't solve.


texts: Loop through string array with exit if test passed

texts:
I need to return True if a page contains any of a list of element types. This code works.

var elements = 0;
var content = $('.TestModule');
if (content !== null && typeof (content) !== "undefined") {
    elements += content.first().find('.btn').length;
    elements += content.first().find('.textbox').length;
    elements += content.first().find('.ui-jqgrid').length;
    elements += content.first().find('.flexboxdiv').length;
    elements += content.first().find('.headerlabel').length;
}
return elements > 0;

But always runs every test which is obviously inefficient so I changed to;

var valid = false;
var content = $('.TestModule');
if (content !== null && typeof (content) !== "undefined") {
    var elementTypes = ['btn', 'textbox', 'ui-jqgrid', 'flexboxdiv', 'headerlabel'];
    for (i = 0; i < elementTypes.length; i++) {
        var num = content.first().find('.' + elementTypes[i]).length;
        if (num > 0) {
            valid = true;
            break;
        }
    }
}
return valid;

Which also works and runs the minimum number of tests. But it looks pretty clunky to me. Can you suggest a better loop/structure/test, please? I don't need a count of element types, just to know whether one or more of any type exists.


texts: Using twitter4j to fetch usernames that retweeted me

texts:
I'm using using twitter4j to fetch usernames that retweeted me. I'm interested in any feedback that make the code more elegant, and also that might reduce the number of calls I'm making to the Twitter API.

import java.util.ArrayList;
import twitone.structure.BaseTwitterClass;
import twitone.structure.TwitApplicationFactory;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class getmyretweeters extends BaseTwitterClass {

    public static void main(String[] args) throws TwitterException {

        Twitter twitter = TwitApplicationFactory.getjoereddingtonTwitter();
        String temp[] = getRetweeters(twitter);
        for (String string : temp) {
            System.out.println(string);
        }
    }

    public static String[] getRetweeters(Twitter twitter) {
        ArrayList<String> names = new ArrayList<String>();
        try {
            for (Status status : twitter.getUserTimeline(new Paging(1, 200))) {
                System.out.println(status.getText());
                if (status.getRetweetCount() > 0) {
                    Thread.sleep(12000);// Because I don't want to breach
                                        // Twitter's rate limits
                    for (Status rt : twitter.getRetweets(status.getId())) {
                        names.add(rt.getUser().getScreenName());
                    }
                }
            }
        } catch (TwitterException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return names.toArray(new String[names.size()]);
    }

}


texts: Functional Sieve of Eratosthenes in Clojure

texts:
For some reason, this is the first time I've ever written an implementation of the Sieve of Eratosthenes. I basically just stared at the Wikipedia walkthrough of the algorithm until it made sense, then tried making the algorithm in idiomatic Clojure.
I'm not using an boolean array representing every number. Instead, I have a marked set, and a primes vector that are maintained separately.

My main concern is performance. I was hoping for better performance than I'm getting. It's only about 2x faster than the naïve implementation (included below the Sieve code for reference). I'd mainly like recommendations for speeding this up.

I decided to go overboard with the use of ->> here. It just fit so perfectly everywhere, but I think I may have taken it too far.

Is there a way to avoid the cond dispatch in naïve-prime??

Anything else notable.

(ns irrelevant.sieves.eratosthenes)

; ----- Sieve -----

(defn sieve-primes [n]
  (loop [p 2 ; First prime
         marked #{} ; Found composites
         primes []]
    (let [mults (->> n
                     (range p)
                     (map #(* p %))
                     (take-while #(< % n)))

          next-p (->> p
                      (inc)
                      (iterate inc)
                      (remove marked)
                      (first))

          new-primes (conj primes p)]

      (if (>= next-p n)
        new-primes
        (recur next-p (into marked mults) new-primes)))))

; ----- Naive -----

(defn naive-prime? [n]
  (cond
    (< n 2) false
    (= n 2) true
    :else (->> n
               (Math/sqrt)
               (inc)
               (range 2)
               (some #(zero? (rem n %)))
               (not))))

(defn naive-primes [n]
  (->> n
       (range 2)
       (filterv naive-prime?)))

Runtime Complexity:
I wrote up a testing function to automate timing with the help of Criterium for benchmarking:
(defn test-times [start-n end-n step-factor]
  (->> (iterate #(* step-factor %) start-n)
       (take-while #(< % end-n))
       (mapv (fn [n] [n (->> (c/quick-benchmark*
                               (fn [] (sieve-primes n))
                               nil)
                             (:mean)
                             (first))]))))

This tests how long it takes for various values of n, then packages the results in a vector of [n time-taken] pairs. Here are the results (times in seconds):
(test-times 1 1e7 2)
=>
[[1 2.3196602948749615E-7]
 [2 2.3105128053865377E-7]
 [4 1.42932799280724E-6]
 [8 5.63559279071997E-6]
 [16 1.2984918224299065E-5]
 [32 3.289705735278571E-5]
 [64 7.087895492662475E-5]
 [128 1.4285673446327686E-4]
 [256 2.923177758112095E-4]
 [512 6.273025793650794E-4]
 [1024 0.0012981272479166666]
 [2048 0.0025652252416666667]
 [4096 0.005141740791666667]
 [8192 0.01068772265]
 [16384 0.022486903166666666]
 [32768 0.05367695991666667]
 [65536 0.11212592816666668]
 [131072 0.23180363016666666]
 [262144 0.48056071016666674]
 [524288 1.1464995601666668]
 [1048576 2.8823068596666666]
 [2097152 6.4231157065]
 [4194304 15.808042165333335]
 [8388608 56.98961213533334]]

Plotting it out, it appears to be roughly O(n^3). The time taken seems to roughly double every time n is doubled (O(n)) until n=524288, then it explodes. A custom Wolfram regression calculator gave a best fit with a cubic curve.


texts: Refactor IQueryable and IEnumerable that share the same condition

texts:
I have extension methods to encapsulate query conditions, however I have to separate IQueryable and IEnumerable. Is there any way I can reduce the redundancy and still not lose the performance benefit of IQueryable?

public static class PAYTRACK_PARTNER_Extension
{
    public static IQueryable<PAYTRACK_PARTNER> WhereInPayer(this IQueryable<PAYTRACK_PARTNER> query, int payerId)
    {
        var result = query.Where(q => q.payer_id == payerId);
        return result;
    }

    public static IEnumerable<PAYTRACK_PARTNER> WhereInPayer(this IEnumerable<PAYTRACK_PARTNER> query, int payerId)
    {
        var result = query.Where(q => q.payer_id == payerId);
        return result;
    }

    public static IQueryable<PAYTRACK_PARTNER> WhereInPayee(this IQueryable<PAYTRACK_PARTNER> query, int payeeId)
    {
        var result = query.Where(q => q.payee_id == payeeId);
        return result;
    }

    public static IEnumerable<PAYTRACK_PARTNER> WhereInPayee(this IEnumerable<PAYTRACK_PARTNER> query, int payeeId)
    {
        var result = query.Where(q => q.payee_id == payeeId);
        return result;
    }

    public static IQueryable<PAYTRACK_PARTNER> WhereIsNotApproved(this IQueryable<PAYTRACK_PARTNER> query)
    {
        var result = query.Where(q => q.partner_is_approve.GetValueOrDefault(false).Equals(false));
        return result;
    }

    public static IEnumerable<PAYTRACK_PARTNER> WhereIsNotApproved(this IEnumerable<PAYTRACK_PARTNER> query)
    {
        var result = query.Where(q => q.partner_is_approve.GetValueOrDefault(false).Equals(false));
        return result;
    }

    public static PAYTRACK_PARTNER SingleByPayerAndPayee(this IQueryable<PAYTRACK_PARTNER> query, int payerId, int payeeId)
    {
        var result = query.Single(q => q.payer_id == payerId && q.payee_id == payeeId);
        return result;
    }

    public static PAYTRACK_PARTNER SingleByPayerAndPayee(this IEnumerable<PAYTRACK_PARTNER> query, int payerId, int payeeId)
    {
        var result = query.Single(q => q.payer_id == payerId && q.payee_id == payeeId);
        return result;
    }
}


texts:
As an example, suppose I had a large amount of data about a set of Restaurants for a large set of Dates in a database that I need to analyze / output to the user.

I have a custom class that holds the data for each restaurant for each date:

Public Class DateData
    Public Property Var1 As Double = 0
    Public Property Var2 As Double = 0
    Public Property Var3 As Double = 0
    Public Property Var4 As Double = 0

    Public Sub Sub1()
      ....
    End Sub

   ... etc ....
End Class

And since I am getting this data for each date (and since date-order does matter for my calculations), I have the following class set up too (where most of the work / calculation is done):

Public Class RestaurantData
    Inherits SortedDictionary(Of Date, DateData)

   Public Property Name As String
   Public Property RestaurantLevelData1 As Double = 0
   Public Property RestaurantLevelData2 As Double = 0

   Public Sub New(ByVal strName As String, ByVal DatesList As List(Of Date))
       _Name = strName
       For Each daDate As Date In DatesList
           Me.Add(daDate)
       Next
   End Sub

   Public Overloads Sub Add(ByVal daDate As Date)
        MyBase.Add(daDate, New DateData)
   End Sub

   Public Sub Sub1()
       For i As Integer = 0 To Me.Keys.Count - 1
           Dim daDate As Date = Me.Keys(i)
           Me(daDate).Sub1()
           .... etc ....
       Next
   End Sub

   ... etc ....
End Class

And, finally, since this is for a large amount of restaurants, I have a class which holds this Dictionary on a restaurant levele:

Public Class RestaurantsDict
    Inherits Dictionary(Of String, RestaurantData)

   Public Overloads Sub Add(ByVal strName As String, ByVal Dates As List(Of Date))
       MyBase.Add(strName, New RestaurantData(strName, Dates))
   End Sub
End Class

I have 2 main questions:

Is this a good way to set this up? My original code consisted of dozens of

Dictionary(Of String, SortedDictionary(Of Date, Double))

But I am a fairly novice programmer and would love to know if there is a more efficient architecture for what I am trying to achieve.
The way I am currently setting this up is very hard to debug. For example, the Count property of my RestaurantData throws an exception of type System.TypeLoadException.


texts:
My code displays a Google chart that shows a mana curve. I'm not very experienced with Google charts, so I'd like help optimizing my code. I'd like my code to be more readable and to have fewer lines (if possible.)

https://jsfiddle.net/p8grf68x/

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Column Chart</title>
    <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>


texts: Hangman implementation for teaching a Python course

texts:
I am teaching a Python crash course and thought a Hangman rendition would be fruitful.

I have an end product that I'll work towards with the hour that I have for the course and I was wondering what could be refactored or implemented to help the exchange of information from myself, intermediate level, to absolute beginners.

from random import choice
import os

def clear():
    os.system('clear')

def play_again():
    play_again = input("\nPlay again? Y/n ").lower()

    if play_again != 'n':
        clear()
        game()

    else:
        print("\n\n\n\nCatch ya later!\n\n\n\n")

def get_secret_word():
    words = ['angry', 'beautiful', 'brave', 'careful', 'charismatic', 'clever',
             'creative', 'cute', 'dangerous', 'exciting', 'famous', 'friendly',
             'happy', 'interesting', 'lucky', 'profound', 'popular', 'rich',
             'thin', 'young']

    secret_word = choice(words)
    return secret_word

def get_guess(bad_guesses, good_guesses, secret_word):
    while True:
        guess = input("Guess a letter: ").lower()

        if guess == '':
            print("What was that?")
            board(bad_guesses, good_guesses, secret_word)

        elif len(guess) != 1:
            input("You can only guess a single letter!")
            board(bad_guesses, good_guesses, secret_word)

        elif guess in bad_guesses or guess in good_guesses:
            input("You've already guessed that letter!")
            board(bad_guesses, good_guesses, secret_word)

        elif not guess.isalpha():
            input("You can only guess LETTERS!")
            board(bad_guesses, good_guesses, secret_word)

        else:
            return guess

def board(bad_guesses, good_guesses, secret_word):
    clear()
    print('** Strikes: {}/8 **'.format(len(bad_guesses)))
    print('')

    for guess in bad_guesses:
        print(guess, end=" ")
    print('\n\n')

    for guess in secret_word:
        if guess in good_guesses:
            print(guess, end=" ")
        else:
            print('_ ', end=" ")

    print('')

def game():
    secret_word = get_secret_word()
    good_guesses = []
    bad_guesses = []
    game_done = False

    while not game_done:
        board(bad_guesses, good_guesses, secret_word)
        guess = get_guess(bad_guesses, good_guesses, secret_word)
        if guess in secret_word:
            good_guesses.append(guess)
            found = True
            for guess in secret_word:
                if guess not in good_guesses:
                    found = False
            if found:
                print("\nYou win!\n")
                print("The secret word was {}.".format(secret_word.upper()))
                game_done = True

        elif guess not in secret_word:
            bad_guesses.append(guess)
            if len(bad_guesses) == 8:
                clear()
                print("\n **  ENGHH!  ** ")
                print("\nStrike ! You lost!")
                print("\nThe secret word was {}".format(secret_word.upper()))
                game_done = True

        if game_done:
            play_again()

        else:
            board(bad_guesses, good_guesses, secret_word)

game()


texts:
I'm trying to make a carousel with jQuery and I want to know, how to simplify the code further? so... this is my code:

$(document).ready(function () {
    $(".cont-btn button").click(function (event) {
        var detectId = event.target.id;

        $(".cont-btn button").removeClass("active");
        $(this).addClass("active");

        for (i = 1; i <= 4; i++) {
            if (detectId === ("btn" + i) && i === 1) {
                $(".cont-img div").css("left", "0%");
            } else if (detectId === ("btn" + i)) {
                $(".cont-img div").css("left", "-" + (i - 1) + "00%");
            }
        }
    });
});
body {
    width: 100%;
    margin: 0;
    padding: 0;
}

.carousel {
    width: 100%;
    height: 150px;
    position: relative;
    overflow: hidden;
}

.carousel .cont-img {
    width: 100%;
    height: 100%;
}

.carousel .cont-img div {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    background-color: aqua;
    transition: left .75s ease-in-out;
}

.carousel .cont-img div:nth-of-type(2) {
    background-color: aquamarine;
    margin-left: 100%;
}

.carousel .cont-img div:nth-of-type(3) {
    background-color: blueviolet;
    margin-left: 200%;
}

.carousel .cont-img div:nth-of-type(4) {
    background-color: cornflowerblue;
    margin-left: 300%;
}

.carousel .cont-btn {
    position: absolute;
    bottom: 18px;
    left: 50%;
    transform: translateX(-50%);
    cursor: default;
}

.carousel .cont-btn button {
    width: 18px;
    height: 18px;
    background-color: transparent;
    border: 2px solid #000;
    border-radius: 100%;
    margin: 0 5px;
    padding: 0;
    outline: none;
    transition: background-color .25s ease-in-out;
    cursor: pointer;
}

.carousel .cont-btn .active {
    background-color: #000;
}

        <button type="button" id="btn1" class="active"></button>
        <button type="button" id="btn2"></button>
        <button type="button" id="btn3"></button>
        <button type="button" id="btn4"></button>

Thank you very much in advance to anyone who can help me.


texts: Convert string array to object with true/false flags

texts:
Currently a filter parameter of a GET request is used to designate items' categories that will be requested from database and displayed.

The parameter contains comma delimited string - each string id for each category: filter=complete,inwork,cancelled,ycancelled.

I want to get a Ruby object with corresponding attributes that will be true or false dependent on string id presence in filter parameter. Current implementation is as follows:

filter = params[:filter].split(',') rescue []
fopt = OpenStruct.new(Hash[%w(complete inwork cancelled ycancelled).map {|fo| [fo.to_sym, filter.include?(fo)]}])

Could this be rewritten in shorter way?


texts:
Given this ciphertext from a Caesar cipher:

fxeyaxklqxhkltkxqebobxtbobxplxjykvxfaflqpxfkxqebxtloiaxrkqfixfxpqyoqbaxrpfkdxqebxfkqbokbq

The task is to decrypt it without being given the key.
My solution:
napis = "fxeyaxklqxhkltkxqebobxtbobxplxjykvxfaflqpxfkxqebxtloiaxrkqfixfxpqyoqbaxrpfkdxqebxfkqbokbq".upper()
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
napis = [ALPHABET.index(i) for i in napis]

for x in range(0,4):
    wynik = [ALPHABET[i+x] if i+x<len(ALPHABET) else ALPHABET[i+x-len(ALPHABET)] for i in napis]
    print("".join(wynik))

output:
FXEYAXKLQXHKLTKXQEBOBXTBOBXPLXJYKVXFAFLQPXFKXQEBXTLOIAXRKQFIXFXPQYOQBAXRPFKDXQEBXFKQBOKBQ
GYFZBYLMRYILMULYRFCPCYUCPCYQMYKZLWYGBGMRQYGLYRFCYUMPJBYSLRGJYGYQRZPRCBYSQGLEYRFCYGLRCPLCR
HZG CZMNSZJMNVMZSGDQDZVDQDZRNZL MXZHCHNSRZHMZSGDZVNQKCZTMSHKZHZRS QSDCZTRHMFZSGDZHMSDQMDS
I HAD NOT KNOWN THERE WERE SO MANY IDIOTS IN THE WORLD UNTIL I STARTED USING THE INTERNET


texts:
This code:

Copies a value from "Sheet1"
Pastes special (as a number) in another sheet "Sheet2"
Jumps to the next line

I already:

Disabled screen refresh
Wrapped the code with Application.EnableEvents = False  and Application.Calculation = xlCalculationManual

1 made the calculation a little faster, but 2 didn't seem to make any effect.

Dim iterations, counter As Integer
iterations= 10000
counter = 1

Do While counter <= iterations

' copy value from Sheet1
Sheets("Sheet1").Range("B4").Copy

' paste value in sheet2
Sheets("Sheet2").Select

Selection.PasteSpecial Paste:=xlPasteValues
ActiveCell.Offset(1, 0).Range("A1").Select

counter = counter + 1

Loop

I usually run 50,000+ iterations (counter = 50000).

How can I improve this code speed?


texts: Sum of differences of adjacent elements in an array

texts:
For an array of N integers, at most K will be taken out (without changing the original order of elements). A function f calculates the sum of differences between adjacent elements (when thought about, for a given sequence of numbers, the result value of f will be lastNumber - firstNumber, because all the others in between will get canceled out). The job is to find out the maximum value that f can have of the newly constructed array when an arbitrary choice of m<=K numbers get taken out of the original array (resulting in a new array).

Example:
A = 1 7 2 5 3 8 2 3 6 5 5 , K = 4
Solution is 5. So, for some m (in range of 0 to K) some m numbers get taken out, giving a new array. Function f deals with that array.

Since for f, only the first and the last element matter, my angle was to cover the cases when these "bounds" shifted, for the given m, compare the results and take the greatest value. If I examined the code correctly, the time complexity is \$o(n^2)\$, but when I sent it over for evaluation, the response was "Time Limit Exceeded". Is there a better approach to this problem or did I miss something in my code (I made a few test examples and the outputs were correct, so it's a matter of algorithm, I believe)?

Here is the code:

#include <iostream>
#include <string>

using namespace std;

int main() {

    int N, K;
    int *arr;
    int max;

    cin >> N;

    arr = new int[N];

    if (N < 2 || N > 500000) {
        fprintf(stderr, "Los input\n");
        exit(EXIT_FAILURE);
    }

    cin >> K;

    if (K < 0 || K > N - 2) {
        fprintf(stderr, "Los input\n");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < N; i++) {
        cin >> arr[i];
        if (arr[i] < -1000000 || arr[i] > 1000000) {
            fprintf(stderr, "Los input\n");
            exit(EXIT_FAILURE);
        }
    }

    max = arr[N-1] - arr[0];

    for (int i = 1; i <= K; i++) {

        for (int j = 0; j <= i; j++) {

            if (max < arr[j+N-1-i] - arr[j])
                max = arr[j + N - 1 - i] - arr[j];

            cout << (arr[j + N - 1 - i] - arr[j]) << endl;

        }

    }
    cout << max << endl;
    delete [] arr;

    return 0;

}


texts: Concurrent blocking Tasks in a BackgroundWorker

texts:
I'm using a StaTaskScheduler (TPL extension) to open some web browser windows simultaneously and navigate to different sites (using WaitN, but it might as well just be a WebBrowser).

In my example below I'm running 5 concurrent browsers. Works fine, but it locked the UI thread, so I wrapped my tasks in a BackgroundWorker. Seems like it does the job, but is it the correct way of handling the issue? Do I need to dispose the worker once I'm done? And finally, is lock (ret) the correct way of keeping ret thread safe?

StaTaskScheduler sta = new StaTaskScheduler(5);
BackgroundWorker bw = new BackgroundWorker();

bw.DoWork += (s, ea) =>
{
    List<string> ret = new List<string>();

    lock (ret)

    Task.WaitAll(Util.GetList().Select(row => Task.Factory.StartNew(() =>
    {

        IEnumerable<string> result = DoUiLockingWork(row.Item1, row.Item2);
        ret.AddRange(result);

    }, CancellationToken.None, TaskCreationOptions.None, sta)).ToArray());

    ea.Result = ret;
};

bw.RunWorkerCompleted += (s, ea) =>
{
    List<string> result = ea.Result as List<string>;

    if (result != null)
        Debug.WriteLine(result.Count);
};

bw.RunWorkerAsync();


texts:
I am solving a coding challenge whose objective is to print the right diagonal of a matrix. And below is my code to do that.

package basics;
import java.util.*;
/**
Problem statement : Print right diagonal of a matrix. Example: For input : a b, c d ; the right diagonal is b c
**/
public class PrintRightDiagonal{

    private int rowSize;
    private int colSize;
    private char[][] matrix;
    private Scanner scanner = new Scanner(System.in);
    private String[] rows;
    private String userInput;

    public static void main(String[] args){
        PrintRightDiagonal printRightDiagonal = new PrintRightDiagonal();
        printRightDiagonal.readMatrixDimensions();
        printRightDiagonal.readInputEntries();
        printRightDiagonal.validateInputEntries();
        printRightDiagonal.insertIntoArr();
        printRightDiagonal.findRDiagonal();
    }

    private void readMatrixDimensions(){
        System.out.println("Please enter the rowsize of the 2D array");
        rowSize = scanner.nextInt();
        System.out.println("Please enter the colsize of the 2D array");
        colSize = scanner.nextInt();
        if(rowSize!=colSize){
            System.err.println("Cannot find the diagonal of a matrix because the rowsize and column size are different");
            System.exit(0);
        }
    }

    private void readInputEntries(){
        System.out.println("Please enter the rows separated by comma. Example if the matrix is a 2x2 enter i/p as ab,cd");
        scanner.nextLine();
        userInput = scanner.nextLine();
    }

    private void validateInputEntries(){
        rows = userInput.split(",");
        if(rows.length!=rowSize){
            System.err.println("Entered rows doesn't match with the rowSize");
            System.exit(0);
        }
        for(String row : rows){
            if(row.length()!=colSize){
                System.err.println("Entered cols doesn't match with the colsize");
                System.exit(0);
            }
        }
    }

    private void insertIntoArr(){
        //Initialize matrix
        matrix = new char[rowSize][colSize];
        int index=0;
        for(String row : rows){
            matrix[index++] = row.toCharArray();
        }
        //print matrix once
        System.out.println("Here is your matrix.");
        for(int i=0; i<rowSize; i++){
                for(int j=0; j<colSize; j++){
                    System.out.print(matrix[i][j] +" ");
                }
                System.out.println("");
        }
    }

    private void findRDiagonal(){
        System.out.println("Here is the Right diagonal of the matrix.");
        for(int i=0,j=colSize-1; i<rowSize && j>=0; i++,j--){
                System.out.print(matrix[i][j] + " ");
        }
    }

}

The above works fine. But, I doubt if the code is readable, is it following an OOP way. I think the class name sounds like a method name. Given a code challenge like this how to ensure that we don't miss the basics like class naming, methods organization. In the above code I am not sure if the method organization is correct.
Consider the following pseudo code.

//pseudo code

    class Name{
     main(){
      a();
      b();
      c();
     }
    }

As in the above pseudo code, the method a(), b(), c() should be written above the main() method or below the main()?

And here is my thought to improve this code. Write a class which just has a main method and from it initialize another class and call its methods, so that main class duty is just to initialize the worker class and call its operations. But, do we really need 2 classes in this case?

Throw some light on this.


texts:
This is a simple class for a label with a score that animates counting up or down.  When someone in the game scores points, the numbers count up or down to the new total.

Here is an example of what it looks like:

I ran into a few problems when building this class.  It was important to prevent the building of further animations while a current animation was playing, because otherwise the score would be incremented too many times.  It was also important to to set the correct values at the end of the sequence of animations in order to make sure that it was always accurate when it completed.

BZAnimatedScoreLabel.h

#import <SpriteKit/SpriteKit.h>

@interface BZAnimatedScoreLabel : SKLabelNode

+(BZAnimatedScoreLabel *) labelWithText:(NSString *)text score:(int)score size:(int)fontSize;

-(void) updateForScore:(int)newScore;

@end

BZAnimatedScoreLabel.m

#import "BZAnimatedScoreLabel.h"

@implementation BZAnimatedScoreLabel {
    int _score;
    SKLabelNode *_scoreLabel;
    NSMutableArray *_actionQueue;
    BOOL _isAnimationPlaying;
}

#pragma mark - Initialization
+(BZAnimatedScoreLabel *) labelWithText:(NSString *)text score:(int)score size:(int)fontSize {
    return [[BZAnimatedScoreLabel alloc]initWithText:text score:score size:fontSize];
}
-(instancetype) initWithText:(NSString *)text score:(int)score size:(int)fontSize {
    self = [super initWithFontNamed:@"Arial"];
    if (self) {
        self.text = text;
        self.fontSize = fontSize;
        self.fontColor = [SKColor whiteColor];
        _score = score;

        _scoreLabel = [[SKLabelNode alloc]initWithFontNamed:@"Arial"];
        _scoreLabel.fontSize = fontSize;
        _scoreLabel.fontColor = [SKColor whiteColor];
        _scoreLabel.text = [NSString stringWithFormat:@"%i", _score];
        _scoreLabel.position = CGPointMake((fontSize * 4), 0);
        [self addChild:_scoreLabel];

        _isAnimationPlaying = NO;
        _actionQueue = [[NSMutableArray alloc]init];
    }
    return self;
}

#pragma mark - Animation
-(void) updateForScore:(int)newScore {
    if (!_isAnimationPlaying) {
        if (newScore > _score) {
            [self updateForHigherScore:newScore];
        } else {
            [self updateForLowerScore:newScore];
        }
    }
}
-(void) updateForHigherScore:(int)newScore {
    for (int i = _score; i <= newScore; i+=10) {
        [self addAnimationToQueueForAmount:i];
    }
    [self playQueuedAnimationsFinalScore:newScore];
}
-(void) updateForLowerScore:(int)newScore {
    for (int i = _score; i >= newScore; i-=10) {
        [self addAnimationToQueueForAmount:i];
    }
    [self playQueuedAnimationsFinalScore:newScore];
}
-(void) addAnimationToQueueForAmount:(int)amount {
    [_actionQueue addObject:[SKAction runBlock:^(void){
        _scoreLabel.text = [NSString stringWithFormat:@"%i", amount];
    }]];
}
-(void) playQueuedAnimationsFinalScore:(int)finalScore {
    _isAnimationPlaying = YES;
    [self runAction:[SKAction sequence:_actionQueue] completion:^(void) {
        _score = finalScore;
        _scoreLabel.text = [NSString stringWithFormat:@"%i", _score];
        _isAnimationPlaying = NO;
        [_actionQueue removeAllObjects];
    }];
}

@end

Here is an example usage in the SKScene:

//object creation
_pointsLabel = [BZAnimatedScoreLabel labelWithText:@"Points = " score:0 size:20];
_pointsLabel.position = CGPointMake(_initialScreenSize.width/1.8, _initialScreenSize.height/28);
[self addChild:_pointsLabel];

//usage
[_pointsLabel updateForScore:_game.currentScore];

I thought about expanding the initialization method of the class to include the size of the scene (for proper spacing of the points from the text) and also the position of the label, but the initialization method is already pretty long and adding two further arguments feels like too much, but I am not sure.


texts: Simple websocket loop that outputs on an interval

texts:
This is a simple app, made with koa, that grabs a question from a database of questions and sends them over websocket. It feels really messy to me.

'use strict'

var koa = require('koa')
var route = require('koa-route')
var kws = require('koa-websocket')
var sqlite3 = require('sqlite3')

var app = kws(koa())

var userList = []

function remove (ws) {
  userList.splice(userList.indexOf(ws), 1)
}

app.ws.use(route.all('/ws', function* (next) {
  this.websocket.on('message', msg => this.websocket.send(msg))
  userList.push(this.websocket)
  this.websocket.room = 'lobby' // Set everyone to lobby (for now)
  this.websocket.onclose = () => { remove(this.websocket) }
  yield next
}))

;(function () {
  var curQuestion = 0
  var qArray = []
  var db = new sqlite3.Database('db.sqlite')
  ;(function doLoop () {
    if (qArray.length > 0) {
      var word = qArray.shift()
      userList.forEach(i => i.readyState === 1 ? i.send(i.room + '|' + word) : remove(i))
    } else {
      db.get('SELECT * FROM tossupsdbnew ORDER BY RANDOM() LIMIT 1;', (err, row) => {
        if (err) throw err
        qArray = row.Question.split(' ')
        qArray.unshift(curQuestion.Answer)
        curQuestion = row
      })
    }
    setTimeout(doLoop, qArray.length ? 200 : 1000)
  })()
})()
// Some code that serves some basic html templates...
app.listen(8080, '0.0.0.0')

tossupsdbnew table schema:

CREATE TABLE `tossupsdbnew` (`ID` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `Answer` text NOT NULL, `Category` varchar(255) NOT NULL, `Subcategory` varchar(255) NOT NULL, `Difficulty` text NOT NULL, `Question #` integer NOT NULL, `Question` varchar(21000) NOT NULL, `Round` text NOT NULL, `Tournament` varchar(225) NOT NULL, `Year` integer NOT NULL);


texts:
* Time complexity: O(N)
* Memory complexity: \$O(1)\$

Is my calculation of complexity correct for this code?

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

using namespace std;

using Vector = vector<vector<int>>;

int main()
{
    const size_t SIZE = 7;

    Vector image(SIZE, vector<int>(SIZE));

    cout << "******* original image ******" << endl;
    int value = 0;
    for (auto& i : image)
    {
        for (auto& j : i)
        {
            cout << (j = value) << ' ';
        }

        value++;
        cout << '\n';
    }

    // rotate image 90 degree clockwise O(N)time & O(1)memory ???
    for (size_t i = 0; i < image.size(); ++i)
    {
        for (size_t j = 0; j < (image.size() - i); ++j)
        {
            swap(image[i][j], image[image.size() - j - 1][image.size() - i - 1]);
        }
    }

    cout << "\n******* rotated image ******" << endl;
    for (const auto& i : image)
    {
        for (const auto& j : i)
        {
            cout << j << ' ';
        }

        cout << '\n';
    }
}


texts:
I have written this code to check all the edge cases in the implemention of an atoi() function.Please review.

//Program to print an atoi().

  public class Atoi{
      public static int atoiFunc(String str,char[] c,int l){

    //If the length is 0,the function returns 0;
    if(l==0){
        return 0;
    }

    //variable to store the result
    int res = 0;
    //variable to check for the sign.Initially,initially with positive 1.
    int sign = 1;

    // try/catch block to check the bounds of Integer datatype.
    try{
        int check = Integer.valueOf(str);
    }
    catch(NumberFormatException e){
        System.out.println("Number is going out of bounds of integer
               datatype.");
        System.exit(0);
    }

    for(int i=0; i<l; i++){
        if(c[i]=='-'){
            i++;
            sign = -1;
        }
        if(c[i]=='+'){
            i++;
        }
        if(c[i]!=' '){
            res = res*10 + c[i] -'0';
        }
    }
    return sign*res;
}

public static void main(String[] args) {

    String s = "-9846032";

    char[] ch = s.toCharArray();

    int len = s.length();

    int val = atoiFunc(s,ch,len);

    System.out.println("Original   : "+s);

    System.out.println("After atoi : "+val);

    }
}


texts: Creating a join table entry by looking up name

texts:
I wrote a stored procedure that allows a join entity to be created by name for my fictional characters database. I would like some feedback on it with regard to exception handling, and conditions I didn't think of. Also I would like to know if this procedure is good as far as performance goes.

The tables it involves are characters, medias, actors, character_media_actor. The schemas are as follows.

CREATE TABLE medias (
  med_unv_id       INTEGER NOT NULL REFERENCES universes (unv_id),
  med_title        VARCHAR(255) NOT NULL,
  med_release_date DATE,
  med_type         INTEGER REFERENCES media_types (mt_id),
  med_id           SERIAL PRIMARY KEY,
  med_attribs      JSON
);

CREATE OR REPLACE VIEW v_medias AS
SELECT
  med_unv_id,
  med_title,
  med_release_date,
  mt_name as type,
  med_id,
  med_attribs,
  mt_uses_actors
FROM medias m
  JOIN media_types mt ON mt.mt_id = m.med_type;

CREATE TABLE actors (
  act_id    SERIAL PRIMARY KEY,
  act_name  VARCHAR(255) NOT NULL,
  act_birth DATE,
  act_death DATE,
  act_imdb  VARCHAR(4096) UNIQUE,
  act_bio   TEXT,
  is_locked  BOOLEAN DEFAULT FALSE,
  CHECK (act_birth < act_death)
);
DROP TABLE IF EXISTS characters CASCADE;
CREATE TABLE characters (
  chr_unv_id INTEGER NOT NULL REFERENCES universes (unv_id),
  chr_name   VARCHAR(255) NOT NULL,
  chr_id     SERIAL PRIMARY KEY,
  chr_bio    TEXT,
  UNIQUE(chr_name,chr_unv_id)
);
CREATE TABLE character_media_actors (
  cma_act_id INTEGER REFERENCES actors (act_id),
  cma_chr_id INTEGER NOT NULL REFERENCES characters (chr_id),
  cma_med_id INTEGER NOT NULL REFERENCES medias (med_id),
  cma_id     SERIAL PRIMARY KEY,
  UNIQUE(cma_act_id,cma_chr_id,cma_med_id)
);

The stored procedure is as follows:

CREATE OR REPLACE FUNCTION add_cma_by_names(
  IN p_med_title VARCHAR(255),
  IN p_act_name  VARCHAR(255),
  IN p_chr_name  VARCHAR(255)
)
  RETURNS VOID AS $$
DECLARE
  lk_act_id INTEGER := (SELECT act_id
                        FROM actors
                        WHERE LOWER(act_name) = LOWER(p_act_name));
  lk_chr_id INTEGER := NULL;
  lk_med_id INTEGER := NULL;
  md_unv_id INTEGER := NULL;
  cr_unv_id INTEGER := NULL;
  mt_actors BOOLEAN;
BEGIN
  -- perform validation first
  IF p_med_title IS NULL OR LENGTH(p_med_title) = 0
  THEN
    RAISE EXCEPTION 'A media title must be given';
  END IF;
  IF p_chr_name IS NULL OR LENGTH(p_chr_name) = 0
  THEN
    RAISE EXCEPTION 'A character name must be given';
  END IF;

  -- load the media and universe ids in one go
  SELECT
    med_unv_id,
    med_id,
    mt_uses_actors
  INTO md_unv_id, lk_med_id, mt_actors
  FROM v_medias
  WHERE LOWER(p_med_title) = LOWER(med_title);
  -- we require the universe id before we can get the character id
  SELECT
    chr_id,
    chr_unv_id
  INTO lk_chr_id, cr_unv_id
  FROM characters
  WHERE LOWER(p_chr_name) = LOWER(chr_name);

  IF mt_actors IS TRUE AND lk_act_id IS NULL
  THEN
    RAISE EXCEPTION
    'Selected media has actors must not be null: actor = %', p_act_name;
  END IF;

  IF lk_med_id IS NULL
  THEN
    RAISE EXCEPTION 'Media Not Found, name = %', p_med_title;
  END IF;

  IF lk_chr_id IS NULL
  THEN
    RAISE EXCEPTION 'Character Not Found, name = %', p_chr_name;
  END IF;

  IF md_unv_id <> cr_unv_id
  THEN
    RAISE EXCEPTION 'Character and Media must be in same universe';
  END IF;

  INSERT INTO character_media_actors (cma_act_id, cma_chr_id, cma_med_id) VALUES
    (lk_act_id, lk_chr_id, lk_med_id);

  RETURN;
END $$
LANGUAGE PLPGSQL;


texts:
The following Golang code accepts a sequence of numbers (any integer and float type) in the terminal, adds them, and prints the result (sum) to the terminal.

Actually in Golang you can't add different integer types together, because of which this script accepts all the digits as a string representation of space-separated digits, then splits it on the spaces into int64 digits. It then sums all of the digits and writes the result to the terminal.

Is there any way to improve this code?

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    a := ReadInput()
    fmt.Println("Here is the result:", AddAll(a))
}

func ReadInput() []float64 {
    reader := bufio.NewReader(os.Stdin)
    fmt.Println("Enter digits to be added (space separated): ")
    text, err := reader.ReadString('\n')
    if err != nil {
        fmt.Println(err)
    }

    textSlice := strings.Fields(text)
    floatsSlice := make([]float64, 0)
    for _, elem := range textSlice {
        i, err := strconv.ParseFloat(elem, 64)
        if err != nil {
            fmt.Println(err)
        }
        floatsSlice = append(floatsSlice, i)
    }

    return floatsSlice
}

func AddAll(floatsSlice []float64) float64 {
    var sum float64
    for _, v := range floatsSlice {
        sum += v
    }
    return sum
}

For example if we enter the following,

1 2.3345 2.5 3.3 8.9 0.5 23

The output will be 41.5345


texts: FileSystemWatcher firing multiple events

texts:
Like others (FileSystemWatcher Changed event is raised twice) I am facing the problem that events of filesystemwatcher are raised twice. I require to catch all non-duplicate events of watcher in real time. I came up with this. So, I want to know if it will be efficient/over-kill/buggy to use this class.

class ModifiedFileSystemWatcher:FileSystemWatcher
{
    public new event RenamedEventHandler Renamed;
    public new event FileSystemEventHandler Deleted;
    public new event FileSystemEventHandler Created;
    public new event FileSystemEventHandler Changed;

    class BooleanWrapper{
        public bool value { get; set; }
    }

    //stores refrences of previously fired events with same file source
    Dictionary<string, BooleanWrapper> raiseEvent = new Dictionary<string, BooleanWrapper>();

    public int WaitingTime { get; set; } //waiting time, any new event raised with same file source will discard previous one

    public ModifiedFileSystemWatcher(string filename="", string filter="*.*"):base(filename,filter)
    {
        base.Changed += ModifiedFileSystemWatcher_Changed;
        base.Created += ModifiedFileSystemWatcher_Created;
        base.Deleted += ModifiedFileSystemWatcher_Deleted;
        base.Renamed += ModifiedFileSystemWatcher_Renamed;
        WaitingTime = 100;
    }

    void PreventDuplicate(FileSystemEventHandler _event, FileSystemEventArgs e)
    {
        if (_event != null)
        {
            //create a reference
            BooleanWrapper w = new BooleanWrapper() { value = true }; //this event will be fired

            BooleanWrapper t; //tmp
            if (raiseEvent.TryGetValue(e.FullPath, out t))
            {
                //a previous event occurred which is waiting [delayed by WaitingTime]
                t.value = false; //set its reference to false; that event will be skipped
                t = w;//store current reference in dictionary
            }
            else raiseEvent[e.FullPath] = w; //no previous event, store our reference

            //Wait on a separate thread...
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                System.Threading.Thread.Sleep(WaitingTime);
                if (w.value) //if we are still allowed to raise event
                {
                    _event(this, e);
                    raiseEvent.Remove(e.FullPath);//remove instance from dictionary
                }
            }, null);

        }
    }

    //Same as above with different event
    void ModifiedFileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
    {
        if (Renamed != null)
        {
            BooleanWrapper w = new BooleanWrapper() { value = true };
            BooleanWrapper t;
            if (raiseEvent.TryGetValue(e.FullPath, out t))
            {
                t.value = false;
                t = w;
            }
            else raiseEvent[e.FullPath] = w;
            System.Threading.Thread.Sleep(WaitingTime);
            if (w.value)
            {
                Renamed(this, e);
                raiseEvent.Remove(e.FullPath);
            }
        }

    }

    void ModifiedFileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
    {
        PreventDuplicate(Deleted, e);
    }

    void ModifiedFileSystemWatcher_Created(object sender, FileSystemEventArgs e)
    {
        PreventDuplicate(Created, e);
    }

    void ModifiedFileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
    {
        PreventDuplicate(Changed, e);
    }

}


texts: Getting validation from inherited classes

texts:
I'm building some code with an inheritance heirarchy, and I want to validate the resulting instances. At present I have a method in the base class can override to return a list of the problems (see the code).

My problem here is that this works, provided the inheriting classes remember to get the base results first, before returning their own. It works, but I'm not sure it's the best design?

using System;
using System.Linq;
using System.Collections.Generic;

namespace Query
{
    /// <summary>
    /// Root class with mehtod
    /// </summary>
    public abstract class baseClass
    {

        /// <summary>
        /// Is the object valid?
        /// </summary>
        /// <returns></returns>
        public bool IsValid()
        {
            return (!GetValidationIssues().Any());
        }

        /// <summary>
        /// Return list of validation issues
        /// </summary>
        /// <returns></returns>
        public virtual List<string> GetValidationIssues()
        {
            var result = new List<string>();
            if (Quantity < 0) result.Add("Quantity is invalid");
            return result;
        }

        public int Quantity { get; set; }
    }

    /// <summary>
    /// First child class, adds a new property and more validation
    /// </summary>
    public abstract class productBase : baseClass
    {
        public override List<string> GetValidationIssues()
        {
            // we must get any base results first!!
            var result = base.GetValidationIssues();
            // do checks for this class
            if (string.IsNullOrWhiteSpace(Name)) result.Add("Name not specified");
            return result;
        }

        public string Name { get; set; }
    }

    /// <summary>
    /// Final instance
    /// </summary>
    public class Product : productBase
    {
        public override List<string> GetValidationIssues()
        {
            // remember to get the base results first
            var result = base.GetValidationIssues();
            // do checks for this class
            if (Price <= 0) result.Add("Price is not valid");
            return result;
        }

        public decimal Price { get; set; }
    }

}


texts: Looping through the ResultSet efficiently and the add the values for columns in List

texts:
I am working on a multithreaded project in which each thread will randomly find columns for that table and I will be using those columns in my SELECT sql query and then I will be executing that SELECT sql query. AFter exectuing that query, I will be looping through the result set and will add the data for each columns into List<String>.

Here columnsList will contains columns delimited by comma. For example-

col1, col2, col3

Below is my code.

class ReadTask implements Runnable {

public ReadTask() {

}

@Override
public run() {
  ...

  while ( < 60 minutes) {

    .....

    final int id = generateRandomId(random);
    final String columnsList = getColumns(table.getColumns());
    final String selectSql = "SELECT " + columnsList + "  from " + table.getTableName() + " where id = ?";
    resultSet = preparedStatement.executeQuery();

    List<String> colData = new ArrayList<String>(columnsList.split(",").length);
    boolean foundData = false;

    if (id >= startValidRange && id <= endValidRange) {

        if (resultSet.next()) {
            foundData = true;
            for (String column : columnsList.split(",")) {
                colData.add(resultSet.getString(column.trim()));
            }
            resultSet.next();//do I need this here?
        }
    } else if (resultSet.next()) {
        addException("Data Present for Non Valid ID's", Read.flagTerminate);
    }

    ....
      }
   }

    private static void addException(String cause, boolean flagTerminate) {
        AtomicInteger count = exceptionMap.get(cause);
        if (count == null) {
            count = new AtomicInteger();
            AtomicInteger curCount = exceptionMap.putIfAbsent(cause, count);
            if (curCount != null) {
                count = curCount;
            }
        }
        count.incrementAndGet();

        if(flagTerminate) {
            System.exit(1);
        }
    }
}

Problem Statement:-

After executing the SELECT sql query. Below are my two scenarios-

I need to see whether the id is between the valid range. If it is between the Valid Range then check whether resultSet has any data or not. If it has data then loop around the resultSet using the columns from the columnsList and start adding it in coldData list of String.
else if id is not in the valid range then I need to check I am not getting any data back from the resultSet. But somehow if I am getting the data back and flag is true to stop the program, then exit the program. Else if I am getting the data back but flag is false to stop the program, then count how many of those happening. So for this, I have created addException method.

Can anyone help me out whether the way I am doing here for my above two scenarios is right or not? It looks like, I can improve the if/else loop code more I guess for my above two scenario.


texts:
I am implementing a game in python, which will give the user a sample encryption, and explain each step from plaintext to cipher. The task for the player is to decrypt a word by undoing each step shown above on the new word.

For this, I have created an abstract algorithm which requires an encrypt function, and a current development status. In the future I think it will require other properties such as explanation text or a difficulty level.

The abstract algorithm looks like this:

from abc import ABC, abstractmethod
from enum import Enum

class Status(Enum):
    """The current development status"""
    in_development = 0
    under_testing = 1
    production_ready = 2
    known_bugs = 3

class BaseAlgorithm(ABC):
    """This is the base on which all other algs are to be built"""
    @abstractmethod
    def encrypt(self, word):
        """Encrypt the word using an internal alg"""
        pass

    @abstractmethod
    def decrypt(self, word):
        """Decrypt the word using an internal alg
        If this is not overloaded, it is assumed that"""
        return self.encrypt(word)

    @property
    @abstractmethod
    def status(self):
        """The current progress and readiness of the alg"""
        pass

An example algorithm is implemented in rotate.py

from . import BaseAlgorithm, Status

class RotateAlg(BaseAlgorithm):
    """Takes a rotation amount  which it uses to encrypt or decrypt
    all words pass into it"""
    def __init__(self, offset):
        try:
            self.offset = int(offset)
        except ValueError:
            raise ValueError("the offset must be an integer") from None

        # Decides which direction is the default way to rotate
        self.rotate_left = True

    def encrypt(self, word):
        """Encrypts by rotating the word"""
        return self.rotate(word)

    def decrypt(self, word):
        """Decrypts by rotating the word back"""
        return self.rotate(word, inverse=True)

    def rotate(self, word, inverse=False):
        """Rotates the word to the left"""
        offset = self.offset
        # Inverse and rotate_left both flip the direction
        # If both are the same the direction remains unchanged
        if inverse == self.rotate_left:
            offset *= -1
        return rotate(word, offset)

    @property
    def status(self):
        return Status.in_development

def rotate(word, offset):
    """Rotates the word right by the amount specified"""
    offset %= len(word)
    return word[offset:] + word[:offset]

Finally how these algorithms would be composed together is a simple accumulating loop

def decode(cipher, encryptions):
    for encryption in reversed(encryptions):
        cipher = encryption.decrypt(cipher)
    return cipher

I feel like this is the wrong approach to take though, as there is a lot of boilerplate for what is essentially a function which is used in two ways. Is there a better design pattern to use in this scenario? I suspect a more functional approach would suit, such as passing the encryption functions into a class that binds them together. My concern is I lose the option of providing metadata with the function with that style.


texts: Leetcode: Detecting duplicate elements in an array within a k-element window

texts:
Upon solving the problem 'contain duplicates` in leetcode:

  Given an array of integers and an integer k , find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k .

  Example 1:

Input: nums = [1,2,3,1] , k = 3

Output: true

  Example 2:

Input: nums = [1,0,1,1] , k = 1

Output: true

  Example 3:

Input: nums = [1,2,3,1,2,3] , k = 2

Output: false

I tried best  to write a Pythonic style solution and improve the performance.

class Solution2:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        lookup = dict()  #{value:index}

        for cur, val in enumerate(nums):
            prev = lookup.get(val)

            if prev != None and cur - prev <= k:
                #logging.debug(f"{cur - prev}")
                return True
            lookup[val] = cur #add it to lookup

        return False

  Runtime: 68 ms, faster than 12.21% of Python3 online submissions for Contains Duplicate II.
  Memory Usage: 20.4 MB, less than 13.64% of Python3 online submissions for Contains Duplicate II.

I am confused about the score. I was 100% assure that it was the best possible solution.

What's the problem with my solution?


texts:
The idea is to obtain the keys as a list ordered by the natural ordering of the keys but first of them all the ones that have priority, stated by the method hasPriority(). The custom comparator code block feels out of place and I wonder if it is possible to improve the code:

private List<String> orderedKeys() {
    return this.variables.entrySet()
            .stream()
            .sorted((e1, e2) -> {
                if (e1.getValue().hasPriority() && e2.getValue().hasPriority()) return e1.getKey().compareTo(e2.getKey());
                if (e1.getValue().hasPriority()) return -1;
                if (e2.getValue().hasPriority()) return 1;
                return e1.getKey().compareTo(e2.getKey());
            })
            .map(e -> e.getKey())
            .collect(Collectors.toList());
}

Edit: this.variables is a reference to a Map of String Keys and custom objects as values that have the boolean method hasPriority().


texts: The console prints a list of items for the user to scroll through using the up and down arrow keys

texts:
I am somewhat new to python (yes I know, a cliché statement) and I wrote this code to scroll through a tuple of strings using the arrow keys. I know that the code is sloppy but I don't know how. Any feedback would be greatly appreciated.
import keyboard
from os import system
from time import sleep

class Menu:
    def __init__(self, *items):
        self.items = items
        self.selections = 6
        self.start = 0
        self.stop = self.start + self.selections
        self.slice = items[self.start:self.stop]
        self.selected = 0
        self.beg = '>'
        self.end = '<'

    def get_input(self):
        if keyboard.is_pressed('up'):
            if self.selected >= 0:
                self.selected += -1
            self.show()
        elif keyboard.is_pressed('down'):
            if self.selected < self.selections:
                self.selected += +1
            self.show()

    def show(self):
        system('cls')

        # shift slice up if the bottom of list is reached
        if self.selected == self.selections:
            if self.stop < len(self.items):
                self.start += 1
                self.stop += 1
                self.slice = self.items[self.start:self.stop]
            self.selected = self.selections-1

        # shift slice down if top of list is reached
        elif self.selected < 0:
            if self.start > 0:
                self.start += -1
                self.stop += -1
                self.slice = self.items[self.start:self.stop]
            self.selected = 0

        # print the slice with the selected item printed like >this<
        for i in range(len(self.slice)):
            if i == self.selected:
                print(self.beg + self.slice[i] + self.end)
            else:
                print(self.slice[i])

test_menu = Menu('item 0',
                 'item 1',
                 'item 2',
                 'item 3',
                 'item 4',
                 'item 5',
                 'last item')
test_menu.show()

while 1:
    test_menu.get_input()
    sleep(0.1)


texts: Simple medical collection/database about patients visits

texts:
I am writing a system for doctors who are regularly visited by patients. The doctor adds each patient's visit to collection/database. The class can save data to an .xml file and restore it. Can you give your feedback about this code?

// https://github.com/veitsi/jcrf-noweb
import java.util.ArrayList;
import java.util.Date;
import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Jcrf {
    @XmlElement
    Jcrf jcrf;
    @XmlElement
    ArrayList<Visit> vst = new ArrayList<Visit>();

    public Jcrf() {
        super();
    }

    public static void main(String[] args) {
        Jcrf jcrf = new Jcrf();
         jcrf.addTestData();

        System.out.println(jcrf.vst);

        jcrf.toXml();
        jcrf.fromXml();

        System.out.println(jcrf.vst);
    }

    public void toXml() {
        try {
            File file = new File("jcrf.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Jcrf.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(this, file);
            jaxbMarshaller.marshal(this, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public void fromXml() {
        try {
            File file = new File("jcrf.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Jcrf.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            jcrf = (Jcrf) jaxbUnmarshaller.unmarshal(file);
            vst = jcrf.vst;
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public void addTestData() {
        vst.add(new Visit(1, 1, 366));
        vst.add(new Visit(1, 2, 365));
        vst.add(new Visit(2, 1, 364));
    }
}

class Visit {
    @XmlElement
    int ptn;
    @XmlElement
    int nmr;
    @XmlElement
    static final Date dt = new Date();
    @XmlElement
    int ttr;

    public Visit() {
    }

    public Visit(int ptn, int nmr, int ttr) {
        super();
        if (ttr < 300 || ttr > 420)
            throw new IllegalArgumentException("bad temperature");
        this.ptn = ptn;
        this.nmr = nmr;
        this.ttr = ttr;
    }

    @Override
    public String toString() {
        return "Visit [ptn=" + ptn + ", nmr=" + nmr + ", ttr=" + ttr + ", dt="
                + dt + "]";
    }

}


texts: Pidfile single process instance mechanism

texts:
I'm writing a system daemon in Rust that may be started by the user manually. Only one instance of the daemon should be running at a time
so I have created a pidfile locking mechanism to prevent multiple instances. This is my first time doing any kind of unix style file locking
and I would appreciate another pair of eyes to check for anything I may have missed.
Style pointers would also be great as I am new to Rust.

use nix::fcntl::{flock, FlockArg};
use nix::sys::signal::kill;
use nix::unistd::Pid;
use std::fs::File;
use std::fs::OpenOptions;
use std::io;
use std::io::{Error, ErrorKind, Read, Seek, SeekFrom, Write};
use std::os::unix::io::AsRawFd;
use std::path;
use std::process;

fn write_pid(mut file: &File) -> Result<(), io::Error> {
    let id = process::id().to_string() + "\n";
    file.write_all(id.as_bytes())?;
    Ok(())
}

fn lock_pidfile(file: &File, pidfile: &path::Path) -> Result<(), io::Error> {
    flock(file.as_raw_fd(), FlockArg::LockExclusiveNonblock).map_err(|_| {
        Error::new(
            ErrorKind::Other,
            format!("Failed to lock pidfile: {}", pidfile.display()),
        )
    })
}

pub fn exclusive(pidfile: &path::Path) -> Result<bool, io::Error> {
    let pf = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(pidfile);

    match pf {
        Ok(file) => {
            lock_pidfile(&file, pidfile)?;
            write_pid(&file)?;
            Ok(true)
        }
        Err(err) => {
            match err.kind() {
                ErrorKind::AlreadyExists => {
                    let mut file = OpenOptions::new().read(true).write(true).open(pidfile)?;
                    lock_pidfile(&file, pidfile)?;
                    let mut id_str = String::new();
                    file.read_to_string(&mut id_str)?;
                    let id: u32 = id_str.trim().parse().map_err(|_| {
                        Error::new(
                            ErrorKind::Other,
                            format!("Failed to parse pidfile: {}", pidfile.display()),
                        )
                    })?;
                    // Kill None just checks if process exists.
                    // Same as kill(pid, 0); in C
                    if kill(Pid::from_raw(id as i32), None).is_ok() {
                        Ok(false)
                    } else {
                        file.seek(SeekFrom::Start(0))?;
                        write_pid(&file)?;
                        Ok(true)
                    }
                }
                _ => Err(err),
            }
        }
    }
}
```


texts:
Running the same test 10,000 times with cProfile tells me that most of the damage happens in the count() function. This is my attempt at a solution to the Quadrant Queries challenge from InterviewStreet (the problem statement can be found here).

According to InterviewStreet, I passed 3/11 testcases and I ran out of CPU time. I have no way of knowing whether I was 3 for 3 and ran out of time or say, 3 for 6 and ran out of time. I don't know if my code works on all input.

Please help me optimize this code:

def reflect_x(i, j, coordinates):
    for pair in xrange(i-1, j):
        coordinates[pair][1] = -coordinates[pair][1]
    return coordinates

def reflect_y(i, j, coordinates):
    for pair in xrange(i-1, j):
        coordinates[pair][0] = -coordinates[pair][0]
    return coordinates

def count(i, j, coordinates):
    quad_one, quad_two, quad_three, quad_four = 0, 0, 0, 0
    for pair in xrange(i-1, j):
        x, y = coordinates[pair][0], coordinates[pair][1]

        if x >= 0 and y >= 0:
            quad_one += 1
        elif x < 0 and y >= 0:
            quad_two += 1
        elif x < 0 and y < 0:
            quad_three += 1
        elif x >= 0 and y < 0:
            quad_four += 1

    print "%d %d %d %d" % (quad_one, quad_two, quad_three, quad_four)

def reflect(coordinates, queries):

    for query in queries:
        if query[0] == "X":
            reflect_x(query[1], query[2], coordinates)
        elif query[0] == "Y":
            reflect_y(query[1], query[2], coordinates)
        elif query[0] == "C":
            count(query[1], query[2], coordinates)
        else:
            print query

if __name__ == "__main__":
    N = int(raw_input())
    coordinates = [[int(pair[0]), int(pair[1])] for pair in (pair.split() for pair in (raw_input() for i in xrange(N)))]

    Q = int(raw_input())
    queries = [[query[0], int(query[1]), int(query[2])] for query in (query.split() for query in (raw_input() for i in xrange(Q)))]

    reflect(coordinates, queries)


texts: What is the best way to make this code dry?

texts:
I have a script that makes a bunch of api calls (xml) and it's not adhering to DRY because I am repeating a lot of the code in the functions, what would be the best way to clean this up and reduce the amount of repeat code?
def get_api_key(hostname, username, password):
    url = 'https://' + hostname + '/api'
    values = {'type': 'keygen', 'user': username, 'password': password}
    response = requests.post(url, params=values, verify=False, proxies=proxies)
    return ET.fromstring(response.text).find('.//result/key').text

def add_template(hostname, api_key, template_name, name):
    url = 'https://' + hostname + '/api'
    values = {'type': 'config',
        'action': 'set',
        'xpath': f"entry[@name='{template_name}']/",
        'element': f"<tag>{name}</tag>",
        'key': api_key
        }
    requests.post(url, params=values, verify=False, proxies=proxies)
    return(template_name)

def add_template_stack(hostname, api_key, stack_name, template_name):
    url = 'https://' + hostname + '/api'
    values = {'type': 'config',
        'action': 'set',
        'xpath': f"entry[@name='{stack_name}']",
        'element': f"<tag>{template_name}</tag>",
        'key': api_key
        }
    requests.post(url, params=values, verify=False, proxies=proxies)
    return(stack_name)

def add_variable(template_name, var_name, netmask, hostname, api_key):
    url = 'https://' + hostname + '/api'
    values = {'type': 'config',
        'action': 'set',
        'xpath': f"entry[@name='{template_name}']/variable/entry[@name='{var_name}']",
        'element': f"<tag>{netmask}</tag>",
        'key': api_key
        }
    requests.post(url, params=values, verify=False, proxies=proxies)
    return(var_name)


texts: Accessing argparse arguments from the class

texts:
I have the following sample code running unit tests:

#!/usr/bin/env python3

import sys
import unittest
import argparse

class ParentTest(unittest.TestCase):
    None

class Test1(ParentTest):
    def test_if_verbose(self):
        import __main__ # FIXME
        print("Success!") if __main__.args.verbose else "" # FIXME

class Test2(ParentTest):
    None

if __name__ == '__main__':
    # Parse arguments.
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-?", "--help",     action="help",                        help="show this help message and exit" )
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose",  help="increase output verbosity" )
    parser.add_argument('files', nargs='*')
    args = parser.parse_args()

    print(args.verbose)

    # Add tests.
    alltests = unittest.TestSuite()
    alltests.addTest(unittest.makeSuite(Test1))
    alltests.addTest(unittest.makeSuite(Test2))

    result = unittest.TextTestRunner(verbosity=2).run(alltests) # Run tests.
    sys.exit(not result.wasSuccessful())

and I'd like to access command-line argument values from the class.

In here it's suggested that using __main__ isn't really a good approach.

Is there any better way of doing it, where individual tests could have access to argument values which were parsed already in main?

Testing:

python3 test.py
python3 test.py -v


texts: Distribute items based on the time duration

texts:
I just finished a small assignment and I would like to get some feedback about the implementation here. Basically, it was all about distributing items ("talks" in this case) throughout the day based on the time constraints (their duration). For instance, a given place have different "tracks" each of which has a morning (9AM - 12PM) and afternoon (1PM - 5PM) session.

The input data is a file with this structure: Talk Name XYmin (where XY are positive numbers).

This is what I came up with (I know it's a little bit silly but I guess it works for the most part):
public final class Conference {
  private static final long MORNING_SPAN = 180; // 09:00 AM - 12:00PM

  private static final long AFTERNOON_SPAN = 240; // 01:00 PM - 05:00 PM

  private final List<Talk> talks;

  private final List<Track> tracks;

  private final long numberOfTracks;

  public Conference(final List<Talk> talks) {
    final var duration = talks.stream().mapToLong(Talk::duration).sum();
    final var daySpan = MORNING_SPAN + AFTERNOON_SPAN;
    this.talks = talks;
    numberOfTracks = duration / daySpan + (duration % daySpan == 0L ? 0L : 1L);
    tracks = new LinkedList<>();
  }

  public List<Track> getTracks() { return tracks; }

  public void displaySchedule() {
    if (tracks.isEmpty()) {
      makeSchedule();
    }
    // More System.out.println statements for the required output
  }

  private void makeSchedule() { // ...this one is the deal!
    for (int i = 0; i < numberOfTracks; i++) {
      final var morning = new LinkedList<Talk>();
      final var afternoon = new LinkedList<Talk>();
      var morningSpan = MORNING_SPAN;
      var afternoonSpan = AFTERNOON_SPAN;
      final var iterator = talks.iterator();
      while (iterator.hasNext()) {
        final var talk = iterator.next();
        if (talk.duration() <= morningSpan) {
          morning.add(talk);
          morningSpan -= talk.duration();
          iterator.remove();
        } else if (talk.duration() <= afternoonSpan) {
          afternoon.add(talk);
          afternoonSpan -= talk.duration();
          iterator.remove();
        }
      }
      tracks.add(new Track(morning, afternoon));
    }
  }
}

public final class Talk {
  public final String title;

  public final String duration;

  public Talk(final String title, final String duration) {
    this.title = title;
    this.duration = duration;
  }

  public long duration() {
    if ("lightning".equalsIgnoreCase(duration)) {
      return Constant.LIGHTNING;
    }
    // Basically this returns the duration for the talk (as long)...that's it
    return Long.parseLong(Constant.NON_NUMBERS.matcher(duration).replaceAll(""));
  }
}

public final class Track {
  private final List<Talk> morning;

  private final List<Talk> afternoon;

  public Track(final List<Talk> morning, final List<Talk> afternoon) {
    this.morning = morning;
    this.afternoon = afternoon;
  }

  // Some more stuff here to display the required output
}

The real deal here is Conference::makeSchedule — that's where I would like to know if there is a better, more efficient way to approach this solution...probably using different data structures, etc. Thanks in advance!


texts:
This is a Leetcode problem -

  You have 4 cards each containing a number from 1 to 9. You need to
  judge whether they could be operated through *, /, +, -, (,)
  to get the value of 24.

  Note -

  1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.

  2. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1]
  as input, the expression -1 - 1 - 1 - 1 is not allowed.

  3. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

Here is my solution to this challenge -

class Solution(object):
    def judge_point_24(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) == 1:
            return nums[0] == 24 or abs(nums[0] - 24.0) <= 0.1
        for i in range(len(nums)):
            for j in range(len(nums)):
                if i == j:
                    continue
                indexes = set([x for x in range(len(nums))])
                indexes.remove(i)
                indexes.remove(j)
                operations = []
                operations.append(float(nums[i]) + float(nums[j]))
                operations.append(float(nums[i]) - float(nums[j]))
                operations.append(float(nums[j]) - float(nums[i]))
                operations.append(float(nums[i]) * float(nums[j]))
                if nums[j] != 0:
                    operations.append(float(nums[i] / float(nums[j])))
                if nums[i] != 0:
                    operations.append(float(nums[j] / float(nums[i])))
                next_items = [nums[index] for index in indexes]
                for x in operations:
                    if self.judge_point_24(next_items + [x]) == True:
                        return True
        return False

Explanation - My solution is to reduce the nums size until it becomes the size of one. Once it is the size of one, check if we have reached 24 or close enough. Basically, I tried to pick two elements from the array and apply all the possible computations and recursively call itself now with the array that has the result of the computation and the rest. As soon as I see True from the call, I return True as well.

Here are some example outputs -

#output = Solution()

#print(output.judge_point_24([4, 1, 8, 7]))

>>> True

#Explanation - (8-4) * (7-1) = 24

#output = Solution()

#print(output.judge_point_24([1, 2, 1, 2]))

>>> False

Here are the times taken for these outputs -

%timeit output.judge_point_24([4, 1, 8, 7])
2.16 ms ± 46 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit output.judge_point_24([1, 2, 1, 2])
43 ms ± 902 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Here is my Leetcode result -

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts:
I have the following models:

User
Picture
Variant

User has_many pictures, picture has_many variants.

Variant has value price and I am trying to find the price of all pictures of selected (e.g. for user id 15) current user.

First I tried like this:

def value(user)

  total = 0

  user.pictures.each do |picture|

    picture.variants.each do |variant|
      total += variant.price
    end

  end

  total.to_f

end

How could I improve this code so that I can avoid the N+1 problem?


texts: GenBank to FASTA format using regular expressions without Biopython

texts:
This is a Biopython alternative with pretty straightforward code. How can I make this more concise?
def genbank_to_fasta():
    file = input(r'Input the path to your file: ')
    with open(f'{file}') as f:
        gb = f.readlines()
        locus = re.search('NC_\d+\.\d+', gb[3]).group()
        region = re.search('(\d+)?\.+(\d+)', gb[2])
        definition = re.search('\w.+', gb[1][10:]).group()
        definition = definition.replace(definition[-1], "")
        tag = locus + ":" + region.group(1) + "-" + region.group(2) + " " + definition
        sequence = ""
        for line in (gb):
            pattern = re.compile('[a,t,g,c]{10}')
            matches = pattern.finditer(line)
            for match in matches:
                sequence += match.group().upper()
        end_pattern = re.search('[a,t,g,c]{1,9}', gb[-3])
        sequence += end_pattern.group().upper()
        print(len(sequence))
        return sequence, tag


texts:
I began studying C# 5.0 a few days ago and am trying to avoid duplicated code for validation of input values.

class transcript
{
  //Use lamda expression and Func for validation logic
  Func<byte, byte> validate = (grade) =>
  {
    if (grade > 100)
      throw new ArgumentOutOfRangeException("grade can`t be more than 100");
    else
      return grade;
  };

  public string name { get; set; }

  public byte kor
  {
    get { return kor; }
    set { kor = validate(value); }
  }

  public byte eng
  {
    get { return this.eng; }
    set { eng = validate(value); }
  }
}


texts: SQL query to count loans issued during each week

texts:
Calculate the number of loans issued by the Regional offices for each business week in the period from 38 to 40 business week of 2011 inclusive. Sort by name of the regional unit, business week.

dataset and snippet here - http://www.sqlfiddle.com/#!18/53151/4

Are the joins correct in this query?

DDL:

create table territory_type(
    id int primary key identity (1,1),
    name nvarchar(50) not null,
);

create table territory(
  id int primary key identity (1,1),
  parent_id int null,
  name nvarchar(50) not null,
  territory_type_id int not null,
  foreign key(territory_type_id) references territory_type(id),
  constraint fk_tr_parent foreign key (parent_id) references territory(id) on delete no action
);

create table deal(
  dl_id int primary key identity (1,1),
  dl_valutation_date datetime not null,
  dl_sum decimal not null,
  dl_territory_id int not null,
  foreign key(dl_territory_id) references territory(id)
);

create table business_calendar(
  id int primary key identity (1,1),
  bc_year int not null,
  week int not null,
  date_begin date not null
);

QUERY:

select
        trd.name as "Regional office",
        bc.bc_year as "Year",
        bc.week as "Week",
        sum(d.dl_sum) as "Sum of credits",
        count(d.dl_id) as "Count of credits"
    from deal as d
    join business_calendar as bc
        on (bc.date_begin < d.dl_valutation_date
        or bc.date_begin = d.dl_valutation_date)
        and (dateadd(day, 6, bc.date_begin) > d.dl_valutation_date
        or dateadd(day, 6, bc.date_begin) = d.dl_valutation_date)
    join territory as t on t.id = d.dl_territory_id
    join territory as trd on t.parent_id = trd.id
    where bc.week in (38,39,40)
    group by trd.name,bc.bc_year, bc.week
    order by trd.name, bc.week asc;


texts:
I am trying to find out quantiles for each column on the table for various firms using spark 1.6

I have around 5000 entries in firm_list and 300 entries in attr_lst. Number of records in table is around 200000.

I am using 10 executors each with 16gb memory.

Currently it is taking around 1 second for each quantile calculation and 2 mins for whole transformation. with this pace, it will run around 10000 Mins for 5000 firms.

Please let me know how can I optimize the performance.

from __future__ import print_function
from src.utils import sql_service, apa_constant as constant,file_io_service
from pyspark.sql.functions import monotonicallyIncreasingId
from pyspark.sql.functions import lit,col,broadcast
from pyspark.ml.feature import Bucketizer
from pyspark.ml import Pipeline
from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType,DoubleType
from pyspark.sql.types import *
from pyspark.ml.feature import *
from concurrent.futures import *
from functools import reduce
from pyspark.sql import DataFrame
import pyspark
import numpy as np

def generate_quantile_reports(spark_context,hive_context,log,attribute_type,**kwargs):

    sql = """describe {}.apa_all_attrs_consortium""".format(kwargs['sem_db'])
    op = hive_context.sql(sql)
    res = op.withColumn("ordinal_position",monotonicallyIncreasingId())
    res.registerTempTable('attribs')

    attr_lst = hive_context.sql("""select col_name from attribs where ordinal_position > 24 AND col_name not like '%vehicle%' AND col_name not like'%cluster_num%' AND col_name not like '%value_seg%' order by ordinal_position""").collect()

    sql = """select distinct firm_id, firm_name from {}.apa_all_attrs_consortium where ud_rep = 1 and lower(channel) not in ('ria','clearing') order by firm_id limit 5 """.format(kwargs['sem_db'])
    dat = hive_context.sql(sql)
    firm_list = dat.collect()
    sql = """select entity_id, cast(firm_id as double), %s from %s.apa_all_attrs_consortium where ud_rep = 1 and lower(channel) not in ('ria','clearing') cluster by entity_id""" % (", ".join("cast(" + str(attr.col_name) + " as double)" for attr in attr_lst), kwargs['sem_db'])

    df = hive_context.sql(sql)
    qrtl_list = []
    df.cache()
    df.count()
    counter = 0
    for (fm,fnm) in firm_list:
      df2 = df[df.firm_id == fm]
      df2 = df2.replace(0, np.nan)
      df_main = df2.drop('firm_id')
      counter += 1
      colNames = []
      quartileList = []
      bucketizerList = []
      for var in attr_lst:
          colNames.append(var.col_name)
      jdf = df2._jdf
      bindt = spark_context._jvm.com.dstsystems.apa.util.DFQuantileFunction.approxQuantile(jdf,colNames,[0.0,0.25,0.5,0.75,1.0],0.0)
      for i in range(len(bindt)):
        quartile = sorted(list(set(list(bindt[i]))))
        quartile = [-float("inf")] + quartile
        quartile.insert(len(quartile),float("inf"))
        quartile.insert(len(quartile),float("NaN"))
        df_main = df_main.filter(df_main[colNames[i]].isNotNull())
        bucketizerList.append(Bucketizer().setInputCol(colNames[i]).setOutputCol("{}_quantile".format(colNames[i])).setSplits(quartile))
      path = " {}/tmpPqtDir/apa_team_broker_quartiles".format(kwargs['semzone_path'])
      qrtl_list.append(Pipeline(stages=bucketizerList).fit(df_main).transform(df_main))
    finalDF = reduce(DataFrame.unionAll, qrtl_list)
    finalDF.repartition(200).write.mode("overwrite").option("header","true").parquet(path)
    df.unpersist()


texts:
I recently read K&R The C Programming Language and wanted to write a small program to count the occurrence of each word in the input (std-input - I piped a file with all shakespeare pieces in there).

Since I wanted to learn how to split source files into multiple files with this project I pretty much outsources every function I could think of.
This is the part I'm most unsure, whether its bad practice or not (I include multiple libraries from the std-lib multiple times. Is this a bad thing?). You'll see.

find_words.c

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include "word_finder.h"
#include "binary_tree.h"

#define MAX_WORD 20

int main(int argc, char *argv[])
{
    char word[MAX_WORD];
    struct tnode *root = NULL;
    int min_count = 1500;
    int max_count = 20000;

    if (argc > 3) {
        printf("Usage: ./find_words [min_count] [max_count] <INPUT_PIPE\n");
        return 0;
    }

    if(argv[1] != NULL)
        min_count = atoi(argv[1]);
    if(argv[2] != NULL)
        max_count = atoi(argv[2]);

    while(get_word(word, MAX_WORD) != 0)
        if(isalpha(word[0]))
            root = addtree(root, word);

    treeprint(root, min_count, max_count);

    return 1;
}

word_finder.h

int get_word(char *word, int limit);

word_finder.c

#include <ctype.h>
#include <stdio.h>
#include "io.h"

int get_word(char *word, int size)
{
    int c;
    while((isspace(c = getch())))
        ;

    if (c == EOF)
        return 0;

    int i = 0;
    do
    {
        *(word+i++) = c;
    } while (isalpha(c = getch()) && i < size-1);

    *(word+i) = '\0';
    ungetch(c);

    return i;
}

io.h

int getch(void);
void ungetch(int);

io.c

#include <stdio.h>
#include "io.h"

#define BUFSIZE 100

/* Buffer can hold up to BUFSIZE - 1 characters */
char buf[BUFSIZE];
int bufhead = 0;
int buftail = 0;

int getch(void)
{
    if (bufhead == buftail)
        return getchar();
    else {
        int temp = buf[buftail];
        buftail = (buftail + 1) % BUFSIZE;
        return temp;
    }
}

void ungetch(int c)
{
    if ((bufhead + 1) % BUFSIZE == buftail % BUFSIZE) {
        fprintf(stderr, "Buffer full, dropped %c.\n", c);
    } else {
        buf[bufhead] = c;
        bufhead = (bufhead + 1) % BUFSIZE;
    }
}

binary_tree.h

struct tnode {
    char *word;
    int count;
    struct tnode *right;
    struct tnode *left;
};

struct tnode *addtree(struct tnode *, char *);
void treeprint(struct tnode *, int, int);

binary_tree.c

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

static char *strduplicate(const char *);
static struct tnode *talloc(void);

struct tnode *addtree(struct tnode *node, char *word)
{
    int cond;

    if(node == NULL) {  //The word doesnt exist in the tree
        node = talloc();
        node->word = strduplicate(word);
        node->count = 1;
        node->left = node->right = NULL;
    } else if((cond = strcmp(word, node->word)) == 0) {
        node->count++;
    } else if(cond < 0) {
        node->left = addtree(node->left, word);
    } else {
        node->right = addtree(node->right, word);
    }

    return node;
}

static struct tnode *talloc(void)
{
    return (struct tnode *) malloc(sizeof(struct tnode));
}

static char *strduplicate(const char *s)
{
    char *p;

    p = (char *) malloc(strlen(s)+1);
    if(p != NULL)
        strcpy(p,s);

    return p;
}

void treeprint(struct tnode *node, int min_count, int max_count)
{
    if(node != NULL) {
        treeprint(node->left, min_count, max_count);
        if(node->count >= min_count && node->count <= max_count)
            printf("%4d %s\n", node->count, node->word);
        treeprint(node->right, min_count, max_count);
    }
}

I'm sorry for the long post (I'm not 100% sure if this is allowed - I'll delete the post immediately if it's not).


texts: PySpark code that turns columns into rows

texts:
I am new to PySpark. My goal is to translate this table:

|Key|Value1|Value2|Value3| ...
+---+------+------+------+
|  1|    v1|    v2|    v3|

into a table like this:

|Key|ColumnName|ColumnValue|
+---+----------+-----------+
|  1|    Value1|         v1|
|  1|    Value2|         v2|
|  1|    Value3|         v3|

And here is my code for doing so:

from pyspark.sql import *

sample = spark.read.format("csv").options(header='true', delimiter = ',').load("/FileStore/tables/sample.csv")

class Closure:
  def __init__(self, columnNames):
    self.columnNames = columnNames

  def flatMapFunction(self, columnValues):
    result = []
    columnIndex = 0
    for columnValue in columnValues:
      if not columnIndex == 0:
        result.append(Row(Key = columnValues[0], ColumnName = self.columnNames[columnIndex], ColumnValue = columnValue))
      columnIndex = columnIndex + 1
    return result

closure = Closure(sample.columns)
sample.rdd.flatMap(closure.flatMapFunction).toDF().show()

I know it is weird that I have to explicitly created the closure, but it looks like it is required, without which the execution would fail with a weird exception.

Questions:

Is it good code?
Is it going to scale well? There will be a few hundred columns but millions of rows.
Is there anything I should do to improve the code?


texts: Fastest way to find if a lot numbers are in multiple intervals

texts:
So I have a task. I've been given \$n\$ numbers and \$m\$ intervals and I need to figure out how many numbers are in the \$m\$ \$i\$-th interval. I've written some code with a complexity of \$O(n \times m)\$, though I need to optimize it more. Any help? Code:

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

int main()
{
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    cout.tie(0);
    int n,m,temp,temp1;
    vector <pair<int, int>> uogienes;
    vector <int> erskeciai;

cin >> n >> m;
for (int i = 0; i< n; i++){
    cin>>temp;
    erskeciai.push_back(temp);
}
temp = 0;
for (int i = 0; i<m; i++){
    cin>> temp >> temp1;
    uogienes.push_back(make_pair(temp, temp1));
}
for(int i = 0; i<m; i++){
        temp=0;
    for(int h = 0; h<n; h++){
       if(uogienes[i].first <= erskeciai[h] && uogienes[i].second >= erskeciai[h]){
        temp++;
        }
    }
cout  << temp << "\n";
}
return 0;
}


texts: Find fibonacci series upto a given maximum in javascript

texts:
I'm attempting to find a fibonacci series where the last number is no greater than a given maximum. Given the start digits 1, 2

Here's my working code.

var fib = [1,2];
var max = 4000000;
var i = 2;
var loop = true

while (loop) {
    if (fib[i-1] + fib[i-2] > max) {
        loop = false;
    } else {
        fib.push(fib[i-1] + fib[i-2]);
        i++;
    }
}

console.log(fib)


texts: Eliminating empty spreadsheet cells from a range

texts:
I am copying data, that is one long list, into an excel sheet and I want to use a macro to organize it visually.  The problem is that the data I am copying has empty cells that are unnecessary and will inhibit my code later in the macro and I want to get rid of them.  This is what I came up with, but I am hoping there is a more efficient way to do it.  The main problem I ran into in trying other methods is I couldn't set a value to a variable to end the second "For" statement before it tried to select a cell that doesn't exist. After it got to the first row it would keep running and would return an error on "ActiveCell.Offset(-1, 0).Range("A1").Select" because there was no cell to select.

Data example:

1, ,2, ,1, ,3, ,1, ,2, ,1, ,4, ,1, ,2, ,1, ,3, ,1, ,2, ,1,...

1, , ,1, , ,2, , ,1, , ,1, , ,2, , ,1, , ,1, , ,3, , ,1, ,...

Each comma represents a new cell, with the numbers and spaces (empty cells) in the same column.

My code:

Sub Organize_Data()

Dim n As Integer
Dim h As Integer
Dim t As Integer
h = 1000
t = h - 1

Cells(h, 1).Select
For n = 1 To t
    If IsEmpty(ActiveCell) Then
    ActiveCell.Offset(-1, 0).Range("A1").Select
    h = h - 1
    Else
    n = t
    End If
Next n

t = h - 1

For n = 1 To t
    If IsEmpty(ActiveCell) Then
    Selection.Delete Shift:=xlUp
    ActiveCell.Offset(-1, 0).Range("A1").Select
    h = h - 1
    Else
    ActiveCell.Offset(-1, 0).Range("A1").Select
    h = h - 1
    End If
Next n

End Sub

Data After Macro:

1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,...

1,1,2,1,1,2,1,1,3,1,...

Possibilities:

I was thinking that in place of the first "For" statement I could use

Selection.End(xlUp).Select

but I don't know how I would set the variable "t" so that the "For" Statement would end before it tried to select a cell that didn't exist.
The other thing I can think of is maybe there is code that I could use for a third part to the "If" statement in the second "For" statement that will stop the "For" statement when it is in the first row.


texts: Rearranging data from one table to another in spreadsheets using apps script

texts:
I need some help with making my code run faster. It currently works by going through all cells in a 201x151 table. If the value in a cell is not equal to zero, then it will return the row number, the column number, and the actual value, and put it in a different table.
Here is the code:
function rearranger() {

  var range = SpreadsheetApp.getActiveSheet().getRange('A2:C10000');

  var ratings = SpreadsheetApp.getActiveSheet().getRange('TopChampionsVSUser!A1:EU201');

  var iterationNumber = SpreadsheetApp.getActiveSheet().getRange('I1:I2').getValues();

  var tr = SpreadsheetApp.getActiveSheet().getRange('L1').getCell(1, 1).getValue();

  var r = iterationNumber[0];
  var c = iterationNumber[1];

  for(r; r < 3000; r++){

    SpreadsheetApp.getActiveSheet().getRange('I1').getCell(1, 1).setValue(r);

    if(c >= 151){
      c = 2;
    }

    for(c; c < 152; c++){

      SpreadsheetApp.getActiveSheet().getRange('I2').getCell(1, 1).setValue(c);

      var currentCellValue = ratings.getCell(r, c).getValue();

      if(currentCellValue != 0){

        range.getCell(tr, 1).setValue(r-1);
        range.getCell(tr, 2).setValue(ratings.getCell(1, c).getValue());
        range.getCell(tr, 3).setValue(currentCellValue);

        tr++;

        SpreadsheetApp.getActiveSheet().getRange('L1').getCell(1, 1).setValue(tr);

      }
    }
  }
}

Do you see something you think can be improved or made more efficient?


texts:
I need to write a class to batch Order objects from 3 calling components running on 3 separate threads. The 3 calling components will call the Batcher class at the same time (within a second of each other), but to handle clock issues and thread interleaving, the method should wait for a maximum of 5 seconds for the 3 calls. If for any reason only 2 calls make it, the batcher should continue after the 5-second timeout and batch what it has. The Batcher class must appear synchronized to the calling components.

I have written a class and it seems to work but I'm new to this and I'd appreciate it if someone could review my class.

public sealed class Batcher
{
    private readonly object _syncLock = new object();
    private readonly Timer _timer;
    private bool _timerSet = false;
    private volatile int _callCount = 0;
    private const int ExecuteImmediatelyCallCount = 3;
    private readonly ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
    private readonly List<Order> _orders = new List<Order>();

    public Batcher()
    {
        _timer = new Timer(Batch, null, Timeout.Infinite, Timeout.Infinite);
    }

    public void  TryBatch(IEnumerable<Order> orders)
    {
        lock (_syncLock)
        {
            _orders.AddRange(orders);
            if(!_timerSet)
            {
                _timerSet = true;
                _timer.Change(5000, Timeout.Infinite);
            }
            _callCount ++;
        }

        if(_callCount >= ExecuteImmediatelyCallCount)
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
            Batch(null);
        }
        _manualResetEvent.WaitOne();
    }

    private void Batch(object state)
    {
        lock (_syncLock)
        {
            if(_orders.Count > 0)
            {
                RemoteService.Send(_orders);
                _orders.Clear();
                _manualResetEvent.Reset();
            }
            _callCount = 0;
        }
    }
)


texts:
I have been playing with Async/parallel execution in entity framework for while. I'm not sure if I'm doing it right.

I have two entity contexts: one for reading and one for writing. The reading context has more than 200000 rows in table Customer. It took 9 minutes on my PC (i7+8GB).

let FindGender(skip : int, take : int) : Async<unit> =
            async {
                try
                    use readContext = new ReadContext()
                    use context = new WriteContext()
                    let! customers = Async.AwaitTask
                                     <| readContext.Customers.OrderBy(fun c -> c.CustomerId).Skip(skip).Take(take)
                                              .ToListAsync()
                    let findGender (c : NA.Data.Entities.Customer) : unit =
                        let name = context.Names.FirstOrDefault(fun i -> i.Name.ToLower() = c.FirstName.ToLower())
                        match name = Unchecked.defaultof<NameTable> with
                        | false ->
                            Console.WriteLine(String.Format("{0}", name.Name))
                            // create customer
                            let customer = new Customer()
                            customer.ExternalCustomerId <- c.CustomerId
                            customer.ExternalCustomerName <- c.FirstName
                            customer.GenderId <- name.Gender
                            customer.GenderName <- name.GenderType.ToString()
                            customer.NameListId <- name.NameId
                            context.Customers.Add(customer) |> ignore
                        | _ -> 0 |> ignore

                    customers |> Seq.iter findGender

                    let! _ = Async.AwaitTask <| context.SaveChangesAsync()
                    return()
                with ex -> printfn "Exception handled. %A" ex
            }
        let sw = new Stopwatch()
        sw.Start()
        let customerCount = 218114
        let step = 1000
        [ 0..step..customerCount ]
        |> Seq.map (fun i ->
               if i + step < customerCount then (i, step)
               else (i, customerCount - i))
        |> Seq.map (fun (step, take) -> FindGender(step, take))
        |> Async.Parallel
        |> Async.RunSynchronously
        |> ignore
        sw.Stop()
        printfn "%A" sw.Elapsed


texts: Pulling behavior from middleware for unit testing express.js

texts:
I want to unit test app with express middleware.

It is not so obvious for me how to separately test each middleware.

I have found one of the approaches: "Pull behavior from the middleware" what is simply wrapping the code inside middleware in function.

My questions:

are there any problems with this approach
I am taking username and password from req with auth function, so I need to pass the whole request to the generateTokenBehavior function, wouldn't it be problematic as much as testing the whole middleware?
I can take username and password from req in generateToken and pass just username and password to generateTokenBehavior function. Then I would need to test the middleware anyways. Does this make sense?

Simplified code of my middleware:

function generateTokenBehavior(data) {
    let username, password;
    // checks for authorisation headers
    if (_.has(data, 'headers.authorization')) {
      username = auth(data).name;
      password = auth(data).pass;
    } else {
      responseData.status = 401;
      responseData.data = {};
      return responseData;
    }
    const token = 'token';
    responseData.status = 200;
    responseData.data = {meta:{token}};
    return responseData;
}

function generateToken(req, res, next) {
    const responseData = generateTokenBehavior(req);
    return res.status(responseData.status).json(responseData.data);
}


texts: Find part of string in array, replace entire row with that part of string if found

texts:
Following is the string: (I'm getting that from config file so its not constant):

string sequence = "Concat({ACCOUNT_NUM},substring(FormatDate(yyyyMMddHHmmss,DateNow())
,2,12), GetLast(GetNextSequence(seq_relation),1))";

It contains multiple custom methods and I want them somewhere in the same order as they appear in the above string. Following is the strategy I applied:

string[] arbitrary = sequence .Split('(').ToArray();

string[] methodsNmore = arbitrary.Take(arbitrary.Length - 1).ToArray();

string[] array2 = methodsNmore.Where(strr => strr.Contains(',')).ToArray();

string[] methods = array2.Select(str => str.Substring(str.LastIndexOf
                                         (',') + 1, str.Length - str.LastIndexOf
                                         (',') - 1)
                                        ).ToArray();

for (int i = 0; i < methods.Length; i++)
{
   string row = Array.Find(methodsNmore, item => item.Contains(methods[i]));

   int ii = Array.IndexOf(methodsNmore, row);

   methodsNmore[ii] = methods[i];
}

The resulting array, methodsNmore, now contains only the names of methods in the same order as in above string sequence.

Is there any other elegant way of doing it?


texts: GIS feature labeling and removal of None or Empty fields

texts:
A working label expression for ArcGIS 10.3. I was using dictionary key:values but sometimes the keys would have the same value so my items were 'disappearing' out of the dictionary. Now I use this simple counter to group my values from a list (0,1) (2,3) (4,5). I think the if functions might be able to be combined, as well as perhaps setting the list[i*2] and list[(i*2)+1] to variables instead of repeating them 3 times.

def FindLabel ( [Elevation] , [Out_Elev] , [Out_Loc] , [In1_Elev] , [In1_Loc] , [In2_Elev] , [In2_Loc] , [In3_Elev] , [In3_Loc]  ):
  list = [Out_Elev],[Out_Loc],[In1_Elev],[In1_Loc],[In2_Elev],[In2_Loc],[In3_Elev],[In3_Loc]
  x = [Elevation] + " Top"
  for i in range(len(list)/2):
    if list[i*2] is not None:
      if list[i*2].strip() != "":
       if list[(i*2)+1] is not None:
         if list[(i*2)+1].strip() !="":
           x = x  + "\n" + "(" + str(list[i*2]) + ": " + str(list[(i*2)+1]) + ")"
  return x