texts: Catching all exceptions and errors in PHP

texts:
I've tried to catch all exceptions and errors in PHP in a way so that I can deal with them consistently.

This is the code with the exception of the very last bit where I instead pass $e on to a method that outputs an error page as HTML.

// Only let PHP report errors in dev
error_reporting(ENV === 'dev' ? E_ALL : 0);

// Register handler
set_error_handler("error_handler");
set_exception_handler("error_handler");
register_shutdown_function("error_handler");

function error_handler()
{
    // Check for unhandled errors (fatal shutdown)
    $e = error_get_last();

    // If none, check function args (error handler)
    if($e === null)
        $e = func_get_args();

    // Return if no error
    if(empty($e))
        return;

    // "Normalize" exceptions (exception handler)
    if($e[0] instanceof Exception)
    {
        call_user_func_array(__FUNCTION__, array(
            $e[0]->getCode(),
            $e[0]->getMessage(),
            $e[0]->getFile(),
            $e[0]->getLine(),
            $e[0]));
        return;
    }

    // Create with consistent array keys
    $e = array_combine(array('number', 'message', 'file', 'line', 'context'),
                       array_pad($e, 5, null));

    // Output error page
    var_dump($e);
    exit;
}

I'm wondering if this is a decent way of doing it or if I have missed anything crucial. Any comments?


texts:
I have been attempting the questions at Project Euler and I am trying to find the sum of Primes under two million (question 10)

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

Here is my attempt which does work, but I would like to know if there is any way to improve this code. Any suggestions welcomed!
class SumOfPrimes
{
    static void Main(string[] args)
    {
        Primes primes = new Primes(2000000);
        long sum = 0;
        foreach(int p in primes.list_of_primes){
            sum += p;
        }
        Console.WriteLine(sum);
        Console.ReadLine();
    }
}

class Primes
{
    public HashSet<int> all_numbers = new HashSet<int>();
    public HashSet<int> list_of_primes = new HashSet<int>();
    public HashSet<int> list_of_nonprimes = new HashSet<int>();

    public Primes(int n)
    {
        all_numbers = new HashSet<int>(Enumerable.Range(1, n));
        for (int i = 2; i < Math.Sqrt(n) + 1; i++)
        {
            for (int j = 3; j <= n / i; j++)
                list_of_nonprimes.Add(i * j);
        }
        list_of_primes = new HashSet<int>(all_numbers.Except(list_of_nonprimes));
    }
}


texts: Calculation of RGB values given min and max values

texts:
I made a start at translating the accepted answer's code here into C#. Any suggestions on the correctness of the translation and the correctness of the original code would be very much appreciated.

public class RgbValues
{
    public int Red { get; set; }
    public int Green { get; set; }
    public int Blue { get; set; }
}

public static RgbValues GetRgbValues(float minimumValue, float maximumValue, float value)
{
    var rgbValues = new RgbValues();
    var halfmax = (minimumValue + maximumValue) / 2.0;
    rgbValues.Blue = (int) Math.Max(0.0, 255.0 * (1.0 - value/halfmax));
    rgbValues.Red = (int)Math.Max(0.0, 255.0 * (value / halfmax - 1.0));
    rgbValues.Green = 255 - rgbValues.Blue - rgbValues.Red;

    return rgbValues;
}

What is a bit worrying is that:

GetRgbValues(10, 10113, 10113)

should really caclulate:

red = 255, green = 0, blue = 0

rather than:

red = 254, green = 1, blue = 0

I guess there is some rounding issue.

Any ideas?


texts: Template for web pages using social plugins

texts:
I created a simple template for web pages that uses social plugins.

The template consists of the html/php with jquery, and the necessary javascript to enable and use social plugins. The javascript file for the social plugins is enable at the very end, and the jQuery file at the beginning...

So far I tested all using the facebook plugin, which i did by creating a button and calling the Facebook Web Share Dialog Box. All works well. I want to do the same for other social plugins like twitter, google+, etc...

I'm looking for improvements on the template not the plugin itself (i can figure that one out by doing some research).

html

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">

    <meta property="og:url" content="">
    <meta property="og:title" content="">
    <meta property="og:description" content="">
    <meta property="og:image" content="">
    <meta property="fb:app_id" content="">
    <meta property="og:type" content="">
    <meta property="og:local" content="es_ES">

TEST SOCIAL PLUGINS

social_plugin.js

// FACEBOOK
window.fbAsyncInit = function() {
    FB.init({
        appId: 'xxxxxxx',
        xfbml: true,
        version: 'v2.7'
    });
};

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/es_ES/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// TWITTER

// GOOGLE +

$(document).ready(function() {
    $("[data-social]").click(function(e) {
        var params = $(this).data("social");

        switch(params['share']) {
            case 'facebook':
                var object_href = params['object'];

                FB.ui({
                    method: 'share_open_graph',
                    action_type: 'og.likes',
                    action_properties: JSON.stringify({
                        object: object_href,
                    })
                }, function(response){});
                break;

            case 'twitter':
                break;

            case 'google_plus':
                break;

            default:
                break;
        }
    });
});


texts:
I'm a Python noob. This is the code I'm using:

for i in argv[2:]:                                 # argv[1] isn't required by s.py
    if ' ' in i:
        argv[argv.index(i)] = '"%s"' % i
args = ' '.join(argv[2:])
os.system('s.py '+args)

Is there a more elegant way to do this?


texts:
I want to read multiple files simultaneously and apply the same function on data.

This code works correctly, but can someone please suggest any better way of writing this?

function fileread(path,stats,callback){
   var buffer = new Buffer(stats.size);
   fs.readFile(path, buffer, function(err, data){
      if(err){
         throw err;
      }

      callback(null, data);
   });
}

function testAsync() {
    var files = ['Statistics_Schema.json','seriesData'];
    async.map(files, fs.stat, function(err, stats){
       var i=0;
       async.map(files, function(path, callback){
          fileread(path, stats[i++], callback);
          },function(err, data){
                for(var j=0; j < data.length; j++){
                 console.log(data[j].toString());
                }
           });
    });
}


texts:
I've solved Project Euler #15 in Haskell, but I feel like there might be a better way to express my solution that I'm not seeing. I start out defining my types:

import qualified Data.Map.Strict as Map
import Data.List

data Position = Position Int Int
                deriving (Show, Eq, Ord)

start :: Position
start = Position 20 20

I probably should have used newtype on a tuple of Ints, but I think this is ok.  I can then generate the list of moves available from a given position via:

moves :: Position -> [Position]
moves (Position x y) | x == 0 && y == 0 = []
                     | x == 0 = [Position x (y - 1)]
                     | y == 0 = [Position (x - 1) y]
                     | otherwise = Position (x - 1) y : Position x (y - 1) : []

From there a naive implementation to solve for the number of paths would simply look like:

naiveWays :: Position -> Int
naiveWays (Position 0 0) = 1
naiveWays pos = sum $ map naiveWays $ moves pos

Of course this is highly inefficient, and takes much to long to complete, so I tried to improve it using memoization. This is where I feel like I could probably use the most improvement:

ways :: Position -> Int
ways = snd . memWays Map.empty

memWays :: Map.Map Position Int -> Position -> (Map.Map Position Int, Int)
memWays mem (Position 0 0) = (mem, 1)
memWays mem pos = loop lookupWays
  where
    lookupWays = Map.lookup pos mem
    computeWays = mapAccumR memWays mem (moves pos)
    mapWays = fst computeWays
    sumWays = sum $ snd computeWays
    loop (Just w) = (mem, w)
    loop (Nothing) = (Map.insert pos sumWays mapWays, sumWays)

Basically memWays takes a Map of known solutions for the subproblems (number of paths from 2,2, etc), and a position and attempts to use it to find the shortest path. If the position is already in the map, it can simply look it up. Otherwise, it maps over the available moves, using the returned Map as an accumulator.

There actually is an even more efficient way to solve it, but I won't spoil that, and since I'm looking for Haskell practice, not math, I'm more interested in figuring out how I can make this approach cleaner.

Edit: Thanks to 200_success for pointing out that I don't need to enumerate moves.  memWays now looks like:

memWays :: Map.Map Position Int -> Position -> (Map.Map Position Int, Int)
memWays mem (Position 0 _) = (mem, 1)
memWays mem (Position _ 0) = (mem, 1)
memWays mem pos@(Position x y) = loop $ Map.lookup pos mem
  where right = memWays mem $ Position (x - 1) y
        down = memWays (fst right) $ Position x (y - 1)
        both = snd right + snd down
        loop (Just paths) = (mem, paths)
        loop Nothing = (Map.insert pos both $ fst down, both)

I feel like this looks a lot cleaner, though if anyone has suggestions for further improvement, I'd love to hear it.


texts: Getting death row inmates' last statement

texts:
Initial version of the code appeared as an answer to an SO question. I refactored the code a bit and it works pretty well, IMHO. I get a solid .csv file with all the data from Texas Department of Criminal Justice's Death Row page.
What I was especially interested in was getting all offenders' last statement, if there was any, which the codes accomplishes.
What I'd want to get here is some feedback on utilizing pandas, as I'm relatively new to it. Also, some memory efficiency suggestions would be nice too, I guess.
For example, should I save the initial version of the .csv file and then read it so I can append the last statements? Or keeping everything in memory is fine?
If you find any other holes, do point them out!
The code:
import random
import time

import pandas as pd
import requests
from lxml import html

base_url = "https://www.tdcj.texas.gov/death_row"
statement_xpath = '//*[@id="content_right"]/p[6]/text()'

def get_page() -> str:
    return requests.get(f"{base_url}/dr_executed_offenders.html").text

def clean(first_and_last_name: list) -> str:
    name = "".join(first_and_last_name).replace(" ", "").lower()
    return name.replace(", Jr.", "").replace(", Sr.", "").replace("'", "")

def get_offender_data(page: str) -> pd.DataFrame:
    df = pd.read_html(page, flavor="bs4")
    df = pd.concat(df)
    df.rename(
        columns={'Link': "Offender Information", "Link.1": "Last Statement URL"},
        inplace=True,
    )

    df["Offender Information"] = df[
        ["Last Name", 'First Name']
    ].apply(lambda x: f"{base_url}/dr_info/{clean(x)}.html", axis=1)

    df["Last Statement URL"] = df[
        ["Last Name", 'First Name']
    ].apply(lambda x: f"{base_url}/dr_info/{clean(x)}last.html", axis=1)
    return df

def get_last_statement(statement_url: str) -> str:
    page = requests.get(statement_url).text
    statement = html.fromstring(page).xpath(statement_xpath)
    text = next(iter(statement), "")
    return " ".join(text.split())

def get_last_statements(offenders_data: list) -> list:
    statements = []
    for item in offenders_data:
        *names, url = item
        print(f"Fetching statement for {' '.join(names)}...")
        statements.append(get_last_statement(statement_url=url))
        time.sleep(random.randint(1, 4))
    return statements

if __name__ == "__main__":
    offenders_df = get_offender_data(get_page())
    names_and_urls = list(
        zip(
            offenders_df["First Name"],
            offenders_df["Last Name"],
            offenders_df["Last Statement URL"],
        )
    )
    offenders_df["Last Statement"] = get_last_statements(names_and_urls)
    offenders_df.to_csv("offenders_data.csv", index=False)

The scraping part is intentionally slow, as I don't want to abuse the server, but I do want to get the job done. So, if you don't have a couple of minutes to spare, you can fetch the offenders_data.csv file from here.


texts:
I've the following code:

    protected Dictionary<NpInfoHelper, object> Informer;
    protected override void OnInit(EventArgs e)
    {
        if (Session.Keys.Count == 1)
        {
            Session.Abandon();
            Response.RedirectPermanent("~/Pages/Login?e=true", true);
        }
        else
        {
            Informer = (Dictionary<NpInfoHelper, object>)Session["Informer"];
        }
        base.OnInit(e);
    }

in every backend .cs file of the .aspx file.

I think this is repetitive. Note that I'll be using Informer in every .aspx.cs file.

The above code is repeated 19 times. Can I make it just one?


texts:
Asking here instead of SO as suggested.
I'm trying to use Julia to solve the common tile game 15 Puzzle using Julia using A* algorithm. I am quite new to the language and my style may seem very C like. When I try the following code, I run out of memory. I'm not sure if its related to the use of a pointer style in my structs or just bad design.
struct Node
    parent
    f::Int64
    board::Array{Int64,1}
end

function findblank(A::Array{Int64,1})
    x = size(A,1)
    for i = 1:x
        if A[i] == x
            return i
        end
    end
    return -1
end

function up(A::Array{Int64,1})
    N = size(A,1)
    Nsq = isqrt(N)
    blank = findblank(A)
    B = copy(A)
    if blank / Nsq <= 1
        return nothing
    end
    B[blank-Nsq],B[blank] = B[blank],B[blank-Nsq]
    return B
end

function down(A::Array{Int64,1})
    N = size(A,1)
    Nsq = isqrt(N)
    blank = findblank(A)
    B = copy(A)
    if (blank / Nsq) > (Nsq -1)
        return nothing
    end
    B[blank+Nsq],B[blank] = B[blank],B[blank+Nsq]
    return B
end

function left(A::Array{Int64,1})
    N = size(A,1)
    Nsq = isqrt(N)
    blank = findblank(A)
    B = copy(A)
    if (blank % Nsq) == 1
        return nothing
    end
    B[blank-1],B[blank] = B[blank],B[blank-1]
    return B
end

function right(A::Array{Int64,1})
    N = size(A,1)
    Nsq = isqrt(N)
    blank = findblank(A)
    B = copy(A)
    if (blank % Nsq) == 0
        return nothing
    end
    B[blank+1],B[blank] = B[blank],B[blank+1]
    return B
end

function manhattan(A::Array{Int64,1})
    N = size(A,1)
    Nsq = isqrt(N)
    r = 0
    for i in 1:N
        if (A[i]==i || A[i]==N)
            continue
        end
        row1 = floor((A[i]-1) / Nsq)
        col1 = (A[i]-1) % Nsq
        row2 = floor((i-1) / Nsq)
        col2 = (i-1) % Nsq
        r+= abs(row1 - row2) + abs(col1 - col2)
    end
    return r
end

# start = [1,2,3,4,5,6,7,9,8]
# start = [6,5,4,1,7,3,9,8,2] #26 moves
start = [7,8,4,11,12,14,10,15,16,5,3,13,2,1,9,6] # 50 moves
goal = [x for x in 1:length(start)]
# println("The manhattan distance of $start is  $(manhattan(start))")
g = 0
f = g + manhattan(start)
pq = PriorityQueue()
actions = [up,down,left,right]
dd = Dict{Array{Int64,1},Int64}()
snode = Node(C_NULL,f,start)
enqueue!(pq,snode,f)
pos_seen = 0
moves = 0
while (!isempty(pq))
    current = dequeue!(pq)
    if haskey(dd,current.board)
        continue
    else
        push!(dd, current.board =>current.f)
    end
    if (current.board == goal)
        while(current.board != start)
            println(current.board)
            global moves +=1
            current = current.parent[]
        end
        println(start)
        println("$start solved in $moves moves after looking at $pos_seen positions")
        break
    end
    global pos_seen+=1
    global g+=1
    for i in 1:4
        nextmove = actions[i](current.board)
        if (nextmove === nothing || nextmove == current.board || haskey(dd,nextmove))
            continue
        else
            global f = g+manhattan(nextmove)
            n = Node(Ref(current),f,nextmove)
            enqueue!(pq,n,f)
        end
    end
end
println("END")


texts: How to optimize my telegram bot written in Python?

texts:
I have written a fairly simple bot that provides information or additional choice based on the user's query. It runs well and does the job, however, I was wondering how can I optimize my code and use the telebot better?
Currently the main action happens in the query handler and something tells me that I am missing possible efficiency gains (when I will attempt to build more choices for example). Below is the code, simplified for demonstration purposes:
import telebot
from telebot import types

token = bottoken

bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def welcome(message):

    # here i give the main choice that is always visible to the user

    markup = types.ReplyKeyboardMarkup(resize_keyboard=False)
    item1 = types.KeyboardButton("Button1")
    item2 = types.KeyboardButton("Button2")

    markup.add(item1, item2)

    bot.send_message(message.chat.id, "Welcome message".format(message.from_user, bot.get_me()),
        parse_mode='html', reply_markup=markup)

@bot.message_handler(content_types=['text'])
def main_choice(message):

    # here i develop each of the main choices and redirect to the callback handler

    if message.text == 'Button1':

        # Forward to callback handler

            markup = types.InlineKeyboardMarkup()
            item1 = types.InlineKeyboardButton("Yes", callback_data = 'demo_yes')
            item2 = types.InlineKeyboardButton("No", callback_data = 'demo_no')

            markup.add(item1, item2)

            bot.send_message(message.chat.id, 'Some text', reply_markup=markup)

    elif message.text == 'Button2':

        # some logic

    else :
        bot.send_message(message.chat.id, 'Sorry, i dont understand. You can use /help to check how i work')

@bot.callback_query_handler(func=lambda call: True)
def tempo(call):

    # here a handle the queries launched both by main buttons and the inline keyboard

    if call.data == "demo_yes":

        keyboard = types.InlineKeyboardMarkup()
        item1 = types.InlineKeyboardButton("Text1", callback_data = 'call1')
        item2 = types.InlineKeyboardButton("Text2", callback_data = 'call2')
        keyboard.add(item1,item2)

        bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)

    elif call.data == "demo_no":

        kkeyboard = types.InlineKeyboardMarkup()
        item1 = types.InlineKeyboardButton("Text3", callback_data = 'call3')
        item2 = types.InlineKeyboardButton("Text4", callback_data = 'call4')
        keyboard.add(item1,item2)

        bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)

    if call.data == "call1":

        keyboard = types.InlineKeyboardMarkup()
        item1 = types.InlineKeyboardButton("Text5", callback_data = 'another_call1')
        item2 = types.InlineKeyboardButton("Text6", callback_data = 'another_call2')
        keyboard.add(item1,item2)

        bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)

    elif call.data == "call2":

        kkeyboard = types.InlineKeyboardMarkup()
        item1 = types.InlineKeyboardButton("Text7", callback_data = 'another_call3')
        item2 = types.InlineKeyboardButton("Text8", callback_data = 'another_call4')
        keyboard.add(item1,item2)

        bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)


texts: Initializing an array of string constants, and another constant array of the equivalent lengths

texts:
Ok, a struct would actually be most convenient, but it woudl be easier on teh system to have 2 seperate arrays rather than an array of structs.
#define PAIR(Str) {(Str), sizeof(Str)-1}
static const struct StrStruct {
    const char *Str;
    unsigned int Len;
} Packed4 DefaultStr[] = {
    PAIR("Error"),
    PAIR("An unexpected error occurred"),
    PAIR("while saving data"),
    PAIR("Close some windows or programs and try again"),
    PAIR("Singleplayer"),
    PAIR("Multiplayer"),
    PAIR("Settings"),
    PAIR("Quit"),
    PAIR("Graphics"),
    PAIR("User Interface"),
    PAIR("Sounds"),
    PAIR("Controls"),
    PAIR("Language"),
    PAIR("Compatibility"),
    PAIR("Help"),
    PAIR("About"),
    PAIR("On"),
    PAIR("Off"),
    PAIR("Field of View"),
};

Simply hardcoding them is 'magic numbers'.
static const char *const Strs[] = {
    "Singleplayer",
    "Multiplayer",
    "Settings",
    "Quit",
    "Graphics",
    "User Interface",
    "Sounds",
    "Controls",
    "Language",
    "Compatibility",
    "Help",
    "About",
    "On",
    "Off",
    "Field of View"
};
static const unsigned short Lengths[] = {
    12,
    11,
    8,
    //...
};

So I came up with my current solution, though kind of a pain in the backside, I have this.
#define ERROR "Error"
#define UNEXPECTEDERROR "An unexpected error occurred"
#define WHILESAVINGDATA "while saving data"
#define CLOSEPROGRAMS "Close some windows or programs and try again"
#define SINGLEPLAYER "Singleplayer"
#define MULTIPLAYER "Multiplayer"
#define SETTINGS "Settings"
#define QUIT "Quit"
#define GRAPHICS "Graphics"
#define UI "User Interface"
#define AUDIO "Audio"
#define CONTROLS "Controls"
#define LANGUAGE "Language"
#define COMPATIBILITY "Compatibility"
#define HELP "Help"
#define ABOUT "About"
#define ON "On"
#define OFF "Off"
#define FOV "Field of View"
static const char *const DStr[] = {
    ERROR,
    UNEXPECTEDERROR,
    WHILESAVINGDATA,
    CLOSEPROGRAMS,
    SINGLEPLAYER,
    MULTIPLAYER,
    SETTINGS,
    QUIT,
    GRAPHICS,
    UI,
    AUDIO,
    CONTROLS,
    LANGUAGE,
    COMPATIBILITY,
    HELP,
    ABOUT,
    ON,
    OFF,
    FOV,
};
#define STRLEN(Str) (sizeof(Str)-1)
static const unsigned short DLen[] = {
    STRLEN(ERROR),
    STRLEN(UNEXPECTEDERROR),
    STRLEN(WHILESAVINGDATA),
    STRLEN(CLOSEPROGRAMS),
    STRLEN(SINGLEPLAYER),
    //...
};

Is there a better way to do this? Is there a cleaner way to initialize an constant array of strings, and a constant array of the equivalent lenghts? I'm mainly looking at the last one. How can I improve that one?


texts: Conversion from decimal to negabinary and vice versa in Haskell

texts:
Recently I set about to writing conversion functions in Haskell between decimal and negabinary. I tried to write them in as much functional a style as possible, also aiming at brevity. Below I present my take at the task. I'd be interested in your refinements of the method I employ or any comments whatsoever.

These are my two functions for converting back and forth:

type NegaBinary = String

dec2negbin :: Int -> NegaBinary
dec2negbin = reverse .
             map intToDigit .
                 unfoldr (\x -> if x==0 then Nothing else Just(abs(xrem x (-2)), xdiv x (-2)))
    where
      xrem a b = if b > 0 then rem a b else (-(rem a (-b)))
      xdiv a b = if b > 0 then div a b else (-(div a (-b)))

negbin2dec :: NegaBinary -> Int
negbin2dec = sum . map (\x -> (snd x)*(-2)^(fst x)) . zip [0..] . reverse . map digitToInt

I defined the NegaBinary type just for clarity. The dec2negbin employs the unfoldr function for sequential divisions and remainder calculations. I also used two local functions: xrem and xdiv, because the standard functions (rem and div) had the undesirable behavior of always approaching the dividend from below (meaning that in div a b => c b*c is always lower than a). What I wanted is for it to approach in the direction from zero, so the behavior is different for positive and negative dividends. I know the definition of dec2negbin is a bit bulky, so improvements are welcome.


texts:
The challenge description is as follows:

You are given an array strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.
Example:
longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2)
--> "abigailtheta"

n being the length of the string array, if n = 0 or k > n or k <= 0
return "".

I solved the challenge with as a side goal to follow and use ECMAScript 6 as much as possible. All suggestions on improving the code are welcome!
Note: I did not like using k and n in code, so I used numStr and arrLen respectively.
const longestConsec = (strArr, numStr) => {
  const arrLen = strArr.length
  if (arrLen === 0 || numStr > arrLen || numStr <= 0) {
    return ""
  }
  const consecStrings = getAllConsecutiveStrings(strArr, numStr, arrLen)
  return getFirstLongestString(consecStrings)
}

const getAllConsecutiveStrings = (strArr, numStr, arrLen) => {
  const numConsecStr = arrLen - numStr
  const result = []
  let consecStr
  for (let i = 0; i <= numConsecStr; i++) {
    consecStr = ""
    for (let s = i; s < i + numStr; s++) {
      consecStr += strArr[s]
    }
    result.push(consecStr)
  }
  return result
}

const getFirstLongestString = strArr => {
  let firstlongestString = ""
  let longestLength = 0
  for (let str of strArr) {
    strLen = str.length
    if (strLen > longestLength) {
      firstlongestString = str
      longestLength = strLen
    }
  }
  return firstlongestString
}


texts: Space and time complexity of operation on lists

texts:
I'm new to programming and even more new to Haskell.  Below is a little tid-bit I wrote that operates on a bunch of lists. I am wondering if someone would be kind enough to walk through the function margProbs line-by-line, and enumerate their respective space/time complexities and/or just possibly suggest improvements.

import qualified Control.Monad as Mo
import qualified Data.Map as M
import qualified Data.List as L
import Data.Maybe

type PaIdx = Int

margProbs :: [[Bool]] -> PaIdx ->  [Double] -> [[Double]] -> Maybe [[Double]]
margProbs bs idx vpa vs = Mo.sequence $ fmap (\( _, ms ) -> collapseWith addV ms ) grouped
    where
        (p, q)   = ( vpa !! 0, vpa !! 1 )
        grouped  = reverse . sortAndGroup $ zip ( snd probBool ) scaled
        scaled   = zipWith (\p v -> scaleV (*) p v ) ( fst probBool ) vs
        probBool = foldr   (\b (probs, bools) -> let (prob,bool) = reducePa b in (prob:probs, bool:bools) ) ([],[]) bs
        reducePa bs = let split = fromJust $ pluckL idx bs in ( if fst split == True then p else q, snd split )

------------
-- Utils --
------------

addV :: ( Num a ) => [a] ->  [a] -> Maybe [a]
addV v1 v2 = if length v1 == length v2 then Just $ zipWith (+) v1 v2 else Nothing

scaleV :: (  Num a ) => ( a -> a -> a ) -> a -> [a] -> [a]
scaleV g num v = fmap (\e -> g num e ) v

collapseWith :: ( Num a ) => ( [a] -> [a] -> Maybe [a] ) -> [[a]] -> Maybe [a]
collapseWith g vs = foldr (\v1 v2 -> v2 >>= \w -> g v1 w ) ( return $ head vs ) ( tail vs )

sortAndGroup :: Ord k => [ (k, a) ] -> [ (k, [a]) ]
sortAndGroup ts = M.toList $ M.fromListWith (++) [(k, [v]) | (k, v) <- ts]

pluckL :: Int -> [a] -> Maybe ( a, [a] )
pluckL idx xs = case splitAt idx xs of
    ( _, [] )      -> Nothing
    ( hs, (t:ts) ) -> Just ( t, hs ++ ts )

Here are the params I used to test this snippet:

ret = margProbs bs 0 v m
bs = [[True,True],[True,False],[False,True],[False,False]]
v = [0.4,0.6]
m = [[0.95,0.05], [0.94,0.06], [0.29,0.71], [0.1, 0.9]]

ret should have value: Just [[0.554,0.446],[0.436,0.564]]

Update

I got rid of all dependencies to the hmatrix library.


texts: Credit card / IMEI check digit in Kotlin

texts:
I recently had the need to implement Luhn's Algorithm in a Java/Kotlin application. I needed a function that would add the check digit to the string of a number like a credit card or IMEI. It could be easily modified to check if the last digit is valid.

At first, I had a code of around 20 lines in Java, but by using every Kotlin quirk I could think of, I managed to do it in one line.

fun String.addLastImeiDigit(): String = "$this${10 - this.withIndex().map { if (it.index.and(1) == 0) it.value.toInt() - 48 else (2 * (it.value.toInt() - 48)).run { (this % 10) + (this / 10) } }.sum() % 10}"

Here it is in a more understandable fashion

fun String.addLastImeiDigit(): String {
    return "$this${10 - this.withIndex().map {
        if (it.index.and(1) == 0) /* if even */
            it.value.toInt() - 48 /* ascii to Int */
        else
            (2 * (it.value.toInt() - 48)).run {
                (this % 10) + (this / 10) /* sum both digits */
            }
    }.sum() % 10}"
}

I understand that obfuscating code like this in a shared code environment would be very bad, but still I think it's great that we can get to do this and that Kotlin avoids so much boilerplate. What do you think about using one-line functions like this one?


texts:
Is this code okay?

import java.util.Stack;

public class StackReverse {

    public static void main(String[] args) {

        final String inputString = "code review";

        final String reversed = reverseString(inputString);
        System.out.println("The reversed string is " + reversed);

    }

    public static String reverseString(String originalString) {
        Stack<Character> stack = new Stack<>();
        String reversed = "";
        for (int i = 0; i < originalString.length(); i++) {
            char ch = originalString.charAt(i);
            stack.push(ch);
        }
        for (int i = 0; i < originalString.length(); i++) {
            char ch = stack.pop();
            reversed = reversed + ch;

        }
        return reversed;

    }

}


texts: Could this QuickSort be made more consise and "nicer"?

texts:
After seeing this example of a "primitive" QS implementation in F# by Scott W

let rec quicksort2 = function
   | [] -> []
   | first::rest ->
        let smaller,larger = List.partition ((>=) first) rest
        List.concat [quicksort2 smaller; [first]; quicksort2 larger]

He has an example in C# which is far longer, I figured that this approach should be able to be more closely modeled than his C# example so this was my best attempt:

private static IEnumerable<T> Quicksort<T>(IEnumerable<T> list)
            where T : IComparable<T>
        {
            if ((list == null) || !list.Any())
                return Enumerable.Empty<T>();

            var smallerAndLarger = list.Skip(1).GroupBy(n => n.CompareTo(list.First()));

            return Quicksort(smallerAndLarger.FirstOrDefault(x => x.Key < 0))
                   .Concat(new List<T>(new[] { list.First() }))
                   .Concat(Quicksort(smallerAndLarger.FirstOrDefault(x => x.Key >= 0)));
        }

Now depending on how you count my solution is "equally" short as the F# one. But it does have more noise, that I cannot argue with. I wonder, can it be made clearer and perhaps even shorter than this?


texts: Posting iOS notifications from sender or from receiver

texts:
In Swift, should I be posting notifications to the iOS notification center from the device sending a text message or from the device receiving it?

I'm using OneSignal, so my code to send a notification from the sender device to the receiver device looks like this:

OneSignal.postNotification(["contents": ["en": "You've got a new message from \(sender.name!)"], "include_player_ids": [receiver.notificationId!]], onSuccess: { (dict) in
    //
    print("successfully posted notification")
    print(dict)
}, onFailure: { (error) in
    print("onesignal error!")
    print(error)
})

Alternatively, I can post the notification from the device after it has retrieved the new message from my database (Firebase):

OneSignal.postNotification(["contents": ["en": "You've got a new message from \(cellData.userInfo.fullName)"], "include_player_ids": [self.currentUser.notificationId]], onSuccess: { (dict) in
    //
    print("successfully posted notification")
    print(dict)
}, onFailure: { (error) in
    print("onesignal error!")
    print(error)
})


texts:
I wrote this code to help with programming challenges. A lot of problems can be solved by complete search so I wrote this function that I can copy/paste between problems to generate permutations quickly. Does anyone have any comments or suggestions to improve this function?

bool bruteforceGenerator(string& permutationIn, const vector<char>& options, const int maxLength)
{
    if(permutationIn.size() == 0) // In case we begin with a blank string just return the starting case
    {
        permutationIn = options[0];
        return true;
    }
    else
    {
        // First try to increment any digit in the string starting from the right
        for(int i = permutationIn.size() - 1; i>=0; i--)
        {
            if(permutationIn[i] != options[options.size()-1]) // If we can increment any digit
            {
                // Increment the individual digit
                auto index = find(options.begin(), options.end(), permutationIn[i]);
                permutationIn[i] = *(index+1);
                // Set all the digits after i back to their start values
                for(int j = i+1; j<permutationIn.size(); j++)
                {
                    permutationIn[j] = options[0];
                }
                return true;
            }
        }

        if(permutationIn.size() < maxLength) // If we could not increment a digit perhaps we could still make the string longer
        {
            permutationIn.push_back(0);
            for(auto &i : permutationIn) i = options[0];
            return true;
        }
        else return false; // If we could not increment any digit and we could not make the string any longer then we are out of permutations
    }
}

The return type of the function was chosen to allow usage of the function to look something like

string permutation;
vector <char> options {'^','v','<','>'};
while(bruteforceGenerator(permutation, options, 2))
{
    // Do something with the permutation
}

Sample output:

^
v
<
>
^^
^v
^<
^>
v^
vv
v<
v>
<^
<v
<<
<>
>^
>v
><
>>


texts:
For this code challenge, I want to create a performant function that creates a rectangular N-dimensional array. (min_dim_size, max_dim_size) is the span size of every dimension. So rectangular_properties is a list with sizes of every dimension of the matrix. The matrix contains random integer values. Also I want the matrix to be immutable on every dimension.

Now I have this code:

def random_hyperrectangular_matrix(dimensions, min_dim_size, max_dim_size):
    rectangular_properties = [randint(min_dim_size, max_dim_size) for _ in range(dimensions)]
    def recc2(dim):
        if dim == 0:
            return randint(0, 100)
        return tuple([recc2(dim - 1) for _ in range(rectangular_properties[dim - 1])])
    random_n_dimensional_matrix = recc2(dimensions)
    return random_n_dimensional_matrix

When I run my code it seems that the generation of this matrix takes a huge amount of time. Is there a lack of performance in it?
Does the generation of tuple([...]) out of a list takes much time?


texts:
I have a method visible on a QuerySet class which should return all articles an user can see. If the user is not logged in, all articles with min_age should'nt be visible, otherwise, if the user is logged in, all articles which min_age is lower than the user's age should be visible. I wrote this code but I think it can be improved. These raise AttributeError aren't good practice, I know, but how can I improve it?

    def visible(self, request=None):
        articles = self.filter(hidden=False)

        try:
            if request is not None:
                if request.user.is_authenticated:
                    if request.user.userprofile.has_filled_out:
                        articles = articles.filter(min_age__lte=request.user.userprofile.age)
                    else:
                        raise AttributeError
                else:
                    raise AttributeError
            else:
                raise AttributeError
        except AttributeError:
            articles = articles.filter(min_age=None)

        return articles


texts: Award Budget Cuts implementation in Java

texts:
PRAMP Award Budget Cuts

  The awards committee of your alma mater (i.e. your college/university) asked for your assistance with a budget allocation problem they’re facing. Originally, the committee planned to give N research grants this year. However, due to spending cutbacks, the budget was reduced to newBudget dollars and now they need to reallocate the grants. The committee made a decision that they’d like to impact as few grant recipients as possible by applying a maximum cap on all grants. Every grant initially planned to be higher than cap will now be exactly cap dollars. Grants less or equal to cap, obviously, won’t be impacted.

  Given an array grantsArray of the original grants and the reduced budget newBudget, write a function findGrantsCap that finds in the most efficient manner a cap such that the least number of recipients is impacted and that the new budget constraint is met (i.e. sum of the N reallocated grants equals to newBudget).

  Example:

input:  grantsArray = [2, 100, 50, 120, 1000], newBudget = 190

output: 47 # and given this cap the new grants array would be
           # [2, 47, 47, 47, 47]. Notice that the sum of the
           # new grants is indeed 190

My approach:

import java.util.Arrays;

class Solution {

  static double findGrantsCap(double[] grantsArray, double newBudget) {
    // your code goes here
    int len = grantsArray.length;

    Arrays.sort(grantsArray);

    //Calculate the newBudget
    double modBudget = newBudget;
    double cap;
    double sum = 0;
    double avg;
    for (double elem: grantsArray)
      sum += elem;

    avg = sum/len;

    if( avg == (int)newBudget)
        return (newBudget)/len;
    else
    {
      Arrays.sort(grantsArray);
      modBudget -= grantsArray[0];
      cap = modBudget/(len - 1);
      for( int i = 1; i < len-1; i++ )
      {
          System.out.println(cap);
           if( (int)cap > grantsArray[i] )
           {
             modBudget -= grantsArray[i];
             cap = modBudget/(len - i - 1);
           }
      }
    }
    return cap;
  }

  public static void main(String[] args) {
    double [] grantsArray = {2,100,50,120,167};
    double newBudget = 400;

    System.out.println(findGrantsCap(grantsArray,newBudget));
  }

}

I have the following questions with regards to the above code:

How can I further improve the algorithm, time or space wise?
Is my solution satisfying all the test cases and why is it failing if any?
Have I made any gross violations to the Java Coding conventions?

Reference


texts: Opening a list of URLs and splitting the queries into different files

texts:
I recently made a program in Python to open a list of URLs and split the queries into different files. I want to make this code more generic and simple. I am open to suggestions.

def parse_file():
    # Open the file for reading
    infile = open("URLlist.txt", 'r')
    # Read every single line of the file into an array of lines
    lines = infile.readlines()
    # For every line in the array of lines, do something with that line
    for line in lines: # for every line in lines.
        print line # print the URL
        # parse the URL query string list
        # if the URL has a query component print out the the first
        # argument(k) and if the URL has multiple arguments, print out
        # the other arguments. (v)
        for k,v in urlparse.parse_qsl(urlparse.urlparse(line).query):
            print k, v

            if k == "blog": # if the printed out arguements have blog in it
                           # write it out to the apropriate file and do this
                           # to all the others.
                with open('blog_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'p':
                with open('p_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'attachment_id':
                with open('attachment_id_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'lang':
                with open('lang_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'portfolio':
                with open('portfolio_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'page_id':
                with open('page_id_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'comments_popup':
                with open('comments_popup_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'iframe':
                with open('iframe_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'width':
                with open('width_file.txt'.format(),'a') as f:
                    f.write(v)
            elif k == 'height':
                with open('height_file.txt'.format(),'a') as f:
                    f.write(v)
                print "--------------------"
    infile.close()
    f.close()
parse_file()


texts:
Create an application named TestNewspaperAd that instantiates and displays a ClassifiedAd object. A ClassifiedAd has fields for number of words and a price. Include get and set properties for the number of words but only a get property for the price--the price should be calculated at nine cents per word. You can create either a console or GUI app.

namespace TestNewsPaperAd
{
    class Newspaper
    {
        static void Main(string[] args)
        {
            const double rate = 0.09;
            double total;
            ClassifiedAd Article = new ClassifiedAd();
            Article.Words = 583;

            total = Article.Words * rate;

            WriteLine("The price of the {0} word article is {1}\n", Article.Words, total);
        }
    }
}
class ClassifiedAd
{
    private int words;
    private double price;

    public int Words
    {
        get
        {
            return words;
        }
        set
        {
            words = value;
        }
    }
    public double Price
    {
        get
        {
            return price;
        }
    }
}


texts:
I have some Python code that copies a table from a website using Selenium,to create a csv, but as I haven't used Selenium much, I have that irksome feeling in the back of my mind that there must be a better way. It's also quite a bit slower than I would like. Here's the relevant code:

# ...Navigate to proper page...

table = self.browser.find_element_by_id('data_table')
head = table.find_element_by_tag_name('thead')
body = table.find_element_by_tag_name('tbody')

file_data = []

file_header = []
head_line = head.find_element_by_tag_name('tr')
headers = head_line.find_elements_by_tag_name('th')
for header in headers:
    header_text = header.text.encode('utf8')
    file_header.append(header_text)
file_data.append(",".join(file_header))

body_rows = body.find_elements_by_tag_name('tr')
for row in body_rows:
    data = row.find_elements_by_tag_name('td')
    file_row = []
    for datum in data:
        datum_text = datum.text.encode('utf8')
        file_row.append(datum_text)
    file_data.append(",".join(file_row))

with open(srcFile, "w") as f:
    f.write("\n".join(file_data))


texts:
I have attemped to define a function which scan an int value in a specified range and returns that value. The lower bound is the lower of the two parameters, the upper bound is the larger of the two parameters.After invalid input, the function displays a message and repeats input (and message, if necessary ) until a valid value is entered, which is then returned.

public static int scanYear() {

    do{
    int year = TextIO.getInt();
    if (checkDate (year) == true)
        return year;
    else
        TextIO.put("year not in the allowed range");

    }while (true);

} // end of scanYear

What is your opinion about the efficiency of the code , what can be improved ? Many thanks.


texts: Transforming a stl vector according to its neighbors

texts:
I have a piece of C++ code that transforms a vector where an element only stays one if itself and both of it's neighbors are one as well. End-points are handled as if the missing element is one. For example:

old: 1 1 0 1 1 1 0 1 1 0
new: 1 0 0 0 1 0 0 0 0 0

The following block of code works, but I'm not sure if it is optimal. We can assume that block and state are of type std::vector<int>, both of size N, and only contain elements 0 or 1:

  // Handle the end-points
  block[0]   = state[0]*state[1];
  block[N-1] = state[N-2]*state[N-1];

  // Set the cooperative behavior
  for(int i=1;i<N-1;i++)
    block[i] = state[i-1]*state[i]*state[i+1];

Is there a better way to do this? Should I be using some kind of trickery with std::accumulate and the like? Profiling show that this piece of code is in the inner-block of my simulation and takes up a sizable fraction of my runtime.


texts: Text Analyzer - Properly implementing Java coding style

texts:
As a new Java learner I would like to improve my coding style.
I wrote a program which gets as an input a file name, and asks for two file names for the output.

The first output file includes all the words from the input file with their number of occurrences.

The second output file includes the words in lexicographic order.

There is some code that is written twice, I think I can fix that by declaring a new method for this part of code, but I'm not sure how to do this properly.

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.io.*;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;

public class TextAnalyzer {

    private static HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
    public static StringBuffer stringBuffer;

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

        if (args.length == 0) {

            System.out.println("Please specify input file as program argument");
            return;

        }

        getWordsCount(args[0]);

        String outputFileName;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter output file name:");
        outputFileName = scanner.nextLine();
        while (outputFileName.isEmpty()) {
            System.out
                    .println("Invalid file name ! Please re-enter output file name:\n");
            outputFileName = scanner.nextLine();
        }

        stringBuffer = new StringBuffer();
        for (Entry<String, Integer> word : wordCount.entrySet()) {
            stringBuffer.append(String.format("%s\t%d%n", word.getKey(),
                    word.getValue()));
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFileName));
        bufferedWriter.write(stringBuffer.toString());
        bufferedWriter.close();

        Set<String> s = wordCount.keySet();
        List<String> l = new ArrayList<String>(s);
        Collections.sort(l);
        String s2 = "";
        for (int i = 0;  i < l.size(); i++) {

            s2 = s2 + l.get(i) + "\n";
        }

        System.out.println("Please enter output file name:");
        outputFileName = scanner.nextLine();
        while (outputFileName.isEmpty()) {
            System.out
                    .println("Invalid file name ! Please re-enter output file name:\n");
            outputFileName = scanner.nextLine();
        }

        bufferedWriter = new BufferedWriter(new FileWriter(outputFileName));
        bufferedWriter.write(s2);
        bufferedWriter.close();

        scanner.close();

    }

    /**
     * Updates the Hashmap wordCount by inserting a word as a key and its number
     * of occurrences as a value.
     *
     * @param filename
     *            the file to read from
     * @throws IOException
     */

    private static void getWordsCount(String filename) throws IOException {
        Scanner scanner = new Scanner(new File(filename));

        while (scanner.hasNext() == true) {
            String token = scanner.next();
            Integer tokenCount = wordCount.get(token);
            if (tokenCount == null) {
                wordCount.put(token, 1);
            } else
                wordCount.put(token, tokenCount + 1);
        }

        scanner.close();
    }// ENDD

}


texts: Convert binary tree to doubly linked list

texts:
The code works and I get the results I want. Please comment about complexity, a shorter way of implementing the solution, and advice for better unit tests.

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

namespace ConsoleApplication2
{
    public class BinaryTreeToList
    {
        public BinaryTreeToList()
        {

        }

        public DoubleLinkedListNode ConvertTreeToDoubleLinkedListNode(TreeNode root)
        {
            if (root == null)
            {
                return null;
            }
            DoubleLinkedListNode res = new DoubleLinkedListNode();
            res.Index = root.Index;
            if (root.Left != null)
            {
                var newNode = ConvertTreeToDoubleLinkedListNode(root.Left);
                newNode.Previous = res;
                res.Next = newNode;
            }
            if (root.Right != null)
            {
                if (res.Next == null)
                {
                    var newNode = ConvertTreeToDoubleLinkedListNode(root.Right);
                    newNode.Previous = res;
                    res.Next = newNode;
                }
                else if (res.Next.Next == null)
                {

                    var newNode = ConvertTreeToDoubleLinkedListNode(root.Right);
                    newNode.Previous = res.Next;
                    res.Next.Next = newNode;

                }
                else
                {
                    DoubleLinkedListNode temp = res;
                    while (temp.Next != null)
                    {
                        temp = temp.Next;
                    }
                    var newNode =  ConvertTreeToDoubleLinkedListNode(root.Right);
                    newNode.Previous = temp;
                    temp.Next = newNode;

                }
            }
            return res;
        }
    }

    public class DoubleLinkedListNode
    {
        public int Index { get; set; }
        public DoubleLinkedListNode Next { get; set; }
        public DoubleLinkedListNode Previous { get; set; }
    }
}

Unit Test

using System;
using System.Collections.Generic;
using ConsoleApplication2;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests
{
    [TestClass]
    public class BinaryTreeConvertToList
    {
        [TestMethod]
        public void TestMethod1()
        {
            BinaryTreeToList binaryTreeToList = new BinaryTreeToList();
            //            0
            //        2         4
            //     6    8          10
            TreeNode root = new TreeNode(0);
            root.Left = new TreeNode(2);
            root.Right = new TreeNode(4);
            root.Left.Left = new TreeNode(6);
            root.Left.Right = new TreeNode(8);
            root.Right.Right = new TreeNode(10);

            var res1 = binaryTreeToList.ConvertTreeToDoubleLinkedListNode(root);
            Assert.AreEqual(0, res1);
            Assert.AreEqual(2, res1.Next);
        }
    }
}


texts:
I've a piece of code down below that I'm really unsure about. Basically an user can type the url (urlStr param of the method) he wants. From this url I need to :

get the data as Base64 so I can display it in an html img src tag.
Being able to crop the image afterward and save the image as a file

What I'm a bit unsure about is the way I deal with the extension and the fact that I use a BufferedImage.

public Object getAsObject(FacesContext arg0, UIComponent arg1, String urlStr) {
    //extension of the image
    String extension = urlStr.substring(urlStr.lastIndexOf(".")+1);
    //object containing some infos I need
    UrlImage urlImage = new UrlImage();
    if(("jpg").equals(extension)||("jpeg").equals(extension)||("png").equals(extension)){
        urlImage.setStringUrl(urlStr);
        ByteArrayOutputStream os = null;
        try {
                final URL url = new URL(urlStr);
                final HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");

                // I'm not sure I should be doing that here
                BufferedImage image = ImageIO.read(connection.getInputStream());

                urlImage.setBuffImg(image);

                connection.disconnect();
                String str;

                os = new ByteArrayOutputStream();
                ImageIO.write(image, extension, Base64.getEncoder().wrap(os));
                str =  os.toString(StandardCharsets.ISO_8859_1.name());
                urlImage.setBase64image("data:image/"+extension+";base64,"+str);
                System.out.println("data:image/"+extension+";base64,"+str);
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }finally {
            IOUtils.closeQuietly(os);
        }
    }
        return urlImage;

}

UrlImage is just:

public class UrlImage{
    private String stringUrl;
    private String base64image;
    private BufferedImage buffImg; // this will be used to crop the image.
}

Basically there is an input field on the website. When user types an URL in the input field, an ajax request is made and the method above is called with the URL the user typed (He could change 10 times the URL which means it will go 10 times through that method). When I've the data as base 64 I send it back to the browser of the user which displays the image. Then the user can crop the image as he pleases and when he is done he presses OK. Afterward I crop the image on server side with the BufferedImage (that I already have because of the previous ajax req) and save the file.

I would have done the process of converting an URL to base 64 on client side if I could but after some tries it seems like it is impossible because of cross-origin issues.

Whole code works though.


texts: Making a job completed, rolling back on error

texts:
I have the following construction in the program:

  while(true) {
    <...>
    try {
        JobManager.markJobCompleted(unitOfWork.getSqlFactory(), jobId, dataOut);
    } catch (DbLogicException e) {
        logger.error(JobManager.CANNOT_MARK_JOB_COMPLETED + jobId, e);
        try {
            unitOfWork.rollback();
        } catch (DbLogicException e1) {
            logger.error(UnitOfWork.CANNOT_ROLLBACK_TRANSACTION, e1);
            unitOfWork.closeSilently();
            return;
        }
        continue;
    }
    <...>
  }

So, the logic is the following:

Trying to mark the job completed
If we fail, try to rollback transaction and proceed to next job item
If transaction rollback failed, something is seriously wrong here, aborting everything

This construction looks a little clumsy to me. Is there a way to refactor it so it would become... beautiful?


texts: Generating markdown documentation for VBA code

texts:
Generating documentation for VBA code

The goal of this exercise to is create an application which can read module files created in VBA project and generate markdown documentation for them.

Key features

User should be able to pass standard module (bas) based on which markdown file is created.

Limitations

There are more more types than just standard module (bas) in VBA project. For now, they are not supported.
Entry point of application (main) is yet not defined.

Project structure

vba-doc-py
│   module_parser.py
│   module_parser_tests.py
│   method_parser.py
│   method_parser_tests.py
│   module_doc.py
│   module_doc_tests.py

Code

module_parser.py

import module_doc

class ModuleParser():
    """This parser is responsible for extracting information from raw VBA code
    which later, can be used for generating markdown document."""

    def make(self, code):
        lines = code.split('\n')

        for ln in lines:
            if 'Attribute VB_Name' in ln:
                dbl_qut = ln.index('\"') + 1
                name = ln[dbl_qut: ln.rindex('\"')]
                doc = module_doc.ModuleDoc(name)

            elif 'Public Sub' in ln or 'Public Function' in ln:
                doc.addMethod(self.__get_method_name(ln), self.__get_args(ln))

        return doc.build()

    def __get_method_name(self, ln):
        method_type = 'Sub' if ' Sub ' in ln else 'Function'
        name_start = len(f'Public {method_type} ')
        open_parenthesis = ln.index('(')
        return ln[name_start:open_parenthesis]

    def __get_args(self, ln):
        open_parentheses = ln.index('(')
        close_parentheses = ln.rindex(')')

        if self.__no_args(open_parentheses, close_parentheses):
            return ''

        # Remove surrounding parentheses
        args = ln[open_parentheses + 1: close_parentheses]

        args_list = args.split(', ')
        output = []

        AS_KEYWORD = ' As '
        for item in args_list:
            as_keyword_start = item.index(AS_KEYWORD)
            arg_type = item[as_keyword_start + len(AS_KEYWORD):]
            output.append(arg_type)

        return output

    def __no_args(self, open_parentheses, close_parentheses):
        return open_parentheses + 1 == close_parentheses

    def __remove(self, text, start_index, count):
        """Returns a new string in which a specified number of characters in the current
        instance beginning at a specified position have been deleted."""

        return text[:start_index] + text[start_index + count:]

method_parser.py

class MethodParser():
    """Class responsible for parsing VBA methods (both Sub and Function)
    and turning them into specified markdown format."""

    def make(self, code):
        return f'# {self.__get_method_name(code)}\n\n```vb\n{code}\n```'

    def __get_method_name(self, ln):
        method_type = 'Sub' if ' Sub ' in ln else 'Function'
        name_start = len(f'Public {method_type} ')
        open_parentheses = ln.index('(')
        return ln[name_start:open_parentheses]

module_doc.py

class ModuleDoc():
    """Represents markdown document on the module level."""

    def __init__(self, name):
        self.name = name
        self.subs = {}

    def addMethod(self, name, args):
        self.subs.update({name: args})

    def build(self):
        output = '# ' + self.name + ' module\n\n'
        if len(self.subs) > 0:
            output += ('# Methods\n\n'
                       '|Name|Description|\n'
                       '|-|-|\n')

            for name in self.subs:
                output += f'|[{name} ({self.__format_args(self.subs[name])})](./{name}.md)||\n'

        return output

    def __format_args(self, args):
        if isinstance(args, list):
            return ', '.join(args)
        else:
            return args

Conclusion

I'm working mainly with C#/VBA and that is mostly a style which I apply here, because it is the style which I know best. Also I'm aware that Python most definitely have it's own style which I'm looking forward to explore.


texts: Scraper for parsing email-ID using email sending button

texts:
I've written a script in python with POST request which is able to send email using send button and then catch the response of that email and finally parse the ID from that. I don't know whether the way I did this is the ideal one but it does parse the email ID from this process. There are 4 email sending buttons available in that webpage and my script is able to scrape them all. Here is what I've tried so far with:

import requests
from lxml import html

main_url = "https://www.yell.com/ucs/UcsSearchAction.do?keywords=pizza&location=London&scrambleSeed=2082758402"

def main_page(url):
    response = requests.get(url, headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36'}).text
    tree = html.fromstring(response)
    for titles in tree.xpath("//div[@class='businessCapsule--callToAction']"):
        title = titles.xpath('.//a[contains(@class,"btn-blue")]/@href')[0] if len(titles.xpath('.//a[contains(@class,"btn-blue")]/@href'))>0 else ""
        process_page(title.replace("/customerneeds/sendenquiry/sendtoone/","").replace("?searchedLocation=London",""))

def process_page(number):
    link = "https://www.yell.com/customerneeds/sendenquiry/sendtoone/"
    payload = {'message':'Testing whether this email really works.','senderPostcode':'GL51 0EX','enquiryTimeframe':'withinOneMonth','senderFirstName':'mth','senderLastName':'iqbal','senderEmail':'habibrahman@gmail.com','senderEmailConfirm':'habibrahman@gmail.com','uniqueAdId':number,'channel':'desktop','ccSender':'true','marketing':'on'}
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36'}
    response = requests.post(link, data = payload, headers = headers)
    items = response.json()
    item = items['emailToCustomerUUID']
    print(item)

main_page(main_url)

These are the four email IDs I've parsed from that webpage:

1. 468145be-0ac3-4ff0-adf5-aceed10b7e5e
2. f750fa18-72c9-44d1-afaa-475778dd8b47
3. d104eb93-1f35-4bdc-ad67-47b13ea67e55
4. 90d2db3b-6144-4266-a86c-aa39b4f99d9a

Post Script: I've used my fake email address and put it in this script so that you can test the result without bringing any change to it.


texts:
I'm new to programming in general (Python is the first language I've tried learning) and I'm working my way through a collection of beginner's challenges.  I'm having a little trouble wrapping my head around functions, positional arguments, and the way they interact with user input.  I wrote this program to test my understanding.  Is there any way it could be made more efficient?

This program does the following things:

It generates a random 3 digit number.
It tells the user how to play the game.
It asks the user to guess the number.
If the number is too low, it returns 'Higher' and if the number is too high it returns 'Lower'.  Finally, if the user guesses the number correctly, it congratulates the user.
Once the correct number has been guessed, it asks the user if he/she wants to play again.
If the user says yes, the program generates a new random 3 digit number and the game starts again.  If the user chooses no, it says goodbye and quits.

Here's the code:

import random

def instructions():
    """Tells user how to operate program."""
    i = """
    I have selected a random 3 digit number.  Your goal is to guess my
    number in the smallest amount of of moves.  I will tell you if your
    guess is too high or too low, but that's all the help you'll get
    from me.
    """
    print(i)

def guess():
    g = int(input("Guess the number: "))
    return g

def hint(x):
    if x > ans:
        print("Lower")
    elif x < ans:
        print("Higher")
    else:
        print(victory(x))

def victory(x):
    if x == ans:
        print("Congratulations!  You got it!")

instructions()

ans = random.randint(100,999)

while True:
    x = guess()
    if x != ans:
        hint(x)
    elif x == ans:
        victory(x)
        replay = input("Would you like to play again? y/n: ").strip().lower()
        if replay == "y":
            ans = random.randint(100,999)
            continue
        else:
            print("Okay then.  Bye-bye.")
            break

Again, just to clarify, I've tested the program and it does work, I'm just looking to see if there's a more efficient way of writing it which doesn't sacrifice any of its current functions.  Thanks.


texts: Angular8 & RxJs: handling Observable in interceptor

texts:
the following tutorial uses an interceptor to show/hide a loading bar:

https://www.freakyjolly.com/http-global-loader-progress-bar-using-angular-interceptors/

export class LoaderInterceptor implements HttpInterceptor {
  private requests: HttpRequest<any>[] = [];

  constructor(private loaderService: LoaderService) { }

  removeRequest(req: HttpRequest<any>) {
    const i = this.requests.indexOf(req);
    if (i >= 0) {
      this.requests.splice(i, 1);
    }
    this.loaderService.isLoading.next(this.requests.length > 0);
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.requests.push(req);

    this.loaderService.isLoading.next(true);
    return Observable.create(observer => {
      const subscription = next.handle(req)
        .subscribe(
          event => {
            if (event instanceof HttpResponse) {
              this.removeRequest(req);
              observer.next(event);
            }
          },
          err => {
            alert('error' + err);
            this.removeRequest(req);
            observer.error(err);
          },
          () => {
            this.removeRequest(req);
            observer.complete();
          });
      // remove request from queue when cancelled
      return () => {
        this.removeRequest(req);
        subscription.unsubscribe();
      };
    });
  }
}

The idea is to call the method removeRequest for every type of http response, including errors etc., to make sure the loading spinner would disappear again no matter what may happens.

I have simplified this interceptor, to favor .pipe and .tap over .subscription, and would return an observable in my removeRequest function:

export class LoaderInterceptor implements HttpInterceptor {
  private requests: HttpRequest<any>[] = [];

  constructor(private loaderService: LoaderService) { }

  removeRequest(req: HttpRequest<any>): Observable<any> {
    const i = this.requests.indexOf(req);
    if (i >= 0) {
      this.requests.splice(i, 1);
    }
    this.loaderService.isLoading.next(this.requests.length > 0);

    return of([]);
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.requests.push(req);
    this.loaderService.isLoading.next(true);

    return next.handle(req).pipe(tap(
      event => {
        return this.removeRequest(req);
      },
      err => {
        return this.removeRequest(req);
      },
      () => {
        return this.removeRequest(req);
      }));

  }

}

Is there any reason at all to not favor the simplified version?


texts:
I have this loop that builds a BOM but it is so slow as I scale it out to even modest data.  All the data resides in two database tables.  I am pulling the data in as list of lists and then iterating over them.

The orders table contains the product serial number and the top level root part numbers that are ordered for that serial number.  The parts_h (hierarchy) table contains every parent - child relationship for every part defined where I work.  I am trying to build one master table by marrying them together.

Here is some sample data:

order = [['ABC1200','1234567'],['ABC1300','1234567'],['ABC1400','2456693']]
# format is [serial number, top level part]

parts_h = [['1234567','3445678'],['3445678','5K9091'],['2456693','4J5689'],
             ['4J5689','09981'],['4J5689','09982'],['09981','2K5050']]
# format is [parent, child]

def bom_build(o,p):
    '''
    This function builds the bill of material for a serial number.
    It takes two inputs.
    1.  O which is a list of lists with each element of a list
    containing the serial number, root part number
    2. P which is a list of lists with each element of a list containing
    the parent part and child part as defined in Parts master
    '''

    bom=[]
    for product in o:
        for part in p:
            if product[1] == part[0]:
                # build first level of BOM
                bom.append([product[0],product[1],part[1],"/"+product[1]+"/"+part[1]])

    # build children
    for part in p:
        for row in bom:
            if row[2] == part[0]:
               bom.append([row[0],part[0],part[1],row[3]+"/"+part[1]])
        continue
    return bom

This is the output, which is correct but slow:

[['ABC1200', '1234567', '3445678', '/1234567/3445678'],
 ['ABC1300', '1234567', '3445678', '/1234567/3445678'],
 ['ABC1400', '2456693', '4J5689', '/2456693/4J5689'],
 ['ABC1200', '3445678', '5K9091', '/1234567/3445678/5K9091'],
 ['ABC1300', '3445678', '5K9091', '/1234567/3445678/5K9091'],
 ['ABC1400', '4J5689', '09981', '/2456693/4J5689/09981'],
 ['ABC1400', '4J5689', '09982', '/2456693/4J5689/09982'],
 ['ABC1400', '09981', '2K5050', '/2456693/4J5689/09981']]

I'm then going to write this to an Impala table.


texts:
I am purely new to C++ memory management.  Am I on the right path, or should I employ a different design strategy or a different memory manager policy (such as weak_ptr)?

#include <mutex>
#include <assert.h>
#include <iostream>
#include <unordered_map>
#include <memory>
#include <string>
#include <stdio.h>

//
// Requirements:
//  1: the bitmap could be used by multiple thread safely.(std::shared_ptr could?)
//    2: cache the bitmap and do not always increase memeory
//@NotThreadSfe
struct Bitmap {
    public:
        Bitmap(const std::string& filePath) {
            filePath_ = filePath;
            printf("foo %x ctor %s\n", this, filePath_.c_str());
        }
        ~Bitmap() {
            printf("foo %x dtor %s\n", this, filePath_.c_str());
        }
        std::string filePath_;
};

//@ThreadSafe
struct BitmapCache {
    public:
        static std::shared_ptr<Bitmap> loadBitmap(const std::string& filePath) {
            mutex_.lock();

            //whether in the cache
            auto iter = cache_.find(filePath);
            if (iter != cache_.end()) {
                if ((*iter).second) {
                    return (*iter).second;
                } else {
                    std::shared_ptr<Bitmap> newPtr(new Bitmap(filePath));
                    (*iter).second = newPtr;
                    return newPtr;
                }
            }

            //try remove unused elements if possible
            if (cache_.size() >= kSlotThreshold) {
                std::unordered_map<std::string,std::shared_ptr<Bitmap>>::iterator delIter = cache_.end();
                for (auto iter = cache_.begin(); iter != cache_.end(); ++iter) {
                    auto& item = *iter;
                    if (item.second && item.second.use_count() == 1) {
                        delIter = iter;
                        break;
                    }
                }
                if (cache_.end() != delIter) {
                    (*delIter).second.reset();
                    cache_.erase(delIter);
                }
            }

            //create new and insert to the cache
            std::shared_ptr<Bitmap> newPtr(new Bitmap(filePath));
            cache_.insert({filePath, newPtr});
            mutex_.unlock();
            return newPtr;
        }
    private:
        static const int kSlotThreshold = 20;
        static std::mutex mutex_;
        static std::unordered_map<std::string,std::shared_ptr<Bitmap>> cache_;
};

/* static */
std::unordered_map<std::string,std::shared_ptr<Bitmap>> BitmapCache::cache_;

/* static */
std::mutex BitmapCache::mutex_;

int main()
{
    //test for remove useless element
    char buff[200] = {0};
    std::vector<std::shared_ptr<Bitmap>> bmpVec(20);
    for (int i = 0; i < 20; ++i) {
        sprintf_s(buff, 200, "c:\\haha%d.bmp", i);
        bmpVec[i] = BitmapCache::loadBitmap(buff);
    }
    bmpVec[3].reset();
    std::shared_ptr<Bitmap> newBmp = BitmapCache::loadBitmap("c:\\new.bmp");

    //test for multiple threading...(to be implemenetd)
    return 0;
}


texts:
I have code which I need to refactor in order to use in many places. So I tried some solutions but always ending with repeated and messy code. So, I decided to ask what possible best solutions are.

This code is used for calculating sale price in e-commerce project. My goal is to put some code in method which will not change over time, or better to say, which will be managed only from one place. This part is considering of setting sale price based on some comparison. And problem occurs in this comparison. I want also to do some formatting of controls like Label based on this result, like setting currency code. The currency code will be sometimes in $, sometimes in USD. So, this means I should somehow isolate this currency code also.

In short, I want to refactor this currency code and formatting controls based on calculated sale price.

So, I created BasketHelper class with Product and Account properties and method SetBasketPayment that return properties I set in this method. Basically, I use this approach to group properties of Product and Account classes and then return values.

Here is my code. Any further explanation, I will provide upon your request.

public class BasketHelper
{
    public Product _product { get; set; }
    public Account _account { get; set; }

    public BasketHelper SetBasketPayment(Product product, Account account,
        HyperLink lblIconOnSale, Label lblSalePrice, Label lblListPrice,
        HyperLink lblIconCampaign)
    {
        decimal _brandAccountDiscountRate = default(decimal);
        decimal _accountDiscount = default(decimal);

        if (HttpContext.Current.Request.IsAuthenticated) {
            MembershipUser mUser = Membership.GetUser();
            if (mUser != null) {
                account = Account.GetAccountByUserId(
                    (Guid)Membership.GetUser().ProviderUserKey);
                try {
                    _accountDiscount = account.DiscountRate;
                } catch (Exception ex) { }

                BrandAccountDiscount brandAccountDiscount =
                    BrandAccountDiscount
                        .GetBrandAccountDiscountByUserAndBrandId(
                            product.BrandId, mUser.ProviderUserKey.ToString());
                if (brandAccountDiscount != null) {
                    _brandAccountDiscountRate = brandAccountDiscount.DiscountRate;
                }
            }
        }

        decimal currencyMultiplier = Currency.GetCurrencyValue(product.CurrencyCode);
        decimal _listPriceTL = product.ListPrice * currencyMultiplier;

        decimal _productCampaignPrice = _listPriceTL * (1 - product.DiscountRate / 100);
        decimal _accountPrice = _listPriceTL * (1 - _accountDiscount / 100);
        decimal _brandPrice = _accountPrice * (1 - _brandAccountDiscountRate / 100);

        lblListPrice.Text = product.ListPrice.ToString("N2") + " " + product.CurrencyCode;

        if (product.DiscountRate > 0) {
            product.SalePrice = _productCampaignPrice;

            lblSalePrice.Text = _productCampaignPrice.ToString("C2") + " + KDV";
            lblListPrice.CssClass += " strike";
            lblIconCampaign.Text = "+%" + product.DiscountRate.ToString("N0");
            lblIconCampaign.Visible = true;
        } else {
            if (_accountPrice < _listPriceTL) {
                product.SalePrice = _accountPrice;

                lblIconOnSale.Text = "%" + _accountDiscount.ToString();
                lblIconOnSale.Visible = true;
            }

            if (_brandAccountDiscountRate > 0) {
                product.SalePrice = _brandPrice;

                lblSalePrice.Text = _brandPrice.ToString("C2") + " +KDV";
            }
        }

        return new BasketHelper {
            _product = product,
            _account = account
        };
    }
}


texts: Program that converts a number to a letter of the alphabet - follow-up

texts:
This is a follow up from my previous post: Program that converts a number to a letter of the alphabet

This is meant to teach my little brother (who only knows how to make games in Geometry Dash) about C, and computers. This is an example I've written meant to be shown and explained to him.

#include <stdio.h>
#include <stdbool.h>

int main() {
  //A string is an array of characters
  const char * alphabet = "ABCDEFGHIJKLMNOPQRSTUVWSYZ";
  int temp,    letter   = 0;

  while( (1 <= letter && letter <= 26) == false){
    /*
     * if scanf fails, valadate input to avoid infinite loop
     * (the below while statement).
     * Uncomment the below printf and comment out the below
     * while statement to see what happens if you type
     * something like "asdef4grvgrthd" instead of a number.
     */
    if(scanf("%d", &letter) != 1){
      while((temp=getchar()) != EOF && temp != '\n');
      //printf("Fun loop :) ");
    }
  }

  printf("The number %i corresponds to the letter '%c'\n",
          letter, alphabet[letter-1]);
}

This is intended to help beginners understand C by being a slightly harder "Hello World" program.


texts:
As a beginner coder in js, I'd like to hear about further improvements of the following code, but nothing too advanced, please.
The program is meant to work the following way:

A user inputs a color array like this one: ["blue", "green"]
The code checks if those words are valid inputs (they should be found in a reference array of COLORS). This is done with catchInvalid function
If they are valid inputs, and so they are found in COLORS array, it gets the index of it. This is done in the decodedValue function

Example1:
COLORS= ["blue", "yellow", "red"]
User input: userColors=["yellow"]
returns index of yellow in COLORS i.e 1.

Example2:
COLORS= ["blue", "yellow", "red"]
User input: userColors=["yellow", "red"]
returns index 12 (index of yellow in colors*10 + index of red in colors (2)).

That's all. It's now working fine, but I wonder if you'd give any suggestions for improving the code.
    const COLORS = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"];
 //this will be the reference array
    const catchInvalid = (color, COLORS) =>{
    //checks if color is in COLORS (which is COLORS)
            if(COLORS.indexOf(color)==-1){
                    return `not a ${color} in ${COLORS}`
            }
            else { }
    }

    const decodedValue = (colorArray) => {
            //if previous 'color' is in the reference array, get the index of the color in COLORS.
    let CODES=[];

    if (colorArray.length==0){
            return "Input a color value"
            }
    else if (colorArray.length==1){
            catchInvalid(colorArray[0], COLORS)
            return COLORS.indexOf(colorArray[0])
            }
    else {
    for(let i=0; i<2;i++){
            //only for the first 2 items in the array.
            catchInvalid(colorArray[i], COLORS)
            CODES.push(COLORS.indexOf(colorArray[i]))
            }
                                                                                return CODES[0]*10 + CODES[1];
        }
}

console.log(decodedValue(["blue"]), decodedValue(["nothing"]), decodedValue(["blue", "green"]))


texts: Generate the name of a computer from its properties

texts:
I am writing a small application to generate the domain name of computers, from their known properties, and business rules.
My Asset class is:
public enum AssetSite
{
    Rotterdam,
    Sydney,
}

public class Asset
{
/// <summary>
/// Gets the Asset Tag of the asset.
/// </summary>
public string AssetTag { get;}

/// <summary>
/// Gets the site to which the asset belongs.
/// </summary>
public AssetSite AssetSite { get; }

/// <summary>
/// Gets a value indicating whether the asset is a laptop.
/// </summary>
public bool IsLaptop { get; }

/// <summary>
/// Gets the name of the asset.
/// </summary>
public string Name
{
    get
    {
        var nameBuilder = new StringBuilder();
        nameBuilder.Append('I'); // Convention: All names start with I

        // Second letter indicates the location of the PC.
        if (this.AssetSite == AssetSite.Sydney)
        {
            nameBuilder.Append('S');
        }
        else if (this.AssetSite == AssetSite.Rotterdam)
        {
            nameBuilder.Append('R');
        }
        else
        {
            throw new ArgumentOutOfRangeException("Invalid site");
        }

        nameBuilder.Append("PC"); //Then, all PCs have 'PC' in their name.

        if (this.IsLaptop)
        {
            nameBuilder.Append("L"); //Laptops get a "L" in their name
        }
        else
        {
            nameBuilder.Append("D"); //Desktops get a "D"
        }

        nameBuilder.Append(this.AssetTag); //Unique identifier of the computer

        return nameBuilder.ToString();
    }
}

Asset objects are created through the deserialization of a JSON file
I am worried about my implementation of the Name getter. It feels way too long and complex, but at the same time, extracting each letter generation to a dedicated method feels way to complex as well.
My main concerns here are readability and maintainability.


texts: Any problems in using hibernate's session.connection() to run native sql

texts:
In my project, they use Hibernate's session the below mentioned way and then save entity objects with in a transaction.

Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();

Employee employee = new Employee() ;

employee.setName("someName") ;
employee.setEmailId ("someId")
employee.setID (100000) ;

session.saveOrUpdate(employee) ;

session.getTransaction().commit();

Now for few functionality I decided to run native SQL. Below is the way i used to run native sql. I wanted to run the queries with-in a transaction and so i decided to write the code the below way

String query = "select name from master_employee where id=?"

Session session = HibernateUtil.getCurrentSession();
session.beginTransaction();

Connection connection = session.connection();
PreparedStatement psStmt = connection.prepareStatement(query);
psStmt.setInt(1,id) ;

ResultSet resultSet = psStmt.executeQuery();
// here i will take data from this result set
psStmt.close();
resultSet.close() ;

// I am not closing the connection object since am taking it from hibernate session
// rather i commit hibernate's transaction
session.getTransaction().commit();

Is this the right way ?? will the transaction's still be managed ?? taking the connection object from session cannot be managed in to the transaction ????

Please tell if there any problems in using this way ??? thanks


texts: Telling a client that there is no result via the DTO pattern

texts:
This is how I handle this situation right now:

For example, I have service that returns UserDto by user ID: GetUserById.

Service never returns null or throws exceptions.
Service always returns DTO objects derived from the base class (DtoBase).
Each DTO object relates to some Entity type. Each entity has an assigned ID (In my example I used long for IDs, but the Response class can be made generic).

DtoBase class:

[DataContract]
public abstract class DtoBase
    : IDtoResponseEnvelop
{
    [DataMember]
    private readonly Response _responseInstance = new Response();

    //This constructor should be called when there is no result
    protected DtoBase()
    {}

    //Each DTO object relates to some Entity (each entity has as ID).
    //And if there is some result this constructor should be called.
    protected DtoBase(long entityId)
    {
        _responseInstance = new Response(entityId);
    }

    #region IDtoResponseEnvelop Members

    public Response Response
    {
        get { return _responseInstance; }
    }

    #endregion
}

Basically, the Response class aggregates operation response information such as: if there is any value, exception and warnings:

[DataContract]
public class Response
{
    #region Constructors

    public Response():this(0){}

    public Response(long entityId)
    {
        _entityIdInstance = entityId;
    }

    #endregion

    #region Private Serializable Members

    [DataMember]
    private BusinessExceptionDto _businessExceptionInstance;

    [DataMember]
    private readonly IList<BusinessWarning> _businessWarningList = new List<BusinessWarning>();

    [DataMember]
    private readonly long _entityIdInstance;

    #endregion

    #region Public Methods

    public void AddBusinessException(BusinessException exception)
    {
        _businessExceptionInstance = new BusinessExceptionDto(exception.ExceptionType, exception.Message, exception.StackTrace);
    }

    public void AddBusinessWarnings(IEnumerable<BusinessWarning> warnings)
    {
        warnings.ToList().ForEach( w => _businessWarningList.Add(w));
    }

    #endregion

    #region Public Getters

    public bool HasWarning
    {
        get { return _businessWarningList.Count > 0; }
    }

    public IEnumerable<BusinessWarning> BusinessWarnings
    {
        get { return new ReadOnlyCollection<BusinessWarning>(_businessWarningList); }
    }

    public long EntityId
    {
        get { return _entityIdInstance; }
    }

    public bool HasValue
    {
        get { return EntityId != default(long); }
    }

    public bool HasException
    {
        get { return _businessExceptionInstance != null; }
    }

    public BusinessExceptionDto BusinessException
    {
        get { return _businessExceptionInstance; }
    }

    #endregion
}

Now, having this in place, on server side we have:

    private UserDto GetUserByIdCommand(IRepositoryLocator locator, long userId)
    {
        var item = locator.GetById<User>(userId);
        if (item != null)
             return Mapper.Map<User, UserDto>(item); //mapper calls UserDto(item.ID) constructor

        _businessNotifier.AddWarning(BusinessWarningEnum.Operational,
            string.Format("User with Id=\"{0}\" not found", userId));
        return new UserDto(); //no Entity id is provided here, since no value available
    }

And, on client side:

    var userDto = UserService.GetUserById(1);
    if(!userDto.Response.HasValue)
    {
          //No result is available
    }

Is my approach fine or is there a better way?


texts:
I have this code that I am using to update OriginalId using the Id value. I there a better way to do this then using all the loops?

Controller

TemplatesDataService.UpdateRegimenCodeId(template.Regimens);

Interface

void UpdateDosageInstructionsCodeId(IEnumerable<Regimen> Regimens);

DataService

public void UpdateDosageInstructionsCodeId(IEnumerable<Regimen> regimens)
        {
            if (regimens != null)
            {
                foreach (var regimen in regimens)
                {
                    Debug.Write(string.Format("{0} {1}", "regimenId", regimen.Id));
                    regimen.OriginalId = regimen.Id;
                    foreach (var regimenPart in regimen.RegimenParts)
                    {
                        regimenPart.OriginalId = regimenPart.Id;
                        Debug.Write(string.Format("{0} {1}", "regimenPart", regimenPart.Id));
                        foreach (var entries in regimenPart.RegimenEntries)
                        {
                            entries.OriginalId = entries.Id;
                            Debug.Write(string.Format("{0} {1}", "RegimenEntries", entries.Id));
                            foreach (var dosage in entries.DosageInstructions)
                            {
                                Debug.Write(string.Format("{0} {1}", "DosageInstructions", dosage.Id));
                                dosage.OriginalId = dosage.Id;
                                UnitOfWork.Save();
                            }
                        }
                    }
                }
            }
        }


texts: C++ template to randomly choose from N elements with uniform distribution

texts:
There is a nice algorithm to randomly choose an element from a list in a single pass:

Pass through the list keeping the element chosen so far (X) and the number of elements processed (N). When processing element Y, let X:=Y with probability 1/N. When nothing is left, return X.

I implemented this using templates:

template <typename T>
const T& chooseImpl(T const& cur, int total) {
  return cur;
}

template <typename T, typename... Args>
const T& chooseImpl(T const& chosen, int total,  T const& next, Args... rest) {
  const T& nextChosen = (rand() % total == 0) ? next : chosen;
  return chooseImpl(nextChosen, total + 1, rest...);
}

template <typename T, typename... Args>
const T& choose(T const& first, Args... rest) {
  return chooseImpl(first, 2, rest...);
}

Example usage:

choose(1, 2, 3, 4, 5, 6); // returns a random number between 1 and 6.
choose(1); // always returns 1.

I only have a problem when choosing from C strings:
    choose("one", "two", "three");

  note:   template argument deduction/substitution failed:

  deduced conflicting types for parameter ‘const T’ (‘char [4]’ and ‘const char*’)


texts:
I have the following code to filter some items by the keys.

const keys = Object.keys(cars.plans)

let filteredPlans = [];

for (const key of keys) {
    if (key !== "1" && key !== "2") {
        filteredPlans.push (cars.plans[key])
    }
}

I am trying to find a more React / efficient way of doing this.

Note that I can't change the data structure as it's provided by an external API. I need a better way of filtering the data by keys.


texts: bash script to delete files resurrected by Adobe InDesign bug

texts:
After a March update, Adobe Indesign will resurrect removed directories it was responsible for creating in the first place, but not any files except for one file called "AdobeFnt.lst". So where once you had a complex folder structure, but then deleted it, you'll now have the whole structure back, but one folder somewhere will contain AdobeFnt.lst (and since it's MacOS, perhaps some .DS_Store files). My mother complained about this, and so I offered to write her a script that will check every minute for these resurrected empty directories. I wrote what's below, for addition to her crontab, but am afraid of deleting things incorrectly.

Would this safely do the job? She saves these InDesign packages to her Desktop, and I was going to tell her to add all folders she saves stuff to into the DIRS array at the top.

#!/bin/bash

# List where you save InDesign packages
DIRS=(
    "$HOME/Desktop"
)

IFS=$'\n'
for DIR in "${DIRS[@]}"; do
    DS=($(find "$DIR" -type d -maxdepth 1 -mindepth 1))
    for D in "${DS[@]}"; do
        FS=($(find "$D" -type f ! -iname .DS_Store))
        if [ ${#FS[@]} -eq 1 ] && [ $(basename "${FS[0]}") = "AdobeFnt.lst" ]; then
            echo "Removing $D"
            rm -r $D
        fi
    done
done
```


texts: Displaying nested arithmetic expressions as a string using Scala pattern matching

texts:
I am learning the concepts of pattern matching in Scala. Following is an exercise for the same. The task is to define a show function that outputs an expression as a String. Following are the definitions involved:

object Test {
  trait Expr
  case class Number(n: Int) extends Expr
  case class Sum(e1: Expr, e2: Expr) extends Expr
  case class Prod(e1: Expr, e2: Expr) extends Expr
  case class Var(name: String) extends Expr

  def nestOperations(e1: Expr, e2: Expr): String = {
    val l = e1 match {
      case Number(n) => n.toString
      case Prod(x, y) => nestOperations(x, y)
      case Var(s) => s
      case Sum(x, y) => "(" + show(x) + " + " + show(y) + ")"
    }
    val r = e2 match {
      case Number(n) => n.toString
      case Prod(x, y) => nestOperations(x, y)
      case Var(s) => s
      case Sum(x, y) => "(" + show(x) + " + " + show(y) + ")"
    }
    l + " * " + r
  }

  def show(e: Expr): String = e match {
    case Number(n) => n.toString
    case Sum(e1, e2) => show(e1) + " + " + show(e2)`
    case Prod(e1, e2) => nestOperations(e1, e2)
    case Var(s) => s
  }
  show(Sum(Number(1), Number(2)))
  show(Sum(Prod(Number(2), Var("x")), Var("y")))
  show(Prod(Sum(Number(2), Var("x")), Var("y")))
}

The expectation is that:
show(Sum(Number(1), Number(2))) outputs 1 + 2
show(Sum(Prod(Number(2), Var("x")), Var("y"))) outputs 2 * x + y
show(Prod(Sum(Number(2), Var("x")), Var("y"))) outputs (2 + x) * y

The program achieves all of the above. I want to know if the nestOperations method can be simplified? Looks like a lot of repetitive code in there.


texts: An implementation for the double factorial

texts:
I have written this piece of code that implements the double factorial in Python both iteratively and recursively; the code works without problems, but I'm interested in improving my overall programming style. Here's the code:

def semif_r(n):                 #recursive implementation
    if n == 0 or n == 1:
        z = 1
    else:
        z= n * semif_r(n-2)
    return z

def semif_i(n):             #iterative implementation
    N = 1
    if n == 0 or n == 1:
        return 1
    elif n%2 == 1:
        for i in range(0,n/2):
            N =  (2*i + 1)*N
            VAL = N
        return n*VAL

    elif n%2 == 0:
        for i in range(0,n/2):
            N =  (2*i+2)*N
            VAL = N
    return VAL

I hope that some experienced programmers can give me some feedback about improving my code!


texts:
I have created a program that prints the Nth term of the Fibonacci sequence. The fib function needs to use tail recursion. If what I have coded isn't tail recursion, I would like to know how to change the fib function so it does.

#include <iostream>
#include <sstream>

int fib(int n, int i = 0, int a = 0, int b = 1)
{
    return (i >= n - 1) ? a : fib(n, i + 1, b, a + b);
}

int main(int argc, char* argv[])
{
    if (argc < 2) {
        std::cerr << "Argument 2 must be the Nth term." << std::endl;
        return -1;
    }

    std::stringstream ss_obj(argv[1]);
    unsigned long int number;

    ss_obj >> number;

    std::cout << "\nFibonacci number: " << fib(number) << std::endl;
    return 0;
}


texts: Pythonic way of removing one word entries from compound list

texts:
Assume a multi-line file (myInput.txt) with lines comprising one or more words.
echo -e "Foo\nFoo bar\nFoo baz\nFoo bar baz\nBar\nBaz\nBaz qux\nBaz qux quux\nQux quux" > myInput.txt

I wish to remove all one-word lines that are identical with the first word of any multi-word lines using Python.
echo -e "Foo bar\nFoo baz\nFoo bar baz\nBar\nBaz qux\nBaz qux quux\nQux quux" > myGoal.txt

The following code satisfies my goal but does not appear overtly Pythonic to me.
from itertools import compress

myList = list()
with open("myInput.txt", "r") as myInput:
    for line in [l.strip() for l in myInput.readlines()]:
        if not line.startswith("#"):
            myList.append(line)

# Get all lines with more than one word
more_than_one = list(compress(myList, [len(e.strip().split(" "))>1 for e in myList]))
# Get all lines with only one word
only_one_word = list(compress(myList, [len(e.strip().split(" "))==1 for e in myList]))
# Keep only unique set of initial words of more_than_one
unique_first_words = list(set([e.split(" ")[0] for e in more_than_one]))
# Remove all union set words from only_one_word
only_one_word_reduced = [e for e in only_one_word if e not in unique_first_words]
# Combine more_than_one and only_one_word_reduced
combined_list = only_one_word_reduced + more_than_one

Do you have any suggestions on making the Python code slimmer and more straightforward?


texts:
I just implemented a version of A* search in JavaScript for educational purposes. I'd really love it if you could take a look and tell me how to improve my code.

The grid passed in is just a multidimensional array (2-D array) where each slot in the inner array is an object with property weight.

The point of this function is to build an "algorithm visualizer", where I have all the nodes that were visited by A* (visited) and all the nodes that A* eventually selected to be part of the shortest path (path). I later take this and display this to the user with my UI logic.

In terms of the heuristic, I use Euclidean Distance.

import PriorityQueue from "./data structures/priorityqueue";

export default function astar(grid, startNode, endNode) {
  function isValid(r, c) {
    if (r < 0 || c < 0) {
      return false;
    }
    if (r < grid.length && c < grid[r].length) {
      return true;
    }
    return false;
  }

  function calculateHeuristic(r, c) {
    let row = (endNode[0] - r) ** 2;
    let col = (endNode[1] - c) ** 2;
    return (row + col) ** (1 / 2);
  }

  let dist = [], // represents distances from start to node
    visited = [], // list of all the nodes A* visits
    ordering = []; // final ordering

  for (let r = 0; r < grid.length; r++) {
    let row = [],
      orderingRow = [];
    for (let c = 0; c < grid[r].length; c++) {
      row.push(Number.MAX_VALUE);
      orderingRow.push(null);
    }
    dist.push(row);
    ordering.push(orderingRow);
  }
  let d = 0;
  let pqueue = new PriorityQueue();
  let priority = calculateHeuristic(startNode[0], startNode[0]) + d;
  pqueue.enqueue([startNode[0], startNode[1], startNode, d], priority);
  let cur,
    neighbors = [
      [1, 0],
      [-1, 0],
      [0, 1],
      [0, -1]
    ];

  while (!pqueue.isEmpty()) {
    cur = pqueue.dequeue();
    let r = cur.element[0],
      c = cur.element[1],
      origin = cur.element[2],
      d = cur.element[3];

    visited.push([r, c]);

    if (dist[r][c] <= d) {
      continue;
    }

    ordering[r][c] = origin;
    dist[r][c] = d;

    if (r === endNode[0] && c === endNode[1]) {
      break;
    }

    for (let n of neighbors) {
      let rr = r + n[0];
      let cc = c + n[1];
      if (!isValid(rr, cc)) {
        continue;
      }
      let dd = d + grid[rr][cc].weight;
      if (dd < dist[rr][cc]) {
        priority = dd + calculateHeuristic(rr, cc);
        pqueue.enqueue([rr, cc, [r, c], dd], priority);
      }
    }
  }

  let path = [endNode];

  let r = endNode[0],
    c = endNode[1];

  while (r !== startNode[0] || c !== startNode[1]) {
    path.push(ordering[r][c]);
    [r, c] = ordering[r][c];
  }
  path.reverse();
  return { visited, path };
}

Thank you for reading and I look forward to your critiques.