texts: Normalize video filenames and move files to destination directory

texts:
I have written a powershell script that will scan a directory for any *mkv, *.mp4, *.avi files, and will parse the filename to get Name, Season Number, Episode number. Then will check against destination directory to determine

If Name exists (if not create it)
If season number exists (if not create it)
Once both these checks have been performed move the file to the destination dir

This syntax works for my purpose, but it is slow... I am lower than a beginner when it comes to powershell (is there such a thing?) - And would like any helpful hints or code mods that the more experienced programmers can provide.

$fileDirectory = "C:\Test\"

foreach ($file in Get-ChildItem $fileDirectory | where {($_.extension -eq '.mkv') -or ($_.extension -eq '.avi') -or ($_.extension -eq '.mp4')}){
    #Setting parent dir to check
    $ParentDir = "\\C:\TV Shows\"

    #setting param to split
    $parts =$file.Name -split '\.'

    #capturing variables
    $ShowName = $parts[0].Trim()
    $SeasonNumber = $parts[1].substring(0,3)
    $EpisodeNumber = $parts[1].substring(3,3)

    #Converting numeric season value to text
    switch ($SeasonNumber){
     S01
     {
        $SeasonNumber = "Season 01";
        break
     }
     S02
     {
        $SeasonNumber = "Season 02"
        break
     }
     S03
     {
        $SeasonNumber = "Season 03"
        break
     }
     S04
     {
        $SeasonNumber = "Season 04"
        break
     }
     S05
     {
        $SeasonNumber = "Season 05"
        break
     }
     S06
     {
        $SeasonNumber = "Season 06"
        break
     }
     S07
     {
        $SeasonNumber = "Season 07"
        break
     }
     S08
     {
        $SeasonNumber = "Season 08"
        break
     }
     S09
     {
        $SeasonNumber = "Season 09"
        break
     }
     S10
     {
        $SeasonNumber = "Season 10"
         break
     }
     default {"Something else happened"; break}
     }
    #Setting path variables
    $ShowDir = Join-Path -Path $ParentDir -ChildPath $ShowName
    $SeasonDir = Join-Path -Path $ShowDir -ChildPath $SeasonNumber

    #Write-Host "$ShowDir\"
    #Write-Host $SeasonDir

    #Checking if Show already has a folder
    if (!(Test-Path "$ShowDir\" -PathType Container)) {
        New-Item -ItemType Directory -Force -Path "$ShowDir\"
    }

    #Checking if directory already has folder
    If(!(Test-Path "$SeasonDir\" -PathType Container))
    {
        #if it does not create it
        New-Item -ItemType Directory -Force -Path $SeasonDir
    }

    Move-Item -Path $file.FullName -Destination $SeasonDir
}


texts: Show and paginate only child categories with wordpress query

texts:
I'm using this piece of code to show and paginate only child categories but this is horribly slow (49 queries in 9,799 seconds.).

Where did I make mistakes and how can I make this run faster?

<?php

$current_cat = get_query_var('cat');
$attributes = array('terms_per_page' => 20, 'taxonomy' => 'category');

// Sanitize and validate our inputs and set variables
$tpp = filter_var( $attributes['terms_per_page'], FILTER_VALIDATE_INT );
$taxonomy = filter_var( $attributes['taxonomy'], FILTER_SANITIZE_STRING );

// Make sure our taxonomy exists to avoid unnecessary work
if ( !taxonomy_exists( $taxonomy ) )
return false;

// Our taxonomy exists, lets continue
// Get the term count to calculate pagination.
$term_count = count( get_terms('category',array('hide_empty'=>'1','child_of' => $current_cat) ) );

// We have terms, now calculate pagination
$max_num_pages = ceil( $term_count / $tpp );
// Get current page number. Take static front pages into account as well
if ( get_query_var('paged')){
$paged = get_query_var('paged');
} elseif ( get_query_var('page')) {
$paged = get_query_var( 'page' );
} else {
$paged = 1;
}
// Calculate term offset
$offset = ( ( $paged - 1 ) * $tpp );

// We can now get our terms and paginate it
$args = array(
'number'     => $tpp, // Amount of terms to return
'offset'     => $offset, // The amount to offset the list by for pagination
'child_of'   => $current_cat,
'orderby'    => 'name',
'order'      => 'ASC',
'hide_empty' => '1',
);
// Set our variable to hold our string
$output = '';
$wpbtags = get_terms( $taxonomy, $args );

if ( ! empty($wpbtags)) {
foreach ($wpbtags as $category) {

//first get the current category ID
$cat_prefix = "category_";
$cat_id = $category->term_id;
//then i get the data from the database
$join_cat = $cat_prefix . $cat_id;
$cat_data = get_option($join_cat);?>

<a href="<?php echo get_category_link($category->term_id); ?>"     onclick="ga('send', 'event', 'ClickNav', 'cats', 'Cat - <?php echo $category-    >cat_name; ?>');">
<div class="one_fourth<?php echo ( ++$counter == 4 )?' last_column':''; ?> home-colour" title="<?php echo $category->name; ?>">

<?php if (!empty($cat_data['cat_img_url'])) : ?>

 <?php echo $category->name; ?>

<img class="res_img" src="<?php echo $cat_data['cat_img_url'] ;?>" alt="<?php echo $category->cat_name; ?>" width="310" height="209" />

<?php elseif (empty($cat_data['cat_img_url'])) :?>

 <?php echo $category->name; ?>

<img class="res_img" src="<?php echo get_stylesheet_directory_uri(); ?>/images/subcat-img-na.png" alt="Posts - <?php echo $category->cat_name; ?>"/>

<?php else : ?>
<?php endif; ?>

<?php } ?>

<?php /* COUNTS FOUR ADDS LAST COLUMN */ if ( $counter == 4 ) : ?>

<?php $counter = 0; endif; wp_reset_query(); ?>

<?php echo '
';
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $max_num_pages = (ceil( $term_count / $tpp))
) );

echo '
';
?>

<?php wp_reset_postdata(); ?>

<?php  /* IF THERE'S NOTHING TO SHOW */ } else {?>

// Show something if there is no posts here

<?php } ?>


texts: Avoid if/else in constructor - NavigableMap?

texts:
I have the following code, based on the input to the constructor I need to initialise some values which are wrapped in a simple POJO. These values are constant as you can see.

However I don't like the if/else construct in the set method and had read about NavigableMap as an alternative for holding range values. Any thoughts on how to improve/clean the below or indeed use this construct? I would like to avoid conditional logic where possible.

private Calibrated calibratedValues;

public CalibrationProperties(long odNumber) {
    setCalibratedValues(odNumber);
}

private void setCalibratedValues(long odNumber) {
if (odNumber < 762) {
    this.calibratedValues = new Calibrated(K0, H0, K0_INV, H0_INV, F0);
} else if (odNumber < 866) {
    this.calibratedValues = new Calibrated(K1, H1, K0_INV, H0_INV, F1);
} else if (odNumber < 1011) {
    this.calibratedValues = new Calibrated(K2, H2, K2_INV, H2_INV, F2);
} else {
    this.calibratedValues = new Calibrated(K3, H3, K3_INV, H3_INV, F3);
}

//Two exceptions
if (odNumber == 858){
    this.calibratedValues = new Calibrated(K2, H2, K2_INV, H2_INV, F2);
}
if (odNumber == 1005){
    this.calibratedValues = new Calibrated(K3, H3, K3_INV, H3_INV, F3);
}
}

public Calibrated getCalibratedValues() {
return calibratedValues;
}

/** Convenience class used to hold calibrated values */
static class Calibrated {
private double[] k;
private double[] h;
private double[] kinv;
private double[] hinv;
private double f;

Calibrated(double[] k, double[] h, double[] kinv, double[] hinv, double f) {
    this.k = k;
    this.h = h;
    this.kinv = kinv;
    this.hinv = hinv;
    this.f = f;
}

public double[] getK() {
    return k;
}

public double[] getH() {
    return h;
}
...


texts: BFS implementation to find connected components taking too long

texts:
This is in continuation to a question I asked here.  Given the total number of nodes (employees) and the adjacency list (friendship amongst employees), I need to find all the connected components.

public class Main {
    static HashMap<String, Set<String>> friendShips;

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

            String dataLine = in.readLine();
            String[] lineParts = dataLine.split(" ");
            int employeeCount = Integer.parseInt(lineParts[0]);
            int friendShipCount = Integer.parseInt(lineParts[1]);
            friendShips = new HashMap<String, Set<String>>();
            for (int i = 0; i < friendShipCount; i++) {
                String friendShipLine = in.readLine();
                String[] friendParts = friendShipLine.split(" ");
                mapFriends(friendParts[0], friendParts[1], friendShips);
                mapFriends(friendParts[1], friendParts[0], friendShips);
            }
            Set<String> employees = new HashSet<String>();
            for (int i = 1; i <= employeeCount; i++) {
                employees.add(Integer.toString(i));
            }
            Vector<Set<String>> friendBuckets = bucketizeEmployees(employees);
            System.out.println(friendBuckets.size());
    }

    public static void mapFriends(String friendA, String friendB, Map<String, Set<String>> friendsShipMap) {
        if (friendsShipMap.containsKey(friendA)) {
            friendsShipMap.get(friendA).add(friendB);
        } else {
            Set<String> friends = new HashSet<String>();
            friends.add(friendB);
            friendsShipMap.put(friendA, friends);
        }
    }

    public static Vector<Set<String>> bucketizeEmployees(Set<String> employees) {
        Vector<Set<String>> friendBuckets = new Vector<Set<String>>();
        while (!employees.isEmpty()) {
            String employee = getHeadElement(employees);
            Set<String> connectedEmployeesBucket = getConnectedFriends(employee);
            friendBuckets.add(connectedEmployeesBucket);
            employees.removeAll(connectedEmployeesBucket);
        }
        return friendBuckets;
    }

    private static Set<String> getConnectedFriends(String friend) {
        Set<String> connectedFriends = new HashSet<String>();
        connectedFriends.add(friend);
        Set<String> queuedFriends = new LinkedHashSet<String>();
        if (friendShips.get(friend) != null) {
            queuedFriends.addAll(friendShips.get(friend));
        }
        while (!queuedFriends.isEmpty()) {
            String poppedFriend = getHeadElement(queuedFriends);
            connectedFriends.add(poppedFriend);
            if (friendShips.containsKey(poppedFriend))
                for (String directFriend : friendShips.get(poppedFriend)) {
                    if (!connectedFriends.contains(directFriend) && !queuedFriends.contains(directFriend)) {
                        queuedFriends.add(directFriend);
                    }
                }
        }
        return connectedFriends;
    }

    private static String getHeadElement(Set<String> setFriends) {
        Iterator<String> iter = setFriends.iterator();
        String head = iter.next();
        iter.remove();
        return head;
    }
}

I have tested my code using the following script, the results of which I consume as sdtIn

#!/bin/bash
echo "100000 100000"
for i in {1..100000}
do
    r1=$(( $RANDOM % 100000 ))
    r2=$(( $RANDOM % 100000 ))
    echo "$r1 $r2"
   done

While I was able to verify (for trivial inputs) that my answer is correct, when I try with huge inputs as with the above script, I see that the run takes long (~20s).

Is there anything I can do better in my implementation ?


texts: Bash script to determine a distro, update, upgrade and install the apps I use

texts:
This is my first bash script. I am trying to learn scripting and needed an idea. This is the first idea I came up with. When I used to distro hop I had to reinstall everything. This helped me out once I got the first part working. Then I wanted to add if then else for more than just Debian distros.

#!/bin/bash

#Script Name : app_install.sh
#Author inflatus
#Created 4 Sept 2015
#Version 0.4

#Description
 #This script will determine the distributon of Linux and use the      appropriate package manager to install my core apps

current_distro=`cat /etc/*-release | grep "^ID=" | grep -E -o "[a-z]\w+"`
close_distro=`cat /etc/*-release | grep "^ID_LIKE=" | grep -E -o "[a-z]\w+"`

echo "$current_distro"
echo "$close_distro"

if [ "$close_distro" = "debian" ]; then

  #Debian
  #Install my apps on a fresh install of a Debian based Linux

  echo "This script will install your apps after a fresh install"

  apt-get update && apt-get dist-upgrade -y
  apt-get install htop traceroute whois gparted curl nmap openvpn rsync iptraf openssh-client git gimp hexchat unison -y

  #Adding repositories

  echo "Adding the repos"

  add-apt-repository ppa:atareao/telegram -y
  add-apt-repository ppa:mumble/release -y
  add-apt-repository ppa:stebbins/handbrake-releases -y
  add-apt-repository ppa:maarten-baert/simplescreenrecorder -y
  add-apt-repository ppa:remmina-ppa-team/remmina-next -y
  add-apt-repository ppa:libreoffice/libreoffice-5-1 -y
  add-apt-repository ppa:wireshark-dev/stable -y

  apt-get update
  apt-get install telegram mumble handbrake simplescreenrecorder remmina remmina-plugin-rdp libfreerdp-plugins-standard libreoffice wireshark -y
  apt-get dist-upgrade -y

  #Time to clean

  echo "Alright, cleaning now."

  apt-get autoclean

  #Finished install

  echo "Finished."

elif [ "$close_distro" != "debian" ]; then

  #Fedora
  #Install my apps on a fresh install of a Fedora based Linux

  echo "This script will install your apps after a fresh install"

  dnf check-update -y
  dnf update -y
  dnf install htop traceroute jwhois gparted curl nmap openvpn rsync iptraf openssh-clients git gimp mumble remmina-plugins-rdp wireshark hexchat -y
  dnf clean all

  #Time to clean

  echo "Alright, cleaning now."
  dnf clean all

  #Finished install

   echo "Finished."

 else

   echo "This is not for you."
fi


texts: Print the upper half triangle of a matrix

texts:
Here is what I've written for a program to print upper half triangle of a matrix. Now I need a way to do it without using goto:

    #include <iostream>
using namespace std;

int main()
{
    int a[10][10], r, c, i, j;
    cout << "Enter the number of rows and columns";
    cin >> r >> c ;
    cout << "Enter the matrix :";
    for(i=0;i<r;++i)
    {
                    for(j=0;j<c;++j)
                    {
                                    cin >> a[i][j];
                    }
    }
    cout << "The matrix is : \n";
    for(i=0;i<r;++i)
    {
                    for(j=0;j<c;++j)
                    {
                                    if(j<i)
                                    goto loop;
                                    cout << a[i][j] << "\t";
                                    loop:
                                         if(j<i)
                                         cout<< " \t";
                                    if(j==(c-1))
                                    cout<<"\n";
                    }
    }
    cin >> r;
}

Any help is appreciated.


texts:
I'm looking to improve a loop within a script that performs scheduled server restarts.

Currently, I'm using a DO While loop with an exit condition within an IF statement once a counter reaches a limit.

I'm looking to change this into a more simpler loop using a Labeled While loop containing a For loop that breaks when the nested If loop catches the counter variable reaching a limit.  I've read it's best to avoid using Break but I just cannot come up with anything.

#current loop
$max = 60;$i = 0
 DO
 {
  IF($i -gt $max){
  [PsCustomObject]@{
  "Server" =  $server
  "Status" = "FailedToReboot!"
  "LastRebootTime" = "$LastReboot"
  "CurrentRebootTime" = "FailedToReboot!"
   }#end custom object

Send-MailMessage <Details>

exit}#exit script and log failed to reboot.

$i++

Start-Sleep -Seconds 10

}#end DO

While (Test-path "\\$server\c$")#After this point, server went offline, continue script.

#new test loop
:WaitingForReboot while (test-path \\$server\C$){
 for($i = 0; $i -le 7){
 $i++
 "Waiting for $server to reboot, waited " + $(10 * $i) + " of 50 seconds"

  IF($i -eq 5){"Exit wait loop";break WaitingForReboot}Else{
    #do nothing in Else, until $i hits 5.
    }#else block
Start-Sleep -Seconds 10
 }#for loop
}#while loop


texts:
I have written a method that checks if n number of true booleans are present in a boolean[] array. Then I improved it to var args format which is as follows:

public static boolean checkNTrue(int n, boolean... args) {
    assert args.length > 0;
    int count = 0;
    for( boolean b : args ) {
        if(b)   count++;
        if( count > n )
            return false;
    }
    return ( count == n );
}

I implement it  to check if only one of all those booleans is true by using:

boolean result = checkNTrue(1, false, true, false, false);

The above returns true confirming the required case.  But what if there are only two boolean arguments? A simple XOR could return the right result.

And in the case of 3 booleans, return (a ^ b ^ c) ^ (a && b && c); works fine too. So, my question is:

Do I need to write separate methods to check in cases with 2 and 3 variables?

Or will this one method do fine? I invite every kind of criticism through downvotes and comments, but please enlighten me! :-)


texts:
Decided to get a little JDK 8 practice in today, so I built two methods to print out the golden ratio, one uses the Stream API the other does not. Wanted to request general feedback on how well I implemented these methods (mainly the stream generator,) considering the given task and if there is anything I could have done better.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created on 7/5/2016.
 *
 */

public class Fibonacci {
    public static void main(String[] args) {
        System.out.printf("Fibonacci Old: %s%n", String.join(", " , Fibonacci.calculateFib(10).stream()
                .map(Object::toString)
                .collect(Collectors.toList())));

        System.out.printf("Fibonacci New: %s%n", String.join(", " , Fibonacci.generateFib()
                .limit(10)
                .map(Object::toString)
                .collect(Collectors.toList())));
    }

    private static List<Integer> calculateFib(int fibCount){
        List<Integer> fibSequence = new ArrayList<>();
        fibSequence.add(0);
        fibSequence.add(1);
        for(int i = 2; i < fibCount; i++){
            fibSequence.add(fibSequence.get(i-1) + fibSequence.get(i-2));
        }
        return fibSequence;
    }

    private static Stream<Integer> generateFib() {
        return Stream.generate(new Supplier<Integer>() {
            List<Integer> list = new ArrayList<>(Arrays.asList(0, 1));
            int i = 0;

            @Override
            public Integer get() {
                list.add(list.get(i) + list.get(i+1));
                return list.get(i++);
            }
        });
    }
}


texts: Elegant way to sort on multiple properties that might be undefined

texts:
I'm trying to sort an array with JavaScript. The objects should be sorted based on several properties (about 4 in my real scenario), which are all strings that may also be null or undefined. A null or undefined value should be treated similar, and should be "earlier" in the sorted array than items with values.

I used unit tests to spec the behavior, and the simplest code that would work (which is really, really verbose) is the following:

function myComparer(a, b) {
  if (!!a.label && !!b.label) {
    var diff = a.label.localeCompare(b.label);
    if (diff !== 0) {
      return diff;
    }
  }

  if (!!b.label && !a.label) {
    return -1;
  }

  if (!!a.label && !b.label) {
    return 1;
  }

  if (!!a.code && !!b.code) {
    var diff = a.code.localeCompare(b.code);
    if (diff !== 0) {
      return diff;
    }
  }

  if (!!b.code && !a.code) {
    return -1;
  }

  if (!!a.code && !b.code) {
    return 1;
  }

  return 0;
}

test("Can compare given labels", function() {
  var result = [{label: 'Z'}, {label: 'A'}].sort(myComparer);
  strictEqual(result[0].label, 'A');
  strictEqual(result[1].label, 'Z');
});

test("Can compare null label with given label", function() {
  var result = [{label: null}, {label: 'A'}].sort(myComparer);
  strictEqual(result[0].label, null);
  strictEqual(result[1].label, 'A');
});

test("Can compare null label with given label - reverse", function() {
  var result = [{label: 'Z'}, {label: null}].sort(myComparer);
  strictEqual(result[0].label, null);
  strictEqual(result[1].label, 'Z');
});

test("Can compare given codes", function() {
  var result = [{code: 'Z'}, {code: 'A'}].sort(myComparer);
  strictEqual(result[0].code, 'A');
  strictEqual(result[1].code, 'Z');
});

test("Can compare null code with given code", function() {
  var result = [{code: null}, {code: 'A'}].sort(myComparer);
  strictEqual(result[0].code, null);
  strictEqual(result[1].code, 'A');
});

test("Can compare null code with given code - reverse", function() {
  var result = [{code: 'Z'}, {code: null}].sort(myComparer);
  strictEqual(result[0].code, null);
  strictEqual(result[1].code, 'Z');
});

test("Will sort on label before code", function() {
  var result = [
    {id: 1, label: 'Z', code: 'Z'},
    {id: 2, label: 'Z', code: 'A'},
    {id: 3, label: 'A', code: 'Z'},
    {id: 4, label: 'A', code: 'A'}].sort(myComparer);
  strictEqual(result[0].id, 4);
  strictEqual(result[1].id, 3);
  strictEqual(result[2].id, 2);
  strictEqual(result[3].id, 1);

});

<link href="http://code.jquery.com/qunit/qunit-1.12.0.css" rel="stylesheet"/>

This will not be pretty for 4 or more properties (I figured you can imagine this, I tried to keep my example a bit smaller).

I can think of several ways to improve this, but I struggle to balance:

Performance
Readability
Verbosity

Which is why I figured I'd ask here: do you have any suggestions on how to refactor my version into something more elegant?

PS. I'm happy to use ECMAScript5 stuff, I can use polyfills if anything's missing in browsers.


texts:
Currenty coding a PHP script that will have a CRON to auto run it.
The point is that it checks the user in Mysql and if it has expired, it will delete it from the admin table and set status to expired.
I have used time() and then when it gets INSERT When his trial starts, it starts for example "1347054850" in the "Start" and then i add "900" on it using +, and the result is "1347055750", So the trial is for 15 minutes.
But the point, will this scipt work propery or does it have issues?

<?php
$Sql = new mysqli("localhost", "root", "*******", "serveradmin");
if ($Sql->connect_error) { die("Sorry, Could not connect (".$Sql->connect_errno.") ".$Sql->connect_error);}
$Data = $Sql->query("SELECT * FROM trial");
while ($q = $Data->fetch_assoc()) {
$Start = $q['Start'];
$Stop = $q['Stop'];
$Steam = $q['Steam'];
$Result = $Start - $Stop;
$Time = time();
if ($q['Expired'] == "True") {echo "All expired \n";} else {
if ($Stop <= $Time) {
echo "Deleted ".$Steam." From trial Reason: Expired";
$Sql->Query("DELETE FROM `sm_admins` WHERE `identity` = '".$Steam."'");
$Sql->Query("UPDATE trial SET `Expired` = 'True' WHERE `Steam` = '".$Steam."'");
}
else
{
echo "All ok, 0 deleted";
}
}
}
?>


texts:
/****************************************************************
VIEW MODULE
view, view_database, view_message
view_arche_1 (external), view_arche_2 (external) - these are
  primarily html files
****************************************************************/

/*view*/

class view extends database
  {
  }

/*view_db*/

class view_db extends view
  {
  function __construct($type)
    {
    parent::__construct();
    $this->invoke($type);
    }
  private function invoke($type)
    {
    switch ($type)
      {
      case "bookmarks":
        $this->html_bookmarks();
        break;
      case "tweets":
        $this->html_tweets();
        break;
      default:
        throw new Exception('Invalid View Type');
        break;
      }
    }
  private function html_bookmarks()
    {
    $email = $_SESSION['email'];
    $query_return = database::query("SELECT * FROM bo  WHERE email='$email' ORDER BY name ASC");
    $html_string='';
    while ($ass_array = mysqli_fetch_assoc($query_return))
      {
      $fav=$this->favicon($ass_array['url']);
      $html_string = $html_string . "$ass_array[name]";
      }
    echo $html_string;
    }
  private function html_tweets()
    {
    $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7");
    $time = time();
    $html_string='';
    while ($a = mysqli_fetch_assoc($query_return))
      {
      $html_string = $html_string . "
$a[fname] posted

$a[message]

";
      }
    echo $html_string;
    }
  private function favicon($url)
    {
    $pieces = parse_url($url);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';
    if(preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs))
      {
      return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico';
      }
    return false;
    }
  }

class view_message extends view
  {
  function __construct($type)
    {
    $this->invoke($type);
    }
  private function invoke($type)
    {
    $this->message($type);
    }
  private function message($type)
    {
    $type_message = array(
    'empty' => '<si_f>Please complete all fields.',
    'name'=> '<su_f>Only letters or dashes for the name field.',
    'email' => '<si_f>Please enter a valid email.',
    'taken' => '<si_f>Sorry that email is taken.',
    'pass' => '<si_f>Please enter a valid password, 6-40 characters.',
    'validate' => '<si_f>Please contact support to reset your password.');
    echo $type_message[$type];
    }
  }


texts:
I have a form, which I want to draw on-top some shapes. To be exact, rectangles and lines.

This is the "Redraw" method. I call this method every 100ms from a different thread.

public void Redraw()
    {
        g.FillRectangle(b, new Rectangle(13, 13, (int)drawMapX + 2, (int)drawMapY + 2)); /* Draw background */

        try
        {
            foreach (Location drawPoint in points)
            {
                g.DrawLine(new Pen(y), new Point((int)Math.Round(masterpos.X), (int)Math.Round(masterpos.Y)), new Point((int)Math.Round(drawPoint.X), (int)Math.Round(drawPoint.Y)));
                g.FillRectangle(r, drawPoint.X, drawPoint.Y, 2, 2);

            }
            g.FillRectangle(gr, masterpos.X, masterpos.Y, 2, 2);

            g.DrawString(Math.Round(pos.X).ToString() + " " + Math.Round(pos.Y), drawFont, gr, masterpos.X + 2, masterpos.Y - 20, centered);
        }
        catch { }
    }

Where "g" is

  Graphics g = Application.OpenForms["Client"].CreateGraphics();

Nothing too interesting about it, draws some shapes in some given places, and some strings

My question: Is my thread safe and memory-leak proof?

void CreateDrawingThread() {new Thread(() => {
            Thread.CurrentThread.IsBackground = true;
            do
            {
                try
                {

                    Thread.Sleep(100);
                    Redraw();
                }
                catch(Exception ex) { Console.WriteLine(ex.ToString()); return; }
            } while (true);

        }).Start();}

Because as you can see, I don't do anything like g.Flush every redraw, I was wondering if it stores old "draws" in memory, or if I'm doing something in a cpu costraining way.


texts:
I need to learn more about Entity Framework, so I created a database to store notes. The database definition is as follows:

public class User
{
    [Key]
    public int UserId { get; set; }

    [MaxLength(20)]
    public string UserName { get; set; }

    public virtual List<Note> Notes { get; set; }
}

public class Note
{
    [Key]
    public int NoteId { get; set; }

    [MaxLength(30)]
    public string Title { get; set; }

    [MaxLength(200)]
    public string Content { get; set; }

    public int UserId { get; set; }
    public virtual User User { get; set; }
}

public class NotesContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Note> Notes { get; set; }
}

I wrote the following helper functions (I'm working off a Console Application for now):

class Program
{
    private static void AddUser(string userName)
    {
        using (var db = new NotesContext())
        {
            db.Users.Add(new User { UserName = userName });
            db.SaveChanges();
        }
    }

    private static void RemoveUser(int userId)
    {
        using (var db = new NotesContext())
        {
            var user = db.Users.FirstOrDefault(u => u.UserId == userId);
            if (user != null)
            {
                db.Users.Remove(user);
                db.SaveChanges();
            }
        }
    }

    private static void ClearUsers()
    {
        using (var db = new NotesContext())
        {
            db.Users.RemoveRange(db.Users);
            db.SaveChanges();
        }
    }

    private static void AddNote(int userId, string title, string content)
    {
        using (var db = new NotesContext())
        {
            db.Notes.Add(new Note { UserId = userId, Title = title, Content = content });
            db.SaveChanges();
        }
    }

    private static void RemoveNote(int noteId)
    {
        using (var db = new NotesContext())
        {
            var note = db.Notes.FirstOrDefault(u => u.NoteId == noteId);
            if (note != null)
            {
                db.Notes.Remove(note);
                db.SaveChanges();
            }
        }
    }

    private static void ClearNotes()
    {
        using (var db = new NotesContext())
        {
            db.Notes.RemoveRange(db.Notes);
            db.SaveChanges();
        }
    }
}

Other than the fact that it would be somewhat expensive to add or remove a set of users using these extensions, rather than getting one DB instance, updating it, and running SaveChanges() once, is there anything I should be doing differently?


texts: Method for obtaining adjacent chunk positions

texts:
I'm currently in the process of making a 2D tile based game. This game has an "infinite" world that can be traversed and modified as needed. I am creating the chunks with a mesh and I apply a texture to them. The chunks texture updates every time I set a tile with a new Sprite.

Each time I set a new tile, the surrounding tiles from the same chunk recalculate based on their adjacent tiles and they set their sprite accordingly (Auto-tiling). This works perfectly fine and I have no issues, unless the tile is along the edge of the chunk.

If the tile is along the edge of the chunk, it updates the texture of the chunk perfectly but the adjacent chunk textures aren't updated. Now, I am using the below code to obtain the adjacent chunks based on the tiles position. This works, however it is extremely ugly and unreadable.

if (tileX == 0 || tileY == 0 || tileX == chunkSize - 1 || tileY == chunkSize - 1)
{
    var chunksToUpdate = new List<Vector3Int> ();
    var position = chunk.Position;

    if (tileX == 0 && tileY == 0)
    {
        chunksToUpdate.Add (new Vector3Int (position.X - chunkSize, position.Y, position.Z)); //left
        chunksToUpdate.Add (new Vector3Int (position.X, position.Y - chunkSize, position.Z)); //down
        chunksToUpdate.Add (new Vector3Int (position.X - chunkSize, position.Y - chunkSize, position.Z)); //downleft

    }
    else if (tileX == 0 && tileY == chunkSize - 1)
    {
        chunksToUpdate.Add (new Vector3Int (position.X - chunkSize, position.Y, position.Z)); //left
        chunksToUpdate.Add (new Vector3Int (position.X, position.Y + chunkSize, position.Z)); //up
        chunksToUpdate.Add (new Vector3Int (position.X - chunkSize, position.Y + chunkSize, position.Z)); //upleft

    }
    else if (tileX == chunkSize - 1 && tileY == 0)
    {
        chunksToUpdate.Add (new Vector3Int (position.X + chunkSize, position.Y, position.Z)); //right
        chunksToUpdate.Add (new Vector3Int (position.X, position.Y - chunkSize, position.Z)); //down
        chunksToUpdate.Add (new Vector3Int (position.X + chunkSize, position.Y - chunkSize, position.Z)); //downright

    }
    else if (tileX == chunkSize - 1 && tileY == chunkSize - 1)
    {
        chunksToUpdate.Add (new Vector3Int (position.X, position.Y + chunkSize, position.Z)); //up
        chunksToUpdate.Add (new Vector3Int (position.X + chunkSize, position.Y, position.Z)); //right
        chunksToUpdate.Add (new Vector3Int (position.X + chunkSize, position.Y + chunkSize, position.Z)); //upright

    }
    else if (tileX == 0)
    {
        chunksToUpdate.Add (new Vector3Int (position.X, position.Y + chunkSize, position.Z)); //up

    }
    else if (tileX == chunkSize - 1)
    {
        chunksToUpdate.Add (new Vector3Int (position.X + chunkSize, position.Y, position.Z)); //right

    }
    else if (tileY == 0)
    {
        chunksToUpdate.Add (new Vector3Int (position.X, position.Y - chunkSize, position.Z)); //down

    }
    else if (tileY == chunkSize - 1)
    {
        chunksToUpdate.Add (new Vector3Int (position.X, position.Y + chunkSize, position.Z)); //up

    }

Clarification: I am checking to see if tileX or tileY are along the edges of the chunk. If they are then I add a new Vector3Int to the list. I also only attempt to obtain the chunks that will be affected by the chunks texture update.

After this, I loop through all of the Vector3Int's in the chunksToUpdate list and update them like so.

foreach (var pos in chunksToUpdate)
{
    MeshChunk updateChunk = GetChunk (pos);

    if (updateChunk != null)
    {
        UpdateChunkTiles (updateChunk);
    }
}

I'm not looking for any criticism about my naming conventions or formatting. I'm wondering if there is a more elegant way of handling this scenario? Can it be refactored to take up less space and its readability improved.


texts: Compute bounding rectangle given 2 points quickly and efficiently

texts:
Is there a faster way to compute the bounding area between 2 points?

// Minified Version
public static Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
    double dx = p2.x - p1.x, dy = p2.y - p1.y;
    return new Rectangle((int) (dx < 0 ? p2.x : p1.x),
        (int) (dy < 0 ? p2.y : p1.y), (int) Math.abs(dx), (int) Math.abs(dy));
}

// Readable Version
public static Rectangle computeBounds(Point2D.Double p1, Point2D.Double p2) {
    double dx = p2.x - p1.x;
    double dy = p2.y - p1.y;

    int x = (int) (dx < 0 ? p2.x : p1.x);
    int y = (int) (dy < 0 ? p2.y : p1.y);
    int w = (int) Math.abs(dx);
    int h = (int) Math.abs(dy);

    return new Rectangle(x, y, w, h);
}


texts:
I want to split the following String into java ArrayList

"[\"1-72\",\"1-111\",\"1-4\"]"

I had wrote a very rough solution but not sure how to enhance it:

String sample = "\"[\"1-72\",\"1-111\",\"157f9d3dfb4-4\"]\"";
sample =  sample.replaceAll("\"", "");      //to replace double quote
sample = sample.replaceAll("\\[", "").replaceAll("\\]","");    //to replace open and close square bracket
List<String> sampleList= Arrays.asList(sample.split(","));
sampleList.forEach(System.err::println);


texts: Class Object to create objects of type Object, in a dynamic way, with magic methods

texts:
I have a project in my mind for quite some time, and it requires me to create dynamic objects.

Usually, casting an array to object does the trick (e.g.: (object)array('test'=>5)). But sometimes, we still want the magic methods to fire up. For that, I have developed a class.

It supports the magic methods __construct, __get, __set, __isset and __unset. This also has a method to check the keys in your object.

class Object {
    private $props = array();
    private $methods = array(
        '__construct'=>null,
        '__get'=>null,
        '__set'=>null,
        '__isset'=>null,
        '__unset'=>null
    );

    private function __run_magic_method( $method, $args=null )
    {
        $obj = (object)$this->props;
        $return = call_user_func_array( $this->methods[$method], array_merge( array(&$obj), (array)$args ) );
        $this->props = (array)$obj;
        return $return;
    }

    private function __has_magic_method( $method )
    {
        return isset( $this->methods[$method] ) && is_callable( $this->methods[$method] );
    }

    function __construct( array $props )
    {
        foreach( array_keys($this->methods) as $method )
        {
            if( isset( $props[$method] ) )
            {
                $this->methods[$method] = $props[$method];
                unset( $props[$method] );
            }
        }

        $this->props = $props;

        if( $this->__has_magic_method( '__construct' ) )
        {
            $this->__run_magic_method( '__construct' );
        }
    }

    function __get( $key )
    {
        if($this->__has_magic_method('__get' ) )
        {
            return $this->__run_magic_method( '__get', array($key) );
        }
        else
        {
            return $this->props[$key];
        }
    }

    function __set( $key, $value )
    {
        if( $this->__has_magic_method( '__set' ) )
        {
            $this->__run_magic_method( '__set', array( $key, $value ) );
        }
        else
        {
            $this->props[$key] = $value;
        }
    }

    function __isset( $key )
    {
        if( $this->__has_magic_method( '__isset' ) )
        {
            return $this->__run_magic_method( '__isset', array($key) );
        }
        else
        {
            return isset( $this->props[$key] );
        }
    }

    function __unset( $key )
    {
        if( $this->__has_magic_method( '__unset' ) )
        {
            return $this->__run_magic_method( '__unset', array($key) );
        }
        else
        {
            unset( $this->props[$key] );
        }
    }

    function __call( $key, $args )
    {
        if( isset( $this->props[$key] ) && is_callable( $this->props[$key] ) )
        {
            return call_user_func_array( $this->props[$key], $args );
        }
        else
        {
            throw new Exception( 'The key "'.addslashes($key).'" is not a callable' );
        }
    }

    private function __keys()
    {
        return array_keys( $this->props );
    }

    static function keys( Object $obj=null )
    {
        if( $obj === null )
        {
            return array();
        }
        else
        {
            return $obj->__keys();
        }
    }
}

Example of usage:

$obj = new Object(array(
    '__construct'=>function(){echo 'constructor executed', PHP_EOL;},
    '__isset'=>function($t,$k){
        echo 'checking key: ', $k, PHP_EOL;
        return isset($t->{$k});
    },
    'test'=>5
));

if( isset($obj->test) )
{
    echo $obj->test;
}

/*
Should output:

constructor executed
checking key: test
5
*/

What can I improve in this code, in terms of readability? What crimes am I committing with this code?


texts: It there a pattern used to process a same function but assign the result to a different variable regarding to a different condition?

texts:
Say I have a code snippet like this

    if(string.Compare(isStandardFlag,"STANDARD",true)==0)
    {
        hearingID = centreSession.standardID;
        centreSession.standardOutcomeID
            = disciplineSvc.SaveResultA(hearingID,OffenceID, Outcome);
        centreSession.standardOutcomeNoteID
            = disciplineSvc.SaveResultB(hearingID, txt1.Text, "ResultHearing");
    }
    else{
        hearingID = centreSession.noneStandardID;
        centreSession.noneStandardHearingOutcomeID
            = disciplineSvc.SaveResultA(hearingID,OffenceID, Outcome);
        centreSession.noneStandardHearingOutcomeNoteID
            = disciplineSvc.SaveResultB(hearingID, txt1.Text, , "ResultHearing");
    }

You can see the 'if' and 'else' do the same thing but just assign the result to different variables.

Is there a pattern I can refer to refactor the code?


texts:
I have a set of images with class = tt like so:

<img src="images/arc_unselected.png" title="Arc" class="tt" />

and I have written this code to change the images after clicking:

     $(".tt").click(function(event) {
           var title = event.target.getAttribute("title")
           resetOtherImages(title)
           if( title == "info"){
              if ( event.target.getAttribute("src") == "images/information_selected.png"){
                 $(this).attr('src', 'images/information_unselected.png')
                 }
              else {
                  $(this).attr('src', 'images/information_selected.png')
                 }
           }else if( title == "Up"){
                 if ( event.target.getAttribute("src") == "images/up_selected.png"){
                 $(this).attr('src', 'images/up_unselected.png')
                 }
              else {
                  $(this).attr('src', 'images/up_selected.png')
                 }
           }else if( title == "Down"){
                 if ( event.target.getAttribute("src") == "images/down_selected.png"){
                 $(this).attr('src', 'images/down_unselected.png')
                 }
              else {
                  $(this).attr('src', 'images/down_selected.png')
                 }

           }else if( title == "SE"){
                 if ( event.target.getAttribute("src") == "images/se_selected.png"){
                 $(this).attr('src', 'images/se_unselected.png')
                 }
              else {
                  $(this).attr('src', 'images/se_selected.png')
                 }
           }else if( title == "Arc"){
                 if ( event.target.getAttribute("src") == "images/ar_selected.png"){
                 $(this).attr('src', 'images/arc_unselected.png')
                 }
              else {
                  $(this).attr('src', 'images/arc_selected.png')
                 }
           }
        })

        function resetOtherImages(title) {
        $('.tt').each(function(){
            if($(this).attr('src') !== title)
            {
              var newName = changeName($(this).attr('src'))
              $(this).attr('src',newName)
            }
        });
        }

        function changeName(imgName) {
           var pos = imgName.indexOf("_");
           var first = imgName.substring(0,pos);
           return first.concat("","_unselected.png");
        }

It works without any problem, but since I have not much experience with javascript I wanted to know if there is a better way to do this, more compact and more readable.


texts:
I'm working on a simple program and am trying to make it faster.

import time
import numpy as np
import matplotlib.pyplot as plt
import pp

first_file = open("ac_data.dat", 'r') #real dataset includes about 20000 terms
res_file = open("res.dat", 'w')
times_file = open("times.dat", 'a')

#times = [0.000000, 0.000500, 0.001000, 0.001500, 0.002000, 0.002500, 0.003000, 0.003500, 0.004000, 0.004500, 0.005000, 0.005500, 0.006000, 0.006500, 0.007000, 0.007500, 0.008000, 0.008500, 0.009000, 0.009500]
#magn = [-13.876622, -10.014824, -16.356894, -11.639914, -13.103313, -14.335239, -12.250072, -10.727098, -8.701272, -9.632907, -9.673712, -10.541722, -14.075446, -13.097790, -12.495679, -10.322924, -14.979391, -14.895666, -11.874325, -9.287736]

times = []
magn = []

for i in first_file:
  dat = [float(j) for j in i.split()]
  times.append(dat[0])
  magn.append(dat[1])

length = len(magn) #supposed to be equal 20000 for original data

#autocorrelation function
def rxx_func(amp):
    N = len(amp)
    rxx = [0]*N

    for m in xrange(N):
        for n in xrange(N-m):
            rxx[m]+=amp[n]*amp[n+m]
    return rxx

#just prove with in-built
def autocorr(x):
    result = np.correlate(x, x, mode='full')
    return result[result.size/2:]

#Parallel or ordinary?
answer = int(raw_input('Non-arallel = 0, parallel = 1 '))

if answer == 0:
    print 'Non-parallel calc was started'
    start = time.time()

    rxx = rxx_func(magn)

    end = time.time()
    calc_time = end - start

    time_string = 'Non-parallel: N = %i    T = %f\n'%(length,calc_time)

else:
    print 'Parallel calc was started'
    ppservers = ()
    ncp = 4
    job_server = pp.Server(ncp, ppservers=ppservers)
    print "Starting pp with", job_server.get_ncpus(), "workers"

    arg_n = tuple(magn)
    job = job_server.submit(rxx_func, (arg_n,), (), ())

    start = time.time()

    rxx = job()
    job_server.print_stats()

    end = time.time()
    calc_time = end - start

    time_string = 'Parallel with %i CPUs: N = %i    T = %f\n'%(ncp,length,calc_time)

print (" \n Task for %i terms takes %f seconds for calc" %(length, calc_time))
print (" Max value of Autocorrelation func achieves %f" %(max(rxx)))
print (" And it'll be normalized to 50 \n")

#normalization to 50
norm_const = 50/max(rxx)

proves = autocorr(magn)

for k in xrange(length):
    rxx[k] = rxx[k]*norm_const
    proves[k] = proves[k]*norm_const

#plotting
plt.plot(times, magn)
plt.plot(times, rxx)
plt.plot(times, proves,'*')

plt.show()

for j in xrange(length): #saving results
    st = '%f    %f    %f\n'%(times[j], rxx[j], proves[j])
    res_file.write(st)

times_file.write(time_string) #saving calc times for comparsion

first_file.close()
res_file.close()
times_file.close()

The program reads datasets from files to lists. Typical datasets look like commented #magn and #time. Real datasets will consist of 20000 lines or more.

I've trying use the "parallel Python" package, but it runs even more slower than non-parallel code.

For example, some results:

Non-parallel: N = 20000    T = 74.530000 sec
Parallel with 2 CPUs: N = 20000    T = 80.229000 sec
Parallel with 4 CPUs: N = 20000    T = 80.594000 sec

And I can't figure out why. Maybe I don't understand how it must be used.


texts: Optimization of General Purpose Makefile

texts:
I wrote a makefile that would generate a simple executable from the example directory structure.
project/
  source/
  include/
  makefile

The makefile itself comes equipped with dependency tracking, and automatically generates two directories named build and dependency. Currently the makefile I made works, yet it takes anywhere from three to five seconds to build the executable on my machine. I was wondering whether my makefile source code was setup inefficiently, or am I just being impatient?
target    := driver.exe
compiler  := g++
ccflags   := -Wall -Werror -pedantic -pedantic-errors -O2 -std=c++17
src_dir   := source
build_dir := build
deps_dir  := dependency
ccfiles   := $(wildcard $(src_dir)/*.cc)
objects   := $(patsubst $(src_dir)/%.cc, $(build_dir)/%.o, $(ccfiles))

deps := $(patsubst $(build_dir)/%.o, $(deps_dir)/%.d, $(objects))
-include $(deps)
deps_flags = -MMD -MF $(@:$(build_dir)/%.o=$(deps_dir)/%.d)

$(target): $(objects)
    @$(compiler) -o $@ $^
    @echo "Successfully built "$@"!"

$(build_dir)/%.o: $(src_dir)/%.cc | setup
    @$(compiler) $(cflags) -o $@ -c $< $(deps_flags)
    @echo "Successfully built "$<" into "$@"!"

.PHONY: setup
setup:
    @mkdir -p $(build_dir) $(deps_dir)

.PHONY: clean
clean:
    rm -rf $(target) $(build_dir) $(deps_dir)


texts: Length-Based Frame Stream En-/Decoding in Go

texts:
I'm relatively new to Go, which is why I decided to post some code here. My goal is to en-/decode a TCP stream. The individual data packets length-based. The first two bytes are the unsigned size in little-endian byte order. The size includes the size field itself. The methods I wrote seem to en-/decode the packets as expected.

Is there a more efficient way to achieve this?
Does Go perhaps already implement such methods somewhere.

func GetPacketByLength(source io.Reader) ([]byte, error) {
    s := make([]byte, 2)
    if _, err := io.ReadFull(source, s); err != nil {
        return nil, err
    }

    // Little-endian uint16
    size := uint16(s[0]) | uint16(s[1])<<8 - 2

    p := make([]byte, size)
    if _, err := io.ReadFull(source, p); err != nil {
        return nil, err
    }

    return p, nil
}

func PutPacketByLength(target io.Writer, p []byte) error {
    s := make([]byte, 2)

    // Little-endian uint16
    s[0] = byte((len(p) + 2))
    s[1] = byte((len(p) + 2) >> 8)

    if _, err := target.Write(s); err != nil {
        return err
    }
    if _, err := target.Write(p); err != nil {
        return err
    }

    return nil
}


texts: 99 bottles of beer on the wall in Python 3

texts:
This is my try on the 99 bottles of beer on the wall lyrics, made in Python 3. I am a beginner willing to learn so be gentle :)

def lyrics():
    if count > 1:
        print(f"{count} bottles of beer on the wall,")
        print("")
        print(f"{count} bottles of beer.")
        print("")
        print("Take one down, pass it around,")
        print("")
    else:
        print(f"{count} bottle of beer on the wall.")
        print("")
        print(f"{count} bottle of beer on the wall,")
        print("")
        print(f"{count} bottle of beer.")
        print("")
        print("Take it down, pass it around,")
        print("")
        print("No more bottles of beer on the wall.")

def bottles():
    global count
    while count > 1:
        lyrics()
        count = count - 1
        if count > 1:
            print(f"{count} bottles of beer on the wall.")
            print("")
        else:
            lyrics()

if __name__ == '__main__':
    count = 99
    bottles()


texts: Asyncronous unit test refactoring in Objective-C

texts:
I have found that writing unit tests helps me to discover both the intent and also reusability of code that I'm working on. It has been generally helpful in helping develop my "code smell."

I was working on two unit tests that are basically mirror images, and realized that I was typing code that looked almost identical. I am hoping that someone could help me refactor the similar parts of these two unit tests into shared setup and tear-down methods.

- (void)testBlockMethodOne
{
    NSError *expectedError = [NSError errorWithDomain:@"An error"
                                         code:42
                                     userInfo:nil];
    [mockClassA setError:expectedError];
    [mockClassA setRunCompletionBlockImmediately:YES];

    __block NSError *actualError = nil;
    __block id actualObject = nil;

    [classB fireClassAsBlockThenDoThisBlock:^(id object, NSError *error) {
        actualObject = object;
        actualError  = error;
    }];

    STAssertNil(actualObject, @"There was a problem");
    STAssertEqualObjects(actualError, expectedError, @"Got the expected error");
}

- (void)testBlockMethodTwo
{
    NSObject *expectedObject = [[NSObject alloc] init];
    [mockClassA setObject:expectedObject];
    [mockClassA setRunCompletionBlockImmediately:YES];

    __block NSError *actualError = nil;
    __block id actualObject = nil;

    [classB fireClassAsBlockThenDoThisBlock:^(id object, NSError *error) {
        actualObject = object;
        actualError  = error;
    }];

    STAssertNil(actualError, @"There was a problem");
    STAssertEqualObjects(actualObject, expectedObject, @"Got the expected object");
}

A little background about what's being tested:

In production code, -fireClassAsBlockThenDoThisBlock is asynchronous. But, of course, in the unit tests I have a mock standing in for "Class A" that just calls the block immediately with either the error or object that I set on the mock.

I've repeated more setup code then I'd really like to between the two tests. My hope is once I see how someone else attacks this, I'll have gained some insight into refactoring block based methods.


texts: Calculate co-occurrences of some words in documents dataset

texts:
It's a function to calculate the co-occurrences of some words in a news dataset, such as Techcrunch, Wired. The words list could be locations, products or people names.

Words list example:

["New York","Los Angeles","Chicago"]

Return result:

{"Chicago": {"New York" : 1, "Los Angeles": 2}}

The co-cocurrence between "Chicago" and "New York" is 1.

The problems:

The code below will caculate the same co-cocurrence of two words twice. And the time cost by a test dataset with 5 articles is 13.5s.

So for a dataset of 100k articles will cost about 75 hours. Is there any better solutions to improve the performance? Thanks!

  "13.5 s ± 415 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)"

def get_co_occurrences(data):
    com = defaultdict(dict)
    for temp in data:
        for i in range(len(city_list)-1):
            for j in range(i+1, len(city_list)):
                w1, w2 = city_list[i], city_list[j]
                if " " + w1 + " " in temp and " " + w2 + " " in temp:
                    print(w1,w2)
                    if com[w1].get(w2) is None:
                        com[w1][w2] = 1
                    else:
                        com[w1][w2] += 1
    return com

Edited: Python version

Python 3.6.2 | packaged by conda-forge | (default, Jul 23 2017, 22:59:30)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)] on linux


texts: JS calculator, respecting order of operations

texts:
I have a function that receives an array of numbers and operations

Ex: userEntry = [3,+,3,x,3] -> returns 12

It is a calculator that adheres to the proper order of operations, therefore multiply/divide behaves differently than addition/subtraction. I have one redundant line of code:

userEntry = calculatorOperations
    .calculationSequence(operationsMD[i], indexOfOperand, userEntry);

is similar to:

 userEntry = calculatorOperations
    .calculationSequence(userEntry[1], indexOfOperand, userEntry);

With different behavior between operations, is it possible to remove this redundant line or is it neccesary?

function operateOnEntry(userEntry) {
//this is where the calculations occur when hitting =
const operationsMD = ['x', '/'];
let indexOfOperand;
let operation;

while (userEntry.includes('x') || userEntry.includes('/')) {
    let i = 0;
    if (!userEntry.includes('x')) {
        i++;
    }
    indexOfOperand = userEntry.indexOf(operationsMD[i]);
    userEntry = calculatorOperations
        .calculationSequence(operationsMD[i], indexOfOperand, userEntry);
}
while (userEntry.includes('+') || userEntry.includes('-')) {
    indexOfOperand = 1;
    userEntry = calculatorOperations
        .calculationSequence(userEntry[1], indexOfOperand, userEntry);
}
return userEntry;
}

let calculatorOperations = {
'x': (arg1, arg2) => {
    return arg1 * arg2;
},
'/': (arg1, arg2) => {
    return arg1 / arg2;
},
'+': (arg1, arg2) => {
    return arg1 + arg2;
},
'-': (arg1, arg2) => {
    return arg1 - arg2;
},
returnIndexOfEntry: (index, userEntry) => {
    let arg1 = Number(userEntry[index - 1]);
    let arg2 = Number(userEntry[index + 1]);
    return [arg1, arg2];
},
returnSpliced: (index, newTotal, userEntry) => {
    userEntry.splice((index - 1), 3, newTotal);
    return userEntry;
},
calculationSequence: (operation, indexOfOperand, userEntry) => {

    let getArgs = calculatorOperations.returnIndexOfEntry(indexOfOperand, userEntry);
    let newTotalForEntry = calculatorOperations[operation](getArgs[0], getArgs[1]);
    let newUserEntry = calculatorOperations.returnSpliced(indexOfOperand, newTotalForEntry, userEntry);
    return newUserEntry;
}
};


texts: Performing an action which may return other actions to be performed, concurrently

texts:
I have a program which, at its core, involves repeatedly performing an action on some value, and based on that action also returning a list of new values to perform that action on. The pure version of my function is:

recurse :: (a -> [a]) -> a -> [a]
recurse f a = a : concatMap (recurse f) (f a)

Which can be used for things like tree traversals, such as:

data Tree a = Node [Tree a] | Leaf a

f (Node ls) = ls
f (Leaf x) = []

recurse f (Node [Leaf 10, Node [Leaf 20, Leaf 3], Leaf 12])
  == [Node [..], Leaf 10, Node [..], Leaf 20, Leaf 3, Leaf 12]

This function becomes more useful if you generalize it to an arbitrary monad:

recurseM :: Monad m => (a -> m [a]) -> a -> m [a]
recurseM f a = do
  xs <- f a
  rests <- mapM (recurseM f) xs
  return $ a : concat rests

But what I really want to do with it is make it asynchronous, because (a) I do not care about the order the results come in, and (b) I anticipate the actions themselves taking a while waiting on network operations. Here is my first pass at writing the async implementation (without results) of the above functions:

recurseAsync_ :: (a -> IO [a]) -> a -> IO ()
recurseAsync_ f a = do
  xs <- f a
  mapM_ (forkIO . recurseAsync_ f) xs

While this works, I'm unfamiliar enough with concurrency in general and in Haskell specifically to be sure that this will actually run all of the code I want in parallel. Also, I'm unsure of how to make this code return the results, but that isn't really the important part of the code.


texts: Is it possible to optimize the following boolean checks?

texts:
The following code works and it prints out only True as it is supposed to, for all the different cases:

class User(object):
  def __init__(self, key):
    self.key = key

def is_ok(user_dbs, self_db):
  count = len(user_dbs)
  if not self_db:
    return not count
  return (count != 1 or self_db.key == user_dbs[0].key) and count != 2

print 'Should print only True:'
print is_ok([],                 None)    is True   # found nothing and no self
print is_ok([],                 User(1)) is True   # found nothing and self
print is_ok([User(1)],          None)    is False  # found one and no self
print is_ok([User(1)],          User(1)) is True   # found one and it is you
print is_ok([User(2)],          User(1)) is False  # found one and it is not you
print is_ok([User(1), User(2)], None)    is False  # found two and no self
print is_ok([User(1), User(2)], User(1)) is False  # found two and one of them is you
print is_ok([User(2), User(1)], User(1)) is False  # found two and one of them is you
print is_ok([User(2), User(3)], User(1)) is False  # found two and none of them is you

The whole thing is to check if the username is available for a new user or when an existing user is updating his current username.

The user_dbs can have maximum 2 records as it has a limit in the actual query. So here is the breakdown:

If there are 2 records then we know for sure that the particular username is not available.
If there are 0 records then we know for sure that this username is available.
If there is 1 record then:

If it's a new user then the username is not available
If it's an existing user and that user is yourself then the username is available, otherwise not.

So can we optimize somehow the is_ok function above?

Try it live: repl.it/XHC


texts:
I want to:

use Watir::Browser methods without browser. instance prefix
expand abilities of Watir::Browser using own methods and overload existing
since I don't need more than one browser launched at the same time, using Module seems to have more sense than class

Here is my try:

require "watir"

module Session_FF
    class << self; attr_accessor :browser end
    def self.element *args
        es = browser.elements *args
        raise "found #{es.size} nodes instead of one" if es.size > 1
        es.first
    end
    def self.method_missing m, *args, &block
        browser.send m, *args, &block
    end
end
def session_FF &block
    Session_FF::browser = Watir::Browser.new :ff
    Session_FF.module_eval &block
ensure
    Session_FF::browser.quit if Session_FF::browser
end

session_FF do
    goto "http://localhost/"
    element(text:"test").click
    #
    #
    #
end

Seems to be more complex, than I expected. How do you think?


texts: Custom MediaController with full screen video image option

texts:
I have overridden setAnchorView() of MediaController class to display full screen option icon using below code.The code seems to be working fine in devices I tested but I have few doubts for which I need review-

The class assumes the anchor view is a FrameLayout to position full
screen imageview.
Should I use try catch inside setAnchorView?

public class FullScreenMediaController extends MediaController {

    private final Boolean isFullScreen;
    private final Listener listener;

    public FullScreenMediaController(Context context, Listener listener, Boolean isFullScreen) {
        super(context);
        this.listener = listener;
        this.isFullScreen = isFullScreen;
    }

    @Override
    public void setAnchorView(View view) {

        super.setAnchorView(view);

        //image view for full screen to be added to media controller
        ImageView fullScreen = new ImageView(super.getContext());

        FrameLayout.LayoutParams params =
                new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.RIGHT;
        params.rightMargin = 50;
        params.topMargin = 20;
        fullScreen.setPadding(10, 10, 10, 10);
        addView(fullScreen, params);

        if (isFullScreen) {
            fullScreen.setImageResource(R.drawable.ic_fullscreen_exit);
        } else {
            fullScreen.setImageResource(R.drawable.ic_fullscreen);
        }

        //add listener to image view to handle full screen and exit full screen events
        fullScreen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onFullScreenClick();
            }
        });
    }

    public interface Listener {
        void onFullScreenClick();
    }
}


texts:
I recently rewrote a piece of software to practice unit-testing. I decided to constrain myself and do dependency-free code, so I can do better and easier tests. I came to the following solution while writing the methods that deal with files :

/* foo.go */
package main

import (
    "io"
    "os"
)

type Foo struct {
    reader io.Reader
}

func NewFoo(filename string) (*Foo, error) {
    return newFoo(filename, os.Open)
}

type opener func(string) (*os.File, error)

func newFoo(filename string, open opener) (*Foo, error) {
    file, err := open(filename)
    if err != nil {
        return nil, err
    }

    return &Foo{
        reader: file,
    }, nil
}

And here is the test file that come along.

/* foo_test.go */
package main

import (
    "errors"
    "os"
    "testing"
)

func TestNewFooOpeningError(t *testing.T) {
    f, err := newFoo("", func(_ string) (*os.File, error) {
        return nil, errors.New("openning error")
    })

    if f != nil {
        t.Error(f, "!=", nil)
    }

    if err.Error() != "openning error" {
        t.Error(err.Error(), "!=", "openning error")
    }
}

func TestNewFooOK(t *testing.T) {
    f, err := newFoo("", func(_ string) (*os.File, error) {
        return nil, nil
    })

    if f == nil {
        t.Error(f, "==", nil)
    }

    if err != nil {
        t.Error(err.Error(), "!=", nil)
    }
}

It looks ok for me, but when there is more than one method to fake, I feel it a bit messy/ugly/unreadable/"pick your own adjective"

My questions are the following :

Is this pattern sane ?
If not, do you have any saner alternative ?
Do you recommend a particular testing good practice for this cases ?


texts:
I have made a small timestamp microservice that converts from UNIX time to a natural language date, and vice versa. Please let me know of anything I could do better.

Here is a demo. Here is the time.js file that holds the class that controls converting the time:

let debug = require('debug')('test');
let moment = require('moment');

class TimeConverter {
  constructor(){
    this.naturalDate = null;
    this.unixTime = null;
  }
  //check if string meets a specific format
  checkString(string){
    let format = /\w{3,9}?\s\d{1,2}?,\s\d{4}?/;
    let unixFormat = /^\d[0-9]{0,20}$/;
    let test = format.test(string);
    let test2 = unixFormat.test(string);

    if (test === true){
      this.natToUnix(string);

    } else if (test2 === true) {
      this.unixToNat(string);

    } else {
      this.naturalDate = null;
      this.unixTime = null;
    }

    return this.getResults();

  }
  //convert natural language date to unix
  natToUnix(string){
    //put into iso format for moment.js
    let newDate = new Date(string);
    //change into unix time
    let date = moment(newDate).unix();
    this.unixTime = date;
    this.naturalDate = string;

  }
  //change unix time to natural language date
  unixToNat(string){

    let date = moment.unix(string);
    let formatted = date.format("MMMM DD YYYY");

    this.unixTime = string;
    this.naturalDate = formatted;

  }

  getResults(){
    let results = {unix: this.unixTime, natural: this.naturalDate};
    debug(results);
    return results;
  }

}

let time = new TimeConverter();

module.exports = time;

Here is the server.js file that has some express code. It handles the routes in the application. It grabs the input from the request parameters, and serves the CSS / index.html files:

  let express = require('express');
  let debug = require('debug')('test');

  let app = express();

  let bodyParser = require('body-parser');
  let time = require('./time.js');
  let port = process.env.PORT || 8080;

  app.use(bodyParser.json());
  //serves static files
  app.use('/static', express.static('public'));
  app.use(bodyParser.urlencoded({ extended: true}));
  //route for inputting the time
  app.get(['/:time','/'], function(req,res){
    res.sendFile(__dirname + "/index.html");
    let data = req.params;

    if (data.time != undefined){
        res.json(time.checkString(data.time));
    }

  });

  //tell server to listen on a port
  app.listen(port, function(){
    debug("listening on " + port);
  });

Here is the repo.


texts: dispatch event listener problem after click

texts:
My code is working fine...
but I want to remove below those(1) lines of code from my example code(2) (JS Code). If I remove those code then a tag is not working. (a tag do not open link or href is not working).
Is it a good approach to done it by writing those code? ( if any problem will occur for ajax request for this ) ? & Is there any way to work a tag by removing those line of code ? Please help me.
Wanna Remove Those Code(1)
 if (e.target.nextElementSibling == null) {

    if (e.target.getAttribute('target') != null) {
        window.open(e.target.getAttribute('href'), e.target.getAttribute('target'));
    } else {
        window.location.href = e.target.getAttribute('href');
    }

Example Code(2)

const lists = document.querySelectorAll('.sidenav nav ul ul')
lists.forEach(function (el) {
    el.className = 'sub-menu';
    el.style.height = 0 + "px";
})
document.querySelectorAll(".sidenav nav  ul li a ").forEach(el => el.addEventListener('click', function (e) {

    e.preventDefault();
    e.stopPropagation();

    if (e.target.nextElementSibling == null) {

        if (e.target.getAttribute('target') != null) {
            window.open(e.target.getAttribute('href'), e.target.getAttribute('target'));
        } else {
            window.location.href = e.target.getAttribute('href');
        }
    }

    let el = e.target.parentElement.children[1];
    let ul = e.target.parentElement.closest('ul');
    if (ul) {
        ul.querySelectorAll('ul').forEach(function (item) {
            item.style.height = 0 + 'px';
        })
    }

    if (typeof el == 'undefined') return;

    if (parseInt(getComputedStyle(el).height) > 0) {
        el.style.height = 0 + "px";
    } else {
        el.style.height = el.scrollHeight + "px";
    }
    return false;

}));
*,*::after,*::before{
    box-sizing: border-box;
}
html,body{
    margin: 0;
    padding: 0;
}
nav{
    padding: 20px;
    height: 4rem;
    width: 250px;
}
nav ul {
     margin: 0;
     padding: 0;
     list-style: none;
     display: flex;
     flex-direction: column;
}
nav ul li {

      background: tomato;
     width: 100%;

}
nav ul li a{
    display: block;
    padding: 10px;
    text-decoration: none;

}
nav ul ul {
  margin-left: 20px;
  height: 0;
    transition: all .2s ease-in ;
}

nav ul ul li {
      width: 100%;
    background: aqua;
}

Home

Cat

Cat 1

Cat 1

about

about

about


texts: Is there a better/cleaner way to assign values based on the result of radio buttons?

texts:
I have 3 radio buttons all grouped inside a group box in a WinForms project. Currently, I am checking which button is checked and assigning values using the following if/else statement, similar to the below example

        if (rb1.Checked)
        {
            selectedButton = 1;
            selectedButtonText = rb1.Text;
        }
        else if (rb2.Checked)
        {
            selectedButton = 2;
            selectedButtonText = rb2.Text;
        }
        else
        {
            selectedButton = 3;
            selectedButtonText = rb3.Text;
        }

        Console.WriteLine(selectedButtonText);

This doesn't look very efficient or scalable. Is there a better way to do this?


texts:
My code takes 143.023 seconds for extracting nodes from a road network  of city like Göteborg in Sweden. Please check it out if I can optimize it.

# -*- coding: utf-8 -*-
import arcpy
from Class import loading_layer
import time

def node_extraction(network_input):
    time_start=time.time()
    nodes_list = []
    list_of_existing_nodes = []
    for feature in network_input:
        coordinates_list = list()

        feature_startX = feature["Shape"].firstPoint.X
        feature_startY = feature["Shape"].firstPoint.Y
        start_list =[]
        start_list.append(feature_startX)
        start_list.append(feature_startY)

        feature_endX = feature["Shape"].lastPoint.X
        feature_endY = feature["Shape"].lastPoint.Y
        end_list =[]
        end_list.append(feature_endX)
        end_list.append(feature_endY)

        if nodes_list.__len__() is not 0:
            if start_list in list_of_existing_nodes:
                point_index=list_of_existing_nodes.index(start_list)
                nodes_list[point_index][1].append(feature["FID"])
            else:
                nodes_list.append((feature["Shape"].firstPoint, [feature["FID"]]))
                list_of_existing_nodes.append(start_list)
            if end_list in list_of_existing_nodes:
                point_index=list_of_existing_nodes.index(end_list)
                nodes_list[point_index][1].append(feature["FID"])
            else:
                nodes_list.append((feature["Shape"].lastPoint, [feature["FID"]]))
                list_of_existing_nodes.append(end_list)
        else:
            nodes_list.append((feature["Shape"].firstPoint, [feature["FID"]]))
            nodes_list.append((feature["Shape"].lastPoint, [feature["FID"]]))
            list_of_existing_nodes.append(start_list)
            list_of_existing_nodes.append(end_list)
    time_end=time.time()
    print time_end-time_start

layer1 = loading_layer("D:/path/to/your/road/data.shp")
layer1.create_new_dict()
node_extraction(layer1.new_features_dict)

Load_layer class is as follows:

import arcpy
from arcpy.sa import *
from arcpy import env
import re
from _collections import defaultdict

class loading_layer(object):

    def __init__(self, input_data):
        self.features_dict = defaultdict(list)
        self.new_features_dict = []
        self.Address = input_data
        self.file_name = re.search(r'\w+.shp',input_data).group()
        self.coord_sys = arcpy.Describe(self.Address).spatialReference
        self.coord_sys_name = arcpy.Describe(self.Address).spatialReference.name

        self.fieldList = [f.name for f in arcpy.ListFields(self.Address)]
        if "matched_to".upper() not in self.fieldList:
            arcpy.AddField_management(input_data, u"Matched_to", "TEXT")
            self.fieldList.append(u"Matched_to")
            print "field is added"
        print str(self.fieldList)

    def iterate_features(self):
        feature_set = arcpy.SearchCursor(self.Address)
        for feature in feature_set:
            yield feature

    def create_new_dict(self):
        iterator = self.iterate_features()
        for item in iterator:
            feature = dict()
            for f in self.fieldList:
                feature[f] = item.getValue(f)
            self.new_features_dict.append(feature)


texts: LeetCode: Number of steps to reduce a number to zero C#

texts:
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/

  Given a non-negative integer num, return the number of steps to reduce
  it to zero. If the current number is even, you have to divide it by 2,
  otherwise, you have to subtract 1 from it.

  Example 1:

  Input: num = 14 Output: 6 Explanation:  Step 1) 14 is even; divide by
  2 and obtain 7.  Step 2) 7 is odd; subtract 1 and obtain 6. Step 3) 6
  is even; divide by 2 and obtain 3.  Step 4) 3 is odd; subtract 1 and
  obtain 2.  Step 5) 2 is even; divide by 2 and obtain 1.  Step 6) 1 is
  odd; subtract 1 and obtain 0. Example 2:

  Input: num = 8 Output: 4 Explanation:  Step 1) 8 is even; divide by 2
  and obtain 4.  Step 2) 4 is even; divide by 2 and obtain 2.  Step 3) 2
  is even; divide by 2 and obtain 1.  Step 4) 1 is odd; subtract 1 and
  obtain 0. Example 3:

  Input: num = 123 Output: 12

  Constraints:

  0 <= num <= 10^6

  public int NumberOfSteps (int num) {
        int count = 0;
         while( num !=0)
         {
             if(num %2==0)
             {
                 num = num/2;
                 count++;
             }
             else
             {
                 if( num == 1)
                 {
                     return count+1;
                 }
                 num = num-1;
                 count++;
             }
         }
         return count;
    }

Please review for performance


texts:
I need a rather simple file encryptor/decryptor in Python, after some research, I decided to use tye pynacl library reading the file in blocks, writing them back out, and then at the end using Blake2b to generate a signature for the file. Each file is encrypted with a unique key, which will be distributed along side the encrypted file, with the file key RSA encrypted using a pre-shared key pair, and that whole message signed with ECDSA to verify it came from me.

The encryption/decryption example code:

import base64
import struct
import nacl.secret
import nacl.utils
import nacl.hashlib
import nacl.hash

BUFFER_SIZE = 4 * (1024 * 1024)

def read_file_blocks(file, extra_bytes=0):
    while True:
        data = file.read(BUFFER_SIZE + extra_bytes)
        if not data:
            break
        yield data

def hmac_file(file, key):
    blake = nacl.hashlib.blake2b(key=key)
    with open(file, 'rb') as in_file:
        for block in read_file_blocks(in_file):
            blake.update(block)
    return blake.hexdigest()

def encrypt_archive(archive_name, encrypted_name):
    key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
    #Use 4 bytes less than the nonce size to make room for the block counter
    nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE - 4)
    block_num = 0

    box = nacl.secret.SecretBox(key)
    with open(archive_name, 'rb') as in_file, open(encrypted_name, 'wb') as out_file:
        for data in read_file_blocks(in_file):
            #Append the block counter to the nonce, so each block has a unique nonce
            block_nonce = nonce + struct.pack(">I", block_num)
            block = box.encrypt(data, block_nonce)
            out_file.write(block.ciphertext)
            block_num += 1

    hmac_key = nacl.hash.sha256(key + nonce, encoder=nacl.encoding.RawEncoder)
    output = {}
    output['key'] = base64.b64encode(key + nonce)
    output['signature'] = hmac_file(encrypted_name, hmac_key)
    return output

def decrypt_archive(encrypted_name, archive_name, key_info):
    key_bytes = base64.b64decode(key_info['key'])

    key = key_bytes[:nacl.secret.SecretBox.KEY_SIZE]
    nonce = key_bytes[nacl.secret.SecretBox.KEY_SIZE:]

    extra_bytes = nacl.secret.SecretBox.MACBYTES
    hmac_key = nacl.hash.sha256(key_bytes, encoder=nacl.encoding.RawEncoder)
    hmac = hmac_file(encrypted_name, hmac_key)
    if hmac != key_info['signature']:
        print('hmac mismatch')
        return

    block_num = 0
    box = nacl.secret.SecretBox(key)
    with open(encrypted_name, 'rb') as in_file, open(archive_name, 'wb') as out_file:
        # nacl adds a MAC to each block, when reading the file in, this needs to be taken into account
        for data in read_file_blocks(in_file, extra_bytes=extra_bytes):
            block_nonce = nonce + struct.pack(">I", block_num)
            block = box.decrypt(data, block_nonce)
            out_file.write(block)
            block_num += 1

key_info = encrypt_archive("C:\\temp\\test.csv", "C:\\temp\\test.enc")
print(key_info)
decrypt_archive("C:\\temp\\test.enc", "C:\\temp\\test.enc.csv", key_info)

Outside of general mistakes, the two things I'm doing I'm not entirely sure are sound:

To keep the block nonces unique, I create a slightly smaller random list of bytes for the nonce than required, then when encrypting the blocks I append the block number, as a four byte integer to the nonce.
When generating the blake2b hash, for a key, I hash the file key and nonce. This seems somewhat useless overall, since if they have the key and nonce, they could just replace the file. Although, I can't really think of a better alternative that doesn't have similar weaknesses. Should I just ditch that bit, since NaCl does per-block MACs anyhow? (which I found out only after I wrote the hmac code)


texts:
If we list all the natural numbers
  below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum
  of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below 1000.

Can someone give me suggestions on how to improve this solution? Also, please tell me whether or not my programming style is good.

#include<stdio.h>

int main()
{
    int a,b,c,d,sum3,sum5,sum15,total_sum;
    b=999/3;
    c=999/5;
    d=999/15;
    sum3=b*(3+999)/2;
    sum5=c*(5+995)/2;
    sum15=d*(15+990)/2;
    total_sum=sum3+sum5-sum15;
    printf("%d",total_sum);
    return 0;
}


texts:
I get back two dictionaries, I need to parse through them and put in an array two objects. I think I did a very poor job and I have a feeling there is a better way to make the code more compact and generic.

I think there is definitely a way to combine these two loops.  Please advise on any better way to accomplish this:

var cases = [[String: AnyObject]]()
var statuses = [[String: AnyObject]]()
var retVal = [AnyObject]()
var dict = [String: AnyObject]()

if jsonReturnValue != nil {
        let (hasError, errorMessage) =  ErrorHandler.hasError(jsonReturnValue)

        if hasError {
            //TODO Display a proper error to the user
            )
            print("Error Message: \(errorMessage)")
        } else {
            for value in jsonReturnValue {
                for (var i = 0; i < value.1.count; i++) {

                    if let dataDict = value.1 as? [String: AnyObject] {

                        let status = dataDict["status"]
                        let case = dataDict["case"]

                        // I think I can combine the two loops below but not sure how.

                        if let val = status as? [AnyObject] {
                            if let items = val[i] as? [String: AnyObject] {

                                for item in items {
                                    dict[item.0] = item.1
                                }
                            }
                            cases.append(dict)
                        }

                        dict.removeAll()

                        if let val = case as? [AnyObject] {
                            if let items = val[i] as? [String: AnyObject] {

                                for item in items {
                                    dict[item.0] = item.1
                                }
                            }
                            statuses.append(dict)
                        }
                    }
                }
            }
        }
    }
    retVal.removeAll()
    retVal.append(cases)
    retVal.append(statuses)
    return retVal
 }


texts:
String fileId = "CPP420.A2_2012072416244467745";
String reg1 = "CPP350";
String reg2 = "CPP420.A1";
String reg3 = "CPP420.A2";
String country = "";
if(fileId.startsWith(reg1)) {
    country = "CA";
} else if(fileId.startsWith(reg2)) {
    country = "US";
} else if(fileId.startsWith(reg3)) {
    country = "FR";
} else {
    System.out.println("Error invalid file");
}

OR

String country = fileId.startsWith(reg1) ? "CA" : "";
       country = fileId.startsWith(reg2) ? "US" : "";
       country = fileId.startsWith(reg3) ? "FR" : "";

if("".equals(country)) {
System.out.println("No country found");
}


texts:
Given a graph that has an Eulerian cycle, write a function which returns the cycle in tuple form.

I came up with following solution for this problem and am stuck trying to make it faster. Do you have any tips?

def eulerian_cycle_1(data):
    graph, edges_amount = get_graph(data) #graph:: {source:[destination]}
    cycle = deque()

    cur = 0
    while edges_amount > 0:
        choices = graph[cur]

        while choices:
            cycle.append(cur)
            edges_amount -= 1
            cur = choices.pop()
            choices = graph.get(cur, None)

        if edges_amount == 0:
            break

        rotate = 0
        for cur in cycle:
            if graph[cur]:
                break
            rotate += 1

        cycle.rotate(-rotate)

    cycle.rotate(-cycle.index(0))
    cycle.append(0)

    return tuple(cycle)

Pseudocode

EulerianCycle(\$G\$):

form a cycle \$c\$ by randomly walking in graph \$G\$ (don't visit the same edge twice!)
while there are unexplored edges in graph \$G\$

select a node \$n\$ in cycle \$c\$ with still unexplored edges
form cycle \$c′\$ by traversing cycle \$c\$ (starting at node \$n\$) and then randomly walking
\$c ← c′\$

return \$c\$


texts:
I am learning Django and to hone my skills in Django, I want to create some product. I am thinking of developing a web app which is about registering the startup companies. I come from a developing country and students/people in the tech field do not know about companies in our country, what they do, etc. I want to build a product for helping both companies and students. The benefit for companies is they will be expose in a market and is about just listing a company. I have created a model for this. Please help me in enhancing the idea through model or say database design.

Here is my model that I came up with:

from django.contrib.gis.db import models as gis_models
from django.contrib.postgres.fields import JSONField
from django.db import models

class Company(models.Model):
    name = models.CharField(max_length=150)
    speciality = models.CharField(max_length=150)
    number_of_employees = models.PositiveSmallIntegerField()
    website = models.URLField(blank=True, null=True)
    facebook = models.URLField(blank=True, null=True)
    twitter_handle = models.URLField(blank=True, null=True)
    address = models.CharField(max_length=140)
    city = models.CharField(max_length=80)
    district = models.CharField(max_length=50)
    image = models.ImageField(upload_to='image/company/')
    description = models.TextField(null=True, blank=True)
    location = gis_models.PointField(blank=True, null=True, geography=True)
    founded = models.DateField(blank=True, null=True)
    team_members = JSONField()
    timestamp = models.DateTimeField(auto_now=True)

    gis = gis_models.GeoManager()
    objects = models.Manager()

    class Meta:
        verbose_name = ("Company")
        verbose_name_plural = ("Companies")

class Product(models.Model):
    company_product = models.ForeignKey(Company, related_name="product", on_delete=models.CASCADE)
    name = models.CharField(max_length=150)
    description = models.TextField(null=True, blank=True)
    image = models.ImageField(upload_to='image/company/products/')

    class Meta:
        verbose_name = ("Product")
        verbose_name_plural = ("Products")

class Category(models.Model):
    company_category = models.ForeignKey(Company, related_name="category", on_delete=models.CASCADE)
    name = models.CharField(max_length=80)

    class Meta:
        verbose_name = ("Category")
        verbose_name_plural = ("Categories")

class Achievement(models.Model):
    company_achievement = models.ForeignKey(Company, related_name="achievement", on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)
    date = models.DateField(blank=True, null=True)

    class Meta:
        verbose_name = ("Achievement")
        verbose_name_plural = ("Achievements")


texts: Implementation of insertion sort in Ruby, code correctness

texts:
To implement an insertion sort that sorts an array with optional block to determine sorting order, how can I improve this code?  (Seeking best practices and code correctness)

def custom_insertion_sort(arr)
  for i in (1..arr.length-1)
    curr = arr[i]
    compare = i-1
    if block_given?
      sorted = yield arr, compare, curr
    else
      sorted = arr[compare] < curr
    end
   while compare >= 0 && sorted
      arr[compare+1] = arr[compare]
      compare -= 1
      if block_given?
        sorted = yield arr, compare, curr
      else
        sorted = arr[compare] < curr
      end
    end
    arr[compare+1] = curr
  end
  arr
end


texts: Cross-platform MySQL database backup using mysqldump

texts:
In a Laravel (PHP framework) project, we implemented a backup feature - backing up user-generated files and database tables. What we've searched so far, the best solution in backing up mysql database is to run the mysqldump command.

So we made the command:

<?php
$storage_path = 'path/to/backups';
$database = env('DB_DATABASE');
$user     = env('DB_USERNAME');
$pass     = env('DB_PASSWORD');
$host     = env('DB_HOST');
$dir_file = "{$storage_path}/{now()->timestamp}-database.sql.gzip";

$backup_cmd = "mysqldump --user={$user} --password={$pass} --host={$host} {$database} | gzip > {$dir_file}";

// Run the command and take the backup.
exec( $backup_cmd, $output, $mysql_backup_status );

In our MS Windows development environment, we got the errors:

dump($output);
array(
   "'mysqldump' is not recognized as an internal or external command",
   "operable program or batch file."
)

The issue is, path to mysqld or mysqldump is not in the system PATH. After adding the path to PATH and restarting the system the command works fine and take backup.

To make the solution cross-platform-friendly we took an initiative to check whether the command mysqldump is available or not, if not we'll gonna take the path to mysqldump.exe from the user.

And with user input we will change the command like below:

// Check default way - the PATH.
exec( 'mysqldump --version 2>&1', $output, $return_val );
if( $return_val != 0 ) {
   //mysqldump in undefined, so get the user defined path to it
   $path = "C:\laragon\bin\mysql\mysql-5.7.19-winx64\bin"; //get as user input
   $mysqldump = "{$path}\mysqldump.exe";
} else {
   $mysqldump = 'mysqldump';
}

$backup_cmd = "{$mysqldump} --user={$user} --password={$pass} --host={$host} {$database} | gzip > {$dir_file}";

// Run the command and take the backup.
exec( $backup_cmd, $output, $mysql_backup_status );

With this measure the code is working well in both the cases:

mysqldump is in PATH
mysqldump is in NOT in PATH

In our mini test unit it worked. But I wonder:

Is it a balanced way of doing this?
Means, the workaround we did (with all the UI/UX, unwanted trailing slash removal, using of exec() etc.) to simply check how we can run mysqldump without glitch - are we doing good? Or, simply making an easy thing critical?
Is the code cross-OS-friendly?

PS:
We're checking --version but finally executing backup command, because running backup command for testing executes it even with PHP system() function, and create a backup file, and we don't want that. We took exec() over system() as it's $output and $return_value seemed more reliable and silent than of system().

Edit

With the answer by baot a good point came into view, the unescaped user-provided data into exec() command. I's aware about it, but finally forgot it to escape.

I now escaped the user input with escapeshellarg() before using 'em into the exec():

// escape unwanted shell command
$mysqldump = escapeshellarg($mysqldump);

$backup_cmd = "{$mysqldump} --user={$user} --password={$pass} --host={$host} {$database} | gzip > {$dir_file}";


texts: Remove last odd number from number list in Python

texts:
The simplified question is:

  Given a list of numbers, write a Python script that will remove the last odd number from the list.

One of the challenges is if the last odd number appears multiple times, some approaches will remove the first occurrence of that number, rather than the last.

One solution that I have is to find the max index for the odd numbers and then pop that number from the list:

def remove_last_odd(numbers):
    count = 0
    for num in numbers:
        if num%2 == 1:
            max = count
        count += 1
    print max
    numbers.pop(max)

def run():
    numbers = [1, 7, 2, 34, 8, 7, 2, 5, 14, 22, 93, 48, 76, 15, 7]
    print numbers
    remove_last_odd(numbers)
    print numbers

run()

This works, but I feel like there's got to be a better way. I've thought about reversing the list, removing the first odd number and then re-reversing:

# use this instead of remove_last_odd function
def remove_backwards(numbers):
    rev_num = numbers[::-1]
    for num in rev_num:
        if num % 2 == 1:
            rev_num.remove(num)
            numbers = rev_num[::-1]
            return numbers

This also works, and feels cleaner, but if anyone can provide advice on preferred methods/more Pythonic approaches, it'd be much appreciated!


texts: Python function to count syllables in a word

texts:
I wrote this function to count the syllables in a word using Python to complete an exercise.

The exercise's text is:

  Return the number of syllables in the given word, according to this
  rule: Each contiguous sequence of one or more vowels is a syllable,
  with the following exception: a lone "e" at the end of a word is not
  considered a syllable unless the word has no other syllables. You
  should consider y a vowel.

I also disagree with the text because using the given instructions the syllable count for the word "example" are 2 and should be 3.

But, as discussed in the comments, the exercise text is the one that I implemented and would like to get suggestions and improvements for.

def count_syllables(word):
    word = word.lower()
    counter = 0
    is_previous_vowel = False
    for index, value in enumerate(word):
        if value in ["a", "e", "i", "o", "u", "y"]:
            if index == len(word) - 1:
                if value == "e":
                    if counter == 0:
                        counter += 1
                else:
                    counter += 1
            else:
                if is_previous_vowel == True:
                    counter += 1
                    is_previous_vowel = False
                    break
            is_previous_vowel = True
        else:
            if is_previous_vowel == True:
                counter += 1
            is_previous_vowel = False
    print ("In \"{}\" I count {} syllables".format(word, counter))

count_syllables("coding")


texts: C# and unity. Moving an object to a target and destroy target once we're close

texts:
This is my first ever c# script. I have played around a little and I think this is some proper c# code. Since it's my very first c# ever, I'm assuming there's a few mistakes, things that could be better, bad conventions and such. If you see any, please let me know so I can improve!
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Mover : MonoBehaviour
{
    [SerializeField] GameObject target;
    private GameObject player; // creating a variable for the player object

    void Update()
    {
        if (target != null) { // if the target is already destroyed, we don't have to do anything anymore
            player = this.gameObject; // the script is attached to the player

            // Here I expected I could get the NavMeshAgent component via something like player.NavMashAgant.
            // I do the same later for target.transform.
            // Is there a reason this component is not accessible via dot notation?
            GetComponent<NavMeshAgent>().destination = target.transform.position; // set the players destination as the targets potion. It starts moving automatically.
            if (AreClose(player, target)) {
                Destroy(target);
            }
        }
    }

    private static double Distance(GameObject a, GameObject b)
    {
        Vector3 aPos = a.transform.position;
        Vector3 bPos = b.transform.position;
        // A really long line.. What is the convention to make this more readable?
        return Math.Sqrt(Math.Pow(aPos.x - bPos.x, 2) + Math.Pow(aPos.y - bPos.y, 2) + Math.Pow(aPos.z - bPos.z, 2));

    }

    private static bool AreClose(GameObject a, GameObject b)
    {
        double result = Distance(a, b);
        if (result < 2.5) // random magic number for now
        {
            return true;
        } else
        {
            return false;
        }
    }
}


texts: Iterating through a range using lodash/AngularJS and saving data

texts:
The code below doesn't seem right to me. The scenario is:

User enters in a "quantity" into a form field.
If the user enters in 5, the loop below should iterate 5 times.
There should now be 5 new entries in the database with the container.product and container.status.

Any advice on making this cleaner?

var container = new Container($scope.batchFields);

container.product = $scope.item.originalObject._id;
container.status = 'active';

_.each($scope.batchFields, function(batch) {
  _.each(_.range(batch.batchesQuantity, 0, -1), function (val,i) {

    // This $save code smells a little with it
    // being inside the _.each.
    container.$save(function(response) {
      $notify.success('purchase.order.edit.created');
      if ($scope.$close) {
        $scope.$close();
      }
    }, function(errorResponse) {
      $scope.errors = errorResponse.data.message;
    });
  });

});


texts:
I had a question about filtering tree view and returning just first match.

I've tried to create list<treenode> and change the code.  Is it possible improve the below code for finding nodes and child nodes that match my criteria?

private List<TreeNode> FindNodeByValue(TreeNodeCollection nodes, string searchstring)
{

    // Loop through the tree node collection
    List<TreeNode> nodelist=new List<TreeNode>();

    foreach (TreeNode node in nodes)
    {
        // Does the value match the search string?
        if (node.Value.ToUpper().Contains (searchstring.ToUpper()))
            // Yes it does match - return it
            nodelist.Add(node);
        //  return nodelist;
        else
        {
            // No it does not match - search any child nodes of this node
            List<TreeNode> childNode = SearchChildNodes(node, searchstring);
            // If the childNode is not null it was a match
            if (childNode != null)
                // Return the matching node
                return childNode;
        }
    }
    // If the matching node is not found return null
    return null;
}

/// <summary>
/// This method searches a node's ChildNodes collection to find a matching value
/// with the incoming search string
/// It will iteratively call itself as it drills into each nodes child nodes (if present)
/// </summary>
/// <param name="parentNode">Parent node to search for a match</param>
/// <param name="searchstring">string to be matched with the Nodes Value property</param>
/// <returns>Treenode of the matching node if found.  If not found it will be null</returns>
private List<TreeNode> SearchChildNodes(TreeNode parentNode, string searchstring)
{
    List<TreeNode> nodelist2 = new List<TreeNode>();
    // Loop through the child nodes of the parentNode passed in
    foreach (TreeNode node in parentNode.ChildNodes)
    {
        // Does the value match the search string?
        if (node.Value.ToUpper().Contains(searchstring.ToUpper()))
            // Yes it does match - return it
            nodelist2.Add(node);
            //return nodelist2;
            //return node;
        else
        {
            // No it does not match - recursively search any child nodes of this node
            List<TreeNode> childNode = SearchChildNodes(node, searchstring);
            // If the childNode is not null it was a match
            if (childNode != null)
                childNode.Add(node);
                // Return the matching node
                return childNode;
        }
    }
    // If the matching node is not found OR if there were no child nodes then return null
    return null;
}

protected void Button1_Click(object sender, EventArgs e)
{
    TreeNode trnode=FindNodeByValue(TreeView1.Nodes, fieldFilterTxtBx.Text);
    if (trnode != null)
    {
        TreeView1.Nodes.Clear();
       // TreeNode newnode = new TreeNode("Detail Engineering");
       // TreeView1.Nodes.Add(newnode);
        TreeView1.Nodes.Add(trnode);
        TreeView1.ExpandAll();
    }
    else
    {
        Label1.Text = "No file found";
    }
}


texts:
I'm creating a script to turn into a commandlet we can reuse as part of our custom PowerShell module. This works, but is very slow. I don't suspect it is anything to do with my code. I have to individually load each site to retrieve the title even though this property is visible off the $site object, it is always empty/null.

Anything else I can do to improve the efficiency?

$path = "C:\Users\$env:USERNAME\Desktop\SPOExport.csv"
$csv = "Title,URL,Sharing Capability,Storage Quota (MB),Template`r`n"
$sites = Get-SPOSite -Limit all | Select Url,SharingCapability,StorageQuota,Template
foreach($site in $sites){
    try{
        $context = New-Object Microsoft.SharePoint.Client.ClientContext($site.Url)
        $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.UserName, $credential.Password)
        $web = $context.Web
        $context.Load($web)
        $context.ExecuteQuery()
        $title = $web.Title
    }
    catch {
        $title = "Error fetching title"
    }
    finally{
        $csv +=$title + "," + $site.Url + "," + $site.SharingCapability + "," + $site.StorageQuota + "," + $site.Template
    }
}
$fso = new-object -comobject scripting.filesystemobject
$file = $fso.CreateTextFile($path,$true)
$file.write($csv)
$file.close()

Note that I have not fully adapted it into a commandlet yet, which will have all the commenting and help text available, I'm more worried about the code and the time it takes for this operation presently.