texts: HackerRank (Stacks) - Maximum element solution gets a timeout

texts:
Apparently my solution is really slow. Can someone help me with why my solution passes a little over half the test cases for this question?

Here is my solution:

function processData(input) {
    //Enter your code here

    let inputArr = input.split("\n");
    let newArr = inputArr.map(x => x.split(" ").map(p => parseInt(p, 10)));
    let stack = [];
    let len = newArr.length;
    for (let i = 0; i < len; i++){
        if (newArr[i][0] === 1){
            stack.push(newArr[i][1]);
        } else if (newArr[i][0] === 2){

            stack.pop();

        } else if (newArr[i][0] === 3){
            console.log(stack.reduce(maxNum));
        }
    }

}

let maxNum = (acc, curr) => Math.max(acc, curr);


texts: Extracting numeric values from a string containing key:value pairs

texts:
I am writing function numericValues(text: String): List[Int] to extract patterns """([a-z]+)\s*:\s*(\d+)""" and return the list of the numeric values :

numericValues("a123 : 0 abc:123 123:abc xyz:1") // List(123, 1)

I would write numericValues like this:

def numericValues(text: String): List[Int] = {
  val regex = """([a-z]+)\s*:\s*(\d+)""".r
  regex.findAllIn(text).toList.flatMap {s =>
    PartialFunction.condOpt(s) { case regex(_, num) => num.toInt }
  }
}

I guess the condOpt invocation is redundant and I wonder how to simplify this implementation. Also, I'd appreciate comments on improvements to style and best practice.


texts: Emacs lisp advice to start ipython repl in the project root

texts:
When starting an ipython repl for my project at work, I pretty much always want it started in the project root, not adjacent to the file for the buffer I'm viewing (this is python and module loading depends on cwd). While I can always start the repl and then %cd /my/project/root that is a pain the 50th time I had to do it. So I figured I could do some digging and get emacs to do it for me.
I guessed correctly that setting default-directory would do the trick and wheee with dynamic scoping I can just run the code in a let and set it to (projectile-project-root). This becomes a straightforward matter therefore of writing :around advice which I've never done before but I think I got it.
The remaining issue is that I don't always want this to happen. Instead I want it to only happen within my big work project monorepo so I need some way of controlling whether the advice was active via a variable I can set with dir-locals. The following is what I came up with
    (defcustom gim/default-directory-to-projectile-root-is-active nil
      "Control whether the gim/default-directory-to-projectile-root advice is currently active or not"
      :type '(boolean))

    (defun gim/default-directory-to-projectile-root (orig-fun &rest args)
      (if (not gim/default-directory-to-projectile-root-is-active)
          (apply orig-fun args)
          (let ((default-directory (projectile-project-root)))
              (apply orig-fun args))))

    (advice-remove 'spacemacs/python-start-or-switch-repl #'gim/default-directory-to-projectile-root)
    (advice-add 'spacemacs/python-start-or-switch-repl :around #'gim/default-directory-to-projectile-root)

Thoughts? Suggestions? Is around advice right? Is this a good way of doing a flag? The duplication on both branches of the if statement is annoying, surely there is a slicker way to do that


texts: Timeouts when calculating stock ratings using LINQ

texts:
I'm getting a lot of timeouts with the following code and I'm running this method around 10,000 times so I need to figure out how I can optimize this so the timeouts will stop. I am getting timeout errors when I try to call the fill method and I believe it is because the queries aren't done processing yet. It is a local database and it is running SQL Server 2014.

public static StockRating performCalculations(SymbolInfo info)
{
    var calc = new Calculations(info.Symbol, info.Market);
    StockRating rating = new StockRating();

    try
    {
        using (DailyGlobalDataTableAdapter dailyGlobalAdapter = new DailyGlobalDataTableAdapter())
        using (DailyNyseDataTableAdapter dailyNyseAdapter = new DailyNyseDataTableAdapter())
        using (DailyGlobalDataDataTable sandp500Table = new DailyGlobalDataDataTable())
        using (DailyNyseDataDataTable dailyNyseTable = new DailyNyseDataDataTable())
        {
            // fill the s&p500 info first
            dailyGlobalAdapter.ClearBeforeFill = true;
            dailyGlobalAdapter.FillBySymbol(sandp500Table, Calculations.sp500);

            var sp500StockDataQuery = from c in sandp500Table
                                      select new StockData { Close = c.AdjustedClose, High = c.High, Low = c.Low, Volume = c.Volume, Date = c.Date };

            calc.sp500Data = sp500StockDataQuery.AsParallel().ToList();

                    dailyNyseAdapter.FillBySymbol(dailyNyseTable, info.Symbol);

                    var nyseQuery = from c in sandp500Table
                                    where c.Date >= DateTime.Now.Subtract(TimeSpan.FromDays(60))
                                    join d in dailyNyseTable on c.Date equals d.Date
                                    select new StockMarketCompare { stockClose = d.AdjustedClose, marketClose = c.AdjustedClose };

                    var nyseStockDataQuery = from c in dailyNyseTable
                                             select new StockData { Close = c.AdjustedClose, High = c.High, Low = c.Low, Volume = c.Volume, Date = c.Date };

                    calc.stockVsMarketCompareData = nyseQuery.AsParallel().ToList();
                    calc.stockData = nyseStockDataQuery.AsParallel().ToList();

            // get the pct return data that is needed for calculations
            calc.fillPctReturns();

            if (calc.stockPctReturns.Count > 0 && calc.marketPctReturns.Count > 0)
            {
                // perform the calculations here
                rating.estimatedReturn = calc.calculateExpectedReturn();
                rating.longRating = calc.calculateRating(Calculations.ratingType.long_rating);
                rating.market = calc.Market;
                rating.mediumRating = calc.calculateRating(Calculations.ratingType.medium_rating);
                rating.shortRating = calc.calculateRating(Calculations.ratingType.short_rating);
                rating.symbol = calc.Symbol;
                rating.risk = calc.calculateRisk();
                rating.isMarginEnabled = calc.isMarginEnabled();
                Console.WriteLine("Ratings calculated for " + info.Symbol + " in the " + info.Market + ". " + stopwatch.ElapsedMilliseconds / 1000 + " seconds elapsed.");
            }
            else
            {
                rating = null;
            }
        }
    }
    catch (Exception ex)
    {
        rating = performCalculations(info);
    }

    return rating;
}

Parallel.For(0, activeSymbolsCount, j =>
                            {
                                symbol = symbolTable.AsParallel().ElementAtOrDefault(j).Symbol;
                                SymbolInfo symbolClass = new SymbolInfo(symbol, market);
                                StockRating rating = performCalculations(symbolClass);
                                saveToTable(rating);
                            });


texts: Cycling between element above and below current array element

texts:
The title sucks, but it's really very simple - given an array and a starting element, cycle between one element above, below, then two element above, and below the starting element. For example:

Start: 5
5 > 6 > 4 > 7 > 3 > 8 > 2 ...

It doesn't matter if the code initially start with the element above or below. To complicate things a little, when you reach the end or beginning of the array, the code should continue to pick valid array elements, instead of going into invalid positions:

Start: 2
2 > 3 > 1 > 4 > 0 > 5 > 6 > 7 ...

This is the code I have. It works, but I don't really like the way to fulfil the second condition above, having that two lines repeated twice.

var distance = 0;

while ((currentHeight + this.heights[index]) < height) {
    sections.push(index);
    currentHeight += this.heights[index];

    distance = -distance + (distance >= 0 ? -1 : 1);
    index += distance;

    if (index < 0 || index >= this.heights.length) {
        distance = -distance + (distance >= 0 ? -1 : 1);
        index += distance;
    }
}

distance is the distance from the starting point, index holds the current position. The code cycles with these two lines:

distance = -distance + (distance >= 0 ? -1 : 1);
index += distance;

and it resolves the invalid array position problem by simply rerunning those two lines if it finds an invalid array position.


texts: Is my controller for editing information about videos doing too much?

texts:
My project uses Zend Framework 2.

I'm trying to determine if I am doing too much in my controller as a rule for my development. I have built my controllers like this for a while and haven't run into many problems but I wanted to get some feedback from this community.

This specific action handles a video management form that contains an image upload form.

Here is the action from my controller:

public function editAction() {
    $id = $this->params('id',null);
    $sl = $this->getServiceLocator();
    $form = $sl->get('AdminVideoForm');
    $image_form = $sl->get('VideoImageUploadForm');
    $image_form->setAttribute('action',$this->url()->fromRoute('admin/video/upload-image') . '?video_id=' . $id);
    $model = [
        'form' => $form,
        'image_form' => $image_form
    ];

    $current_video = $this->videoTable->fetchById($id);
    if(!$current_video) {
        $this->flashMessenger()->setNamespace('video-admin')->addMessage('Invalid Video ID');
        return $this->redirectToListing();
    }
    $model['id'] = $id;
    $model['video'] = $current_video;
    $form->bind($current_video);

    $request = $this->getRequest();
    if($request->getQuery('returnTo')) {
        $model['returnTo'] = $request->getQuery('returnTo');
    }
    else {
        $model['returnTo'] = $this->url()->fromRoute('admin/video');
    }
    $form->setAttribute('action',$this->url()->fromRoute('admin/video/edit',['id' => $id]) . '?returnTo=' . rawurlencode($model['returnTo']));

    if($request->isPost()) {
        $form->setData($request->getPost());
        if($form->isValid()) {
            $this->videoTable->saveVideo($form->getData());
            return $this->redirectToListing();
        }
    }
    return $model;
}


texts:
I'm extremely amateur when it comes to C++ in general, but I wanted to make a little "Pyramid Escape" text based game. I'm not done whatsoever but before I continue I want to see what I could possible do differently.

//
//  main.cpp
//  TextFiles
//
//  Created by Neal Carico on 3/12/15.
//  Copyright (c) 2015 Nedev. All rights reserved.
//

#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, const char * argv[]) {

string start;
string restart;
string dead;
int turn1;
int turn2;
int turn3;
int turn4;
string decision1;
string decision2;
string decision3;
string decision4;
string decision5;
int random1;
int random2;
int random3;

while(restart != "dontrestart" || dead != "false"){
cout << "Welcome to the worlds largest pyramid. . . Type 'start' to enter or 'leave' to walk away..." << endl;
cin >> start;

///The Start
if (start == "start"){

///The main part of the game.

    cout << "Oh no! The pyramid collapsed trapping you in. You are the only one alive. . ." << endl;

    int score=0;

    cout << "Okay. So you have two options here. . .Left(1) or right(2)?" << endl;
    cin >> turn1;
    if(turn1 == 2){
        cout << "BAM! The roof collapsed over you and you die. Sad stuff" << endl;
        cout << "Thank you for playing. Your score was " << score << endl;
        exit(1);
    }
    cout << "You took the left path. And then BAM! The path to the right collapsed... lucky you." << endl;
    score++;
    cout << "There gold on the ground.. do you pick it up?[y/n]" << endl;
    cin >> decision1;

    if(decision1 == "y"){
        cout << "You greedy bastard you. Lucky I like the irony and am not going to kill you in this instance... You find 10 gold." << endl;
        score = score + 10;
    }

    cout << "You start heading forward again and come to another turn. But this time there are actually four options... :)" << endl;
    random1 = rand() % 4 +1;
    cout << "Your options are as follows. 1) Up to right 2)Down to right 3)Up to left and 4)Down to left. This one changes everytime ;). The random number is " << random1 << endl;
    cin >> turn2;
    if (turn2 == random1) {
        cout << "BAM! The roof collapsed over you and you die. Sad stuff" << endl;
        cout << "Thank you for playing. Your score was " << score << endl;
        exit(1);
    }
    cout << "Sweet. You made it. There's a point." << endl;
    score++;

    cout << "Okay you start walking down the tunnel and something is moving in the distance. Do you approach it or head back to one of the other tunnels?(continue/return" << endl;
    cin >> decision2;
    if(decision2 == "continue"){
        cout << "Yup, I'm not nice enough to give you a break 2 times in a row. Dead." << endl;
        cout << "BLAAAHHHGGGG!! The figure is a crazed mummy who attacks you and you die. Sad stuff" << endl;
        cout << "Thank you for playing. Your score was " << score << endl;
        exit(1);
    }
    cout << "There is a screeching sound as you turn around." << endl;
    score++;

///End of game stuff

}else if(start == "leave"){
    cout << "You walked away and heard a huge BOOM and saw the pyramid collapsed trapping the tour group in. You are" <<
    " one lucky person. Sure you lived, but you didn't even play the game. How lame.You can type 'restart' to try again, but you're always going to be a loser to me." << endl;
}else{
    cout << "Error. Please type restart or 'dontrestart' (notice there are no spaces) to exit the game..." << endl;
}
    cin >> restart;
    if (restart !="restart"){
        exit(1);
    }

}
return 0;

}


texts: First missing positive integer in linear time and constant space

texts:
This problem was asked by Stripe.

  Given an array of integers, find the first missing positive integer in
  linear time and constant space. In other words, find the lowest
  positive integer that does not exist in the array. The array can
  contain duplicates and negative numbers as well.

  For example, the input [3, 4, -1, 1] should give 2. The input [1, 2,
  0] should give 3.

  You can modify the input array in-place.

class DailyCodingProblem5 {

    public static void main(String args[]) {
        int[] arr = { 3, 4, -1, 1 };
        int res = solution(arr);
        System.out.println(res);

        int[] arr2 = { 1, 2, 0 };
        res = solution(arr2);
        System.out.println(res);
    }

    private static int solution(int[] arr) {
        int n = arr.length;
        int i = 0;
        for (i = 0; i < n; i++) {
            int val = arr[i];

            if (val <= 0 || val > n)
                continue;
            while (val != arr[val - 1]) {
                int nextval = arr[val - 1];
                arr[val - 1] = val;
                val = nextval;
                if (val <= 0 || val > n) {
                    break;
                }
            }
        }
        for (i = 0; i < n; i++) {
            if (arr[i] != i + 1) {
                return i + 1;
            }
        }
        return n+1;

    }
}

How can i improve the above solution? Is there any improvements i can have in my code ?


texts:
I have just started trying to learn Haskell and tried to think of a practical, but simple problem to try and solve.  I have a strong background in C, but am just beginning to dip my toes in the world of functional programming.

The idea came from my investing in notes on Prosper: given a list of note ratings, and a desired distribution, what should the next note purchase be, in order to most align with the desired distribution.

Here's an example:

Say I currently own 5 notes of an "A" rating, and 4 notes of a "B" rating.  If my desired distribution is 50% "A" and 50% "B", then the next note purchased should be of a "B" rating. However, if my desired distribution was 90/10, the next note should be an "A" rating.

The below code seems to work (albeit with no error checking), but feels very unreadable.  What are some ways I could refactor to make the code more readable or idiomatic to Haskell?

module Main where

import Data.List
import Data.Ord

main::IO()
main = print $ recommendNote [ "B", "C", "D", "D", "HR" ]  [ 0, 0, 0, 0.5, 0.25, 0.25, 0]

noteTypes :: [String]
noteTypes = [ "AA", "A", "B", "C", "D", "E", "HR" ]

recommendNote :: (Ord a, Fractional a) => [String] -> [a] -> String
recommendNote notes targetDist = let y = zip (subtractLists targetDist (getDistribution notes)) noteTypes
                                in snd (maximumBy (comparing fst) y)

subtractLists :: (Num a) => [a] -> [a] -> [a]
subtractLists = zipWith (-)

count :: [String] -> String -> Int
count inList x =  length $ filter (x==) inList

getNoteCount :: [String] -> [Int]
getNoteCount inList = map (count inList) noteTypes

getDistribution :: (Fractional a) => [String] -> [a]
getDistribution inList = percentize $ map fromIntegral (getNoteCount inList)

percentize :: (Fractional a) => [a] -> [a]
percentize inList = map (/ sum inList) inList


texts: Validate and Add Service Provider/Location in C#

texts:
I have a button that will validate the textbox for the service provider and the dropdown list for the locations. I have 3 tables: Locations, Service_Providers, and Service_Providers_Locations with a many-to-many relationship. But the tables that are affected are mainly Service_Providers and Service_Providers_Locations. However, upon running, the button inserts the record even if there are duplicates. What we want is to not allow duplicate record in the transaction table Service_Providers_Locations. There can be the same name of service provider, but not same location. Our code allows duplicate record insertion. We are using a three-tier approach.

protected void btnAddServiceProvider_Click(object sender, EventArgs e)
    {
        bll.Name = txtServiceProvider.Text;
        DataTable temp = bll.ServiceProviderCheckExisting();
        if (temp.Rows.Count == 0)
        {
            bll.IsDeleted = "n";
            bll.ServiceProviderAdd();
            temp = bll.ServiceProviderCheckExisting();
            bll.ServiceProviderID = temp.Rows[0][0].ToString();
            bll.LocationID = ddlLocations.SelectedValue;
            bll.IsApproved = "y";
            bll.ServiceProviderLocationAdd();
            gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
            gvServiceProviders.DataBind();
        }
        else
        {
            bll.ServiceProviderID = temp.Rows[0][0].ToString();
            temp = bll.GetServiceProviderLocationUsingServiceProviderID();
            if (temp.Rows.Count == 0)
            {
                bll.LocationID = ddlLocations.SelectedValue;
                bll.IsApproved = "y";
                bll.ServiceProviderLocationAdd();
                gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
                gvServiceProviders.DataBind();
            }
            else
            {
                for (int x = 0; x < temp.Rows.Count; x++)
                {
                    if (ddlLocations.SelectedValue == temp.Rows[x][1].ToString())
                    {
                        lblServiceProviderError.Text = "This service provider already exists for that location.";
                    }
                    else
                    {
                        bll.LocationID = ddlLocations.SelectedValue;
                        bll.IsApproved = "y";
                        bll.ServiceProviderLocationAdd();
                        gvServiceProviders.DataSource = bll.GetServiceProviderLocations();
                        gvServiceProviders.DataBind();
                    }
                }
            }
        }
    }


texts: Find the sum of prime numbers below 2 million

texts:
This code is trying to find the sum of prime numbers below 2 million. The code does work as intended, but it takes a very long time ( 6 minutes) for the code to execute completely. What is the problem and how can I make it more efficient?

#include <iostream>
using namespace std;

unsigned long summationOfPrime();
bool isPrime(int n);
int main() {

cout <<summationOfPrime() << endl;

}

unsigned long summationOfPrime()
{
const int num = 2000000;
unsigned long sum = 0;
for(int i = 2; i < num; i++)
{
    if(isPrime(i) == true)
    {
        sum += i;

    }
}

return sum;
}

bool isPrime(int n)
 {
// Corner case
if (n <= 1)
    return false;

// Check from 2 to n-1
for (int i = 2; i < n; i++)
    if (n % i == 0)
        return false;

return true;
}


texts: Search Array of Strings in Array of String, receive Int-Array of indexes

texts:
I'm looking for an lib which can search an array of strings with multible search-strings (array). I want to get an int-array of all indexes/matches.

private int[] getIndexArray(String[] pArray, String[] pSearchStrings) {
    int[] indexes = new int[0];
    for (String str : pArray) {
        if (ArrayUtils.contains(pSearchStrings, str))
            indexes = ArrayUtils.add(indexes, ArrayUtils.indexOf(pArray, str));
    }
    return indexes;
}

Is there a better way of doing it?


texts: Convert list to a string with double quotes

texts:
For an external application I need to send a command as a string, like this:

["START", "1", "2", "3", "4", "STOP"]

Note the double quotes!

I create this command with the following function:

def create_command(amount):
    command = ["START"]
    list = create_list(amount)
    command += list
    command += ["STOP"]
    command = str(command )
    command = command.replace("\'", "\"")
    return command

And I create a list from a given number with the following function:

def create_list(data):
    list = []
    data = str(data)
    for letter in data:
        list.append(letter)
    return list

Is the a way to make both functions more pythonic and not so straightforward?  I don't really like them now, they look a bit clumpsy and I think there must be a better way do the thing.


texts: Trie Data Structure Implementation in C++11 using Smart Pointers -- follow-up

texts:
Link to my first question.

Link to my latest source code.

I followed @JDługosz recommendations. How does it look? Do you have any further recommendations? Is it better (if possible) to replace shared_ptr with unique_ptr? How could someone extend it to use the Unicode character set?

#pragma once

#include <iostream>
#include <memory>
#include <string>

namespace forest {
    class trie {
    private:
        struct Node {
            std::shared_ptr<Node> children[26];
            bool end = false;
        };
        std::shared_ptr<Node> root = std::make_shared<Node>();
    public:
        void insert(const std::string & key) {
            std::shared_ptr<Node> n = root;
            for (auto c : key) {
                int index = c - 'a';
                auto& slot = n->children[index];
                if (!slot) slot = std::make_shared<Node>();
                n = slot;
            }
            n->end = true;
        }
        bool search(const std::string & key) {
            std::shared_ptr<Node> n = root;
            for (auto c : key) {
                int index = c - 'a';
                auto& slot = n->children[index];
                if (!slot) return false;
                n = slot;
            }
            return n && n->end;
        }
    };
}


texts:
I came to C++ from Java. This is my attempt at making a calculator on about 2 days worth of knowledge. I don't really know what is redundant or unnecessary. Nor do I know of the better ways to achieve this effect.

First class (it does the math):

#pragma once
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class a {
public:
double add(double a, double b) {
    return a + b;
}
double sub(double a, double b) {
    return a - b;
}
double mult(double a, double b) {
    return a * b;
}
double div(double a, double b) {
    return a / b;
}
};

Second class (it makes the strings):

#pragma once
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class text {
public:
string add(double a, double b, double ans) {
    return to_string(a) + " + " + to_string(b) + " = " + to_string(ans);
}
string sub(double a, double b, double ans) {
    return to_string(a) + " - " + to_string(b) + " = " + to_string(ans);
}
string div(double a, double b, double ans) {
    return to_string(a) + " / " + to_string(b) + " = " + to_string(ans);
}
string mult(double a, double b, double ans) {
    return to_string(a) + " * " + to_string(b) + " = " + to_string(ans);
}
string first() {
    return "First Number: ";
}
string second() {
    return "Second Number: ";
}
string op() {
    return "Operator: ";
}
string wrong() {
    return "Invalid Operator!";
}
};

Main method:

#include "a.h"
#include "text.h"
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
text ask;
a mather;
string temp;
char op;
double a, b, ans;

cout << ask.op();
cin.get(op);
cout << ask.first();
cin >> a;
cout << ask.second();
cin >> b;

switch (op) {
case '+':
    ans = mather.add(a, b);
    temp = ask.add(a, b, ans);
    break;
case '-':
    ans = mather.sub(a, b);
    temp = ask.sub(a, b, ans);
    break;
case '/':
    ans = mather.div(a, b);
    temp = ask.div(a, b, ans);
    break;
case '*':
    ans = mather.mult(a, b);
    temp = ask.mult(a, b, ans);
    break;
default:
    cout << "Invalid Operator!";
}

cout << temp;
cin.get();
cin.get(); //I don't know how to avoid using this twice
return 0;
}


texts:
This is an exercise in a book which ask me to implement

  Write an in-place function to eliminate adjacent duplicates in a []string slice.

I am relatively new to golang and I am not sure if my implementation is correct and effective or not.

func removeAdj(strings []string) []string {
    for i := 0; i < len(strings); i++ {
        dup := false
        lastJ := i
        for j := (i + 1); j < len(strings); j++ {
            if strings[i] == strings[j] {
                dup = true
                lastJ = j
            } else {
                break
            }
        }

        if dup {
            strings[i] = ""
            first := strings[:i]
            second := strings[lastJ+1:]

            strings = append(first, second...)
            i = -1
        }
    }

    return strings
}

Tests:

Input:  [a z x x z y]
Output: [a y]
Input:  [g e e k s f o r g e e g]
Output: [g k s f o r]
Input:  [c a a a b b b a a c d d d d]
Output: []
Input:  [a c a a a b b b a c d d d d]
Output: [a c a c]


texts:
I am wanting to implement an AlertDialog with a list into my app and I created a sample to see if I can get the result that I am looking for. It seems I do have the result I wanted but before I implement it into my actual app, is there a way to make my code better?:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Press here" />

</RelativeLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                showAlertDialogWithList();
        }
    }

    public void showAlertDialogWithList() {
        List<String> mAnimals = new ArrayList<>();
        mAnimals.add("Cat");
        mAnimals.add("Dog");
        mAnimals.add("Horse");
        mAnimals.add("Elephant");
        mAnimals.add("Rat");
        mAnimals.add("Lion");
        mAnimals.add("Tiger");
        mAnimals.add("Bird");
        mAnimals.add("Zebra");
        mAnimals.add("Cheetah");
        mAnimals.add("Hyena");

        final CharSequence[] animals = mAnimals.toArray(new String[mAnimals.size()]);
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle("Animals");
        dialogBuilder.setItems(animals, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String selectedText = animals[i].toString();
                Toast.makeText(getApplicationContext(), selectedText, Toast.LENGTH_SHORT).show();
            }
        });

        AlertDialog alertDialogObject = dialogBuilder.create();
        alertDialogObject.show();
    }

}


texts:
I'm a front end developer who is brand new to backend development. My task is to model json in a Java object. It's just some mock data for now that my controller returns.

{
"data": {
    "objectId": 25,
    "columnName": [
        "myCategory",
        "myCategoryId"
    ],
    "columnValues": [
        [
            "Category One",
            1
        ],
        [
            "Category Two",
            2
        ],
        [
            "Category Three",
            3
        ],
        [
            "Category Four",
            4
        ],
        [
            "Category Five",
            5
        ]
    ]
}

}

And here's my attempt. The controller returns this json correctly. But isn't this too simple? What I believe should be done is extrapolate the columnName and columnValues arrays into separate classes but I'm not sure how.

package com.category;

import java.util.List;

public class MyObjectData {
    private int objectId;
    private List columnName;
    private List columnValues;

    public int getObjectId() {
        return objectId;
    }
    public void setObjectId(int objectId) {
        this.objectId = objectId;
    }

    public List getColumnName() {
        return columnName;
    }

    public void setColumnName(List colName) {
        this.columnName = colName;
    }

    public List getColumnValues() {
        return columnValues;
    }

    public void setValues(List values) {
        this.columnValues = values;
    }

}

Regarding the columnNames and columnValues, I feel like I should be doing something like this in the model instead:

private List<ColumnNames> columnNames;
    private List<ColumnValues> columnValues;

    public List<ColumnNames> getColumnNames() {
        return columnNames;
    }

    public void setColumnNames(List<ColumnNames> columnNames) {
        this.columnNames = columnNames;
    }

    public List<ColumnValues> getColumnValues() {
        return columnValues;
    }

    public void setColumnValues(List<ColumnValues> columnValues) {
        this.columnValues = columnValues;
    }

And then I'd have two separate classes for them like this:

package com.category;

import java.util.List;

public class ColumnName {

    private String columnName;

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

}

package com.category;

import java.util.List;

public class ColumnValue {

    private String columnValue;
    private int columnValueId;

    public String getColumnValue() {
        return columnValue;
    }

    public void setColumnValue(String columnValue) {
        this.columnValue = columnValue;
    }

    public String getColumnValueId() {
        return columnValueId;
    }

    public void setColumnValueId(int columnValueId) {
        this.columnValueId = columnValueId;
    }

}

I feel like I have all the right pieces but just not sure if this is a better approach than my initial attempt...which works. Just looking for input. Thanks in advance.


texts: Search string in file, replace it, and write back to file

texts:
I have this simple function that just reads a file, replaces all occurances of a string, and write it back to the file:

def fileSearchReplace(targetFile, search, replace):
    with open(targetFile, 'r') as openFile:
        filedata = openFile.read()

    newData = filedata.replace(search, replace)

    with open(targetFile, 'w') as openFile:
        openFile.write(newData)

I was wondering if there are any better implementation?


texts:
What could I do better in my code or logic?

Wikipedia Search

$(function(){

  $('.search-input').keyup(function(data){

  var pesquisar = $('.search-input').val();

  $('.box-logo').fadeOut(500, function(){
    $('header').css('padding','12px 0');
  });

$.getJSON('https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch='+ pesquisar +'&callback=?',function(data){

  console.log(data);

  var key;

  $('.sec-result .row').html('');
  for(key in data.query.pages){

    var titleArt = data.query.pages[key].title;
    var extractArt = data.query.pages[key].extract;
    var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
    var imgArt;

    if(data.query.pages[key].hasOwnProperty('thumbnail')){
      imgArt = data.query.pages[key].thumbnail.source;
    } else {
      imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
    }

    var contentHTML = '

'+ titleArt +'

' + extractArt + '

';

    $('.sec-result .row').append(contentHTML);
  }

 });

 })

})


texts: Find only one subset sum with a specified value in python for large sets

texts:
how can I optimize my code for a large set (10000 elements)?

found = False

def subset_sum(numbers, target, partial=[]):
    global found
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target:
        print("sum(%s)=%s" % (partial, target))
        raise Exception('element found')
    if s >= target:
        return  # if we reach the number why bother to continue

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i+1:]
        subset_sum(remaining, target, partial + [n])

For example, for 50 elements it takes 41 seconds.


texts: Translating LaTeX documents into different languages using DeepL API

texts:
I'm coming from C and C++ and have often troubles using Python's full potential. This is a script I wrote to translate LaTeX documents into different languages. A parser replaces all latex specific syntax with hashes and then sends it all to deepl. The pydeepl wrapper is from Github.

What do you think of this code?

import sys
import re
import pydeepl
from random import choice
from tqdm import tqdm

def make_xlat(*args, **kwds):
    adict = dict(*args, **kwds)
    rx = re.compile('|'.join(map(re.escape, adict)))
    def one_xlat(match):
        return adict[match.group(0)]
    def xlat(text):
        return rx.sub(one_xlat, text)
    return xlat

if __name__ == "__main__":
     fileInputName = sys.argv[1]
     #fileInputName = "Introduction.tex"
     fileOutName = fileInputName.split('.')[0]+"_trans.tex"

     fileIn  = open(fileInputName, "r")
     fileOut = open(fileOutName, "w")

     fileStr = fileIn.read()

     print("Starting hashing...")

     #replace commands like \begin{*}, \end{*}, tabs etc. with hashes
     searchObj1 = re.findall( r"\\begin\{\w+\}|\t|    |\r|\\end\{\w+\}|\\usepackage\{\w+\}|\\newcommand\{\w+\}|\\include\{.*\}|\\input\{\w+\}|\\\w+\[.*\}|\%.*", fileStr)
     #random number for every found command + a prefix which hopefully doens't appear in text. Used to skip lines later, which don't need translation
     list1 = ['X#X' + str(choice(range(1111, 9999, 1))) for x in searchObj1]
     #make a dictionary out of hashes
     d1 = dict(zip(searchObj1,list1))
     translate = make_xlat(d1)
     hashedText = translate(fileStr)

     #replace all latex commands (starting with a backslash) with hashes
     searchObj2 = re.findall( r"\\\w+",hashedText)
     #random number  + prefix again
     list2 = ['X#X' + str(choice(range(1111, 9999, 1))) for x in searchObj2]
     #make a dictionary
     d2 = dict(zip(searchObj2,list2))
     translate = make_xlat(d2)
     hashedText = translate(hashedText)
     #print(hashedText)
     #fileOut.write(translate(hashedText))

     d1.update(d2) # combine dictionaries
     #with open('hash_dict.json', 'w') as f:
     #json.dump(d1, f)

     print("Hashing done. Starting translation...")

     translated = ''
     for line in tqdm(hashedText.splitlines()): #tqdm is a progressbar
         #print(line)
         if line.startswith("X#X") and len(line) == 7:
             translated = translated + line + '\n'
             continue
         if line == '\n':
             translated = translated + '\n'
         elif line == '':
             translated = translated + '\n'
         else:
             translated = translated+pydeepl.translate(line, "DE", "EN")+'\n'
     #translated = translated+pydeepl.translate(hashedText, "DE", "EN")
     #print(translated)

     d1Inv = {val:key for (key, val) in d1.items()} #swap dictionary
     translate2 = make_xlat(d1Inv)
     fileStrOut = translate2(translated)
     #print(fileStrOut)

     fileOut.write(fileStrOut)

     print("success")
     fileIn.close()
     fileOut.close()

EDIT 1: One flaw I already know is that I'm sending sentences by sentences which makes it really slow. However, sending all lines at once produces errors which I couldn't get rid of. Deepl scrambles stuff around and dehashign doesn't work anymore.


texts: Longest substring with 2 unique characters in a given string at linear time

texts:
This is my java implementation based on the solution of Aasmund Eldhuset here.
Please give your opinion on my code (correctness, efficiency and coding conventions):

public static String longest2Str(String s){
    int len;
    int i = 1;
    int subStart = 0;
    int nextGroupStart = 0;
    int longestStart = 0;
    int longestEnd = 0;
    char firstUnique, secondUnique, c;

    if ( (s == null) || (s.length() < 2) ) {
        return null;
    }

    len = s.length();
    firstUnique = s.charAt(subStart);

    // find first letter in s that isn't equal to the firstUnique
    for (; (i < len) && (s.charAt(i) == firstUnique); i++);

    secondUnique = s.charAt(i);
    for (; i < len; i++) {
        c = s.charAt(i);
        if ( (c == firstUnique) || (c == secondUnique) ) {
            if (c != s.charAt(i - 1)) {
                nextGroupStart = i;
            }
        }
        else {
            if ( i - subStart > longestEnd - longestStart ){
                longestStart = subStart;
                longestEnd = i;
            }
            subStart = nextGroupStart;
            nextGroupStart = i;
            firstUnique = s.charAt(subStart);
            secondUnique = c;
        }
    }

    return s.substring(longestStart, longestEnd);
}


texts: Macro to generate an enum and an array of strings

texts:
Often when I find myself working with magic number enum values and I want to know what they represent, so I create an array of strings in order to print out their label.

This macro automates that process.

//#define DEBUG
#define GENERATE_ENUM(ENUM) ENUM,
#define GENERATE_STRING(STRING) #STRING,
#define GENERATE_ENUM_LIST(MACRO, NAME) \
   enum NAME                            \
   {                                    \
      MACRO(GENERATE_ENUM)              \
   };

//#ifdef DEBUG
#define GENERATE_ENUM_STRING_NAMES(MACRO, NAME) \
   const char *NAME##_Strings[] = {             \
       MACRO(GENERATE_STRING)                   \
   };

//#else
//#define GENERATE_ENUM_STRING_NAMES(MACRO, NAME)
//#endif

To use do:

#include <stdio.h>

/* ~ The macro ~ */

#define nuclearLaunchCodes(T) \
  T(ONE) \
  T(TWO) \
  T(THREE)

GENERATE_ENUM_STRING_NAMES(nuclearLaunchCodes, nuclearLaunchCodesData)
#undef nuclearLaunchCodes

int main() {
  printf("%s\n", nuclearLaunchCodesData_Strings[0]);
}


texts: Configure Webpack to handle cache-busting

texts:
I'm not very familiar with webpack, and I was very afraid that what I implemented for cache busting would break something. What I have seems to work. When I open up the built folder, under pub, I see 3 files:

main.someHashHere.js
index.html
manifest.someOtherHashHere.js

Previously, before I implemented cache-busting, there was no index.html. (1) I'm wondering, is it supposed to show up in this folder with the other two js files? (In previous deployments, before adding cache-busting, it there was no index.html file there).

Here's what I have:

var path = require('path');
var webpack = require('webpack');
var AssetsPlugin = require('assets-webpack-plugin'); // *
var HtmlWebpackPlugin = require('html-webpack-plugin'); // *
var WebpackMd5Hash = require('webpack-md5-hash'); // *

var basePlugins = [
  new webpack.DefinePlugin({
    __PRODUCTION__: true,
    'process.env.NODE_ENV': JSON.stringify('production'),
  }),
];

var usedPlugins = [
  new webpack.optimize.OccurenceOrderPlugin(),
  new webpack.optimize.UglifyJsPlugin({
    compressor: {
      warnings: false,
    },
  }),
  new webpack.optimize.CommonsChunkPlugin({ // *
    names: "manifest" // *
  }), // *
  new AssetsPlugin(), // *
  new HtmlWebpackPlugin(), // *
  new WebpackMd5Hash(), // *
];

/* Config */
module.exports = {
  entry: {
    main: [path.join(__dirname, '/lib/main')],
  },
  eslint: {
    configFile: 'lib/.eslintrc',
  },
  resolve: {
    root: path.resolve(__dirname, 'lib'),
    alias: {
      ...
    },
  },
  output: {
    path: path.join(__dirname, '/pub/'),
    filename: '[name].[chunkhash].js', // *
    chunkFilename: '[name].[chunkhash].js', // *
    sourceMapFilename: '[name].js.map',
    publicPath: '/pub/',
  },
  plugins: usedPlugins,
  module: {
    preLoaders: [
      ...
    ],
    loaders: [
      ...
    ],
  },
};

Everything commented with an asterik was included for the sole purpose of cache-busting.

(2) What I'm most concerned about is whether or not I have added anything that will be breaking or have any unintended consequences?


texts: Calculate with numbers from different number systems

texts:
This program calculates with numbers from different number systems and outputs the result in the desired number system.

You call it like that:

java Calculator <operator> <number> <base> <otherNumber> <base> (solutionBase)

Unfortunately it does not work with floating point numbers.

Example:

$java Calculator + 5234 7 FABCD43 16 3
200022201200110011

My gut feeling says me that my code is quite ugly but it doesnt tell me how to improve it. Do you have some hints for me how to make this more beautiful?

public class Calculator {
    public static void main(String[] args) {
        // display usage if user wants so
        if (args[0].contains("help")) {
            displayHelp();
            return;
        }

        // parse arguments
        String operator = args[0];
        String number1 = args[1];
        int baseOfNumber1 = Integer.parseInt(args[2]);
        String number2 = args[3];
        int baseOfNumber2 = Integer.parseInt(args[4]);
        int baseOfSolution = 0;
        if (args.length == 6) {
            baseOfSolution = Integer.parseInt(args[5]);
        }

        int number1Dec = randomBaseToDecimal(number1, baseOfNumber1);
        int number2Dec = randomBaseToDecimal(number2, baseOfNumber2);

        // calculate and print out
        int solutionDec = 0;
        if (operator.equals("+")) {
            solutionDec = number1Dec + number2Dec;
        } else if (operator.equals("-")) {
            solutionDec = number1Dec - number2Dec;
        } else if (operator.equals("x")) {
            solutionDec = number1Dec * number2Dec;
        } else if (operator.equals("/")) {
            solutionDec = number1Dec / number2Dec;
        }

        if (args.length == 6) {
            System.out.println(decimalToRandomBase(solutionDec,
              baseOfSolution));
        } else {
            System.out.println(solutionDec);
        }
    }

    private static int randomBaseToDecimal(String number, int base) {
        int result = 0;
        for (int i = 0; i < number.length(); i++) {
            int digit = Character.getNumericValue(number.charAt(i));
            result = base * result + digit;
        }
        return result;
    }

    // works only till base 16
    private static String decimalToRandomBase(int number, int base) {
        StringBuilder finalNumber = new StringBuilder();
        while (number != 0) {
            if ((number % base) > 9) {
                switch ((number % base)) {
                    case 10: finalNumber.append("A"); break;
                    case 11: finalNumber.append("B"); break;
                    case 12: finalNumber.append("C"); break;
                    case 13: finalNumber.append("D"); break;
                    case 14: finalNumber.append("E"); break;
                    case 15: finalNumber.append("F"); break;
                }
            } else {
                finalNumber.append(number % base);
            }
            number = number / base;
        }
        return new StringBuilder(finalNumber).reverse().toString();
    }

    private static void displayHelp() {
        System.out.println("This program calculates with numbers of different bases");
        System.out.println("Example: ");
        System.out.println("java Calculator + 34 5 554 6");
        System.out.println("You can also specify the base of the output number as the last argument:");
        System.out.println("java Calculator + 34 5 554 6 2");
    }
}


texts:
I have a function that calculates the biggest number in an array after doing the following:

arrayManipulation(4, [[2, 3, 603], [1, 1, 286], [4, 4, 882]])

The array initially consists of only zeroes. The first parameter tells what the length of the array of 0s should be.

Here it's 4, so [0,0,0,0]

The second parameter is an array of arrays. Each nested array has 3 values. The start index, last index and the value to add to the zeroArray between the two indices. The zeroArray index starts from 1.

For example, in the beginning the zero array is [0,0,0,0]. Then from the nested array [2, 3, 603], add 603 at indices from 2 to 3. So the zero array becomes [0,603,603,0]. Then the second nested array is used. This is done till all the nested arrays are used.

After that's done, I need to find the biggest number in the zeroArray(its value now is [ 286, 603, 603, 882]) which here is 882.

I am trying this here, but it timed out.

function arrayManipulation(n, operations) {
    let zeroArray = Array(n);
    zeroArray.fill(0, 0, zeroArray.length);
    let biggest = 0;
    for (let j = 0; j < operations.length; j++) {

        let startIndex = operations[j][0];
        let endIndex = operations[j][1];
        let number = operations[j][2];
        for (let k = startIndex; k <= endIndex; k++) {
            zeroArray[k - 1] += number;
            if (biggest < zeroArray[k - 1]) {
                biggest = zeroArray[k - 1];
            }
            if (k == endIndex)
                console.log(startIndex, endIndex, number, JSON.parse(JSON.stringify(zeroArray)));
        }
    }
    console.log(biggest);
    return biggest;

}


texts: Sum of squares of 2 largest numbers out of a list of 3 numbers

texts:
The problem is:

  Define a procedure that takes 3 number arguments and returns the sum of the squares of the 2 largest numbers.

I am a CS graduate and I am revising my university notes. This is my code so far:

(define (square n) (* n n))

(define (square_of_larger_numbs a b c)
  (cond ((and (> a b) (> a c))
         (cond ((> b c)
         (+ (square a) (square b)))
               (else (+ (square a) (square c))))
        )(else (cond ((> b c)
                      (+ (square b) (square c)))
                      (else (+ (square b) (square c))))
               )
         )
  )

(display (square_of_larger_numbs 4 3 3))

It seems to be working but the code looks terrible unreadable. Please note that I am not allowed to sort yet, as the book I am reading hasn't mentioned sorting yet, so I assumed that sorting is not welcomed as a part of the solution.

How can I make this more efficient/ readable?


texts: Implementation of the square root for real time application

texts:
For the real time control software I need square root calculation. I have heard that the sqrt function from the standard library isn't good choice due to the unpredictable number of iterations used during calculation. Based on that information I have decided to implement the sqrt function in my own based on the Newton tangent method. So I have exploited the iteration formula
$$x_{k+1} = -\frac{f(x_k)}{f'(x_k)} + x_k,$$ where $$f(x) = x^2 - a$$ and $$a\in\mathbb R_0^+, a_{min} = 0.1, a_{max} = 400.0$$.
Based on the above mentioned formulas I have
$$x_{k+1} = \frac{1}{2}\cdot\left(x_k + \frac{a}{x_k}\right)$$
I have chosen $$x(0) = 2$$ and based on my observations four iterations give good results in comparison with the sqrt from the standard library.
#define ITERATIONS 4

double squareRoot(double a)
{
    double xk  = 2.0; // x(k)

    uint8_t k;
    for(k = 0; k < ITERATIONS; k++)
    {
        xk  = 0.5*(xk + a/xk);
    }

    return xk;
}

Despite that fact I have some doubts regarding the choice of the initial value and number of iterations.


texts: Editing system files in Linux (as root) with GUI and CLI text editors

texts:
My intention is to POSIX-ly write one generalized function for running various text editors I use for different purposes through sudoedit, i.e. editing files as root safely. Safely = for instance, if a power loss occurs during the file edit; another example could be lost SSH connection, etc.

Originally, I had these Bash functions defined for this purpose in my .bash_aliases file:

function sucode
{
    export SUDO_EDITOR='/usr/bin/code --wait'
    sudoedit "$@"
}
function susubl
{
    export SUDO_EDITOR='/opt/sublime_text/sublime_text --wait'
    sudoedit "$@"
}
function suxed
{
    export SUDO_EDITOR='/usr/bin/xed --wait'
    sudoedit "$@"
}

Since yesterday, I'm trying to generalize that solution for other Linux users to be able to take advantage of it. Momentary peek:

# Text editing as root; The proper way through `sudoedit`.
sudoedit_internal()
{
    [ "${#}" -lt 3 ] && { printf '%s\n' 'sudoedit_internal(): Invalid number of arguments.' 1>&2; return; }
    editor_path=$( command -v "${1}" )
    [ -x "${editor_path}" ] || { printf '%s\n' "sudoedit_internal(): The editor path ${editor_path} does not exist on this system." 1>&2; return; }
    editor_wait_option=${2}
    shift 2
    env SUDO_EDITOR="${editor_path} ${editor_wait_option}" sudoedit "${@}"
}
# CLI
suvi()   { sudoedit_internal vi   '' "${@}"; }
sunano() { sudoedit_internal nano '' "${@}"; }
# GUI
sucode() { sudoedit_internal code -w "${@}"; }
susubl() { sudoedit_internal subl -w "${@}"; }
suxed()  { sudoedit_internal xed  -w "${@}"; }

These 5 editors I use. Please take that as an example only.

As I should not update this question any further, you can find the up-to-date version of this script snippet in my Unix & Linux Answer.


texts:
For my models for a certain section I thought it would be better to have a base class model for both "view" and "edit" models, like so:

public abstract class Setting
{
    [Required]
    public int SettingId { get; set; }

    public string Name { get; set; }

    [Required]
    [MaxLength(255)]
    public string Value { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedDt { get; set; }
}

public class ViewSetting : Setting
{
}

public class EditSetting : Setting
{
}

So in my Service or Views I use the appropriate ViewSetting or EditSetting. Right now I don't have anything that would be different - but should I follow a pattern like this to maintain a separation of concerns here? Or should I just stick to using one Setting class? (as an aside, I'm using Entity Frameworks but in my Service layer is where I convert to/from the models for the ORM)


texts:
Here's a program I made for estimating a double integral over a general region. It's pretty accurate, but it's VERY, VERY slow. (Getting an accurate enough result takes about 30 seconds)

Here's the code; the lines are indented just for readability.

ClrHome
Input "Surface: ",Str0
Str0→Y₈
Input "y-Bound 1: ",Str0
Str0→Y₉
Input "y-Bound 2: ",Str0
Str0→Y₀
Input "X1: ",A
Input "X2: ",B
Input "Num of intv: ",N
(B-A)/N→D
0→V
For(K,0,N-1
    A+KD+.5D→X
    V+fnInt(abs(Y₀-Y₉),X,A+KD,A+(K+1)D)fnInt(Y₈,Y,Y₀(X),Y₉(X))/(Y₀(X)-Y₉(X→V
End
DelVar DDelVar XDelVar YDelVar Str0
Disp "
Disp "Volume in R: ",V

Variables explained:

Str0: Arbitrary (input)
Y₈: Equation of surface f(x,y)
Y₉: Equation of one bound of region R
Y₀: Equation of other bound of region R
A: x-value of left bound of region R (input)
B: x-value of right bound of region R (input)
N: Number of Δx intervals (input)
D: Size of Δx interval
X: x-value of midpoint of Δx interval
V: Volume under the surface f(x,y) bound by the region R (output)

Basically, how I'm tackling it is I'm taking a slice of the region R on the x-y plane (Δx is the width) and finding its area (fnInt(abs(Y₀-Y₉),X,A+KD,A+(K+1)D)). Then I find the x-value that's the middle of that slice, and I find the average z-value along that x (fnInt(Y₈,Y,Y₀(X),Y₉(X))/(Y₀(X)-Y₉(X))), which I assume to be a reasonable estimate for the height of that entire slice of volume. Then I run a For( loop a bunch of times and add up all of the slices together to find the total volume.

But the problem is that I need lots of intervals (about 50-100) to get an accurate enough answer, which takes a ridiculous amount of time.

I already tried to optimize it a little by getting around all the expr('s I used to have, but it's still very very slow.

Any suggestions on optimizing?


texts: Given a string, return n distinct characters with their respective counts, as well as the remainder of the string

texts:
Going through some old code, I found this function.

Given a string carrier and integer nsyms, it consumes nsyms distinct characters from the carrier string and returns a dictionary containing consumed characters and their respective counts, and the remainder of the carrier string.

def enc_consume(carrier, nsyms):
  chrs = defaultdict(int)

  i = 0  # see this?

  for i,c in enumerate(carrier):
    # `i` is not used in the loop
    chrs[c] += 1
    if len(chrs) == nsyms:
      break

  return chrs, carrier[i+1:]  # but it's used here

How would you rewrite this? I found the assignment i = 0 confusing, since it was followed by a for i..., which will of course do the assignment as well.

EDIT: The point of the explicit assignment i = 0 is that if carrier is empty, the loop will not execute. If it weren't for the assignment, i would be undefined by the time it is used in return.


texts: Using Linq instead of multiple foreach loops

texts:
A project I'm working on often has lists within lists within lists etc.  The original author often uses complicated linq expressions, but when adapting them I mostly get hopelessly bogged down and resort to foreach's which makes me feel like a lesser being (joke).  With an expression such as the following, what would the equivalent Linq expression be, and would you bother taking the time to make it, instead of the 'easy' foreach option.

        var participantList = new List<string>();

        foreach (var community in communities)
        {
            foreach (var tournament in community.Tournaments)
            {
                foreach (var round in tournament.Rounds)
                {
                    foreach (var match in round.Matches)
                    {
                        if (match.Home.ParticipantId.IsNotNull())
                        {
                           participantList.Add(match.Home.ParticipantId);
                        }
                        if (match.Away.ParticipantId.IsNotNull())
                        {
                           participantList.Add(match.Away.ParticipantId);
                        }
                    }

                }
            }
        }


texts: 3-way multiplexer built on 2-way multiplexers in Verilog

texts:
I created this project on EDA Playground that builds a variable-width 3-way multiplexer out of 2 variable-width 2-way multiplexers. It will be part of homework that I assign, so I want to follow all best practices. I followed the lowRISC Verilog Coding Style Guide.
Design Modules
module mux2 #(
  parameter Width = 4
) (
  input              control,
  input [Width-1:0]  a,
  input [Width-1:0]  b,
  output [Width-1:0] y
);

  assign y = control ? b : a;

endmodule

module mux3 #(
  parameter Width = 4
) (
  input [1:0]        control,
  input [Width-1:0]  a,
  input [Width-1:0]  b,
  input [Width-1:0]  c,
  output [Width-1:0] y
);

  wire [Width-1:0] mux_a_out;

  mux2 #(
    .Width   (Width)
  ) mux_a (
    .control (control[0]),
    .a       (a),
    .b       (b),
    .y       (mux_a_out)
  );

  mux2 #(
    .Width   (Width)
  ) mux_b (
    .control (control[1]),
    .a       (mux_a_out),
    .b       (c),
    .y       (y)
  );

endmodule

Test Module
module test;
  reg[1:0] control;
  reg[7:0] a;
  reg[7:0] b;
  reg[7:0] c;
  reg[7:0] y;

  mux3 #(
    .Width(8)
  ) mux3(
    .control (control),
    .a       (a),
    .b       (b),
    .c       (c),
    .y       (y)
  );

  initial begin
    a = "A";
    b = "B";
    c = "C";

    for (int i = 0; i < 3; i++)
      begin
        control = i;
        #1
        $display("When Control = %d, Y = %c", control, y);
      end
  end

endmodule


texts: Code Challenge: basic arithmic operations using only incrementation operator

texts:
Challenge

  Write a function that takes 2 integer operands left and right
  (both >= 0) and evaluates one of the following basic arithmic
  operations:

  addition
  multiplication
  exponentation

  The challenge is you are prohibited from using any built-in operator,
  except for an incrementation (++ or +1). The entropy is all
  results that are in bounds of the maximum value of an integer.

Provided Classes

public enum Operation
{
    Addition,
    Multiplication,
    Exponentation
}

public static class Expression
{
    public static int Evaluate(int left, int right, Operation operation)
    {
        throw new NotImplementedException(); // .. this should be implemented
    }
}

Unit Tests

[TestClass]
public class Fixtures
{
    [TestMethod]
    public void Fixture()
    {
        Assert.AreEqual(5, Expression.Evaluate(2, 3, Operation.Addition));
        Assert.AreEqual(6, Expression.Evaluate(2, 3, Operation.Multiplication));
        Assert.AreEqual(8, Expression.Evaluate(2, 3, Operation.Exponentation));
    }
}

My Solution

I have decided to use the hyperoperation (Wikipedia Link). The only arithmic operator used is in the first branch (if (n == 0) -> b + 1).

  $$ H_n(a,b) = a[n]b =
 \begin{cases}
                       b + 1 & \text{if } n = 0 \\
                           a & \text{if } n = 1 \text{ and } b = 0 \\
                           0 & \text{if } n = 2 \text{ and } b = 0 \\
                           1 & \text{if } n \ge 3 \text{ and } b = 0 \\
   H_{n-1}(a, H_n(a, b - 1)) & \text{otherwise}
 \end{cases}$$

And my implementation of Evaluate:

public static class Expression
{
    public static int Evaluate(int left, int right, Operation operation)
    {
        return Hyper(left, (int)operation + 1, right);
    }

    static int Hyper(int a, int n, int b)
    {
        // https://en.wikipedia.org/wiki/Hyperoperation
        // a = left operand   (a >= 0)
        // n = hyper operator (n >= 0)
        // b = right operand  (b >= 0)

        if (a < 0) throw new ArgumentOutOfRangeException(nameof(a));
        if (b < 0) throw new ArgumentOutOfRangeException(nameof(b));
        if (n < 0) throw new ArgumentOutOfRangeException(nameof(n));
        if (n == 0) return b + 1;
        if (b == 0) return n == 1 ? a : n == 2 ? 0 : 1;

        return Hyper(a, n - 1, Hyper(a, n, b - 1));
    }
}

Questions

Are there any overlooked flaws in my solution?
Could this be optimized for performance?
Are there perhaps better alternatives, and why would they be better?
Any general review of my code, style, conventions are invited.


texts:
Is this query acceptable in terms of performance (I get the correct data) or can it be optimized?

SELECT
    bankInstitution.name,
    person.firstName,
    person.surname,
    offer.offerId,
    bank.personId,
    bank.bankOtherName,
    bank.sortCode,
    bank.number,
    loan.loanId
    offer.campaignId,
FROM bank
    JOIN loan ON bank.personId = loan.personId AND bank.isCurrent = 1
    JOIN offer ON loan.loanId = offer.loanId
    JOIN person ON person.personId = bank.personId
    JOIN bankInstitution ON bankInstitution.bankInstitutionId = bank.bankInstitutionId
WHERE offer.CampaignId = 1 AND offer.Processed Is NULL


texts: Getting matching items in lists based on nullable properties

texts:
I'm iterating through two lists to find matching objects. The objects have two string properties, Id1 and Id2 below. If Id1 is not null, empty or whitespace, I want to use it to find a matching object in the other list. Otherwise I want to make use of Id2.

If both Id1 and Id2 are set to null by the extension method on either p or p2, I want to skip the iteration, since I know that I won't find a match.

public static string NullIfEmptyOrWhiteSpace(this string value)
{
    return string.IsNullOrEmpty(value) ? null : value;
}

foreach (Product p2 in productList1)
{
    Product match = productList2.FirstOrDefault(p =>
    {
        string pId = p.Id1.NullIfEmptyOrWhiteSpace() ??
                     p.Id2.NullIfEmptyOrWhiteSpace();

        string p2Id = p2.Id1.NullIfEmptyOrWhiteSpace() ??
                      p2.Id2.NullIfEmptyOrWhiteSpace();

        if (pId == null || p2Id == null)
            return false;

        return pId.Equals(p2Id);
    });

    // do stuff with match
}

This seems to work, but it feels like I'm re-inventing the wheel here. Are there any built in methods that I can make use of to simplify the code? Perhaps a class that implements IEqualityComparer?

Example use case:

List<Product> list1 = new List<Product>()
{
    new Product() { Id1 = "123", Id2 = null },
    new Product() { Id1 = "435", Id2 = null },
    new Product() { Id1 = null, Id2 = "123" }
}

List<Product> list12 = new List<Product>()
{
    new Product() { Id1 = "123", Id2 = null },
    new Product() { Id1 = "456", Id2 = null },
    new Product() { Id1 = null, Id2 = "123" }
}

// do something with each matching item in the first list
// which would be item #1 and item #3 above


texts: AVX512 - Add two 512-bit integers using _addcarryx_u64 function

texts:
My purpose is to add two __m512i variables (c = a + b) as efficiently as possible. To do so, I'd like to use the _addcarryx_u64 function which takes uint64_t as inputs.

unsigned char _addcarryx_u64 (unsigned char c_in,
                              unsigned __int64 a,
                              unsigned __int64 b,
                              unsigned __int64 * out)

I manage to obtain a working function based on buffers:

__m512i _m512_add(const __m512i a, const __m512i b)
{
    const size_t n = sizeof(__m512i) / sizeof(uint64_t);
    uint64_t buf_a[n], buf_b[n], buf_c[n];

    _mm512_storeu_si512((__m512i *)buf_a, a);
    _mm512_storeu_si512((__m512i *)buf_b, b);

    unsigned char c_in = 0;

    for (unsigned i = n-1; i < n; --i)
        c_in = _addcarryx_u64(c_in, buf_a[i], buf_b[i], &(buf_c[i]));

    return _mm512_setr_epi64(buf_c[0], buf_c[1], buf_c[2], buf_c[3],
                             buf_c[4], buf_c[5], buf_c[6], buf_c[7]);
}

But it is not as efficient as I expected. Note that I compare timing and result with the GMP library and another function (based on intrinsics functions but not _addcarryx_u64) that I previously wrote.

My question is the following, is there a more efficient way to access the different uint64_t than using some buffers?
I was thinking like a table (a[i]) or using extraction functions but didn't find anything satisfying my needs / didn't manage to do it.


texts: Simplifying Counter of Checked Checkboxes

texts:
Is the following code a proper solution to my problem? I have a feeling it can be simplified quite a bit.

  If one of the first four checkboxes is checked the sum is 1; if two 1.5; if three 2; if four 2.5. If the bar5 is checked then it's 1 + calculated value of first four (if any is checked). Afterwards, multiply by 100.

function checkboxCount() {
 var form = document.forms["calculator"];
 var bar5 = form.elements["bar5"];
 var foo = document.querySelectorAll("input[name=foo]");
 count = 0;

 for (var i = 0; i < foo.length; i++) {
  if (foo[i] && foo[i].checked == true) {
   count++;
  }
 }
 if (count == 1 && bar5.checked == true) {
  count = 1;
 } else if (count == 1) {
  count = 1;
 }
 if (count == 2 && bar5.checked == true) {
  count = 2;
 } else if (count == 2) {
  count = 1.5;
 }
 if (count == 3 && bar5.checked == true) {
  count = 2.5;
 } else if (count == 3) {
  count = 2;
 }
 if (count == 4 && bar5.checked == true) {
  count = 3;
 } else if (count == 4) {
  count = 2.5;
 }
 if (count == 5 && bar5.checked == true) {
  count = 3.5;
 }
 return count;
}

function calculateTotalCost() {
 var totalCost = 0;
 var printCost = document.getElementById('calculatedCost');
 totalCost = 100 * checkboxCount();

 printCost.innerHTML = "$" + totalCost;
}
<form id="calculator">

<fieldset>
<input type="checkbox" name="foo" id="bar1" onclick="calculateTotalCost()">Bar 1
<input type="checkbox" name="foo" id="bar2" onclick="calculateTotalCost()">Bar 2
<input type="checkbox" name="foo" id="bar3" onclick="calculateTotalCost()">Bar 3
<input type="checkbox" name="foo" id="bar4" onclick="calculateTotalCost()">Bar 4
<input type="checkbox" name="foo" id="bar5" onclick="calculateTotalCost()">Bar 5
</fieldset>

</form>


texts: Noughts and crosses command line game in Python 3.5

texts:
Based on this Code Review answer, I have created a noughts and crosses game in Python, which asks for an index (1 to 9) and updates the grid, and displays it on the screen. I have done some very untidy programming in places, and would please like some help on how to make it more readable, and avoid repeating statements, such as print_grid(). Also I would like to make the 'Change player' part more simple. Any other constructive criticism or improvements also gratefully recieved.

winning_lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6),
             (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]

def get_turn(player):
    return int(input("Player %d: " % player).strip()) - 1

def format_player(num):
    return ' OX'[num]

def print_grid(board):
    """Formats and prints the grid."""

    print('\n'
          '{}│{}│{}\n'
          '─┼─┼─\n'
          '{}│{}│{}\n'
          '─┼─┼─\n'
          '{}│{}│{}\n'
          '\n'
          .format(*board))

def check_for_win(board, player):
    """Returns True for win, anything else, False"""
    for winning_line in winning_lines:  # Take all possible winning lines one by one
        for pos in winning_line: # Test each index of the winning line
            if board[pos] != format_player(player):
                break
        else: return True
    return False

def play_game():
    player = 1
    board = [" "] * 9

    while True:
        print_grid(board)
        place = get_turn(player)
        if place in range(9) and board[place] == " ":
            board[place] = format_player(player)

            if check_for_win(board, player):
                print_grid(board)
                return player

            # Change player

            if player == 1:
                player = 2
            else:
                player = 1

winner = play_game()

print("Player %d wins!" % winner)


texts: Looking up a hostname for a given path and client ID

texts:
I have this code in my library and I wanted to see whether we can avoid duplicating stuff.

private String getAddress(final String path, final int clientId) {
    if (TestUtils.isEmpty(mapping) || TestUtils.isEmpty(mapping.get(path))  || TestUtils.isEmpty(mapping.get(path).get(clientId))) {
        logger.logError("mapping must not be empty. full path= ", path, ", clientId= ", clientId, ", Mapping= ",
                mapping);
        return null;
    }
    final int localId = mapping.get(path).get(clientId);
    final String hostname = getHostname(path, localId);
    return hostname;
}

Here mapping is defined as,

private final Map<String, Map<Integer, Integer>> mapping;

Is there anything we can improve in the above code? I do see duplicated stuff as I am checking in the if statement and then using same thing just below it.


texts:
I wish to transpose a square matrix, permanently overwriting it.
This is not the same as creating a 2nd matrix with the transposed contents of the 1st matrix.

I call the procedure with 3 parameters: the address of the original matrix, its rank, and the address of a scratch buffer that is large enough.
First, all the elements are spread out over the scratch buffer. Later the scratch buffer is copied back to the original storage.

How can I optimize this code?

; TransposeSquareMatrix(Address, Rank, Scratch)
Q:  push    ebp
    mov     ebp, esp
    push    ecx edx esi edi
    mov     esi, [ebp+8]    ; Address
    mov     edx, [ebp+12]   ; Rank
    mov     edi, [ebp+16]   ; Scratch buffer
    lea     eax, [edx-1]    ; Additional address increment
.a: push    edi             ; (1)
    mov     ecx, [ebp+12]   ; Rank
.b: movsb                   ; Spreading out the elements of one row
    add     edi, eax
    dec     ecx
    jnz     .b
    pop     edi             ; (1)
    inc     edi
    dec     edx
    jnz     .a              ; Repeating it for every row
    mov     edi, [ebp+8]    ; Address
    mov     ecx, [ebp+12]   ; Rank
    imul    ecx, ecx
    mov     esi, [ebp+16]   ; Scratch buffer
    rep movsb               ; Overwriting the original matrix
    pop     edi esi edx ecx
    pop     ebp
    ret     12
; --------------------------


texts: Group by consecutive values in first column and second column value

texts:
I have a typing log in which rows are grouped by consecutive package_name, and within those groups rows are grouped if they are logged within 180,000 ms from each other. This is working but is there a cleaner way to achieve it? An edge case would be when more than 1000 consecutive episodes are logged for the same package_name (though I think it is unlikely).

library(dplyr)

metrics <- data.frame(timestamp = c(seq(100000, 100200, by=100), seq(200000, 200200, by=100), seq(400300, 400304, by=1), seq(600400, 600600, by=100), seq(800700, 800900, by=100)),
                      package_name = c(rep("package1", 3), rep("package2", 3), rep("package2", 5), rep("package2", 3), rep("package1", 3)))

metrics <-  metrics %>%
     mutate(typing_episode = ifelse(package_name != lag(package_name), 1, 0),
     typing_episode = ifelse(is.na(typing_episode), 0, typing_episode),
     typing_episode = cumsum(typing_episode) + 1) %>%
     group_by(typing_episode) %>%
     mutate(time_diff2 = timestamp - lag(timestamp),
             time_diff2 = ifelse(is.na(time_diff2), 0, time_diff2),
             second_group = ifelse(time_diff2 > (1000 * 60 * 3), 1, 0),
             second_group = cumsum(second_group) + 1,
             typing_episode2 = typing_episode * 1000 + second_group)

print(metrics)


texts:
I needed to get the minimum and maximum date values from a query using the Sequel ORM in Ruby from my database. Sequel has a range method that returns a Range value. I'm having it return values from a timestamp field, so they're coming back as a range of Time objects.

In order to split it into two variables using parallel assignment, I figured this was about as concise and succinct as I could get:

template_min_datestamp, template_max_datestamp = [Template.range(:created_at)].map{ |r| [r.min, r.max] }

I considered using:

template_min_datestamp, template_max_datestamp = Template.min(:created_at), Template.max(:created_at)

but that'd cause two hits to the database, which just makes my eye twitch.

Simplifying it for the innocent, and factoring out the ORM calls, it'd look something like this in regular Ruby:

t1 = Time.parse('Jan 1, 2013 12:00:00 -700')
t2 = Time.parse('Jan 31, 2013 12:00:00 -700')
template_min_datestamp, template_max_datestamp = [t1..t2].map{ |r| [r.min, r.max] }

It seems like there'd be a more direct way to break apart a range into two elements on one line using parallel assignment, but it's escaping me right now.

Anyone got some enlightenment to share?


texts: Scheduling a task into a period within a day, depending on whether or not it is a weekend

texts:
I have a function which needs to detect part of the day depending on whether it's the weekend or not (the weekend affects the lunch time indication). The method is quite long and I'd like to know how it can be better.

double PartOfDayRule::ExtractFeature(dto::ActionableItem & item) {
                double morning, firstWorkPart, lunch, secondWorkPart, afterWork, beforeSleep, sleepTime;
                morning = 0;
                firstWorkPart = 1;
                lunch = 2;
                secondWorkPart = 3;
                afterWork = 4;
                beforeSleep = 5;
                sleepTime = 6;

                double result = -1;
                dto::DateTime itemTime = item.scheduledStart;
                if(util::time::inRange(item.ctx->sleepTimeEnd, item.ctx->workTimeStart, itemTime)){
                    result = morning;
                    goto result;
                }

                dto::DateTime lunchStart;
                dto::DateTime lunchStop;
                if(!item.ctx->isWorkingDay){
                    lunchStart = item.ctx->workTimeStart;
                    lunchStop = item.ctx->workTimeFinished;
                }else{
                    long firstWorkPartLength = util::time::between<std::chrono::hours>(item.ctx->workTimeStart, item.ctx->workTimeFinished) / 2;
                    lunchStart = item.ctx->workTimeStart + std::chrono::hours{firstWorkPartLength};
                    lunchStop = lunchStart + std::chrono::hours{1};
                }
                if(util::time::inRange(lunchStart, lunchStop, itemTime)){
                    result = lunch;
                    goto result;
                }

                if(util::time::inRange(item.ctx->workTimeStart, lunchStart, itemTime)){
                    result = firstWorkPart;
                    goto result;
                }

                if(util::time::inRange(lunchStop, item.ctx->workTimeFinished, itemTime)){
                    result = secondWorkPart;
                    goto result;
                }

                dto::DateTime sleepPreparationTime = item.ctx->sleepTimeStart - std::chrono::hours{1};
                if(util::time::inRange(item.ctx->workTimeFinished, sleepPreparationTime, itemTime)){
                    result = afterWork;
                    goto result;
                }

                if(util::time::inRange(sleepPreparationTime, item.ctx->sleepTimeStart, itemTime)){
                    result = beforeSleep;
                    goto result;
                }

                result = sleepTime;
                result:
                return result;

            }


texts:
I recently read a really interesting post on adding functional pattern matching to C#. Here's a quick and dirty implementation using delegates and dictionaries.

Right now, I require that Match return an object of type TReturn. Is there any way I can easily extend my current implementation to be void (i.e. Match is not required to return anything) without significant code duplication? When I first tried this, I ended up essentially copying Match but omitting the second type parameter.

/// <summary>
/// Represents a switch on TIn.
/// </summary>
public class Match<TIn, TReturn>
{
    private Dictionary<Type, Delegate> funcs =
        new Dictionary<Type, Delegate>();

    private Dictionary<TIn, TReturn> values =
        new Dictionary<TIn, TReturn>();

    private TReturn _else;

    /// <summary>
    /// Adds a case, action pair
    /// </summary>
    public void Case<T>(Func<T, TReturn> func)
        where T : TIn
    {
        funcs[typeof(T)] = func;
    }

    /// <summary>
    /// Adds a case, value pair
    /// </summary>
    public void Case(TIn x, TReturn value)
    {
        values[x] = value;
    }

    /// <summary>
    /// Adds the default case value
    /// </summary>
    public void Else(TIn x, TReturn value)
    {
        _else = value;
    }

    /// <summary>
    /// Evaluates the match on a query
    /// Returns an object of type TReturn
    /// for first successful match
    /// </summary>
    public TReturn Eval<T>(T query)
        where T : TIn
    {
        TReturn value;
        if (values.TryGetValue(query, out value))
            return value;

        Delegate func;
        if (funcs.TryGetValue(query.GetType(), out func))
            return (TReturn)func.DynamicInvoke(query);

        return _else;
    }
}

And here's a simple test. One thing I was wondering: is it inefficient to declare a new Match inside the Calculate method?

class Program
{
    public static double Calculate(Expression exp)
    {
        var match = new Match<Expression, double>();
        match.Case<Num>((x) => x.Value);
        match.Case<Mul>((x) => Calculate(x.Left) * Calculate(x.Right));
        match.Case<Add>((x) => Calculate(x.Left) + Calculate(x.Right));
        return match.Eval(exp);
    }

    public static void Main(string[] args)
    {
        Expression tree = new Add(new Add(new Num(1), new Num(2)), new Mul(new Num(3), new Num(4)));
        double x = Calculate(tree) // = 15
    }
}

abstract class Expression
{
    public double Value;
}

abstract class BinaryExpression : Expression
{
    public Expression Left;
    public Expression Right;

    public BinaryExpression(Expression left, Expression right)
    {
        Left = left; Right = right;
    }
}

class Add : BinaryExpression
{
    public Add(Expression left, Expression right)
        : base(left, right)
    {
    }
}

class Mul : BinaryExpression
{
    public Mul(Expression left, Expression right)
        : base(left, right)
    {
    }
}

class Num : Expression
{
    public Num(double x)
    {
        Value = x;
    }
}


texts:
In my answer to this question, I wrote a new solution.  Personally, I would not use a stack, but given that a stack was required, how good is this solution?

In this solution, I add half of the word, not including the middle character if applicable, to the stack and remove it from the string.  If there is a middle character in the total string, the sizes of the string and the stack are not equal, and the middle character is at the beginning of the string, making it easy to delete (we don't need to compare it to itself, do we?).  Then, I iterate through the stack, comparing the top of the stack to the beginning of the string; if they are equal, I remove the character from the stack and the string, and continue; otherwise, I return false;.  If there are no characters left in the stack, I return true;.

bool isPalindrome(string word) {

    stack<char> s;
    for (int i = 0; i <= word.size() / 2; i++) {
        s.push(word[0]);
        word.erase(0, 1);
    }

    if (word.size() > s.size()) {
        word.erase(0, 1);
    }

    if (s.size() == 0) {
        return true;
    }

    while (s.size() > 0) {

        if (s.top() == word[0]) {
            s.pop();
            word.erase(0, 1);

            // return true only when our stack is empty
            if (s.size() == 0 || word.size() == 0) {
                return true;
            }
        }
        else {
            return false;
        }
    }
}


texts: Find the closest number in a sorted list to a given target number

texts:
Given a list of n integers sorted in ascending order, find the closest
  number (value) in the list to a given target number. How quickly can
  you do it?

I'm interested to know if there's any feedback for my code.

def getClosestValue(arr, target):
    n = len(arr)
    left = 0
    right = n - 1
    mid = 0

    # edge case
    if (target >= arr[n - 1]):
        return arr[n - 1]
    # BSearch solution: Time & Space: Log(N)

    while (left < right):
        mid = (left + right) // 2 # find the mid

        if (arr[mid] == target):
            return arr[mid]

        if (target < arr[mid]):
            # If target is greater than previous
            # to mid, return closest of two
            if (mid > 0 and target > arr[mid - 1]):
                return findClosest(arr[mid - 1], arr[mid], target)
            # update right
            right = mid
        else:
            if (mid < n - 1 and target < arr[mid + 1]):
                return findClosest(arr[mid], arr[mid + 1], target)
            # update i
            left = mid + 1
    return arr[mid]

# findClosest
# We find the closest by taking the difference
# between the target and both values. It assumes
# that val2 is greater than val1 and target lies
# between these two.

def findClosest(val1, val2, target):
    if (target - val1 >= val2 - target):
        return val2
    else:
        return val1

# Sample code
arr = [1, 2, 3, 4, 5, 5, 8, 10]
target = 7
print(getClosestValue(arr, target))


texts: Getting all likes from a specific user on a news wall with fewer graph API calls

texts:
Right now, my solution counting likes of a specific user is

Starting a recursive call on the "/{user-id}/posts" edge
Iterate through all posts
On each post iterate through each like on the likes edge

If someone knows a better, easier way with less graph API calls necessary, please let me know!

/*
*
*   Count my_user_id likes in wall of user "123"
*
*   ex: url = /123/posts
*
*   setTimeout to avoid exceed api level rate limit, code 613
*/

function findMyLikes(url,my_user_id,count,callback) {
    console.log(url);
    FB.api(url, function (response) {
        if (response.data) {
            response.data.forEach(function (post) {
                //console.log(post);
                if (post.likes) {
                    post.likes.data.forEach(function (like) {
                        if (like.id == my_user_id) {
                            count++;
                        }
                    });
                }
            });
        }

        if (response.paging && response.paging.next) {
            setTimeout(function() {findMyLikes(response.paging.next,my_user_id,count,callback)},1000);
        } else {
            callback(count);
        }
    });

};


texts: I need a better way to add css per each page on wordpress

texts:
I just started to use WordPress to start building a website, but as I need to use the get_header() function to retrieve the <head> content and I have a very large project, I wanted to put a CSS file depending on the page that is being displayed. After a few tries I came up with a solution, but I think that I can do it in a better way and I need your help to optimize it.
Here is my PHP snippet that goes into the functions.php file:
function website_files_per_page() {
    $pagelist = get_pages();
    $index = sizeof($pagelist);
    while ($index --) {
        $pagename = $pagelist[$index]->post_name;
        if (is_page($pagename)){
            $styleName = "website_".$pagename."_styles";
            $styleDir = get_theme_file_uri("/style/".$pagename.".css");
            wp_enqueue_style($styleName, $styleDir);
            break;
        }
    }
}
add_action("wp_print_styles", "website_files_per_page");


texts: Is this use of an array of function names and bracket-notation function calling a hacky/evil solution?

texts:
Background: I was making a chrome extension that injects movie ratings into theatres' showtimes pages. The problem I was duplicating a lot of code calling similar but just slightly different functions. Sometimes I wanted to do an $(el).prepend, sometimes $(el).append, or $(el).after, or $(el).find('something').prepend, or $(el).closest('something').prepend/append/after.

An example of an instance of a function I'm trying to generalize/abstract:

$('.FFEC-Display').each(function(i, el){
    var title = $(el).find('h3').text().replace(blacklistRegexp, '').trim();
    /* can ignore the three lines below, they are always the same
    var tomato = findTomato(title, tomatoes);
    var classes = ["poster-width", "overlay"];
    var templateData = tomato ? prepareData(tomato, classes) : { query: title, classes: namespaceClasses(classes) };
    */
    $(el).find('.movie-link').prepend(Handlebars.templates.ratings(templateData)); //this is the line that gives me trouble
});

Another instance:

$('.MovieItemsRotator .item').each(function(i, el){
    var title = $(el).find('.Title').text().replace(blacklistRegexp, '').trim();
    /* you can ignore the code in here
    var tomato = findTomato(title, tomatoes);
    var classes = ["overlay", "overlay-poster"];
    var templateData = tomato ? prepareData(tomato, classes) : { query: title, classes: namespaceClasses(classes) };
    */
    $(el).prepend(Handlebars.templates.ratings(templateData));
});

I have three more instances of very similar functions, and plan on adding more. Full code page here on GitHub

One of the half-joking answers in my SO question inspired me to write a solution using strings of function names, iteratively called on $(el) to solve the problem.

It started out as an exercise just because it seemed like too fun a solution not to try and write, but now I'm feeling more tempted to actually use the code, as opposed to this other one, which seems much more readable/maintainable. Hopefully people with more experience can give me some advice.

The code in question:

json = [
  {target: '.FFEC-Display', title : 'h3', actions : [{action: 'find', target: '.movie-link'}, 'prepend']},
  {target: '.MovieItemsRotator .item', title: '.Title', actions: ['prepend']}
];

$.each(json, function(index, j){
  $(j.target).each(function(i, el){
    var title = $(el).find(j.title).text().replace(blacklistRegexp, '').trim();
    /* you can ignore the code in here
    var tomato = findTomato(title, tomatoes);
    var classes = ["poster-width", "overlay"];
    var templateData = tomato ? prepareData(tomato, classes) : { query: title, classes: namespaceClasses(classes) };
    */
    var abomination = $(el);
    $.each(j.actions, function(k, action){
      if(typeof action === "string") {
        abomination = abomination[action]();
      } else {
        abomination = abomination[action.action](action.target);
      }
    });
    abomination(Handlebars.templates.ratings(templateData));
  });
});


texts:
This is a basic command line program that, given a number, returns a list of primes up to and including that number. Also handles a lack of command line arguments and non-number arguments.

I ran into a bunch of problems with Options while I was writing this, which led to me using unwrap() out of desperation. I'd rather never use unwrap, and instead handle None or Err or whatever. Additionally, I'd prefer not to have everything so mutable.

// A bad implementation of the Sieve of Eratosthenes

// Usage:
//  primesTo x = comma-separated list of all primes up to x

use std::env;

// Returns a vector of primes from 2 to max
fn primes_to(max: u32) -> Vec<u32> {
    let mut all: Vec<u32> = (2..max+1).collect();
    let mut primes: Vec<u32> = vec!();

    while all.len() > 0 {
        let (a, b) = sieve(all, primes);
        all = a;
        primes = b;
    }
    primes
}

// Sieve a non-empty list
fn sieve(list: Vec<u32>, mut primes: Vec<u32>) -> (Vec<u32>, Vec<u32>) {
    // We have a Vec<u32>
    // We want a u32 and a Vec<u32>
    let mut i_list = list.into_iter();
    let head: u32 = i_list.next().unwrap();
    let mut tail: Vec<u32> = i_list.collect();
    tail.retain(|&x| x % head != 0);
    primes.push(head);
    (tail, primes)
}

fn prettyprint_primes(mut primes: Vec<u32>) -> () {
    let temp = primes.pop().unwrap();
    for prime in primes {
        print!("{:}, ", prime);
    }
    print!("{:}", temp);
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let arg: Option<&String> = args.get(1);

    match arg {
        None => {
            println!("Please enter a number to receive primes.");
            println!("Usage:");
            println!("\ttoPrime x");
        },
        Some(x) => {
            match x.parse::<u32>() {
                Ok(max) => {
                    let primes: Vec<u32> = primes_to(max);
                    prettyprint_primes(primes);
                },
                _ => println!("That's not a number; please enter a number"),
            }
        }
    }
}


texts: Render the area of circle using HTML and JavaScript

texts:
1. Problem Statement

  Write a JavaScript function calcCircleArea(r) that takes as a parameter the radius of a circle and calculates and returns its area. Put the function in a file named circle-area.js. Write a HTML page circle-area.html that includes the script circle-area.js and calculates and prints in the page body the area of circles of size r=7, r=1.5 and r=20.

  2. Expected Output

r = 7; area = 153.93804002589985
r = 1.5; area = 7.0685834705770345
r = 20; area = 1256.6370614359173

Solution:

function calcCircleArea(r){
    if(r >= 0){
        return window['Math']['PI'] * r * r;
    }else{
        return "wrong input";
    }
}

document.write('r = 7; area = ' + window['calcCircleArea'](7) + "
");
document.write('r = 1.5; area = ' + window['calcCircleArea'](1.5) + "
");
document.write('r = 20; area = ' + window['calcCircleArea'](20) + "
");
<!doctype html>

        <meta charset="UTF-8">
        <title>Circle area</title>

Can I invoke calcCircleArea from the HTML code to render the given output?
Can the else condition in calcCircleArea have better code?


texts: Is this the Clojure way to web-scrape a book cover image?

texts:
Is there a way to write this better or more Clojure way? Especially the last part with with-open and the let. Should I put the -> form into a separate function? Is this function to overloaded (to much stuff) or is this still ok?

 (defn scrape-book-cover [url image-filename]
   (let [out-stream (io/output-stream image-filename)
         image (-> url
                   (java.net.URL.)
                   (html/html-resource)
                   (html/select [:div.bookcoverXXL :> :div :> :img])
                   (first) (:attrs) (:src)
                   (->> (str "http:"))
                   (http-client/get {:as :byte-array})
                   (:body))]
     (with-open [out out-stream]
       (.write out image))))


texts:
I wanted to explore how I can associate routes with "controllers" with Sanic as a base. It works fine but "feels" a bit clunky but I can't put my finger on why/how.

routes.py - Returning controller methods from a given route

from .index import IndexRoutes
from .clients import ClientRoutes
from Controllers.IndexController import *
from Controllers.ClientController import *

CLASSES = [
    IndexRoutes,
    ClientRoutes
]

def add_routes(app):
    routes = get_routes()

    for route in routes:
        for m in route['methods']:
            controller = m['controller']
            method = m['method']

            app.add_route(
                eval(controller + '.' + method),
                route['prefix'] + m['path'],
                methods=m['request_methods']
            )

def get_routes():
    routes = []

    for c in CLASSES:
        methods = getattr(c, 'ROUTE_METHODS')

        route = {
            'name': getattr(c, 'ROUTE_NAME'),
            'methods': [],
            'prefix': getattr(c, 'ROUTE_PREFIX')
        }

        for method in methods:
            route['methods'].append(getattr(c, method)())

        routes.append(route)

    return routes

client.py - Example of route definitions

class ClientRoutes:
    ROUTE_NAME = 'clients'
    ROUTE_METHODS = ['index', 'create', 'update', 'single', 'destroy']
    ROUTE_PREFIX = 'clients'

    def index():
        return {
            'controller': 'ClientController',
            'method': 'index',
            'path': '/',
            'request_methods': ['GET']
        }

    def create():
        return {
            'controller': 'ClientController',
            'method': 'create',
            'path': '/',
            'request_methods': ['POST']
        }

    def single():
        return {
            'controller': 'ClientController',
            'method': 'single',
            'path': '/<id>',
            'request_methods': ['GET']
        }

    def update():
        return {
            'controller': 'ClientController',
            'method': 'update',
            'path': '/<id>',
            'request_methods': ['PUT']
        }

    def destroy():
        return {
            'controller': 'ClientController',
            'method': 'destroy',
            'path': '/<id>',
            'request_methods': ['DELETE']
        }

ClientController.py - Example of controller

from sanic import response
from Database.Model import Model
from Database.Client import Client
from Helpers.transformers import to_dict

class ClientController:

    async def index(request):
        clients = Model(Client)
        return response.json(to_dict(clients.get()))

    async def create(request):
        data = request.json
        try:
            if 'name' not in data:
                raise KeyError('Name is required')
            else:
                if len(data['name']) < 1:
                    raise ValueError('Name is required')
        except KeyError as e:
            return response.json(str(e), 400)
        except ValueError as e:
            return response.json(str(e), 400)

        client = Model(Client)
        return response.json(to_dict(client.save(data)))


texts:
Problem (Rephrased from here):

  The radical of \$n\$, \$rad(n)\$, is the product of distinct prime factors of \$n\$. For example, \$504 = 2^3 × 3^2 × 7\$, so \$rad(504) = 2 × 3 × 7 = 42\$.

  We shall define the triplet of positive integers \$(a, b, c)\$ to be an abc-hit if:

  \$GCD(a, b) = GCD(a, c) = GCD(b, c) = 1\$
  \$a < b\$
  \$a + b = c\$
  \$rad(abc) < c\$

  If \$(a,b,c)\$ is an abc-hit such that \$c<120000\$, Find sum of all \$c\$.

I have this code which runs in ~25.727 seconds, which I would like to write in a better way.

Firstly I noted these:

If GCD(a,b)=1 then GCD(a,a+b)=1 and GCD(b,a+b)=1
rad(a*b*c)=rad(a)*rad(b)*rad(c) if GCD(a,b,c)=1

Code:

private static double[] rad;
private static int[] primes;

public static void main(String[] args) {
    long t1 = System.currentTimeMillis();
    System.out.println(solve());
    long t2 = System.currentTimeMillis();
    System.out.println((double) (t2 - t1) / 1000.0);
}

private static long solve() {
    final int lim = 1000;
    long sumc = 0;
    sievePrimesArray(lim);
    sieveRadArray(lim);
    for (int a = 1; a < lim; a++) {
        // The value of `b` is minimum `a+1`, so `notcoprime` is an
        // array which tells if `i` and `a` have some common prime factor.

        boolean[] notcoprime = new boolean[lim - a - 1];
        for (int i = 0; i < primes.length && primes[i] <= a; i++) {
            if (a % primes[i] == 0) {
                // We need `primes[i]*j>=a+1`

                for (int j = (a + 1) / primes[i] + (((a + 1) / primes[i] < a + 1) ? 1 : 0);
                     primes[i] * j < lim; j++) {
                    notcoprime[primes[i] * j - (a + 1)] = true;
                }
            }
        }
        for (int b = a + 1; b + a < lim; b++) {
            int c = a + b;
            if (!notcoprime[b - (a + 1)]) {

            // Here to avoid overflow I used `double` and since `BigInteger` was slow.
            // The maximum value of `rad` rad reached is `119999` and
            // `rad[a-1]*rad[b-1]<=119999*119999=14399760001` which is still in `double`

                if (rad[a-1] * rad[b-1] < (double) c / rad[c-1]) {
                    sumc += c;
                }
            }
        }
    }
    return sumc;
}

Rather than finding all prime factors of a number, I multiply rad[x*p] by p where p is prime, once.

public static void sieveRadArray(int lim) {
    rad = new double[lim];
    Arrays.fill(rad, 1);
    for (int x : primes) {
        for (int j = 1; x * j < lim; j++) {
            rad[j * x - 1] *= x;
        }
    }
}

private static void sievePrimesArray(int lim) {
    boolean[] isPrime = new boolean[lim + 1];
    Arrays.fill(isPrime, true);
    for (int i = 2; i * i <= lim; i++) {
        if (isPrime[i]) {
            for (int j = i; i * j <= lim; j++) {
                isPrime[i * j] = false;
            }
        }
    }
    ArrayList<Integer> prime_list = new ArrayList<Integer>();
    prime_list.add(2);
    for (int j = 3; j < lim; j++) {
        if (isPrime[j]) {
            prime_list.add(j);
        }
    }
    primes = prime_list.stream().mapToInt(i -> i).toArray();
}