texts:
I have a string like this :

val content = "some_text{macro1}another_text{macro2}text"

I want to replace the {macro1} and {macro2} with macro1 and macro2, i.e. just to remove the { and }.

I wrote some piece of code which works fine, but for me it seems very hard to read:

val Pattern = """\{(.*)\}""".r

Pattern.findAllIn(content).matchData.foldLeft(content) ( (newContent: String, current: Regex.Match) => {
     newContent.replace(current.group(0), current.group(1))
   }
)

How I can improve this code? Please note: since it's in Scala, I prefer it in the functional way.


texts: Classifying the user into an age bracket

texts:
In this program, I have to check the range of a given age and then print a message as per the age. I want to optimize the if else  logic.

/* Sample code to read in test cases:*/

import java.io.*;
public class Main {
 public static void main (String[] args) throws IOException {
    File file = new File(args[0]);
    BufferedReader buffer = new BufferedReader(new FileReader(file));
    String line;
    while ((line = buffer.readLine()) != null) {
        line = line.trim();
        // Process line of input Here

        int age = Integer.parseInt(line);

          if(age>=0 && age<=2){
              System.out.println("Still in Mama's arms");
             // break;
          }else if(age>=3 && age<=4){
               System.out.println("Preschool Maniac");
              // break;
          }else if(age>=5 && age<=11){
               System.out.println("Elementary school");
             // break;
          }else if(age>=12 && age<=14){
               System.out.println("Middle school");
             // break;
          }else if(age>=15 && age<=18){
               System.out.println("High school");
             // break;
          }else if(age>=19 && age<=22){
               System.out.println("College");
             // break;
          }else if(age>=23 && age<=65){
               System.out.println("Working for the man");
             // break;
          }else if(age>=66 && age<=100){
               System.out.println("The Golden Years");
              //break;
          }else{
               System.out.println("This program is for humans");

          }
         }
      }
    }

Is there any other way to do this program? Using a switch, it becomes more complex to type with so many cases for the age.


texts: Finding number of brackets sequences of length n containing a specific string s

texts:
I am trying to solve a problem where I need to find the number of bracket sequences \$p\$ and \$q\$ such that for a given bracket sequence s. I have that \$p + s + q\$ is a valid bracket sequence. Also \$|p+s+q| = 2n\$.

We can use dynamic programming here, i.e. let dp[i][j] = the number of bracket sequences (which are a prefix of a valid bracket sequence) with \$i\$ ('s and \$j\$ )'s. Also \$i\ge j\$.

Now we have

\$\displaystyle dp(i, j)=
\begin{cases}
0&i<j\text{ or }i<0\text{ or }j<0\\
1&j=0\\
dp(i-1, j)+dp(i, j-1)&\text{otherwise}
\end{cases}\$

Now let us suppose

\$p\$ has \$x\$ ('s and \$y\$ )'s
\$s\$ has \$l\$ ('s and \$r\$ )'s.

Then we must have \$y\ge x\$ for \$p\$ to be valid, \$x+l\ge y+r\$ for \$p+s\$ to be valid and the same must hold for \$p+s_i\$ i.e. in any prefix \$s_i\$ of \$s\$ appended to \$p\$.

So we have \$x+l_i\ge y+r_i\$ or \$x-y+l_i-y_i\ge 0\$. We have \$x-y+l_i-y_i\ge x-y+\min_i\{l_i-r_i\}\ge0\$. So we need to have \$x+\min_i\{l_i-r_i\}\ge y\$

So we can loop over all possible values of \$x,y\$ and see if we can find \$p,q\$. Number of ways of \$p\$ will be dp[x][y]. Now if we reverse all brackets in \$p+s+q\$ (which is also a valid sequence), we can see that \$q\$ has \$n-y-r\$ ('s and \$n-x-l\$ )'s. So the number of ways of that is dp[n-y-r][n-x-l]

Note: I need to find the solution mod \$10^9+7\$. You can find more details here.

This is the solution that I came up with. I am facing high memory usage (i)How can I improve the memory usage? (ii) Also is there a way I can make it more concise?

The only problem could be the \$dp\$ which will hold \$n^2\$ entries of Int64

import           Data.Array
import           Data.Int
import           Data.List
import           Data.Function
import           Control.Monad

main :: IO ()
main = do
    [n', m] <- map read . words <$> getLine -- n'=2n, m=|s|
    s       <- getLine
    print $ solve n' s

solve n' s =
    let
        n   = n' `div` 2 -- number of ( or )
        l   = length $ filter (== '(') s
        r   = length s - l
        mm  = 10 ^ 9 + 7 :: Int64
        arr = array ((0, 0), (n, n))
                    [ ((i, j), f i j) | i <- [0 .. n], j <- [0 .. n] ] -- the dp array
        f i j
            | j == 0 -- base case dp
            = 1
            | j > i -- invalid sequence
            = 0
            | otherwise
            = let left = if i > 0 then arr ! (i - 1, j) else 0
                  down = if j > 0 then arr ! (i, j - 1) else 0
              in  (left + down) `mod` mm
        minVal =
            minimum $ scanl (\v c -> if c == '(' then v + 1 else v - 1) 0 s -- min li - ri
    in
        (`mod` mm)
        . sum
        $ [ let leftWays  = arr ! (x, y)
                rightWays = arr ! (n - y - r, n - x - l)
            in  (leftWays * rightWays) `mod` mm
          | x <- [0 .. n - l] -- x+l<=n
          , y <- [0 .. x + l - r] -- y <= x, y + r <= x - l
          , x + minVal >= y -- x + min (li - ri) >= y
          ]


texts:
I have a function which returns an error. I would like to handle this error on the caller function, so I need to know the reason of the error in the caller function.

Below there is my solution, but I am not sure, that it is ideomatic Go code and would be thankfull for any comments.

Here is the function:

func (e *Engine) returnOrCreateArtist(musicService musicservices.IMusicService, serviceArtistId string) (*core.Artist, error) {

    artist, err := e.DataRepository.ArtistRepository.GetByArtistId(serviceArtistId)
    if err != nil {
        artist, err = musicService.DownloadArtist(serviceArtistId)
        if err != nil {
            return nil, NewDownloadArtistError(err)
        }

        artist, err = e.DataRepository.ArtistRepository.Store(artist)
        if err != nil {
            return nil, NewStoreArtistError(err)
        }
    }

    return artist, nil
}

It can returns errors of two types, so I have created two structs to distinct two types of my error:

type DownloadArtistError struct {
    InnerError error
}

func (e *DownloadArtistError) Error() string {
    return e.InnerError.Error()
}

func NewDownloadArtistError(e error) *DownloadArtistError {
    return &DownloadArtistError{InnerError: e}
}

type StoreArtistError struct {
    InnerError error
}

func (e *StoreArtistError) Error() string {
    return e.InnerError.Error()
}

func NewStoreArtistError(e error) *StoreArtistError {
    return &StoreArtistError{InnerError: e}
}

And here is a part of caller function:

artist, err := e.returnOrCreateArtist(musicService, track.ServiceArtistId)
if err != nil {
     switch e := err.(type) {
         case *DownloadArtistError:
            logger.With(zap.Error(e)).Errorw("не удалось получить исполнителя на музыкальном сервисе",
                "Track.ServiceId", track.TrackId,
                "Track.PlaylistId", track.PlaylistId,
                "Track.ArtistId", track.ServiceArtistId)
         case *StoreArtistError:
            logger.With(zap.Error(err)).Errorw("не удалось сохранить исполнителя",
                "Track.ServiceId", track.TrackId,
                "Track.PlaylistId", track.PlaylistId,
                "Track.ArtistId", track.ServiceArtistId)
            }
        continue
    }


texts: Max difference between two array elements

texts:
Can I get feedback on below code? Problem statement is Maximum difference between two elements such that larger element appears after the smaller number

Would this solution be still considered O(n) for time complexity? I know I do one additional pass but I found this way to be more intuitive

Is error handling done properly? Other ways to improve it?

int maxDiff(int *arr, int len);

int main(void)
{
  int arr[] = {80, 2, 6, 3, 100};
  int len = sizeof(arr)/sizeof(int);
  int max_diff = maxDiff(arr, len);
  printf(" max diff is %d \n ", max_diff);
  return 0;
}

int maxDiff(int *arr, int len)
{
  int min = INT_MAX;
  int max = INT_MIN;
  int max_index;

  if (len < 1 || arr == NULL)
  {
      printf(" No element present \n ");
      return INT_MIN;
  }

  for (int i = 0; i < len; i++)
  {
     if (arr[i] > max)
     {
       max = arr[i];
       max_index = i;
     }
  }

  for(int i = 0; i < max_index; i++)
  {
     if (arr[i] < min)
     {
       min = arr[i];
     }
  }

  return max - min;
}


texts:
I decided to try and complete the Parsing/RPN calculator algorithm from Rosetta Code in Rust. I'm still learning Rust and would appreciate feedback on my code.

use std::str::FromStr;

fn rpn(expression: &str) -> f64 {
    let mut stack: Vec<f64> = Vec::new();
    let tokens: Vec<&str> = expression.split_whitespace().collect();
    for token in tokens {
        match token {
            "+" => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(a + b);
            },
            "-" => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(a - b);
            },
            "*" => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(a * b);
            },
            "/" => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(a / b);
            },
            "^" => {
                let b = stack.pop().unwrap();
                let a = stack.pop().unwrap();
                stack.push(a.powf(b));
            },
            _ => {
                stack.push(f64::from_str(token).unwrap());
            }
        }
    }
    stack.pop().unwrap()
}

fn main() {
    let expression = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
    println!("{}", rpn(expression));
}

I had attempted to write the commutative operations without assigning the operands to variables (i.e. a and b) like this:

stack.push(stack.pop().unwrap() + stack.pop().unwrap());

However, I received:

error: cannot borrow `stack` as mutable more than once at a time [E0499]

Another Approach

One approach I noticed some of the other languages' implementations using was to first check if a token is a number and push it onto the stack before checking for the operations. This allowed them to pop the two operands for the operations after they were sure it wasn't a number.

fn rpn(expression: &str) -> f64 {
    let mut stack: Vec<f64> = Vec::new();
    for token in expression.split_whitespace() {
        let value = token.parse::<f64>();
        if value.is_ok() {
            stack.push(value.unwrap());
            continue;
        }
        let b = stack.pop().unwrap();
        let a = stack.pop().unwrap();
        match token {
            "+" => stack.push(a + b),
            "-" => stack.push(a - b),
            "*" => stack.push(a * b),
            "/" => stack.push(a / b),
            "^" => stack.push(a.powf(b)),
            _ => {}
        }
    }
    stack.pop().unwrap()
}


texts: Big Nerd Ranch Bronze Challenge: Disallow Alphabetic Characters

texts:
I just completed BNR's bronze challenge for disallowing alphabetic characters, and would love some feedback on what I did right and wrong, and how I can improve my code for reusability and maintainability.

Here's a snippet of instruction from their book, iOS Programming: The Big Nerd Ranch Guide (5th Edition) (Big Nerd Ranch Guides):

  Currently, the user can enter alphabetic characters either by using a Bluetooth keyboard or by pasting copied text into the text field. Fix this issue. Hint: you will want to use the NSCharacterSet class.

I basically have a text field that takes numeric input. I allow the user to enter digits 0-9, inclusive with negative numbers and one decimal point. What the app does is convert Fahrenheit to Celsius, but that's not entirely relevant.

My ViewController is conforming to the UITextFieldDelegate protocol, and I'm implementing:

optional public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool

Here's my snippet:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let existingTextHasDecimalSeparator = textField.text?.rangeOfString(".")
    let replacementTextHasDecimalSeparator = string.rangeOfString(".")

    if string.characters.count == 0 {
        return true
    }
    else {
        if let _ = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "-0123456789.")) {
            if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
                return false
            }
            else {
                return true
            }
        }
        return false
    }
}


texts:
I'm looking to make some improvements to a deliberately crude API written in PHP, it's designed to handle simple requests and talk to the DB.

I have the following DB class:

class DB
{
    public function connect()
    {
        $serverName = ".";
        $connectionInfo = array("Database"=>"Demo","UID"=>"sa","PWD"=>"qwe123");
        $connection = sqlsrv_connect( $serverName, $connectionInfo);

        return $connection;
    }

    public function close($connection)
    {
        return sqlsrv_close($connection);
    }

    public function query($connection, $query, $params = null)
    {
        return sqlsrv_query($connection, $query, $params);
    }
}

And then for requests I do:

$db = new DB();
$conn = $db->connect();

$sql = "INSERT INTO Applications (name, friendly_name, description, enabled, visible, icon, video) VALUES (?, ?, ?, ?, ?, ?, ?)";

$params = array($name, $friendly_name, $description, $enabled, $visible, $icon, $video);

$query = $db->query($conn, $sql, $params);

if( $query === false )
{
    $response = array('error' => 'Error');
}
else
{
    $response = array('success' => 'Success');
}

$db->close($conn);

return $response;

I was wondering how I could improve this further and not have to repeat the db connect and creating an instance of the class and close the connection.

I know I could and should be using PDO, but for this example I want to keep it old school.


texts:
I was trying to do this question and I get TLE on one the test cases (the actual link to the question  will ask you to login).
What is an inversion?

An inversion of an element is the number of elements to the left which
are greater. Sum of number of numbers throughout a segment is the
answer.

It is based on Segment Trees.
My attempt is this:
#include <bits/stdc++.h>
#define ll long long
using namespace std;

struct segtree {

    int size;
    vector<int> sums;

    void init(int n){
        size=1;
        while(size<n)
            size*=2;
        sums.assign(2*size,0);
    }

    void change(int i,int v,int x,int lx,int rx){
        if(rx-lx==1){sums[x]+=v;return;}
        int m=(lx+rx)/2;
        if(i<m)
            change(i,v,2*x+1,lx,m);
        else
            change(i,v,2*x+2,m,rx);
        sums[x]= sums[2*x+1] + sums[2*x+2];
    }
    void change(int i,int v){
        change(i,v,0,0,size);
    }

    int calc(int l,int r,int x,int lx, int rx){
        if(lx>=l&&rx<=r) return sums[x];
        if(rx<=l||lx>=r) return 0;
        int m =(lx+rx)/2;
        return calc(l,r,2*x+1,lx,m) + calc(l,r,2*x+2,m,rx);
    }
    int calc(int l){
        return calc(l,size,0,0,size);
    }
};

int main(){

    int n, m;
    cin >> n >> m;

    vector<int> a(n);

    for(int i=0;i<n;++i)
        cin >> a[i];

    while(m--) {
        int op;
        cin >> op;

        if(op == 1){

            int x, y;
            cin >> x >> y;

            x-=1;

            segtree st;
            st.init(40);

            int sum = 0;

            for(int i=x;i<y;++i){
                int val = a[i];
                sum += st.calc(val);
                st.change(val-1, 1);
            }

            cout << sum << "\n";

        } else {
            int x, y;
            cin >> x >> y;
            a[x-1]=y;
        }
    }

    return 0;
}

I wanna know a better time complexity version of the program.


texts:
I'm creating a Tic Tac Toe solver algorithm. The idea is to iterate through each row, column and both diagonals and put them into a map in JavaScript. With that map I can run other logic to check for a winner and where that winner's position is.

I'm not building an actual TTT game nor am I writing any AI for now. My question is if there's a better way of achieving the same results without having to use two for loops to get the columns and second diagonals.

let board = [
  ['x','o','x'],
  ['o','o','o'],
  ['o','o','x']
];

const mapper = board => {
  let map = {},
  d1 = [],
  d2 = [];

  for (let i = 0; i < board.length; i++) {
    let tmp = [];
    // get all rows
    map[`ROW${i}`] = board[i];

    // get second diagonals
    d2.push(board[i][board.length-1-i]);

    for (let j = 0; j < board.length; j++) {
      // get all columns
      tmp.push(board[j][i]);

      // get first diagonals
      if (i === j) {
        d1.push(board[i][j])
      }
    }

    map[`COL${i}`] = tmp;
  }

  map[`DIA1`] = d1;
  map[`DIA2`] = d2;

  return map;
}

const checkForWinner = board => {
  return mapper(board);
}

checkForWinner(board);


texts: Please review my solution to Project Euler program 1

texts:
Can someone give me suggestions on how to improve this program?

The objective is to find the sum of all the multiples of 3 or 5 below 1000.

#include <stdio.h>

main()
{
    int S, s3,s2,S1;
    int a=333,b=3,c=999, i=5,j=995, k=199, m = 15, n= 66, o= 990;
    S1= a*(b+c)/2;
    s2= k*(i+j)/2;
    s3= n*(m+o)/2;
    S= S1 + s2 - s3;
    printf("sum is:%d",S);
    return 0;
}


texts: Encoding the problem domain of products and prices into the typesystem in F#

texts:
I'm trying to design a model for purchasing amounts of products in F#, following the ideas for designing for correctness (source). The idea is to use the type system to capture the different legal states, making it impossible to represent invalid states as defined by your requirements.

Since I'm not too experienced with F# yet I was hoping to get some feedback on my approach. Can the following be represented in a simpler manner and are there any problems with this design? This does obviously not support a dynamic list of currencies, so this would be an area of improvement. Another issue would be dealing with negative amounts which is not prevented.

// Monatary units
[<Measure>] type dkk
[<Measure>] type usd

// Amounts of products
[<Measure>]
type kg
[<Measure>]
type unit

type Weight = decimal<kg>
type Count = int<unit>
type Amount =
| Weight of Weight
| Count of Count

type Money =
| DKK of decimal<dkk>
| USD of decimal<usd>

type UnitPrice<[<Measure>]'u> =
| DkkPrAmount of decimal<dkk/'u>
| UsdPrAmount of decimal<usd/'u>

type WeightedProduct = { Name:string; UnitPrice:UnitPrice<kg> }
type UnitProduct = { Name:string; UnitPrice:UnitPrice<unit> }
type Product =
| WeightedProduct of WeightedProduct
| UnitProduct of UnitProduct

type AmountOfProduct =
| KgOfProduct of (WeightedProduct * Weight)
| CountOfProduct of  (UnitProduct * Count)

Some examples of how you would use the types:

// Available products
let snickers = { Name = "Snickers"; UnitPrice = DkkPrAmount 12.95m<dkk/unit> }
let mars = { Name = "Mars"; UnitPrice = DkkPrAmount 11.95m<dkk/unit> }
let twix = { Name = "Twix Double Pack"; UnitPrice = DkkPrAmount 18.95m<dkk/unit> }
let flour:WeightedProduct = { Name = "Wheat Flour"; UnitPrice = DkkPrAmount 15.95m<dkk/kg> }

let calculatePrice amountOfProduct =
    match amountOfProduct with
    | KgOfProduct (product, weight) ->
        match product.UnitPrice with
        | DkkPrAmount dkPrice -> DKK (weight * dkPrice)
        | UsdPrAmount usPrice -> USD (weight * usPrice)
    | CountOfProduct (product, count) ->
        match product.UnitPrice with
        | DkkPrAmount dkPrice -> DKK ((decimal count) * (dkPrice * 1.0m<unit>))
        | UsdPrAmount usPrice -> USD ((decimal count) * (usPrice * 1.0m<unit>))

let calculateTotalPrice purchase priceConverter =
    purchase
    |> List.map calculatePrice
    |> List.map priceConverter
    |> List.sum

let dkkPerUsd = 6.23m<dkk/usd>
let usdPerDkk = 0.16m<usd/dkk>

let toDkk money =
    match money with
    | DKK dkk -> dkk
    | USD usd -> dkkPerUsd * usd

let toUsd money =
    match money with
    | DKK dkk -> usdPerDkk * dkk
    | USD usd -> usd

let purchase = [CountOfProduct (snickers, 1<unit>); CountOfProduct (mars, 1<unit>); CountOfProduct (twix, 3<unit>); KgOfProduct (flour, 20.0m<kg>)]
let totalPrice = calculateTotalPrice purchase toDkk


texts: How do I shorten my Rust code to get integer values from regex named capture groups?

texts:
I am completely new to rust. My first rust code is simple text filter application for parsing log file and accumulating some information. Here is my code:

//use std::io::{self, Read};
use std::io::{self};
use regex::Regex;

fn main() -> io::Result<()> {
    let re_str = concat!(
        r"^\s+(?P<qrw1>\d+)\|(?P<qrw2>\d+)",//qrw 0|0
        r"\s+(?P<arw1>\d+)\|(?P<arw2>\d+)",//arw 34|118
        );
    let re = Regex::new(re_str).unwrap();
    //let mut buffer = String::new();
    //io::stdin().read_to_string(&mut buffer)?;
    let buffer = " 0|1 2|3\n 4|5 6|7\n 8|9 10|11\n";

    let mut lines_skipped = 0;

    let mut m_qrw1:i32 = 0;
    let mut m_qrw2:i32 = 0;
    let mut m_arw1:i32 = 0;
    let mut m_arw2:i32 = 0;

    for line in buffer.lines() {
        match re.captures(line) {
            Some(caps) => {
                // I would like to shorten these long lines =>
                let qrw1 = caps.name("qrw1").unwrap().as_str().parse::<i32>().unwrap();
                let qrw2 = caps.name("qrw2").unwrap().as_str().parse::<i32>().unwrap();
                let arw1 = caps.name("arw1").unwrap().as_str().parse::<i32>().unwrap();
                let arw2 = caps.name("arw2").unwrap().as_str().parse::<i32>().unwrap();
                if qrw1 > m_qrw1 {m_qrw1 = qrw1}
                if qrw2 > m_qrw2 {m_qrw2 = qrw2}
                if arw1 > m_arw1 {m_arw1 = arw1}
                if arw2 > m_arw2 {m_arw2 = arw2}
            }
            None => {
                lines_skipped = lines_skipped + 1;
            }
        }
    }
    println!("max qrw1: {:.2}", m_qrw1);
    println!("max qrw2: {:.2}", m_qrw2);
    println!("max arw1: {:.2}", m_arw1);
    println!("max arw2: {:.2}", m_arw2);

    Ok(())
}

Playground

This works as expected, but I think those long chained calls which I created to get integer values of regex named capture groups are a bit ugly. How do I make them shorter/more in idiomatic rust style? I've got an advice to use ? operator instead of unwrap calls but I'm not sure how to apply it in this case.


texts:
I'm working on a Phoenix/Absinthe application and I thought to expose encrypted sequential IDs instead of UUIDs since these are a bit shorter.
Encryption on Elixir/Erlang seems very hard, so I think I'll use UUIDs eventually.

Anyway I'd like to know how bad, from security perspective, is the solution I came up with:

defmodule MyAppWeb.GraphQL.Types.EncId do
  use Absinthe.Schema.Notation

  defp secret_key(len \\ 32) do
    Application.get_env(:my_app, MyAppWeb.Endpoint)
    |> Keyword.get(:secret_key_base, "")
    |> String.slice(0, len)
  end

  defp pad_bytes(binary, block \\ 16) do
    padding_bits =
      case rem(byte_size(binary), block) do
        0 -> 0
        r -> (block - r) * 8
      end

    <<0::size(padding_bits)>> <> binary
  end

  defp unpad_bytes(<<0, tail::bitstring>>), do: unpad_bytes(tail)
  defp unpad_bytes(binary), do: binary

  defp encrypt(raw_binary) do
    padded_binary = pad_bytes(raw_binary)

    :crypto.crypto_one_time(:aes_256_ecb, secret_key(), padded_binary, true)
  end

  defp decrypt(raw_enc) do
    :crypto.crypto_one_time(:aes_256_ecb, secret_key(), raw_enc, false)
    |> unpad_bytes()
    |> :erlang.binary_to_term()
  end

  def serialize(id) do
    id
    |> :erlang.term_to_binary()
    |> encrypt()
    |> Base.url_encode64(padding: false)
  end

  def parse(%{value: enc_id}) do
    try do
      {:ok, raw_enc} = Base.url_decode64(enc_id, padding: false)
      {:ok, decrypt(raw_enc)}
    rescue
      _ -> :error
    end
  end

  scalar :enc_id, name: "EncId" do
    serialize(&__MODULE__.serialize/1)

    parse(&__MODULE__.parse/1)
  end
end


texts: Tinder-esque location pulse animation effect

texts:
As shameful as it is to say I wanted to see what all the fuss about was with Tinder, but after downloading it I found I was more interested with its animation effects and started wondering how they did them!

I decided I wanted to see if I could replicate some of them using jQuery so they can be used on web apps and sites and such, but it's always nice to have these snippets lying around if I ever need them.

This seems lightweight enough, and I'm pretty sure I've covered everything, each circle element is targeted individually, the elements are removed after to stop a build up etc. But just out of curiosity, would anyone have approached it differently?

$(document).ready(function () {
    var x = 0;

    addCircle(x);

    setInterval(function () {
        if (x === 0) {
            x = 1;
        }

        addCircle(x);

        x++;
    }, 1200);
});

function addCircle(id) {
    $('body').append('

');

    $('#' + id).animate({
        'width': '300px',
        'height': '300px',
        'margin-top': '-150px',
        'margin-left': '-150px',
        'opacity': '0'
    }, 4000, 'easeOutCirc');

    setInterval(function () {
        $('#' + id).remove();
    }, 4000);
}

Example


texts: Re-organizing indices in case of fragmentation is T-SQL

texts:
In order to keep the fragmentation ratio of indices low, you should re-organize the indices from time to time on MSSQL. Microsoft describes in the link below how you can check the fragmentation of indices on tables in MSSQL and then how you can re-organize (re-build) the indices to reduce the fragmentation percentage:
https://docs.microsoft.com/en-us/sql/relational-databases/indexes/reorganize-and-rebuild-indexes?view=sql-server-ver15
It would be nice to have a procedure that automatically re-organizes the indices in case the fragmentation percentage reaches a specific threshold. The procedure below does that:
create procedure ui_reorganize_indices @db_name nvarchar(127), @table_name nvarchar(127)
as
begin
    declare @avg_fragmentation_in_percent float
    declare @index_name nvarchar(127)
    declare @alter_index_command nvarchar(256)

    declare rebuild_index_cursor cursor local for
        select name AS IndedxName, avg_fragmentation_in_percent
        FROM sys.dm_db_index_physical_stats
            (DB_ID (@db_name)
                , OBJECT_ID(@table_name)
                , NULL
                , NULL
                , NULL) AS a
        INNER JOIN sys.indexes AS b
            ON a.object_id = b.object_id
            AND a.index_id = b.index_id
            and avg_fragmentation_in_percent > 20.0;

    open rebuild_index_cursor
        fetch next from rebuild_index_cursor into @index_name, @avg_fragmentation_in_percent
        while @@fetch_status = 0
        begin
            select @alter_index_command = formatmessage('alter index %s on %s REORGANIZE', @index_name, @table_name)
            print @alter_index_command
            exec (@alter_index_command)
            fetch next from rebuild_index_cursor into @index_name, @avg_fragmentation_in_percent
        end
    close rebuild_index_cursor
end
go

Have you guys used similar procedures to improve the health of your indices?


texts: Optimizing BZ2 decompression code for big data set

texts:
I have the following fully working code that:

Walks through all sub-folders in a given directory;
Captures dirpath and filename for the compressed file (i.e., Dir/*.json.bz2);
Creates a decompressed file with the same dirpath and new file ending (i.e., Dir/*.json). Notably, each newly created decompressed file has a unique numbered filename (i.e., 1.json, 2.json, ..., n.json);
Decompresses BZ2 archives and writes them on disk.

I tested the code using 1,380 BZ2 archives (~1.5GB) and it takes substantial time to process them. Considering that my goal is to decompress 40,000 BZ2 archives (~45Gb) per run, please suggest if there is a plausible way to optimize the code in order to increase its speed. Thanks!

import os

file_counter = 0
for dirpath, dirname, files in os.walk('/Users/mymac/Documents/Dir'):
    for filename in files:
        file_counter += 1
        if filename.endswith('.json.bz2'):
            filepath = os.path.join(dirpath, filename)
            newfilepath = os.path.join(dirpath, "{0}.json".format(file_counter))
            with open(newfilepath, 'wb') as new_file, bz2.BZ2File(filepath, 'rb') as file:
                for data in iter(lambda : file.read(100 * 1024), b''):
                    new_file.write(data)

Additionally, I am curious which option will be more efficient: (A) run the code and then delete all processed BZ2's, or (B) add some lines in the code and delete each decompressed BZ2 while running the code?


texts: Compress numbers in a string array (#3, #1, #2, #4) to range (#1:#4)

texts:
This function takes a string array,

{"foo", "#123", "#124", "bar", "#125", "#126"}

makes a new array with the numbers converted to a range:

{"foo", "#123:126", "bar"}

and returns:

"foo,#123:126,bar"

Note it doesn't and shouldn't change {"#1", "#2"} to {"#1:#2"}

using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
    static void Main(string[] args)
    {
        var ids = new string[] {
            "foo", //output: unmodified
            "#60", "#59", "#61", "#62", //from integer is in between, output: #59:#62
            "#12", "#14", "#17", "#13", "#18", "#bar", "#19", "#20", //two ranges and string intertwined, output: #12:#14,#17:#20,#bar
            "#25", "#26", //output: unmodified
            "#39", "#38", //output: unmodified
            "baz", //output: unmodified
            "#12", "#13", "#14" //duplicate sequences, output: #12:#14
        };
        Console.WriteLine("foo,#59:#62,#12:#14,#17:#20,#bar,#25,#26,#38,#39,baz,#12:#14");
        Console.WriteLine(Compress(ids));
        Console.Read();
    }
    static string Compress(IEnumerable<string> IDs)
    {
        var result = new List<string>();
        var ignore = new HashSet<string>();
        foreach (var item in IDs)
        {
            if (ignore.Contains(item)) continue;
            var id = item;
            if (id.StartsWith("#"))
            {
                int fromInt;
                if (int.TryParse(id.Substring(1), out fromInt))
                {
                    var less1 = $"#{fromInt - 1}";
                    var plus1 = $"#{fromInt + 1}";
                    var hasPlus1 = IDs.Contains(plus1);
                    if (IDs.Contains(less1) && hasPlus1) continue;
                    var plus2 = $"#{fromInt + 2}";
                    if (hasPlus1 && IDs.Contains(plus2))
                    {
                        ignore.Add(plus1);
                        ignore.Add(plus2);
                        var toInt = fromInt + 2;
                        while (IDs.Contains($"#{toInt + 1}"))
                        {
                            toInt += 1;
                            ignore.Add($"#{toInt}");
                        }
                        id = $"#{fromInt}:#{toInt}";
                    }
                }
            }
            result.Add(id);
        }
        return string.Join(",", result);
    }
}


texts: Recursive function, high performance critical

texts:
def uniop_nested(func,o_list):
    def inner(i_list):
        if isinstance(i_list[0],np.ndarray):
            return map(func, i_list)
        else:
            return map(inner, i_list)
    return inner(o_list)

def binop_nested(func, o1, o2):
    if not isinstance(o1,np.ndarray):
        return [binop_nested(func, i1, i2)  for (i1,i2) in zip(o1,o2)]
    else:
        return func(o1,o2)

def add_nested(s1,s2):
    return binop_nested(np.add,s1,s2)

My code need to work with lists of ndarrays and list of lists of ndarrays.  Profiling shows this is some of the most performance critical code in my project.

How can I optimise it?
Can I rewrite the recursion as a loop?
Is there nice way to rewrite, them as Cython or a C extention? (I have no experience with this)

My Stack Overflow question here indicates that changing datatypes is probably not going to the solution.

More info:

Operands (o1 o2, s1, s2) are short lists. Profiling has shown me that using it.izip is slower.
Function return results are unlikely to be repeated. As the ndarrays are full of floats being tweaked with mathematical operations based of floats. (We are talking a large segment of Rn possible values)
Functions being applied are simple, the add_nested is the most common op by far, but there are a few onthers like uniop_nested(np.zeros_like, o_list).
ndarrays are of different sizes/shapes. (so a multidimentional ndarray won't work)

Context:
This is being used for training Restricted Boltzmann Machines (RBMs) and Neural network.
I have a generic "Trainer" class,
that takes a Trainee class as a parameter.
the Trainee class exposes a few methods like:

Get_update_gradient - a function that returns  (for a RBM [Restricted Boltzmann Machine]) a list containing a ndarray of weight changes and 2 ndarrays of bias changes, or (for a multilayer neural net) a list containing a list of weight matrix changes and a list of bias changes
knowledge: a property exposing either a list containing (for a RBM) a 2 bias arrays and a weight matrix or (for a neural net) a list of weight matrixes and bias arrays

It may seem that the Trainer class is simple, and unnesc, however it is moderately complex, and its use is common between the RBM and neural net classes. (Both benefit from the use of momentum and minibatchs)
A typical use is:

trainee.knowledge  = binop_nested(lambda current_value,update: learning_rate*update+current_value, trainee.knowledge, updates)


texts:
I have been working on this hackerrank problem:

  Louise and Richard have developed a numbers game. They pick a number (1 ≤ n < 264)
  and check to see if it is a power of 2. If it is, they divide it by 2.
  If not, they reduce it by the next lower number which is a power of 2.
  Whoever reduces the number to 1 wins the game. Louise always starts.

  Given an initial value, determine who wins the game.

  As an example, let the initial value n = 132. It's Louise's turn so
  she first determines that 132 is not a power of 2. The next lower
  power of is 128, so she subtracts that from 132 and passes 4 to
  Richard. 4 is a power of 2, so Richard divides it by 2 and passes 2 to
  Louise. Likewise, 2 is a power so she divides it by 2 and reaches 1.
  She wins the game.

  If they initially set counter to 1, Richard wins. Louise cannot make a
  move so she loses.

My question is, could somebody verify/help me with the current time complexity of this? And given this time complexity, what are some ways I could reduce it?

I have tried to solve the time complexity, but it is quite confusing for me. What I have so far is: it takes O(log(N)) time to "reach" a given value N, since you are going up by factors of 2. Here I believe the worst case scenario is every number you land on is a power of two, since whenever you have a number that isn't a power of two, subtracting the highest power of two below it will reduce it by more than you would halving it. With that in mind, you have to "reach" a given value n log(M) times, where M is the first value for N.

So we have Log(N) to reach a value N, and you have to do this log(M) times. The part that confuses me is that the value N halves each time. I don't know how to approach the rest of this. Any help with this would be greatly appreciated.

What are some improvements to my code I could make?

static String counterGame(long n) {
    int turn = 0;
    long current = 2;
    long previous = 2;
    if (n == 1) return "Louise";
    while (true) {
        if (current == n) {
            n /= 2;
            if (n == 1) {
                break;
            } else {
                turn ^= 1;
                current = 2;
                previous = 2;
            }
        } else if (current < n) {
            previous = current;
            current *= 2;
            continue;
        } else {
            n = n - previous;
            if (n == 1) {
                break;
            }
            turn ^= 1;
            current = 2;
            previous = 2;
        }
    }
    return (turn == 1) ? "Richard" : "Louise";
}


texts: Controlling parallel jobs with condition_variable

texts:
I'm trying to set up a system where I can have an arbitrary number of parallel tasks, all of which wait for a go signal, do their work, and then stop while a manager collects the results, prepares for the next batch of work, and so on.

The easy way I know to do this is to launch a packaged_task for each job, for each iteration. However, I have got the impression that launching threads (and more so with the higher abstractions) have some considerable overhead, which I would want to avoid. My limited testing of those other options confirm that belief.

The best I've come up with so far is to have threads that are kept alive, and loop based on signals from condition_variable entities.

std::mutex mx;
std::condition_variable global;
bool start = false;
bool ready = false;
std::map<int, std::atomic<bool>> status;
using namespace std;
void work(int n) {
    while (true) {
        {
            unique_lock<mutex> lock{mx};
            //std::cout<<"Job #"<<n<<" waiting for ready signal.\n";
            while (!ready) { global.wait(lock); }
        } {
            unique_lock<mutex> lock{mx};
            status[n] = false;
            //std::cout<<"Job #"<<n<<" ready, waiting for start signal.\n";
            while (!start) { global.wait(lock); }
        }
        this_thread::sleep_for(chrono::milliseconds(10)); // simulate work
        status[n] = true;
    }
}
int main(int argc, char ** argv) {
    const auto num_jobs = (argc<=1? 1000:atoi(argv[1]));
    vector<thread> jobs;
    for (auto n=1;n<=num_jobs;n++) { jobs.emplace_back(work, n); }
    while (true) {
        cin.ignore(); {
            unique_lock<mutex> lock{mx};
            start = false;
            ready = true;
            status.clear();
            global.notify_all();
        } cin.ignore(); {
            unique_lock<mutex> lock{mx};
            ready = false;
            start = true;
            global.notify_all();
        }
        while (!all_of(status.begin(), status.end(),   // Wait for all jobs
               [](auto&& t){ return t.second.load(); }))
        { /*this_thread::sleep_for(chrono::seconds(1));*/ }
    }
    for (auto& job : jobs) { job.join(); }
}

I tried to compact the code, but tell me if it's too obfuscated. What the program does is to create some arbitrary number of workers, which wait for the launch signal from cin and then perform the simulated work.

I had to create two stages for the task to possibly be in, in a ready-set-go mechanic where the thread lands in a waiting clause after completing its job. My first attempt was to use just one wait for the task, but I can't figure out a a way to disable the single flag before some tasks are looping back around and then would start a second iteration immediately.

So basically what I'm asking: is this a good approach to the problem discussed in the first paragraph? If yes, can it be made better? Surely this is a well trodden issue for programmers trying to do parallel optimization, what is the conventional way to deal with my scenario?


texts: A scheme macro that defines the "where“ syntax

texts:
A new scheme user trying to use syntax-rules to define something like the Haskell where keyword.

Sometimes this is useful since when we do programming, we first design in the high level, where all the names left undefined. In later steps, we define those names and complete the program. where keyword preserves the order of definition which keeps the last name defined first.

The idea is simple. I start with a define-syntax

(define-syntax do
   (syntax-rules (where let)

The desired pattern is (do *body* (where *definitions*)), so we first due with the case when there are no definitions.

     [(_ body (where ())) body]

If the body is a let binding, I take out one where definition and append to the let bindings, and recurs. (This implies the where definitions appear in front of any existing let definitions in the result, and the order of where definitions will be reversed).

     [(_ (let (v ...) body) (where (w0 w ...)))
      (do (let (w0 v ...) body) (where (w ...)))]

Finally, if the body is not a let binding, I need to take out one definition and make a let binding.

     [(_ body (where (w0 w ...)))
      (do (let (w0) body) (where (w ...)))]

Now terminate the definition.

     ))

This definition works fine:

(do (x y z) (where ([x +] [y 1] [z 2])))
;3

Questions:

The naming. Are there a better name for do?
Support for similar bindings like let*, letrec, let*-values etc. All of those seems to share the same pattern and so I can just replicate the code to do so but there are quite a few variations (6 in total if I was right). So are there any way to eliminate the code duplication?
Are there any other ideas to improve the code?


texts:
Code review my binary search! It isn't supposed to be superfast or anything. It's optimized for clarity and only sorts arrays of pointers. Also in the same style is my quicksort code review question: Yet another quicksort.

/*
  used as the base case of bsearch.
*/
static void const* misc_bsearch_linear(void const** A, void const** Z, void const* K, bool (*cmp)(void const*, void const*))
{
  /*
    burn forward while *A < K. if there is anything left, it will have
    to be that *A >= K.
  */
  while ((A < Z) && cmp(*A, K)) A++;

  /*
    if there is nothing left, we're done.
  */
  if (!(A < Z)) return NULL;

  /*
    now we know *A >= K.
  */
  {
    if (cmp(K, *A)) {
      /* when K < *A */
      /* this means *A > K, so no dice */
      return NULL;
    } else {
      /* when K >= *A */
      /* this means *A == K, so return it */
      return *A;
    }
  }
}

static void const* misc_bsearch_internal(void const** A, void const** Z, void const* K, bool (*cmp)(void const*, void const*))
{
  /*
    must stop loop when there are 3 or fewer elements, otherwise it
    could go on forever in the bottom case.
  */
  while ((Z - A) > 3) {
    void const** M = (A + ((Z - A) >> 1));

    if (cmp(*M, K)) {
      /* when *M < K */
      A = M + 1;
    } else {
      /* when *M >= K */
      Z = M + 1;
    }
  }

  /*
    we're down to at most 3 elements, to downgrade to linear search to
    finish up.
  */
  return misc_bsearch_linear(A, Z, K, cmp);
}

/*
  cmp should return true iff [arg1] < [arg2] (strictly).
*/
static INLINE void const* misc_bsearch(void const** A, uintptr_t L, void const* K, bool (*cmp)(void const*, void const*))
{
  return misc_bsearch_internal(A, (A + L), K, cmp);
}

#define MISC_BSEARCH_VARIANT(s, t)                                   \
  static INLINE t* misc_bsearch_##s(t** A, uintptr_t L, t const* K, bool (*cmp)(t const*, t const*)) \
  {                                                                  \
    return ((t*)(misc_bsearch(((void const**)(A)), L, K, ((bool (*)(void const*, void const*))(cmp))))); \
  }


texts:
Accomplishment: Tic Tac Toe game with Python & Kivy

I have created a simple tic tac toe game with a random bot logic (really random after a user selects a mark). Next step would be to insert the minimax algorithm for example, but I would like to know if the path I've taken to construct my code is correct and could it be improved.

I have two files: main.py and ai.py

main.py

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.config import Config
from ai import Ai
from random import randint

class TicTacToe(App):

    title = 'Tic Tac Toe'
    board = []
    choices = ["X","O"]

    # On application build handler
    def build(self):
        Config.set('graphics', 'width', '600')
        Config.set('graphics', 'height', '600')
        self.layout = StackLayout()
        for x in range(9): # range() explanation: http://pythoncentral.io/pythons-range-function-explained/
            bt = Button(text='', font_size=200, width=200, height=200, size_hint=(None, None), id=str(x))
            bt.bind(on_release=self.btn_pressed)
            self.board.append(bt)
            self.layout.add_widget(bt)
        return self.layout

    # On application start handler
    def on_start(self):
        self.init_players();
        greeting = "Hello Player! You are playing with \"" + self.player + "\""
        self.popup_message(greeting)

    # On button pressed handler
    def btn_pressed(self, button):
        if len(button.text.strip()) < 1: # Continue only if the button has no mark on it...
            button.text = self.player
            self.bot.make_move(self.board)
            self.check_winner()

    # Initializes players
    def init_players(self):
        rand_choice = randint(0,1);
        self.bot = Ai(self.choices[rand_choice]);
        self.player = self.choices[0] if rand_choice == 1 else self.choices[1]

    # Checks winner after every move...
    def check_winner(self):
        pass # Just void..

    def popup_message(self, msg):
        popup = Popup(title="Welcome!", content=Label(text=msg), size=(300, 100), size_hint=(None, None))
        popup.open()

if __name__ == '__main__':
    TicTacToe().run()

ai.py

from random import randint

class Ai:
    def __init__(self, choice):
        self.choice = choice

    # Main function for bot making a move
    def make_move(self, board):
        self.make_random_move(board) # Do a random move

    # Makes a random move by generating a random integer and checking if the place is free
    def make_random_move(self, board):
        free_buttons = []
        for button in board: # Simple for loop to extract the free buttons
            if len(button.text.strip()) < 1: # If the button has no mark, stripping spaces...
                free_buttons.append(button)

        if len(free_buttons) > 1: # If any free buttons left... let's make the move
            rand = randint(0, len(free_buttons) - 1) # Generate a random integer from 0 to the length of the array
            free_buttons[rand].text = self.choice


texts:
I have this script for creating SQLite backups, and I was wondering whether you'd have any suggestions on how to improve this. I was thinking that maybe it should create the backup dir if it doesn't exist, but not sure if it's necessarily better.
Besides functionality/performance tips, any styling/formatting tips are also much appreciated.
#!/usr/bin/env python
"""
This script creates a timestamped database backup,
and cleans backups older than a set number of dates

"""

from __future__ import print_function
from __future__ import unicode_literals

import argparse
import sqlite3
import shutil
import time
import os

DESCRIPTION = """
              Create a timestamped SQLite database backup, and
              clean backups older than a defined number of days
              """

# How old a file needs to be in order
# to be considered for being removed
NO_OF_DAYS = 7

def sqlite3_backup(dbfile, backupdir):
    """Create timestamped database copy"""

    if not os.path.isdir(backupdir):
        raise Exception("Backup directory does not exist: {}".format(backupdir))

    backup_file = os.path.join(backupdir, os.path.basename(dbfile) +
                               time.strftime("-%Y%m%d-%H%M%S"))

    connection = sqlite3.connect(dbfile)
    cursor = connection.cursor()

    # Lock database before making a backup
    cursor.execute('begin immediate')
    # Make new backup file
    shutil.copyfile(dbfile, backup_file)
    print ("\nCreating {}...".format(backup_file))
    # Unlock database
    connection.rollback()

def clean_data(backup_dir):
    """Delete files older than NO_OF_DAYS days"""

    print ("\n------------------------------")
    print ("Cleaning up old backups")

    for filename in os.listdir(backup_dir):
        backup_file = os.path.join(backup_dir, filename)
        if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
            if os.path.isfile(backup_file):
                os.remove(backup_file)
                print ("Deleting {}...".format(ibackup_file))

def get_arguments():
    """Parse the commandline arguments from the user"""

    parser = argparse.ArgumentParser(description=DESCRIPTION)
    parser.add_argument('db_file',
                        help='the database file that needs backed up')
    parser.add_argument('backup_dir',
                         help='the directory where the backup'
                              'file should be saved')
    return parser.parse_args()

if __name__ == "__main__":
    args = get_arguments()
    sqlite3_backup(args.db_file, args.backup_dir)
    clean_data(args.backup_dir)

    print ("\nBackup update has been successful.")

Note: Code works in both Python 2 and Python 3.


texts: Write your implementation of Ruby's String#count method

texts:
The task is to write a simplified version of Ruby's String#count method oneself. Simplified because it doesn't have to have the negation and sequence parts of the original.
Here my solution:
def custom_count(string, search_char)
    sum = 0
    seg_string = string.split("")
    seg_char = search_char.split("")

    for i in seg_string
        for j in seg_char
            if i == j
                sum += 1
            end
        end
    end

    sum
end

p custom_count("Hello, World!", "l")    # => 3
p custom_count("Hello, World!", "lo")   # => 5
p custom_count("Hello, World!", "le")   # => 4
p custom_count("Hello, World!", "x")    # => 0
p custom_count("Hello, World!", "w")    # => 0
p custom_count("Hello, World!", "W")    # => 1

Is there a better way to solve the task? Perhaps without using nested loops?


texts: Is there a way to refactor the c# code having multiple conditions?

texts:
Is there a better way to refactor my below code where I have many conditions in if and else statement
The reason for refactoring is to make code cleaner and readable
    public static PaymentOptions GetPaymentOptions_Auto(TestConfigurationCDO testConfiguration, int siteId)
{
    var paymentOptions = new PaymentOptions();

    var paymentOptionList = SitePaymentRepository.GetSitePaymentInfoBySiteId(
        testConfiguration,
        siteId);

    var lowestPriority = paymentOptionList.Min(x => x.Priority);
    var paymentAuto = paymentOptionList.Where(x => x.Priority == lowestPriority).FirstOrDefault();

    if (paymentAuto.PaymentType == PaymentMethod.Klarna)
    {
        paymentOptions = new KlarnaOptions();
    }
    else if (paymentAuto.PaymentType == PaymentMethod.PayPalDirect ||
        paymentAuto.PaymentType == PaymentMethod.Braintree ||
    paymentAuto.PaymentType == PaymentMethod.BankTransfer || paymentAuto.PaymentType == PaymentMethod.AdyenDropIn)
    {
        paymentOptions = new ClientCheckoutOptions()
        {
            paymentMethod = paymentAuto.PaymentType
        };
    }
    else if (paymentAuto.PaymentType == PaymentMethod.PayPalExpress)
    {
        paymentOptions = new PaypalOptions();
    }
    else
    {
        paymentOptions = new PaypalOptions();
    }
    return paymentOptions;
}


texts: Suggestion for improving this code to be more readable and easy for beginners?

texts:
I'm a JavaScript beginner trying to learn by doing. Here I have a table with different values: I have used two for loops. Is there an easier way to achieve this? For example having just one for loop, or instead of it use something else? Even better would be if you could give suggestions to improve the code to be more readable (beginner friendly?)

let animals
let animalCols = ['Animal', 'Animal 2']
let peopleCols = ['Person', 'Person 2']

function myFunction() {
  paivitys(animals, animalCols)
}

function paivitys(dataa, arvvoja) {
  console.log(dataa);
  //----
  if (dataa.hasOwnProperty("animal")) {
    document.getElementById("1name").innerHTML = dataa.animal;
  } else {
    document.getElementById("1name").innerHTML = dataa.person;
  }
  //----
  if (dataa.hasOwnProperty("animal2")) {
    document.getElementById("2name").innerHTML = dataa.animal2;
  } else {
    document.getElementById("2name").innerHTML = dataa.person2;

  }

  document.getElementById("1name1").innerHTML = arvvoja[0];
  document.getElementById("2name1").innerHTML = arvvoja[1];

  //-----
  document.getElementById("id").innerHTML = dataa.id;
}

function paivitaselekt(dataa, arvvoja) {
  for (var i = 0; i < dataa.length; i++) {
    var valitse = document.getElementById("Select");
    var option = document.createElement("option");

   for (var i = 0; i < dataa.length; i++) {
    var valitse = document.getElementById("Select");
    var option = document.createElement("option");
    for (var j = 0; j < arvvoja.length; j++) {
       option.textContent += dataa[i][arvvoja[j]] + " ";
    }
    valitse.appendChild(option);
} ;
    valitse.appendChild(option);
  }
}

animals = {
  "animal": "tiger",
  "animal2": "lion",
  "id": "54321",
  "dole": {
    "Key": "fhd699f"
  }
}

paivitys(animals, animalCols);
let kokoarray;

people = [{
    "person": "kaka",
    "person2": "julle",
    "id": "9874",
  },
  {
    "person": "Ronaldo",
    "person2": "jussi",
    "id": "65555",
  }
]
kokoarray = people;
paivitaselekt(kokoarray, ["person", "id"]);

document.getElementById("Select").addEventListener("change", function(event) {
  const otettutunnsite = event.target.value.split(" ")[1];
  const otettutieto = kokoarray.filter((dataa) => dataa.id === otettutunnsite)[0];
  paivitys(otettutieto, peopleCols);
});
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    />
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
      integrity="sha384UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
      crossorigin="anonymous"
    />

        Animal
        Animal
        id

  <select id="Select" ></select>
  <button onclick="myFunction()">backtozero</button>


texts:
Challenge:

  Reverse the digits of a number and add it to the original
  until the number is a palindrome

Specifications:

  Your program should accept as its first argument a path to a filename.
  Each line in this file is one test case containing an integer n < 10,000.

  Assume each test case will always have an answer and
  that it is computable with less than 100 iterations.

  For each line of input, print a line of output
  containing the number of iterations to compute the palindrome
  and the resulting palindrome, on one line separated by a single space.

Solution:

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

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

        while (input.hasNextLine()) {
            findAndPrintPalindrome(input.nextLine());
        }
    }

    private static void findAndPrintPalindrome(String line){
        System.out.println(getPalindrome(line));
    }

    private static String getPalindrome(String line) {
        int reverseCount = 0,
            currentNum = Integer.parseInt(line)
        ;

        while (!isPalindromic(currentNum)) {
            currentNum += reverse(currentNum);
            reverseCount++;
        }

        return reverseCount + " " + currentNum;
    }

    private static boolean isPalindromic(int s) {
        return s == reverse(s);
    }

    private static int reverse(int n) {
        return Integer.parseInt(
            new StringBuilder(Integer.toString(n)).reverse().toString()
        );
    }
}

Sample Input:

  8
  125
  195

Sample Output:

  0 8
  1 646
  4 9339

I'm looking to pinpoint:

Anything I could alter to optimize this program.
General feedback on good vs poor practices in my code.


texts:
Purpose:
Given a Worksheet Table (ListObject) that may, or may not, have a filter currently applied to it, return a range consisting only of the filtered data.

Method:
Loop through each row in the table.
If row is visible, add it to a filteredRange via Union().
Return filteredRange.

Specific Areas of Interest:
Is the function name sufficiently intuitive?
Is there an easier way to achieve the desired results?
Are there edge cases I haven't accounted for?

Function:

Public Function GetFilteredTableRange(ByRef targetTable As ListObject, Optional ByVal includeHeaders As Boolean = False)
    '/ given a table, return a range object that contains only those rows which are visible
    '/ Do this by looping through tableRows, adding all visible rows to a unionRange

    Dim allDataRange As Range
    Set allDataRange = targetTable.DataBodyRange

    Dim filteredRange As Range
    Dim rowRange As Range

    If includeHeaders Then
        Set rowRange = targetTable.HeaderRowRange
        Set filteredRange = rowRange
    End If

    For Each rowRange In allDataRange.Rows()
        If rowRange.EntireRow.Hidden = False Then

            If filteredRange Is Nothing Then
                Set filteredRange = rowRange
            Else
                Set filteredRange = Union(filteredRange, rowRange)
            End If

        End If
    Next rowRange

    Set GetFilteredTableRange = filteredRange

End Function


texts: Add user to a database and perform relevant checks

texts:
Below is a function that adds a new user to the database using their email and password. I am using Flask and SQLAlchemy.

@app.route('/users', methods = ['POST'])
@require_appkey
def registerUser():
    errorsList = []
    userInfo = request.get_json()

    # Get "email" and "password"
    email = userInfo.get('email')
    password = userInfo.get('password')
    if email is None or password is None:
        errorsList.append(Error("email/password","Email or Password not entered"))
        return make_error(MainError('400','Incorrect Input',errorsList))

    # Check password meets criteria
    if len(password) > 1024:
        errorsList.append(Error("password","Password maximum length is 1024 characters"))
    if len(password) < 8:
        errorsList.append(Error("password","Password must be at least 8 characters"))

    # Check email meets criteria
    email = email.strip()
    # Check if email address is valid (syntactically)
    match = re.match("[^@]+@[^@]+\.[^@]+", email)
    if match is None:
        errorsList.append(Error("email","Not a valid email address"))
    # Check if email address is already in database
    with contextlib.closing(DBSession()) as session:
        try:
            if session.query(USER).filter_by(USERSEMAIL=email).count():
                errorsList.append(Error("email","This email address already exists"))
        except Exception as error:
            session.rollback()
            logger = logging.getLogger('__name__')
            logger.error(error)
            errorsList.append(Error("database","An error occurred with the database. Please try again later."))
            return make_error(MainError('500','Database error',errorsList))

    # If errors exist, return all errors
    if errorsList:
        return make_error(MainError('400','Incorrect Input',errorsList))

    # Add user to database
    user = USER(email, password)
    with contextlib.closing(DBSession()) as session:
        try:
            session.add(user)
            session.commit()
        except Exception as error:
            session.rollback()
            logger = logging.getLogger('__name__')
            logger.error(error)
            errorsList.append(Error("database","An error occurred with the database. Please try again later."))
            return make_error(MainError('500','Database error',errorsList))
        return jsonify(data=user.serialize())

def make_error(mainError):
    response = jsonify(data=mainError.serialize())
    response.status_code = int(mainError.code)
    return response

class MainError:
    def __init__(self, code, message, errorsList):
        self.code = code
        self.message = message
        # List of Error objects
        self.errorsList = errorsList

def serialize(self):
    return {
    'errorCode': self.code,
    'message': self.message,
    'errorList': [error.serialize() for error in self.errorsList],
    'success': 'false'
    }

My specific questions (not all directly related to Python) are:

Should I be using return in so many different places?
Is there a better way to structure my code? I would love to hear any thoughts you all have on how this could be written better.
Is the way in which I am handling my errors correct?
Seeing as I will probably be using the Database error often, is it worth putting into a function?


texts: Dynamically generated attribute accessors in Perl

texts:
In my spare time I'm working at a perl library, which is the lightweight implementation of a package I did some time ago. In the previous iteration I used Moose as object-oriented framework, as suggested by many people on the Internet.

Later in time I realized how Moose was a total overkill for my use case (I'm not a big fan of the 8-hours dependencies setup time), and that's the reason why I went for a refactoring.

Suddenly I found myself to face a situation where I want something similar to what I used to have with Moose, but in a far simper way: I would like one of my modules to have simple setter/getter properties without manually defining all of them.

I came out with the following simple implementation, which seems to be quite effective:

#!/usr/bin/perl -w

use strict;
use warnings;

package Foo;

BEGIN {
    no strict 'refs';
    foreach my $mname (qw/bar baz/) {
        *$mname = sub {
            my $self = shift;
            if (@_) {
                $self->{$mname} = shift
            } else {
                $self->{$mname}
            }
        }
    }
}

sub new { bless {}, shift }

What do you think of it? Do you see any evident drawback? This is the code I used for testing it, and it seems to work just fine:

package main;

use feature 'say';

my $x = Foo->new();
for (1 .. 10) {
    $x->bar($_);
    say 'bar: ', $x->bar;
    say 'baz: ', $x->baz || '<none>';
    $x->baz($_);
}
$x->goat_cheese(3) # broken


texts: Android app for sending username and password requests

texts:
I'm developing an Android app that performs several requests to a server using the AndroidAsynchronousHttpClient. One of these requests (as an example) is responsible to send the username and password. I created a class Sign that has a static method (see below) to which I provide a callback to handle the server's response. Is this considered a bad practice?

I'm asking this because I'm having a hard time testing with Mockito.

public class Sign {

public static void signin(String username, String password,
        final SigninResponseHandler responseHandler) {

    RequestParams params = new RequestParams();
    params.put("username", username);
    params.put("password", password);

    MyAPIClient.getInstance().post(path, params,
            new JsonHttpResponseHandler()
            {
                @Override
                public void onSuccess(JSONObject responseObject)
                {
                    String responseAPIStatus = responseObject.getString("status");
                    if (status.isEquals("success")
                    {
                        responseHandler.callback(true, null);
                    }

                }

                @Override
                public void onFailure(Throwable e, JSONObject errorResponse)
                {
                    responseHandler.callback(false, new CustomError(e));
                }
            });
}


texts: Function to find the minimum depth of a tree

texts:
For a leetcode problem to find the minimum depth of the binary tree, I have written the below solutions. The solution is accepted, but can I do any other changes to make the code elegent?

   public class Solution {

        public int minDepth(TreeNode root) {
            if(root == null)
            {
                return 0;
            }

            //to handle the leaf node case...
            if(root.left == null && root.right == null)
            {
                return 1;
            }

            //To handle the case that has only right children..
            if(root.left == null)
            {
                return minDepth(root.right) + 1;
            }

            if(root.right == null)
            {
                return minDepth(root.left) + 1;
            }

            return Math.min( minDepth(root.left)+1,minDepth(root.right)+1);
        }
    }


texts:
I am new to node.js and asynchronous programming and this is my first small project to learn it. I have written a small Telnet chat server and the program works but I want to know if this is the correct way to write programs in node.js (asynchronous programming model).

var tcp = require('net');
var Server = tcp.createServer();
var pwd=[]; // keep tracks of connected clients
var ip=[];  // keeps tracks of connected clients IP address
var Cpwd = "Rushabh"; // password that you require to login

Server.on('connection'  ,function(conn){
    conn.setEncoding('utf-8');
    conn.write("Password:");// ask user for password on their terminal
    console.log("[" + conn.remoteAddress + "] has joined the chat");

    conn.on('data' , function(data){
        if(pwd.indexOf(conn)>-1){//check if it is an old client or a new client
            console.log("[" + conn.remoteAddress + "]:"  + data);

            if(pwd.length > 0){ // check if atleast one client is connected
                sendMessage(conn , data);// broadcast message to all client connected
            }
        }
        else{//if it is a new client then server should first check for password
            data= data.toString('utf-8').trim();
            var message = " has joined the chat";
            if(Cpwd == data){ // if it is a new client than check for password
                pwd.push(conn);
                ip.push(conn.remoteAddress);
                sendMessage(conn , message);
            }
            else {
                conn.write("Password rejected:" + data);conn.end();}// disconnect client
            }
        });

      conn.on('end' , function() { // remove the client from reference array

       var i , client;
         for(i in pwd){
           client = pwd[i];
           if(!client.writable){
             pwd.splice(i,1);
             console.log(ip[i]+ " has left the chat");
             ip.splice(i,1);
           }
         }

     });

});

    function sendMessage(conn , message){ //function to send message to all connected client

      var i , client;
      for(i in pwd){
        client = pwd[i];
        if(client.writable){
          if(conn === client){
            client.write("[me]:" + message);
          }
          else
            client.write("[" + conn.remoteAddress +"]:" + message);
        }
        else{
          pwd.splice(i , 1);
          console.log(ip[i]+ " has left the chat");
          ip.splice(i,1);
        }
      }
    }
    Server.listen(8000);


texts: Transforming a list of maps representing bands

texts:
I have the following code, it takes a list of maps representing bands and transforms the band properties via the pipeline_each method.

As you can see in the code, I am dealing with a lot of Options being returned when I modify the band data in the map - I am using an immutable map object and therefore need to return a new map each time the function is called.

I am also not happy about the type of the bands data structure being a List[Map[String, Any]] - particularly the Any part because I need to convert the values I get out of the maps to String types in order to modify them. I am stuck with this data structure though.

How can I make this code better, specifically addressing my concerns above?

    object Exercise {

  val bands: List[Map[String, Any]] = List(Map("name" -> "sunset rubdown", "country" -> "UK", "active" -> true),
  Map("name" -> "women", "country" -> "Germany", "active" -> false),
  Map("name" -> "a silver mt. zion", "country" -> "Spain", "active" -> true))

  def set_canada_as_country(band: Map[String, Any]): Map[String, Any] = {
    Map("name" -> band.get("name").get, "country" -> "Canada", "active" -> band.get("active").get )
  }

  def strip_punctuation_from_name(band: Map[String, Any]): Map[String, Any] = {
    Map("name" -> band.get("name").get.toString.replace(".", ""), "country" -> band.get("country").get, "active" -> band.get("active").get )
    //toString above is kinda gross and could cause a class cast exception
    //do I have to handle all the case matching on some/none for all the above calls to get?
  }

  def capitalize_names(band: Map[String, Any]): Map[String, Any] = {
    Map("name" -> band.get("name").get.toString.toUpperCase, "country" -> band.get("country").get, "active" -> band.get("active").get )
    //same again - don't like the toString
  }

  def pipeline_each(data: List[Map[String, Any]], fnList: List[Map[String, Any] => Map[String, Any]]): List[Map[String, Any]] = {
    fnList.foldLeft(data) {(bandList, currFn) => bandList.map(currFn)}
  }

}

I execute the above code via the REPL like so:

Exercise.pipeline_each(Exercise.bands,
  List(
    Exercise.set_canada_as_country,
    Exercise.strip_punctuation_from_name,
    Exercise.capitalize_names))


texts: Performance for creating millions of database entries

texts:
class Generator
{
    public function createCodes($count, $project, $generator)
    {
        $batchSize = 250;
        $batches = ceil($count / $batchSize);

        $sharedColumns = [
            'timestamp' => time(),
            'parent_id' => $project->id,
            'source' => $generator->name,
            'generator_id' => $generator->id,
        ];

        $created = 0;
        for ($batch = 0; $batch < $batches; $batch++) {
            $size = min($batchSize, $count - $created);

            $time = time();
            $inserts = [];
            for ($i = 0; $i < $size; $i++) {
                $parentCode = self::generateCode();
                $inserts[] = [
                    'type' => 'parent',
                    'parent_code' => '',
                    'code' => $parentCode,
                    'series' => self::generateSeries(),
                ];

                for ($j = 0; $j < $generator->children; $j++) {
                    $inserts[] = [
                        'type' => 'child',
                        'parent_code' => $parentCode,
                        'code' => self::generateCode(),
                        'series' => self::generateSeries(),
                    ];
                }
            }

            $columns = array_keys($sharedColumns + $inserts[0]);
            $valueString = '(' . implode(', ', array_fill(0, count($columns), '?')) . ')';
            $queryString = 'INSERT INTO project_codes (' . implode(',', array_map('Database::quoteIdentifier', $columns)) . ') VALUES ';
            $queryString .= implode(',', array_fill(0, count($inserts), $valueString));

            // Flatten all entries and add shared columns
            $values = array_reduce($inserts, function ($carry, $item) use ($sharedColumns) {
                return array_merge($carry, array_values($sharedColumns), array_values($item));
            }, []);

            $query = \Database::getInstance()->prepare($queryString);
            $query->execute($values);

            $created += $size;
        }
    }

    static $codeChars = 'ABCDEFGHJKLMNPQRTUVWXY34789';

    protected static function generateCode()
    {
        return substr(str_shuffle(self::$codeChars), 0, 9);
    }

    protected static function generateSeries()
    {
        $numbers = range(1, 30);
        shuffle($numbers);
        $numbers = array_slice($numbers, 0, 5);

        return implode(',', $numbers);
    }
}

The software this code is used in manages prize draws. Companies let the software generate codes that they can e.g. print on their products. Buyers of these products can enter codes back into the system to enter a prize draw. At specified dates the system draws winners from the entered codes and notifies them.

What this particular piece of code should be capable of is to generate a specified amount of random (and unique) codes so they can later be exported by the company and printed on their products. The generated code is stored in the code column, but winners are determined by the series column which is hidden from the end user/customer.

The code doesn't yet guarantee uniqueness. My plan is to select all duplicates for code and series (after generation and inserts) and just generate new ones until there are no duplicates anymore. That way I don't have to check each of the million generated codes for uniqueness.

I tested this with a count of 1 million, which took 163s to complete and according to memory_get_peak_usage(true) consumed 4MB of RAM (which I find unlikely, but ok).

I experimented with different batch sizes but the gain of fewer queries seemed to pretty much cancel out with the additional function calls and higher array sizes for the array reduction.

Is there anything I can do to decrease execution time? I don't expect a million entries to be generated in 10 seconds, but if there's any gain to be had I'd appreciate it.


texts: Is there a better way to convert to a specific type with reflection?

texts:
Rather than doing what is essentially a large switch statement for every possible type, is there a better more generic way of converting to a specific type with reflection?  I've looked up TypeConverter but don't understand the documentation.

if (header.Property.PropertyType == typeof(Int32))
{
  header.Property.SetValue(instanceOfTrade, value.ToInt(), null);
}
else if (header.Property.PropertyType == typeof(decimal))
{
  header.Property.SetValue(instanceOfTrade, value.ToDecimal(), null);
}
else if (header.Property.PropertyType == typeof(DateTime))
{
  header.Property.SetValue(instanceOfTrade, value.TryToDateTime(), null);
}
else
{
  header.Property.SetValue(instanceOfTrade, value.ToString(), null);
}


texts:
For what I'm doing, I need to be able to draw a buffered image directly into a larger buffered image. I've searched around a little and still have failed to find a better way, but my current way is extremely inefficient and I would like a better way if it's possible. Any improvements onto this design would also be great, even if it's not a totally separate way.

public static final void drawOntoBI(final BufferedImage on, final BufferedImage draw, final int x, final int y)
{
    // Calls method instead of needing to call them every loop
    final int width = draw.getWidth(), height = draw.getHeight(), onwidth = on.getWidth(), onheight = on.getHeight();
    // Stores temporary variables so they wont be recalculated
    int x3, y3;
    // Goes through all of the pixels in the drawn image to copy them
    for(int x2 = 0; x2 < width; x2++)
    {
        x3 = x + x2; // Prevents having to do the same math 3 times
        for(int y2 = 0; y2 < height; y2++)
        {
            y3 = y + y2;
            // Makes sure the image to be drawn is not out of bounds, if it is, go to the next location
            if(x3 > onwidth - 1 || x3 < 1 || y3 > onheight - 1 || y3 < 1) break;
            // Draws the pixel on the image where it needs to be from the x and y looped in the image
            on.setRGB(x3, y3, draw.getRGB(x2, y2));
        }
    }
}

This is the second biggest bottleneck on my program, so it really is important to be improved. It's called all the time, and is rather slow. Memory isn't an issue, so memory-using methods can be considered.


texts: Counting the out-of-order elements of an array

texts:
Is there any way to write is C function better so the procedure could spend less time to calculate the results?

Assume that the array size is 1.000.000 and  all the numbers are greater than 0.

The function read the array backwards, saves the first number to maximum, then check the next number, a, and if it's greater than the maximum, it adds +1 to total. Then the maxinum takes the value of a and procide to next one until the end of array.

static int total = 1;

int chck_high( int *my_array, int *endp) {
    // this function should only be called if there is at least one value in the array
    int maximum = *(--endp);

    while ( endp > my_array ) {
        int a = *(--endp);

        if ( a > maximum ) {
            total++;
            maximum = a;
        }
    }

    return maximum;
}

I tried to use unsigned ints, but I don't know if it's worth it. Can someone please tell me if there is a better way to write that code?

Previous version of the code:

int process( int *my_array, int *endp) {
    int a, b;
    //static int total = 1;
    if ( my_array == 0 ) return 0;
    if ( my_array == endp ) return INT_MIN;
    else a = *my_array++;
    if ( (b= process( my_array, endp )) == INT_MIN ) return a;
    if ( a > b )
    {total++; return printf( "%d > %d and total now is %d\n", a, b, total ), a; }
    return b;
}

The two functions called with the following code:

chck_high(my_array, my_array + count);

where my_array is my array with nums and count is the number that says the size of the array.


texts: List class object, which only contains lists as elements

texts:
I need a class which behaves, and is in reality a list.
However I need to ensure that the elements of this list are only of the list class itself.

In effect it is always a list of lists.

I wrote the following working code:

class MyListOfLists(list):

    def __init__(self, *args, **kwargs):
        super(MyListOfLists, self).__init__(self._my_args(args), **kwargs)

    def __setitem__(self, *args, **kwargs):
        super(MyListOfLists, self).__setitem__(self._my_args(args), **kwargs)

    def append(self, *args, **kwargs):
        super(MyListOfLists, self).append(self._my_args(args), **kwargs)

    def _my_args(self, args):
        return [e for e in args if isinstance(e,list)]

The following code to test:

my_list = MyListOfLists(['a','b'],['c','d'], 'a')
print(my_list)

which will gives the expected output:

[['a', 'b'], ['c', 'd']]

My question is:
Apart from __init__, append() and __setitem__, which other functions/methods do I need to capture of the original list class in order to ensure that the elements are lists ?

Or to widen the question: would there be another way of doing this ?

[EDIT based on comments, 17-Nov-2017]

It is indeed bad design to drop non list types silently, hence the _my_args() function will look something like this:

def _my_args(self, args):
    if any(e for e in args if not isinstance(e,list)):
        raise TypeError
    return args

I would like to get back to the main question: what other methods of the list class do I really need to capture, do I really need to capture things like insert(), __add__, __iadd__ and possibly others ? or is there another way of doing this.

[EDIT based on self tinkering]

My code looks like this at the moment, questions remain the same:

class MyListOfLists(list):

    def __init__(self, *args, **kwargs):
        super(MyListOfLists, self).__init__(self._my_args(args), **kwargs)

    def __setitem__(self, i, *args, **kwargs):
        super(MyListOfLists, self).__setitem__(i, *self._my_args(args), **kwargs)

    def append(self, *args, **kwargs):
        super(MyListOfLists, self).append(*self._my_args(args), **kwargs)

    def insert(self, i, *args, **kwargs):
        super(MyListOfLists, self).insert(i, *self._my_args(args), **kwargs)

    def extend(self, *args, **kwargs):
        super(MyListOfLists, self).extend(*self._my_args(args), **kwargs)

    def _my_args(self, args):
        if any(e for e in args if not isinstance(e,list)):
            raise TypeError
        return args


texts: LeetCode: Network Delay Time DFS solution C#

texts:
https://leetcode.com/problems/network-delay-time/

  There are N network nodes, labelled 1 to N.

  Given times, a list of travel times as directed edges times[i] = (u,
  v, w), where u is the source node, v is the target node, and w is the
  time it takes for a signal to travel from source to target.

  Now, we send a signal from a certain node K. How long will it take for
  all nodes to receive the signal? If it is impossible, return -1.

Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2

Please review for performance, I know I can solve this with Dijkstra's algorithm and Bellman ford.
I am still working on those. and will upload them for review.

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

namespace GraphsQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/network-delay-time/
    /// </summary>
    [TestClass]
    public class NetworkDelayTimeTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            int N = 4;
            int K = 2;
            int[][] times = { new[] { 2, 1, 1 }, new[] { 2, 3, 1 }, new[] { 3, 4, 1 } };
            NetWorkDelayTimeDfs dfs = new NetWorkDelayTimeDfs();
            Assert.AreEqual(2, dfs.NetworkDelayTime(times, N, K));
        }
    }

    public class NetWorkDelayTimeDfs
    {
        private Dictionary<int, int> dist;

        public int NetworkDelayTime(int[][] times, int N, int K)
        {
            var graph = new Dictionary<int, List<List<int>>>();
            //we build a dictionary
            // key = from vertex
            // values - weight and destination
            foreach (var edge in times)
            {
                if (!graph.TryGetValue(edge[0], out var temp))
                {
                    temp = graph[edge[0]] = new List<List<int>>();
                }

                temp.Add(new List<int> {edge[2], edge[1]});
            }

            // we sort by the weight
            foreach (var node in graph)
            {
                node.Value.Sort((a, b) => a[0] - b[0]);
            }

            // all the edges get max value
            dist = new Dictionary<int, int>();
            for (int i = 1; i <= N; i++)
            {
                dist.Add(i, int.MaxValue);
            }

            DFS(graph, K, 0);

            // we compute the max distance.
            // if one of the edges equals int.max
            // we can't reach it so we return -1;
            int ans = 0;
            foreach (var cand in dist.Values)
            {
                if (cand == int.MaxValue)
                {
                    return -1;
                }

                ans = Math.Max(ans, cand);
            }

            return ans;
        }

        private void DFS(Dictionary<int, List<List<int>>> graph, int node, int elapsed)
        {
            //if the distance bigger then what we already have for this node.
            // return there is nothing to update
            if (elapsed >= dist[node])
            {
                return;
            }

            dist[node] = elapsed;
            if (graph.ContainsKey(node))
            {
                //we run DFS to all the other nodes
                //we update the total distance to elapsed + weight
                foreach (var info in graph[node])
                {
                    DFS(graph, info[1], elapsed + info[0]);
                }
            }
        }
    }

}


texts:
I need to refactor following class:

public class Message
{
    public Guid ID { get; set; }
    public string MessageIn { get; set; }
    public string MessageOut { get; set; }
    public int StatusCode { get; set; } //EDIT could be changed during message lifecycle

    public bool IsDeletable
    {
        get
        {
            switch (this.StatusCode)
            {
                case 12:
                case 13:
                case 22:
                case 120:
                    return true;
                default:
                    return false;
            }
        }
    }

    public bool IsEditable
    {
        get
        {
            switch (this.StatusCode)
            {
                case 12:
                case 13:
                case 22:
                case 120:
                    return true;
                default:
                    return false;
            }
        }
    }

    public string Message
    {
        get
        {
            switch (this.StatusCode)
            {
                case 11:
                case 110:
                    return this.MessageIn;
                case 12:
                case 13:
                case 22:
                case 120:
                    return this.MessageOut;
                default:
                    return string.Empty;
            }
        }
    }
}

I would like to remove the business rules IsDeletable and IsEditable
I would like to remove these switch statements at the same time

I am not sure if it's worth knowing that I am mapping entity to database table through Entity Framework.

One more problem that I have is that fields MessageIn and MessageOut are dependent on StatusCode. One of them are always populated. I could create new property but still the switch case is there:

public string Message
{
    get
    {
        switch (this.StatusCode)
        {
            case 10:
            case 12:
            case 13:
            case :
              return this.MessageIn;
           default:
             return this.MessageOut;
        }
    }
    set { // switch again}
}


texts:
I did a project in Python where I combined user-input, random, and the turtle module to make a sort of "Mandala Generator", or a program that can generate a simple design either randomly or by the specifications of users. Is there any way I can shorten my code without drastically changing it?

#custom mandala project Python
import turtle
import random
import time

#is the game in progress?
drawing = False

#define turtle
pen = turtle.Turtle()
pen.setheading(90)
pen.pensize(3)
pen.speed(12)

#colors empty list
colors = []

#define variables
LINE1, LINE2 = "~" * 36, "~" * 24

#define check input function
def get_input(response, values):
    #make sure the input is in the choices
    while True:
        value = input(response).strip().lower()
        if value in values:
            return value

#define main function
def main():
    print(LINE1 + "\nCustom Mandala Generator\n" + LINE1)
    name = input("What is your name? ")
    print("In this custom mandala generator, you get to choose the size and colors of your mandala, or have the computer generate a random one,", name, ".\n" + LINE2)
    time.sleep(1)
    ready = input("Are you ready or not? ")

    if ready[0].lower() == "y":
        answer = get_input("Would you like to use our random generator function or our custom function? {random/custom} ", {"random", "custom"})

        #universal variables
        size = random.uniform(1.5, 2.5)
        fd = 75 * size

        if answer == "random":
            colors.extend(("darkred", "red", "yellow", "darkgreen", "green", "lightgreen", "darkblue", "blue", "purple"))
            #rt = right turn
            rt = random.uniform(100, 300)

        elif answer == "custom":
            print(LINE2 + "\nYou can choose any colors from this list for your Mandala: \nDarkred, red, yellow, darkgreen, green, lightgreen, darkblue, blue, purple")
            color1 = get_input("What is the first color? ", {"darkred", "red", "yellow", "darkgreen", "green", "lightgreen", "darkblue", "blue", "purple"})
            color2 = get_input("What is the second color? ", {"darkred", "red", "yellow", "darkgreen", "green", "lightgreen", "darkblue", "blue", "purple"})
            colors.extend((color1, color2))
            rt = int(input("What angle would you like your Mandala to turn at? "))

        #pre-draw sequence
        print(LINE2 + "\nInitializing...")
        print("Determining features... \nColor... \nSize...")
        time.sleep(3)
        print(LINE1 + "\nYour final result should be drawing as of this point!\nThanks for using the generator,", name, "!")

        for counter in range(50):
            selection = random.choice(colors)
            pen.color(selection)
            pen.forward(fd)
            pen.right(rt)

    else:
        print("Come and use the custom generator later!")

main()


texts: Member list reveals member information on click (#2)

texts:
Not a follow-up, but related to Member list reveals member information on click (#1). I now want my CSS reviewed.

What I'm doing?

The content in a list of members is revealed by jQuery (see review #1). Instead of having the content pop out, I'm using a transition to make this smooth. Because one can't transition to height: auto;, it's triggered by using max-height: 2000px;.

I have feeling this can be improved.

HTML:

            Member Name 1

Content area. No layout things inside. Paragraphs, lists, images.

            Member Name 2

Content area. No layout things inside. Paragraphs, lists, images.

            Member Name 3

Content area. No layout things inside. Paragraphs, lists, images.

CSS:

.block-list__link {
    text-decoration: none;

    .block-list__title:after {
        /* Adding a space followed by `&raquo;` after titles inside links */
        content: "\0020" "\00BB";
    }
}

.block-list__thumbnail {
    width: 100px;
    height: 100px;
    background-color: #f60;
    float: left;
}

.block-list__title {
    line-height: 100px;
    margin-bottom: 0;
    margin-left: 30px;
}

.block-list__content {
    overflow: hidden;

    /* Omitting vendor-prefixes for demonstration */
    transition: max-height 0.8s linear;

    height: 0;
    max-height: 0;

    &.visible {
        margin-top: 30px;
        height: 100%;
        max-height: 2000px;
    }
}


texts:
I am trying to write a simple domino (five-game) game with 2 players. I must say I am very bad at OOP design, and so I don't want to get myself too deep into coding then realize I have a bad design to start with. I'd appreciate if someone shed some light on how to better design this.

Here is summary of the game:

there are 28 dominos
there will be 2 players
initially, each player receives 7 random tiles, the remaining 14 tiles are left to the bone yard pool
initially, whichever player got the heaviest tile gets to play first
whoever scores x points first wins the game (e.g: 100,150,etc)

Here is what I have so far:

Player class:

public class Player
{
    //properties
    string ID { get; set; } //player id
    int Wins { get; set; }
    int Losses { get; set; }
    bool IsMyTurn { get; set; }
    List<Domino> Hand { get; set; } //each player will have a list of domino tiles

    void ShowHand(); //just display what's in their hands if needed
    void PlayerStatistic();  //get user's historical wins/losses, number game played, etc.

}

Game class:

public class Game
{
    //properties
    int ID { get; set; } //game id, assuming each player can play multiple games as once
    Player PlayerTurn { get; set; } //signifies if it is his turn
    Dominos DominoSet { get; set; }
    List<string> Board { get; set; }

    void Move(Player player, Domino domino);

    public Game(Player player1, Player player2)
    {
        ID = 0; //TODO
        DominoSet = new Dominos();  //create a set of dominos
        Board = new List<string>(); //create a new game board that store all the moves
        Domino curDomino = InitializePlayers(player1, player2, DominoSet.AllDominos);
        DominoSet.AllDominos.RemoveRange(0, 14); //remove all dominos that have been assigned to 2 players
        //...and other good stuffs
    }

}

Domino class, which was intended to describe a single domino:

public class Domino
{
    public string Name { get; set; } // "0,1", "0,2", etc.
    public int Head { get; set; } //each domino has 2 side, i called it head and tail
    public int Tail { get; set; }
    public int Weight { get; set; } //a 0-27, e.g: a "6,6" domino would have the highest predifined weight of 27
    public bool IsDouble { get; set; }  //whether the tile is double or not

    public Domino(string name, int head, int tail, int weight){
       Name = name;
       Head = head;
       Tail = tail;
       Weight = weight;
       IsDouble = (head == tail ? true : false);
    }
}

Dominos class, which was intended for use to store a list of 28 domino set, and perform other actions such as shuffle dominos, track domino, etc.:

public class Dominos
{
       private string[] _tiles = {"0,1","0,2","0,3","0,4","0,5","0,6",
                               "1,2","1,3","1,4","1,5","1,6",
                               "2,3","2,4","2,5","2,6",
                               "3,4","3,5","3,6",
                               "4,5","4,6",
                               "5,6",
                               "0,0","1,1","2,2", "3,3", "4,4","5,5","6,6"};
       public List<Domino> AllDominos { get; set; }
       public void Shuffle(){} //radomize the dominos

       public Dominos()
       {
           AllDominos = new List<Domino>();

           for (int i = 0; i < _tiles.Length; i++)
           {
               string[] word = _tiles[i].Split(',');
               Domino d = new Domino(_tiles[i], int.Parse(word[0]), int.Parse(word[1]), i);
               AllDominos.Add(d);
           }
           Shuffle();//randomize the domino list
       }
}

Main program to wire things together:

class Program
{
    static void Main(string[] args)
    {
        Player _player1 = new Player("Player1");
        Player _player2 = new Player("Player2");
        Game _game = new Game(_player1, _player2);
    }
}


texts: Support entitlement date check for customer assets

texts:
I'm new to Java right now. Here is my following code snippet:

for(int i = (SelectedAssets.size()-1); -1 < i; i--){

    Double supportTime = 0;
    //Date class must be used. Cannot replace with another class
    Date oDate=SelectedAssets[i].Entitlement_End_Date__c;
    Date dateDifference = oDate.daysBetween(date.today());
    /****************************************************************************
        If the number of days between Entitlement End Date and Todays
        date is a positive number, then that means the support given to client is expired since
        entitlement end date happened before todays date.
    *****************************************************************************/
    if(dateDifference>0){
        supportTime=((dateDifference/365.00));
        //If the number of days is greater than one year, I want
        //to find out exactly the amount of days it's gone over in decimals.
        if(supportTime>1){
            supportTime=1;
            supportTime+=(date.today().daysBetween(TheEndDate)/365.00);
        }
    }
    else{
        //if it hasn't gone over a year, find out how much time has elapsed in years.
        supportTime=oDate.daysBetween(TheEndDate)/365.00;
    }
}

Is there any redundancies anywhere that I'm overlooking? Is there an easier way of doing this with fewer lines?