texts:
When you jump to a search result in Vim, your cursor can end up near the bottom (or top) of the window, making it difficult to see the surrounding context.

Some people like to automatically center the cursor after such a jump, but I find that to be too drastic, since it means even small jumps cause scrolling.

There's also a 'scrolloff' option you can set, which keeps the cursor some fixed number of lines away from the top/bottom of the window at all times, except when near the start or end of the file.

I like to keep 'scrolloff' set to a low value most of the time. It's only after certain navigation jumps that I want to apply a larger offset. So I wrote a vimscript function that applies a given offset.

The first implimentation increased 'scrolloff', redrew the screen, then returned 'scrolloff' to its original value, but this caused an annoying flicker each time the screen was redrawn.

I've reimplemented it to calculate and apply the necessary scroll operations. The interesting part was tuning the calculations so that edge-cases were considered.

The desired offset decreases gradually as you approach the start / end of the file. The offset is also scaled down as necessary if the window is too small to accomodate the given value.

func! Nudge(o) abort
  let offset = min([a:o, winheight(0)/2])

  let bot_want = min([offset, line('$') - line('.')])
  let bot_have = winheight(0) - winline()
  if bot_want > bot_have
    call s:nudge_bot(bot_want - bot_have)
  else
    let top_want = min([offset, line('.') - 1])
    let top_have = winline() - 1
    if top_want > top_have
      call s:nudge_top(top_want - top_have)
    endif
  endif
endf

func! s:nudge_bot(count)
  exec 'normal!' a:count . "\<C-E>"
endf

func! s:nudge_top(count)
  exec 'normal!' a:count . "\<C-Y>"
endf

Vimscript is never pretty, but it was fun to work through this one.


texts: Pivot some rows to new columns in DataFrame

texts:
I'm after a pythonic and pandemic (from pandas, pun not intended =) way to pivot some rows in a dataframe into new columns.

My data has this format:

           dof  foo  bar  qux
idxA idxB
100  101     1   10   30   50
     101     2   11   31   51
     101     3   12   32   52
     102     1   13   33   53
     102     2   14   34   54
     102     3   15   35   55
200  101     1   16   36   56
     101     2   17   37   57
     101     3   18   38   58
     102     1   19   39   59
     102     2   20   40   60
     102     3   21   41   61

The variables foo, bar and qux actually have 3 dimensional coordinates, which I would like to call foo1, foo2, foo3, bar1, ..., qux3. These are identified by the column dof. Each row represents one axis in 3D, dof == 1 is the x axis, dof == 2 the y axis and dof == 3 is the z axis.

So, here is the final dataframe I want:

           foo1  bar1  qux1  foo2  bar2  qux2  foo3  bar3  qux3
idxA idxB
100  101     10    30    50    11    31    51    12    32    52
     102     13    33    53    14    34    54    15    35    55
200  101     16    36    56    17    37    57    18    38    58
     102     19    39    59    20    40    60    21    41    61

Here is what I have done.

import pandas as pd

data = [[100, 101, 1, 10, 30, 50],
        [100, 101, 2, 11, 31, 51],
        [100, 101, 3, 12, 32, 52],
        [100, 102, 1, 13, 33, 53],
        [100, 102, 2, 14, 34, 54],
        [100, 102, 3, 15, 35, 55],
        [200, 101, 1, 16, 36, 56],
        [200, 101, 2, 17, 37, 57],
        [200, 101, 3, 18, 38, 58],
        [200, 102, 1, 19, 39, 59],
        [200, 102, 2, 20, 40, 60],
        [200, 102, 3, 21, 41, 61],
        ]

df = pd.DataFrame(data=data, columns=['idxA', 'idxB', 'dof', 'foo', 'bar', 'qux'])
df.set_index(['idxA', 'idxB'], inplace=True)

#
# Here is where the magic happens - and I'm not too happy about this implementation
#

# Create an ampty dataframe with the same indexes
df2 = df[df.dof == 1].reset_index()[['idxA', 'idxB']]
df2.set_index(['idxA', 'idxB'], inplace=True)

# Loop through each DOF and add columns for `bar`, `foo` and `qux` manually.
for pivot in [1, 2, 3]:
    df2.loc[:, 'foo%d' % pivot] = df[df.dof == pivot]['foo']
    df2.loc[:, 'bar%d' % pivot] = df[df.dof == pivot]['bar']
    df2.loc[:, 'qux%d' % pivot] = df[df.dof == pivot]['qux']

However I'm not too happy with these .loc calls and incremental column additions inside a loop. I thought that pandas being awesome as it is would have a neater way of doing that.


texts:
I have a HTTP client factory that creates a separate HTTP proxy instance for each of my services - which are in the cloud. The factory creates each instance on the basis of an interface which the service implements. All of the proxies inherit from a base class called DalServiceBaseClient which you will see in my code. I don't quite like the way the factory resolves the type to be returned based on the interface.

Here's a simplified version of my code:

Here's how I call my factory to create one of the possible proxies:

var gatewayFactory = new GatewayFactory();
var masterClient = gatewayFactory.CreateMasterClient("someBaseAddress");

Here that same method in GatewayFactory:

public IMasterService CreateMasterClient(string baseAddress)
{
    return (MasterServiceClient)CreateHttpClient<IMasterService>($"{baseAddress}api/master/");
}

And here's the private create method in GatewayFactory where all of the magic happens:

private DalServiceBaseClient CreateHttpClient<T>(string baseAddress)
{
    var httpClient = new HttpClient
    {
        BaseAddress = new Uri(baseAddress)
    };

    if (typeof(T) == typeof(IMasterService))
    {
        return new MasterServiceClient(httpClient);
    }
    if (typeof(T) == typeof(ISlaveService))
    {
        return new SlaveServiceClient(httpClient);
    }
    if (typeof(T) == typeof(IRoleService))
    {
        return new RoleServiceClient(httpClient);
    }

    // A lot more ifs..

    throw new ArgumentException("No type exists for the provided interface");
}

Since there are a lot of different proxies my method ends up having a lot of ifs and I haven't been able to find a more elegant way of doing this.


texts: How clean is this mustache template for a listing page?

texts:
This was our old site that I am redesigning.

Someone else hardcoded with inline CSS and javascript in tables.

I wanted to make it dynamic, so I added Mustache and made this template:

{{#labs}}

{{{lab}}}

      {{#stadt}}
        {{{stadt}}}

      {{/stadt}}

      {{#telefon}}
        {{{telefon}}}

      {{/telefon}}

      {{#webseite}}

          {{{webseite}}}

      {{/webseite}}

{{/labs}}

Here is some of the JSON file:

{ "labs" : [
{
    "lab":"Ri&szlig;mann Zahntechnik GmbH",
    "stadt":"D-06917 Jessen",
    "telefon":"+49 (0) 3537 21 38 61",
    "webseite":"www.rissmann-zahntechnik.de"
  },

Would it make a big enough difference to not have the full word as the name?  So maybe like "l" instead of "lab" and "w" instead of "webseite", etc.

Here is the result of the listings:

The even spacing between the icon and the values was achieved by this CSS rule:

.lab i { width: 27px; }

Also, does it make sense to have it in a single
 tag, or should I consider placing each value in its own
?


texts:
I need a NumPy matrix with comparisons among all elements in a sequence:

from numpy import matrix
seq = [0, 1, 2, 3]
matrix([[cmp(a, b) for a in seq] for b in seq])

I'd like to know if there is a better way to do this.


texts:
The problem

  For any given array, find a corresponding zig-zag array such the each
  element (a,b,c,d,e...) follows the rule:

a < b > c < d > e < f

In other words, every other element is greater than both of its neighbouring elements and the remaining elements are smaller than their neighbours.

For example, for the list:

[4, 3, 7, 8, 6, 2, 1]

the output is:

[1 8 2 7 3 6 4]

My solution

array = [4, 3, 7, 8, 6, 2, 1]
array.sort()

while len(array) > 1:
    print(array[0], array[-1], sep = " ", end= " ")
    array.pop(0)
    if array: array.pop(-1)
print(array[0])


texts:
I have to recursively solve the following problem, using a brute force approach:

Suppose two people, A and B, have an even number of ordered boxes, each with a given value. For example, boxes = {5, 3, 7, 10}. They need to split the boxes between them, in this way: person A chooses either the first or the last box in the set, then person B does the same, and so on until there are no boxes left.

Person A wants to know, what's the maximum value he can get, in total, bearing in mind that at each turn person B can make two choices as well. In other words, the problem is to come up with an algorithm that simulates all the choices of both people, considering they're all aiming to have the maximum value in the long term.

So, for now I have this:

public static int maxValue(ArrayList <Integer> boxes, int choice, int person){
    int value;

    //Stop condition - if there are no more boxes, return 0
    if (boxes.isEmpty())
        return 0;

    if (choice == 0) //Person chose the first box in the sequence
        value = boxes.remove(0);
    else //Person chose the last box in the sequence
        value = boxes.remove(boxes.size() - 1);

    //Person A makes a choice, checking which one works best in the long run
    if (person == 1)
        return (value + max(maxValue(boxes, 0, 2), maxValue(boxes, 1, 2)));

    //Person B makes a choice, checking which one works best in the long run
    else
        return (value + max(maxValue(boxes, 0, 1), maxValue(boxes, 1, 1)));
}

For an input of boxes = {5, 3, 7, 10}, the code is supposed to produce 15, yet the one I wrote above gives me 25. After placing some debugging prints, I saw it goes:

Person A chooses '10'
Person B chooses '7'
Person A chooses '3'
Person B chooses '5'

And then just adds all the values. I'm figuring it's because of the way the function is called by person A with reference to person B (in max(maxValue(boxes, 0, 2), maxValue(boxes, 1, 2))), and vice-versa, and also because of that stop condition (if I change it slightly the value returned is different).


texts: Fetch network interfaces configuration for hosts from list

texts:
Can you please review a little my simple Python code? I wrote this script to get list of hosts from text file and then iterate over these and get IP configured on active network interfaces  - and finally add them to JSON dictionary file.

import sys
import json
import wmi
import logging
import os

HOSTS_FILE = sys.argv[1]
JSON_FILE = 'ip_list_PRD.json'

def addhostelement(host_enc, json_dict):
    host_name = str(host_enc).rstrip('\n')
    logger.info("Trying to get IP configuration of host " + host_name)
    hosts_dict = json_dict
    hosts_dict['hosts'][host_name] = []
    wmi_session = wmi.WMI(host_name)
    query_res = wmi_session.query("select IPAddress from Win32_NetworkAdapterConfiguration where IPEnabled='True'")
    logger.info("Found " + str(len(query_res)) + " IP addresses")
    for instance_ip in query_res:
        ip_address = instance_ip.wmi_property("IPAddress")
        ip_value = ip_address.value[0]
        logger.info("Adding IP address " + ip_value + " to " + host_name + " node")
        json_dict['hosts'][host_name].append(ip_value)

    with open(JSON_FILE, 'w') as json_output_file:
        json.dump(json_dict, json_output_file)

def formatjsonfile():
    obj = None
    with open(JSON_FILE) as jsonfileformat:
        jsondata = json.load(jsonfileformat)
        outfile = open(JSON_FILE, 'w')
        outfile.write(json.dumps(jsondata,indent=4,separators=(',', ':'),ensure_ascii=True))
        outfile.close

if __name__ == "__main__":
logging.basicConfig(level=logging.getLevelName(os.environ.get("LOG_LEVEL", "INFO")),
                    format="[%(levelname)s] %(funcName)20s() %(message)s")
logger = logging.getLogger(__name__)

    with open(HOSTS_FILE, 'r') as hosts_file_read:
        host_lines = hosts_file_read.readlines()
    with open(JSON_FILE) as json_data:
        json_dict = json.load(json_data)
    for host_enc in host_lines:
        if host_enc not in json_dict:
            addhostelement(host_enc, json_dict)

    formatjsonfile()


texts: PDO sign up function inserting data into multiple tables

texts:
This is a sign up function called on form submission. It firstly inserts key user data into the users table. If successful, secondary data is then inputted into respective tables (such as user job titles and user experience). I'm not really sure whether stacking queries 2-5 is the best way to do it, so I would be interested in knowing how this function could be improved and/or made more secure.

    public function registerFreelancer($firstname, $lastname, $email, $password, $location, $portfolio, $jobtitle, $priceperhour, $experience, $bio, $userType){

        global $bcrypt;
        global $mail;

        $time       = time();
        $ip         = $_SERVER['REMOTE_ADDR'];
        $email_code = sha1($email + microtime());
        $password   = $bcrypt->genHash($password);// generating a hash using the $bcrypt object

        $query  = $this->db->prepare("INSERT INTO " . DB_NAME . ".users
            (firstname, lastname, email, email_code, password, time_joined, location, portfolio, bio, ip)
            VALUES
            (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $query->bindValue(1, $firstname);
        $query->bindValue(2, $lastname);
        $query->bindValue(3, $email);
        $query->bindValue(4, $email_code);
        $query->bindValue(5, $password);
        $query->bindValue(6, $time);
        $query->bindValue(7, $location);
        $query->bindValue(8, $portfolio);
        $query->bindValue(9, $bio);
        $query->bindValue(10, $ip);

        try{
            $query->execute();

            // Send email code usually here

            $rows = $query->rowCount();

            if($rows > 0){

                $last_user_id =  $this->db->lastInsertId('user_id');

                $query_2 = $this->db->prepare("INSERT INTO " . DB_NAME . ".freelancers (freelancer_id, jobtitle, priceperhour) VALUE (?,?,?)");

                $query_2->bindValue(1, $last_user_id);
                $query_2->bindValue(2, $jobtitle);
                $query_2->bindValue(3, $priceperhour);

                $query_2->execute();

                $query_3 = $this->db->prepare("INSERT INTO " . DB_NAME . ".user_types (user_type_id, user_type) VALUE (?,?)");

                $query_3->bindValue(1, $last_user_id);
                $query_3->bindValue(2, $userType);

                $query_3->execute();

                $query_4 = $this->db->prepare("INSERT INTO " . DB_NAME . ".user_experience (experience_id, experience) VALUE (?,?)");

                $query_4->bindValue(1, $last_user_id);
                $query_4->bindValue(2, $experience);

                $query_4->execute();

                if($userType == 'designer') {
                    $query_5 = $this->db->prepare("INSERT INTO " . DB_NAME . ".designer_titles (job_title_id, job_title) VALUE (?,?)");

                    $query_5->bindValue(1, $last_user_id);
                    $query_5->bindValue(2, $jobtitle);

                    $query_5->execute();

                } else if ($userType == 'developer') {
                    $query_5 = $this->db->prepare("INSERT INTO " . DB_NAME . ".developer_titles (job_title_id, job_title) VALUE (?,?)");

                    $query_5->bindValue(1, $last_user_id);
                    $query_5->bindValue(2, $jobtitle);

                    $query_5->execute();
                }

                return true;
            }

        }catch(PDOException $e){
            die($e->getMessage());
        }
    }


texts: React: Live DOM element position/dimension resolver hook optimization

texts:
I implemented the following react hook to get live updates of an element's position and dimensions in the DOM:

/**
 * @author devskope
 */

import { useCallback, useRef, useState } from 'react';
import { throttle } from '../limiters';

const useElementDimensions = () => {
  const [dimensions, setDimensions] = useState({});
  const ref = useRef();

  const doUpdate = ({ current: node }) => {
    if (node) {
      const rect = node.getBoundingClientRect();
      const offsetY = Math.round(rect.top + window.scrollY);  // add absolute position to top of viewport
      setDimensions({ offsetY, ...rect });
    }
  };

  const updateDimensions = useCallback((ref, opts = {}) => {
    const { delay = 400 } = opts;
    return throttle(() => doUpdate(ref), delay);  // regulate update rate
  }, []);

  return { dimensions, ref, updateDimensions };
};

The hook can be used in a component to obtain the position to the top of an element as follows:

import useElementDimensions from '../../lib/hooks/useElementDimensions';

const TopCategories = (props) => {
  const { id,} = props;

  const { dimensions, ref, updateDimensions } = useElementDimensions();

  const offset = dimensions?.offsetY;

  /**
   * Update  dimensions on page scroll, can be hooked to any event or manually triggered
   *
   * How to I trigger this when images load to offset elements or when new elements enter the dom??????
   */
  useEffect(() => {
    window.addEventListener('scroll', updateDimensions(ref, { delay: 700 }));
  }, []);

  useEffect(() => {
    console.log(offset);
  }, [offset]);

  return (
    <div id={id} ref={ref}>
     target element is ${offset} px from the top
    </div>
  );
};

How can this implementation be made more efficient/performant?

Thanks.


texts:
Please suggest improvements and a possible better way of doing it in place.

public static void main(String[] args) {
    int[][] mat = { { 1, 2 }, { 3, 4 } };
    rotate(mat);
}

public static void rotate(int[][] matrix) {
    if (matrix == null) {
        return;
    }
    int n = matrix.length - 1;
    int temp = 0;
    int[][] mat2 = new int[n + 1][n + 1];
    mat2 = matrix;
    for (int row = 0; row <= n; row++) {
        for (int col = 0; col <= n; col++) {
            // mat2[n-col][row] = matrix[row][col];
            temp = matrix[col][n - row];
            matrix[col][n - row] = matrix[row][col];
            matrix[row][col] = temp;
        }
    }
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            matrix[i][j] = mat2[i][j];
        }
    }
}


texts: Registration and Login System for Application

texts:
I am developing a social platform and currently just completed the registration and login PHP pages. The application is an android application
that authenticates against a MySQL DB. I am seeking critiques on how "safe" and correct my PHP pages are that I am authenticating against, IE: Am I storing and authenticating passwords in a safe manner. This is my first try so I am up for changes.

Registration Page

<?php
define('HOST', 'localhost');
define('USER', 'admin');
define('PASS', 'password');
define('DB', 'database');
$con = mysqli_connect(HOST, USER, PASS, DB);

$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$age = $_POST["age"];
$id = $_POST["id"];
$hash = password_hash($password, PASSWORD_DEFAULT);

$sql = "INSERT INTO `table` (Username,Password,Email) values
       ('$username','$hash','$email')";

if (mysqli_query($con, $sql)) {
$response["success"] = 1;
$response["message"] = "Success";
die(json_encode($response));
} else {

$response["success"] = 0;
$response["message"] = "Invalid ";
die(json_encode($response));
}
mysql_close();
php
?>

Login Auth

<?php
define('HOST', 'localhost');
define('USER', 'admin');
define('PASS', 'password');
define('DB', 'database');
mysql_connect(HOST, USER, PASS);
mysql_select_db(DB)or die;
$username = $_POST["username"];
$password = $_POST["password"];

if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
    // Create some data that will be the JSON response
    $response["success"] = 0;
    $response["message"] = "One or both of the fields are empty .";
    die(json_encode($response));
}
$query = "SELECT * FROM `table` WHERE `Username` = '$username' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$hash = $row["Password"];
if (password_verify($password, $hash)) {
    $response["success"] = 1;
    $response["message"] = "You have been sucessfully login";
    die(json_encode($response));
} else {

    $response["success"] = 0;
    $response["message"] = "invalid username or password ";
    die(json_encode($response));
}
} else {

$response["success"] = 0;
$response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
mysql_close();

Any input or information to make this better/more functional is greatly appreciated.


texts: Calling Service and Initiate under ngOnOnit (not in Constructor) Hook in Angular4

texts:
I am using WP REST API V2 with Angular v5.

I am display all items available from API for /do route inside WeDoComponent component.

Now I want to use same component - <app-wedo> inside another component with restricted numbers of items.

To do so, I have added one attribute loadOnly inside HTML template of HomeComponent and I am instantiate service under constructor and using this reference with ngOnInit life-cycle hook.

HTML Template with loadOnly attribute

<app-we-do loadOnly="3"></app-we-do>

I just wanted to verify if the approach below is right considering best practices in Angular or would that be affecting performance in negative way or somehow bad for a project... Any input would be appreciated.

Thanks in advance :)

WeDoComponentCode

import { Component, OnInit, Input } from '@angular/core';
import { ApiService } from '../services/api.service';

@Component({
  selector: 'app-we-do',
  templateUrl: './we-do.component.html',
  styleUrls: ['./we-do.component.scss']
});

export class WeDoComponent implements OnInit {
  weDo;
  loading: boolean = true;
  @Input('loadOnly') loadOnly;

  constructor(private musicService: ApiService) {}

  ngOnInit() {
    let _self = this;
    if (_self.loadOnly) {
      _self.musicService.getAPIData('services?embed&per_page=' + _self.loadOnly).subscribe(res => this.weDo = res);
    } else {
      _self.musicService.getAPIData('services').subscribe(res => this.weDo = res);
    }
    console.log('_self: ', _self);
  }

}


texts: CSS and HTML5 for this fixed header on scroll

texts:
When I had to create a fixed header on scroll, I found a few examples on Stack Overflow but they were terrible in the sense that they relied on a fixed page height. Have a look at what I created which does not rely on a wrapper around the header and the content.

Default

On Scroll

Demo on CodePen.

HTML

Art in Finland

Archive

Events

Contact

CSS

header {
  height:360px;
  z-index:10;
}
.header-banner {
  background-color: #333;
  background-image: url('http://37.media.tumblr.com/8b4969985e84b2aa1ac8d3449475f1af/tumblr_n3iftvUesn1snvqtdo1_1280.jpg');
  background-position: center -300px;
  background-repeat: no-repeat;
  background-size: cover;
  width: 100%;
  height: 300px;
}

header .logo {
  background-color: transparent;
  background-image: url('http://www.futhead.com/static//img/14/clubs/1887.png');
  background-position: center top;
  background-repeat: no-repeat;
  position: absolute;
  top: 72px;
  height: 256px;
  width: 256px;
}
header h1 {
  position: absolute;
  top: 72px;
  left: 240px;
  color: #fff;
}

.fixed-header {
  position: fixed;
  top:0; left:0;
  width: 100%;
}

nav {
  width:100%;
  height:60px;
  background: #292f36;
  postion:fixed;
  z-index:10;
}

nav ul {
  list-style-type: none;
  margin: 0 auto;
  padding-left:0;
  text-align:right;
  width: 960px;
}
nav ul li {
  display: inline-block;
  line-height: 60px;
  margin-left: 10px;
}
nav ul li a {
  text-decoration: none;
  color: #a9abae;
}

/* demo */
.content{ width: 960px; max-width: 100%; margin:0 auto; padding-top: 60px; }
article { width: 720px; float: left; }
article p:first-of-type { margin-top: 0; }
aside { width: 120px; float: right; }
aside img { max-width: 100%; }
body {
  color: #292f36;
  font-family: helvetica;
  line-height: 1.6;
}

jQuery

$(window).scroll(function(){
    if ($(window).scrollTop() >= 300) {
       $('nav').addClass('fixed-header');
    }
    else {
       $('nav').removeClass('fixed-header');
    }
});


texts: Using BufferedReader to read lines of a file into a list

texts:
To help improve my proficiency with Java, I would like to know how should I close these FileReaders as I have come across multiple answers, and what could I do better with this block of code?

/**
 * Returns a Vector<String> object that that can be parsed into classes.
 * The file arugment must specify a realative or aboustle adress to the file.
 * @param file to read
 * @return
 */
public static ArrayList<String> read(File file) {

    ArrayList<String> data = new ArrayList<String>();

    String lineRead;

    try {

        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        while ( (lineRead = br.readLine()) != null ) {
                data.add(lineRead);
        }

        br.close();
        fr.close();

    } catch(IOException e) {
        e.printStackTrace();
    }

    return data;
}


texts:
A little while ago, I had to write a little C# application to recover my HDD data (full context on this question)

To answer my problem I developed a console application which job was to recursively copy the entire folder tree of my HDD.

The code can be seen below :

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

namespace CopyCat
{
    class Program
    {
        private static long _fileCount = 0;
        private static long _byteCount = 0;
        private static long _byteProgress = 0;
        private static ProgressBar _progressCount = new ProgressBar();

        static void Main(string[] args)
        {
            Directory.Exists(args[0]);
            Directory.Exists(args[1]);

            FileDiscovery(args[0]);
            FileCopy(args[0], args[1]);

            Console.ReadLine();
        }

        static void FileCopy(String source, String dest)
        {
            try
            {
                foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.TopDirectoryOnly))
                {
                    try
                    {
                        if (file == null) continue;

                        var oFile = File.OpenRead(file);
                        var dFile = File.Open(Path.Combine(dest, Path.GetFileName(file)), FileMode.Create,
                            FileAccess.ReadWrite);
                        oFile.CopyTo(dFile, 104857600);

                        oFile.Close();

                        dFile.Flush();
                        dFile.Close();

                        _byteProgress += new FileInfo(file).Length;

                        _progressCount.Report((double)_byteProgress / (double)_byteCount);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("[COPY][ERROR] : Couldn't copy file  : {0} => {1}", file, e.Message);
                    }
                }
                foreach (var directory in Directory.EnumerateDirectories(source, "*", SearchOption.TopDirectoryOnly))
                {
                    if (directory == @"G:\$RECYCLE.BIN") continue;
                    var dir = Path.GetFileName(directory);
                    if (!Directory.Exists(Path.Combine(dest, dir)))
                    {
                        Directory.CreateDirectory(Path.Combine(dest, dir));
                    }

                    FileCopy(directory, Path.Combine(dest, dir));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("[COPY][WARNING] : Couldn't open directory  : {0}", source);
            }
        }

        static void FileDiscovery(String dir)
        {
            try
            {
                foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.TopDirectoryOnly))
                {
                    _fileCount++;
                    _byteCount += new FileInfo(file).Length;
                }
                foreach (var directory in Directory.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly))
                {
                    FileDiscovery(directory);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("[DISCOVERY][WARNING] : Couldn't open directory : {0}", dir);
            }
        }

        static String HumanReadableByteCount(long bytes, Boolean si = false, int precision = 2)
        {
            int unit = si ? 1000 : 1024;
            if (bytes < unit) return bytes + " B";
            int exp = (int)(Math.Log(bytes) / Math.Log(unit));
            String pre = (si ? "kMGTPE" : "KMGTPE")[(exp - 1)] + (si ? "" : "i");
            return String.Format("{0} {1}{2}", Math.Round(bytes / Math.Pow(unit, exp), precision), pre, si ? "b" : "B");
        }
    }
}

(Using a custom ProgressBar)

I wanted to know specifically how I could improve the copying speed.


texts:
I keep looking at this trying to figure if there's a better way.  All three functions work, but I wanted to get some insights and ideas from others.

IsLoadDay determines if the date parameter is a "Load Day".  Load Days are Tuesday through Saturday, but we skip holidays and designated No Load Days.  There are two existing tables of Holidays (HOLDY_WA_STATE) and No Load Days (afrs_daily_load_no_load_date).

GetNextLoadDay and GetPreviousLoadDay are intended to be used.  They each use IsLoadDay to determine if the date parameter is a Load Day, and then move forward or backward through time until a Load Day is found.

GetNextLoadDay will check the date parameter and determine if it is a Load Day whereas GetPreviousLoadDay will first go one day back and then start checking if the date is a Load Day.

IsLoadDay Function

CREATE FUNCTION [dbo].[IsLoadDay](@Dt DATE)
RETURNS BIT
AS
BEGIN
DECLARE @IsLoadDay BIT = 1
IF DATENAME(DW, @Dt) IN ('SUNDAY', 'MONDAY')
    BEGIN
        SET @IsLoadDay = 0
    END
ELSE
IF EXISTS(SELECT 1 FROM [DBMGMT].[dbo].[afrs_daily_load_no_load_date] WHERE [load_date] = @Dt AND [load_ind] = 'N')
    BEGIN
        SET @IsLoadDay = 0
    END
ELSE
IF EXISTS(SELECT 1 FROM [master].[dbo].[HOLDY_WA_STATE] WHERE [HOLDY_DATE] = @Dt)
    BEGIN
        SET @IsLoadDay = 0
    END
RETURN @IsLoadDay
END
GO

GetNextLoadDay Function

CREATE FUNCTION [dbo].[GetNextLoadDay](@Dt DATE)
RETURNS DATE
AS
BEGIN
DECLARE @NxtDt DATE
SET @NxtDt = @Dt
WHILE [dbo].[IsLoadDay](@NxtDt) != 1 BEGIN
    SET @NxtDt = DATEADD(D, 1, @NxtDt)
END
RETURN @NxtDt
END
GO

GetPreviousLoadDay Function

CREATE FUNCTION [dbo].[GetPreviousLoadDay](@Dt DATETIME)
RETURNS DATETIME
AS
BEGIN
DECLARE @PrvDt DATE
SET @PrvDt = DATEADD(D, -1, @Dt)
WHILE [dbo].[IsLoadDay](@PrvDt) != 1 BEGIN
    SET @PrvDt = DATEADD(D, -1, @PrvDt)
END
RETURN @PrvDt
END
GO


texts: Bitcoin, detecting deposits to the node.js server

texts:
I'm trying to detect deposits that a user will make. I added explainatory comments inline.

Can you spot any flaws in it?

var _ = require('underscore')

var check = function(client, site) {
    // check last 10 transactions
    bitcoin_client.cmd('listtransactions', '*', 10, function(e, transactions) {

            if (!transactions) return;
            var TRANSACTION = transactions.transactions;

            for (var i = 0; i < TRANSACTION.length; i++) {
                depositDetector(i)()
            };

            function depositDetector(i) {
                return function() {
                    //check if it's received
                    if (TRANSACTION[i].category == "receive" && TRANSACTION[i].amount >= 0.00000100) {

                        var txid = TRANSACTION[i].txid
                        var address = TRANSACTION[i].address
                        var amount = TRANSACTION[i].amount
                        var confs = TRANSACTION[i].confirmations

                        // find it in deposits database

                        deposit.find({
                            'txid': txid
                        }).exec(function(e, _deposit) {
                                // if there is deposit with that txid's
                                //save their confirmations
                                if (_deposit.length > 0) {
                                    _.each(_deposit, function(a) {
                                        a.confs = confs;
                                        a.save() //confirmations updated
                                    })

                                } else { // the txid is new, find user with it's address
                                    //and update user with that transaction amount.

                                    user.findOneAndUpdate({
                                        'btc_address': address
                                    }, {
                                        $inc: {
                                            'btc_balance': amount
                                        }
                                    }).exec(function(e, _user) {

                                            // !e && save deposit to database / finished

                                        }
                                    })

                            }
                        })

                }
            }
        }
    })

}


texts: Testing database table creation with NUnit

texts:
I'm new to using NUnit and have written a test to check for the existence of a database table. I have the below code that should check whether a new table named NewTable has been created in the database. It works correctly but I can't help feeling there's probably a better way of doing this. Thanks.

using(var conn = context.NewConnection()) {
    var tables = conn.GetSchema("Tables");
    foreach(System.Data.DataRow row in tables.Rows) {
        foreach(System.Data.DataColumn col in result.Columns) {
            if(row[col.ColumnName].ToString() == "NewTable")
                Assert.Pass();
        }
    }
}

Assert.Fail("NewTable not created");


texts:
I recently started to work with python and came to idea to automate process of looking for new jobs. There is nice website and I managed to get content, because they use angular to render webpage and using just requests gives no results, because page is rendered using javascript.

Below code is functional, but a bit slow, it take about 10-15 seconds to get rendered page. Full process include going through all job ads, get title,description,link, etc, and check local database to see whether this ad already exists. If not, new mail is sent through mailgun. Any suggestion is welcomed.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from bs4 import BeautifulSoup
import pdfkit
import requests
from db import DB

# Variables
base_url = "https://www.helloworld.rs"
links = []

def send_mail(title, body, attach):
    return requests.post(
        "https://api.mailgun.net/v3/MY_URL/messages",
        auth=("api", "MY-API-KEY"),
        files=[("attachment", open(attach))],
        data={"from": 'Job Bot <my@mail>',
              "to": ["another@mail"],
              "subject": "New job: " + title,
              "text": body})

class Render(QWebPage):

    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        self.app.quit()

# full url of jobs of interests
url = 'https://www.helloworld.rs/oglasi-za-posao/#/page=0&tag=&cat=&show_more=0&senioritet=1&vreme_postavljanja=&rok_konkursa=&jezik='
try:
    r = Render(url)
except:
    print "[!] Connection error!"
    exit(0)

result = r.frame.toHtml()
formatted_result = str(result.toAscii())
bs = BeautifulSoup(formatted_result, 'lxml')
jobs = []
for job in bs.find_all('div', class_="job-item"):
    _company = job.find('strong')
    try:
        company = _company.a.text
    except:
        company = _company.text
    company = company.replace('\n', '')
    company = company.replace('\r', '')
    company = company.replace('\t', '')

    title = job.h3.a.string
    description = job.find('p', class_="description").contents[0]
    link = base_url + job.find('a', class_="job-link")["href"]
    jobs.append({"title": title, "description": description, "company": company, "link": link})

db = DB(db="DATABASE-NAME")

#get all links from db to check if new result exists
db_links = db.execute("SELECT link FROM jobs")
for u in db_links.fetchall():
    links.append(u[0])

for job in jobs:
    job_title = job['title'].encode("utf-8")
    job_company = job['company'].encode("utf-8")
    job_description = job['description'].encode("utf-8")
    job_link = job['link']
    if job_link not in links:
        db.execute(
            "INSERT INTO jobs (title,description,company,link) VALUES ('{}','{}','{}','{}','{}')".format(
                job_title,
                job_description,
                job_company,
                job_link))
        mail_body = "{}\n\n{}".format(job_description, job_link)
        print "[+] New ad, sending mail."
        generated_pdf_location = "/tmp/" + job_title + ".pdf"
        pdfkit.from_url(job_link, generated_pdf_location)
        print send_mail(job_title, mail_body, generated_pdf_location)
    else:
        print "[-] Already exists, skipping."


texts:
I'm currently trying to do data quality checks in python primarily using Pandas.
The code below is fit for purpose. The idea is to do the checks in Python and export to an Excel file, for audit reasons.
I perform checks like the below in 4 different files, sometimes checking if entries in one are also in the other, etc.
df_symy is just another DataFrame that I imported inside the same class.

I'm wondering if there's a better way to do this task, for example:

create a function for each check
create a more meaningful way to check the data and present the results, etc

def run_sharepoint_check(self) -> pd.DataFrame:
        """Perform checks on data extracted from SharePoint.

        Check 1: Amount decided is 0 or NaN
        Check 2: Invalid BUS ID
        Check 3: Duplicated entries. It also tags the latest entry
        Check 4: SYMY Special not in SharePoint
        """
        # Use this function to check the data we have from SharePoint
        # and return DF with checks in the excel file
        # Another function will be used to process the data and produce
        # the final list
        df = self.sharepoint_data.copy()

        df_symy = self.symy_data
        df_symy = df_symy.loc[df_symy['COMMITMENT_TYPE'].str[0] == 'S']

        symy_cols = ['BUYER_NUMBER', 'Balloon ID',
                     'CLD_TOTAL_AMOUNT', 'POLICY_CURRENCY']

        df = df.merge(right=df_symy[symy_cols],
                      how='outer',
                      left_on=['Balloon ID', 'BUS ID'],
                      right_on=['Balloon ID', 'BUYER_NUMBER'])

        check_1 = df['Amount decided'] == 0 | df['Amount decided'].isna()
        df.loc[check_1, 'check_1'] = 'Amount decided is 0 or NaN'

        check_2 = df['BUS ID'].isna()
        df.loc[check_2, 'check_2'] = 'Invalid BUS ID'

        check_3 = df.duplicated(subset=['Balloon ID', 'BUS ID'], keep=False)
        df.loc[check_3, 'check_3'] = 'Duplicated entry'

        check_3_additional = ~df.duplicated(
            subset=['Balloon ID', 'BUS ID'], keep='first'
        )
        # Filter only the entries that are duplicated
        # Out of those, the first one is the latest
        df.loc[(check_3) & (check_3_additional),
               'check_3'] = 'Duplicated entry (Latest)'

        # Match Balloon+BUSID (SYMY) to SharePoint
        check_4 = (~df.duplicated(subset=['Balloon ID', 'BUS ID'],
                                  keep='first')) & (df['BUS ID'].isna())
        df.loc[check_4, 'check_4'] = 'SYMY SA not in SharePoint'

        check_cols = ['check_1', 'check_2', 'check_3', 'check_4']

        # .fillna('OK') just for visual purposes in Excel.
        df[check_cols] = df[check_cols].fillna('OK')

        # self.data_checks_dfs in the init method is an empty dictionary.
        self.data_checks_dfs['SharePoint_checks'] = df

        return df

So, how can I improve this?
Does anyone have this type of task that has been automated using Python?


texts: JavaScript function to convert underscore-case to camel-case (and vice-versa)

texts:
Actually I needed a function which converts underscore to camel-case.
But then I've had the idea: Why not extend the function so, that is works the other way around?

Finally I recalled that there is a third case which programmers use: Pascal-Case. So I included that too.

The function doesn't work perfect but as long as the different cases are used as expected it works alright.

Any hints and suggestions concerning improvements are welcomed.

/**
* Converts a string to either underscore-case or camel-case or
*   to pascal-case.
* @param {string} toChange
* @param {string} [toCase='toUnderscoreCase'] - Options:
*   'toUnderscoreCase' | 'toCamelCase' | 'toPascalCase'
* @returns {string} according toCase-param.
*   Returns an empty string in case of error.
*/

function changeCase(toChange, toCase) {
  var needle = null;
  var funct = null;
  var needleChangingUpperLower = /[a-z0-9]_[a-z0-9]/g;
  var needleToUnderscore = /(([a-zA-Z0-9]*?)(([a-z0-9][A-Z]))|([a-zA-Z0-9]*)$)/g;

  toCase = toCase || 'toUnderscoreCase'

  if ( !toChange ||
      typeof toChange !== 'string' ||
      toChange.length < 2 ) {
    return '';
  }

  if (toChange.search(/[^\w]/g) > -1) {
    return '';
  }

  function toChangingUpperLower(match) {
    var chars = match.split('_');

    return chars[0] + chars[1].toUpperCase();
  }

  function toUnderscore(match, wordComplete, wordTruncated, wordChange) {
    var ret = '';

    if (wordChange) {

      var chars = wordChange.split('');

      ret += wordTruncated.toLowerCase() + chars[0] + '_' + chars[1].toLowerCase();
    } else {
      ret = wordComplete.toLowerCase();
    }

    return ret;
  }

  switch (toCase) {
    case 'toCamelCase':
      needle = needleChangingUpperLower;

      toChange = toChange.slice(0, 1).toLowerCase() + toChange.slice(1);

      funct = toChangingUpperLower;

      break;
    case 'toPascalCase':
      needle = needleChangingUpperLower;

      toChange = toChange.slice(0, 1).toUpperCase() + toChange.slice(1);

      funct = toChangingUpperLower;

      break;
    case 'toUnderscoreCase':
      needle = needleToUnderscore;

      funct = toUnderscore;

      break;
    default:
      return '';
  }

  return toChange.replace(needle, funct);
}

// --- Usage-examples and test-cases --------
var tests = [ {
  toChange: 'get_amount_of_taxes',
  toCase: ''
},

{
  toChange: 'ThisIsTheSoCalledPascalCase',
  toCase: 'toCamelCase'
},
{
  toChange: 'thisIsTheSoCalledCamelCase',
  toCase: 'toPascalCase'
},
{
  toChange: 'set_sum_of_articles',
  toCase: 'toCamelCase'
},
{
  toChange: 'getAmountOfTaxes',
  toCase: 'toUnderscoreCase'
},
{
  toChange: 'XMLHttpRequest',
  toCase: 'toUnderscoreCase'
},
{
  toChange: 'theXMLconnector1ForABC',
  toCase: 'toUnderscoreCase'
},
{
  toChange: 'aB',
  toCase: 'toUnderscoreCase'
},
{
  toChange: 'c',
  toCase: 'toUnderscoreCase'
},
{
  toChange: [2, 3],
  toCase: 'toUnderscoreCase'
},
{
  toChange: 'abc#123Spec',
  toCase: 'toUnderscoreCase'
},
{
  toChange: 'abc_890-spec',
  toCase: 'toCamelCase'
},
{
  toChange: 'get_amount_of_taxes',
  toCase: 'abc123'
} ];

tests.forEach(function(test) {
  var result = changeCase(test.toChange, test.toCase);
  var log = console.log;
  var err = console.error;

  !result
  ? err( '%s\n%s',
        'Something has gone wrong.',
        JSON.stringify(test, null, 2))
  : log( '%s - %s',
        result,
        JSON.stringify(test, null, 2));
});


texts: Basic Imitation of C# Enumerable in VBA - or any other static class

texts:
Since implementing static classes in VBA actually seems possible I came up with an idea to try to imitate C#' Enumerable class (well, to some extent...). This is just an idea but it should work with any sort of a class serving the purpose of a static one, ie. Math, Factory, etc.

quick note: the original Enumerable uses Linq which is not an option in VBA ( forget this ) therefore the functionality as of now will be very limited.

The point here is to be able to kind of replace the syntax of

Dim i as Long
for i = 1 to 100
    'do something...
next

with

Dim number as Variant
for each number in Enumerable.Range(1,100)
    'do something...
next

So you can iterate almost any Range of numbers "on-fly".

So far I have been able to come up with a very simple working version (but! -> try to see the potential) I would like to demonstrate here and ask for your opinion of possibly improving it and things to consider within the current implementation.

You need Notepad or another text editor and copy-paste the following

VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "Enumerable"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Private c As Collection

Public Function Range(param1, param2) as Collection
    Set c = new Collection
    Dim i as Long
    for i = param1 to param2
        c.add i
    next
    set Range = c
End Function

Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
    Set NewEnum = c.[_NewEnum]
End Property

Save this file to your desktop as Enumerable.cls (make sure it's not an Enumerable.cls.txt)

Start Excel and go right into the VBE (alt+F11)

Right click the VBA Project and select Import File and select the Enumerable.cls.

Right click the VBA Project again and Insert a Module (Module1)

Now, copy-paste the below code into the Module1

Sub Main()

    Dim number As Variant

    For Each number In Enumerable.Range(1, 100)
        Debug.Print number
    Next

End Sub

and run w/ F5. Numbers from 1 to 100 should be printed to the Immediate Window at this point.

Notice - You did not have to instantiate the Enumerable class and you are able to iterate via any range of numbers - as long as they don't cause an overflow error on the Long data type

Notice2 - The current very basic version has not been tested with negative numbers - would it be worth fully supporting it and possibly combining it with a possibility of reverse iterating the collection?

Please, share your opinions :)

For fun: replace the code in Module1 with

Sub Main()

    Dim number As Variant

    For Each number In Enumerable.Range(1, 100)
        Debug.Print FizzBuzz(number)
    Next

End Sub

Public Function FizzBuzz(ByVal value As Long) As String
    If (value Mod 15 = 0) Then
        FizzBuzz = "FizzBuzz"
        Exit Function
    End If
    If (value Mod 3 = 0) Then
        FizzBuzz = "Fizz"
        Exit Function
    End If
    If (value Mod 5 = 0) Then
        FizzBuzz = "Buzz"
        Exit Function
    End If
    FizzBuzz = value
End Function


texts: Correct Implementation of Custom UIView into ViewController Programatically

texts:
I am familiar with using storyboards to construct UI elements in Xcode, but I am only beginning to learn how to make UI programmatically (without a storyboard).

I wanted to know if this is the correct way to implement a UIView into an existing ViewController class.

DetailView (Custom UIView class):

.h file (header)

@interface DetailView : UIView

@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) UIImageView *ratingView;
@property (strong, nonatomic) UILabel *tagLabel;
@property (strong, nonatomic) UILabel *plotLabel;

@end

.m file (implementation)

- (instancetype)init {

if(self = [super init]){
    // Creating the large movie image
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 64.0, 375.0f, 200.0f)];

    // Creating the rating image
    _ratingView = [[UIImageView alloc] init];

    // Creating the tag Label
    _tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(38, 274, 355, 200)];
    self.tagLabel.font =  [UIFont fontWithName:@"HelveticaNeue" size:12];

    // Creating the plot label
    _plotLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 299, 355, 200)];
    self.plotLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:14];

    [self addSubview:self.imageView];
    [self addSubview:self.ratingView];
    [self addSubview:self.tagLabel];
    [self addSubview:self.plotLabel];
}

return self;
}

View Controller:

Commented code is another way I attempted to implement the DetailView

- (void)viewDidLoad {
[super viewDidLoad];
self.detailView = [[DetailView alloc] init];

self.title = self.movie.title;
self.view.backgroundColor = [UIColor whiteColor];

self.detailView.imageView.image =
[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.movie.fanArt]]];
//[self.view addSubview:self.detailView.imageView];

[self setRatingImage:self.movie.rating];
//[self.view addSubview:self.detailView.ratingView];

self.detailView.tagLabel.numberOfLines = 0;
self.detailView.tagLabel.text = self.movie.tagline;
[self.detailView.tagLabel sizeToFit];
//[self.view addSubview:self.detailView.tagLabel];

self.detailView.plotLabel.numberOfLines = 0;
self.detailView.plotLabel.text = self.movie.plot;
[self.detailView.plotLabel sizeToFit];
//[self.view addSubview:self.detailView.plotLabel];

[self.view addSubview:self.detailView];
}


texts:
Question : Build a graph in python, given its edge representation.

from collections import defaultdict

graph = { '1' : ['2' ,'4','5'],
          '2' : ['3'] ,
          '3' : ['5'] ,
          '4' : ['2']
          }

def generate_edges(graph):
    edges = []

    for node in graph:
        for next_node in graph[node]:
            #if edge exist than append
            edges.append((node,next_node))
    return edges

def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path

        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath:
                    return newpath
        return None

print generate_edges(graph)

print find_path(graph, '1','5')

How can i improve this code?


texts: Loop for inserting a node into a binary search tree

texts:
I am trying to implement binary search tree. One method which I am trying to implement in the most efficient and stylish way is node insertion.
I am under the impression that  while (true) is a bad practice, correct?

    while (true){
        if(n <currentNode.data){
            if (currentNode.left == null){
                currentNode.left = new node(n);
                break;
            }else{
                currentNode = currentNode.left;
            }
        }else
            if (currentNode.right == null) {
                currentNode.right = new node(n);
                break;
            } else{
                currentNode = currentNode.right;
            }
    }

and here is the whole code:

package graph;

public class BSearchTree {
    private node head = null;
    public BSearchTree(int [] entries){
        for (int a : entries){
            insert(a);
        }
    }
    public void insert(int n){
        if (head == null){
            head = new node(n);
            return;
        }
        node currentNode = head;
        while (true){
            if(n <currentNode.data){
                if (currentNode.left == null){
                    currentNode.left = new node(n);
                    break;
                }else{
                    currentNode = currentNode.left;
                }
            }else
                if (currentNode.right == null) {
                    currentNode.right = new node(n);
                    break;
                } else{
                    currentNode = currentNode.right;
                }
        }

    }

    public static void main(String[] args) {
        BSearchTree bst = new BSearchTree(new int[]{2,4,1,5});
        System.out.println(bst.toString());
    }

    private class node {
        int data = -1;
        node left = null;
        node right = null;

        public node(int n){
            data = n;
        }
    }
}


texts:
I'm trying to solve this problem. I changed Scanner and used BufferedReader but I'm still getting TLE with the given code. Can I have a code review to help determine where else performance can be optimized?

import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;

class LittleDeepuAndArray {
    public static void main(String args[] ) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        long N = Long.parseLong(line);
        List<Long> list = new ArrayList<Long>();
        String line5 = br.readLine();
        String[] numbers = line5.split(" ");
        for(int z=0;z<N;z++) list.add(Long.parseLong(numbers[z]));
        String line2 = br.readLine();
        long M = Long.parseLong(line2);
        long X=0;
        int k=0,m=0;
        long zz=0;
        long size=list.size();
        for(k=0;k<M;k++) {
            X = Long.parseLong(br.readLine());
            for (m=0;m<size;m++) {
                zz=list.get(m);
                if(X<zz) list.set(m,zz-1);
            }
        }
        for (m=0;m<size;m++) {
            if(m==size-1) System.out.print(list.get(m));
            else System.out.print(list.get(m) + " ");
        }
    }
}


texts:
I have a directory with lot of files and folders in it. The function which I wrote works, but I want to make it more efficient and faster. I was thinking of multiprocessing or threading.

The code which I wrote is as follows:

LIST.delete(0,END) # this is a list view
usePATH = '/nfzcae/nvh_mdp/Messdatenbank_Powertrain'
fileLevels = [] # code of interest is below

for path, dirs, f in os.walk(usePATH):
    for d in dirs:
        for f in glob.iglob(os.path.join(path, d,'*COMPARE.mat')):
            if 'COMPARE.mat' in f:                                          # if 'COMPARE.mat' in f and not 'MIN' in f and not 'MAX' in f / if 'COMPARE.mat' in f )   # if 'COMPARE.mat' in f and not 'MIN' in f and not 'MAX' in f
                fileLevels.append(f.split('/'))                             # Split path string at all '/'
                LIST.insert(END,f)                                          # Insert path with name string into the listbox
                LIST.update_idletasks()                                     # Update listbox after each element added
                nr = LIST.size()                                            # Get current number of files in listbox
                VAR.set(nr)                                                 # Set number of files as a variable for label
                LIST.see(END)                                               # See last element added
                FILE_LIST.append(f)
            else:
                pass                                                        # Do nothing
LIST.insert(END,'Search finished')

It is actually made for a GUI Button. I want to make this code faster. I know that threading does not work for nested for loops, so I am stuck in figuring out how to use the multithreading module for this problem. Any ideas? I am having an idea on these lines:

get all the Sub directories names in a list
parallel pool now using the list and write a function which checks the Sub Folders for the file Name containing the keyword

Will this work??

P.S: The Folder has lot of subdirectories (more than 1000)


texts: LeetCode 173: Binary Search Tree Iterator

texts:
The original problem statement is here, here is the super short summary:

Your binary search tree iterator must implement the following interface:

pub struct TreeNode {
  pub val: i32,
  pub left: Option<Rc<RefCell<TreeNode>>>,
  pub right: Option<Rc<RefCell<TreeNode>>>,
}

struct BSTIterator {}

impl BSTIterator {
    fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {}

    fn next(&mut self) -> i32 {}

    fn has_next(&self) -> bool {}
}

The binary search iterator must return the values of the binary search tree from smallest to largest. It must use O(h) memory, where h is the height of the tree. Both next and has_next must run in O(1) amortized time.

My solution to this is gradual, controlled recursion:

Given the root of the tree in constructor, traverse all the left children and remember them.
On each next call, pop the last remembered node and return it. If that node had a right child, traverse it and all of its left children, and remember them.

The implementation:
use std::cell::RefCell;
use std::rc::Rc;

// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }
}

struct BSTIterator {
    nodes: Vec<Rc<RefCell<TreeNode>>>,
}

impl BSTIterator {
    fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
        let mut nodes = vec![];

        if let Some(root) = root {
            BSTIterator::insert(&mut nodes, root);
        }

        BSTIterator { nodes }
    }

    /// Return the next smallest number
    fn next(&mut self) -> i32 {
        let rc = self.nodes.pop().unwrap();
        let node = (*rc).borrow();

        if let Some(node) = &node.right {
            BSTIterator::insert(&mut self.nodes, Rc::clone(node));
        }

        node.val
    }

    /// True if there is a next smallest number, false otherwise
    fn has_next(&self) -> bool {
        !self.nodes.is_empty()
    }

    fn insert(nodes: &mut Vec<Rc<RefCell<TreeNode>>>, node: Rc<RefCell<TreeNode>>) {
        let mut node = Some(node);
        while let Some(rc) = node {
            nodes.push(Rc::clone(&rc));

            node = (*rc)
                .borrow()
                .left
                .as_ref()
                .and_then(|lft| Some(Rc::clone(&lft)));
        }
    }
}

fn main() {
    let mut node50 = TreeNode::new(50);
    let mut node25 = TreeNode::new(25);
    let mut node75 = TreeNode::new(75);
    let mut node12 = TreeNode::new(12);
    let mut node32 = TreeNode::new(32);
    let mut node62 = TreeNode::new(62);
    let mut node80 = TreeNode::new(80);

    node25.left = Some(Rc::new(RefCell::new(node12)));
    node25.right = Some(Rc::new(RefCell::new(node32)));

    node75.left = Some(Rc::new(RefCell::new(node62)));
    node75.right = Some(Rc::new(RefCell::new(node80)));

    node50.left = Some(Rc::new(RefCell::new(node25)));
    node50.right = Some(Rc::new(RefCell::new(node75)));

    let mut it = BSTIterator::new(Some(Rc::new(RefCell::new(node50))));

    while it.has_next() {
        println!("{}", it.next());
    }
}

The compiler kept screaming at me, and it was my first time working with Rc and RefCell. Which anti-patterns do I have here? Is (*rc).borrow().left.as_ref().and_then(/*...*/) a reasonable thing to write in insert?


texts:
This question has a follow-up: Follow up to Shuffling a list of track indices

I have a bunch of paths in an ArrayList<String> and when a user has activated the shuffle button, I want to have a random order to play all of them. This class should help me get every index once. The methods getNext() and getPrevious() should help me to get the last / next song when the user clicks on either the next or previous button.

public class ShuffleGenerator {

    private ArrayList<Integer> indexList;
    private int currentIndex;

    public ShuffleGenerator(){
        indexList = new ArrayList<Integer>();
        currentIndex = 0;
    }

    public void initalize( int seed, int size ){

        if( !indexList.isEmpty() ){
            indexList.clear();
        }

        if( size > 0 ){

            //fill it with indices
            ArrayList<Integer> indices = new ArrayList<Integer>();
            for( int i = 0; i < size; i++ ){
                indices.add(i);
            }

            Random rnd = new Random(seed);

            do{

                int index = rnd.nextInt(indices.size());
                indexList.add( indices.get(index) );
                indices.remove(index);

            }while( indices.size() > 0 );

        }

    }
    /**
     * Get the next index.
     * @return -1 if failed otherweise the index.
     */
    public int getNext(){

        //if currentIndex is invalid
        if( currentIndex+1 >= indexList.size() || indexList.isEmpty() ){
            return -1;
        }

        currentIndex++;
        return indexList.get(currentIndex);
    }

    /**
     * Get the previous index.
     * @return -1 if failed otherwise the index.
     */
    public int getPrevious(){

        //if currentIndex is invalid
        if( currentIndex-1 < 0 || indexList.isEmpty() ){
            return -1;
        }

        //decrement the current index so we can get the previous one
        currentIndex--;

        return indexList.get(currentIndex);
    }

}

I tested it twice and it seems like I get every index from 0 to size-1 in a random order. But is it really giving me every index? I might have made a mistake and just not noticed yet. And is there anything to improve?


texts: Sum of two elements of a list equaling a target

texts:
In effort to learn OCaml, I'm going through some easy LeetCode problems and attempting to implement them. I arrive at the correct answer, but I'm still developing an intuition for canonical OCaml code. I'd appreciate any feedback on my implementation.

As mentioned, this is problem 1 on LeetCode. A quick summary of the problem: given an array of integers, return the indices of the 2 numbers that sum to a given "target".

For example, given nums: [2, 7, 11, 15] and target: 13, the result should be [0, 2] (the integers at indices 0 and 2 sum to 13).

Furthermore, we can assume a unique solution exists for the given array and target.

Here is my refined attempt at implementing this in OCaml:

let two_sum nums target =
  let rec aux i j =
    let n1 = List.nth nums i in
    let n2 = List.nth nums j in
      if n1 + n2 = target then [i; j]
      else if j = (List.length nums) - 1 then aux (i + 1) (i + 2)
      else aux i (j + 1)
  in aux 0 1;;

I appreciate any feedback.


texts:
https://leetcode.com/problems/merge-two-sorted-lists/

Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace SortingQuestions
{
    [TestClass]
    public class Merge2SortedLists
    {
        [TestMethod]
        public void TwoListsMerge()
        {
            ListNode l1 = new ListNode(1);
            l1.next = new ListNode(2);
            l1.next.next = new ListNode(4);
            ListNode l2 = new ListNode(1);
            l2.next = new ListNode(3);
            l2.next.next = new ListNode(4);
            var res = MergeTwoLists(l1, l2);
            Assert.AreEqual(1, res.val);
            Assert.AreEqual(1, res.next.val);
            Assert.AreEqual(2, res.next.next.val);
            Assert.AreEqual(3, res.next.next.next.val);
            Assert.AreEqual(4, res.next.next.next.next.val);
            Assert.AreEqual(4, res.next.next.next.next.next.val);
        }
        [TestMethod]
        public void OneEmptyList()
        {
            ListNode l1 = new ListNode(1);
            l1.next = new ListNode(2);
            l1.next.next = new ListNode(4);
            ListNode l2 = null;
            var res = MergeTwoLists(l1, l2);
            Assert.AreEqual(1, res.val);
            Assert.AreEqual(2, res.next.val);
            Assert.AreEqual(4, res.next.next.val);
        }

        public ListNode MergeTwoLists(ListNode l1, ListNode l2)
        {
            ListNode result = new ListNode(0);
            if (l1 == null && l2 == null)
            {
                return null;
            }

            ListNode currRes = result;
            while (l1 != null && l2 != null)
            {
                if (l1.val < l2.val)
                {
                    currRes.next = l1;
                    l1 = l1.next;
                    currRes = currRes.next;
                }
                else
                {
                    currRes.next = l2;
                    l2 = l2.next;
                    currRes = currRes.next;
                }
            }
            if (l1 != null)
            {
                currRes.next = l1; //concat all the rest
            }
            else
            {
                currRes.next = l2;
            }
            return result.next; // we don't pass the first value
        }
    }

    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }
}

if you could please review this code from testing point of view, in an interview. what edge cases would you expected to be tested here. please remember this is about 30 minutes. also please comment on style.


texts: Prototype GameManager for game written in Unity

texts:
I am self taught, so I'm consistently seeking ways to code better, and more efficiently. If anyone has the time, please advise me on what can be done better with explanations as to why the old method is considered inefficient, and why the new method proves to be better. Also, where I can implement more self explanatory code.

using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;

namespace Mans.Prototype.Lumberjack {
    [System.Serializable]
    public class GameManager : MonoBehaviour {

        public static GameManager instance { get; private set; } //singleton
        private static Timer _timer;

        [SerializeField] private GameObject _logPrefab;
        [SerializeField] private float _seconds;

        public Timer timer {
            get { return _timer; }
            set { _timer = value; }
        }
        public static GameObject logPrefab {
            get { return instance._logPrefab; }
        }

        private void Awake() {
            instance = this;
            timer = new Timer( _seconds );

            InitializeScenes();
        }
        private void Start() {
            ObjectManager.Initialize();

            UIManager.ToggleUIElement( "InGame" );
            SceneManager.SetActiveScene( SceneManager.GetSceneByName( "Level" ) );
        }
        private void Update() {
            if ( Input.GetKey( KeyCode.Return ) ) {
                Scene temp = SceneManager.GetSceneByName( "Level" );
                SceneManager.UnloadSceneAsync( temp );
                SceneManager.LoadScene( temp.buildIndex, LoadSceneMode.Additive );
            }
        }
        private void FixedUpdate() {
            if ( timer.seconds < 1f && ObjectManager.instance.treeCount > 0 ) {
                PlayerManager.instance.player.GetComponent<Animator>().enabled = false;
                UIManager.ToggleUIElement( "InGame", false );
                UIManager.ToggleUIElement( "GameOver", true );
                return;
            } else if ( timer.seconds > 0f && ObjectManager.instance.treeCount <= 0 ) {
                return;
            }
            InputManager.instance.HandleInput();

            --_timer;
        }

        private void InitializeScenes() {
            //Preload starting scenes
            LoadScene( "Scenes/UI" );
            LoadScene( "Scenes/Level 1/Level" );
            LoadScene( "Scenes/Player" );
        }
        public static void LoadScene( string path ) {
            //Loads a scene. Created so other scripts can manipulate the levels without having to include relevant namespaces each time.
            SceneManager.LoadScene( path, LoadSceneMode.Additive );
        }

        public static void MoveObjectToScene( GameObject @object, string name ) {
            //moves from current active scene to scene of choice, usually the level scene.
            SceneManager.MoveGameObjectToScene( @object, SceneManager.GetSceneByName( name ) );
        }
    }
}

I'm unsure if I have elaborated enough, if not, say so and I will update with more explanations where necessary. No specific goal, other than to improve the readability and efficiency of the code.


texts: How to good code for multiple if conditions?

texts:
We have to check Git and SVN folders.
    public static String getREPOType(String repoPath){
        boolean gitRepo = new File(repoPath, Constants.GIT_FOLDER).exists();
        String repoType = null;
        if(gitRepo){
            repoType = Constants.GIT;
        }else{
            boolean svnRepo = new File(repoPath, Constants.SVN_FOLDER).exists();
            if(svnRepo){
                repoType = Constants.SVN;
            }else{
                // New type, need to be handled
            }
        }
        return repoType;
    }

Please help if this can be refactored in Java


texts:
Part of my code:

def get_file():

    custom_data_folder = input("Name of custom data directory - " +
                               "Hit ENTER to default: ")
    file_name = input("File name: ")
    default_path = os.path.abspath(os.path.join('data', file_name))
    custom_path = os.path.abspath(os.path.join(custom_data_folder, file_name))

    if custom_data_folder == '':
        return(default_path if os.path.exists(default_path) is True
                         else "The file or path does not exist.")
    else:
        return(custom_path if os.path.exists(custom_path) is True
                           else "The file or path does not exist.")

My script assumes a file is in a directory called "data", but I wanted to provide an option of a entering a custom directory where a file could be.

It works, but is there a better way to go about doing what this function is trying to accomplish?


texts: Nested layouts - BoxLayout inside BorderLayout

texts:
I have this code:

JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.PAGE_AXIS));
TitledBorder tb2 = BorderFactory.createTitledBorder(null, "Control Panel",
        TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION, myFont, new Color(0, 153, 0));
controlPanel.setBorder(tb2);

JPanel fromDate = new JPanel();
fromDate.setLayout(new BoxLayout(fromDate, BoxLayout.X_AXIS));
fromDate.add(new JLabel("From date: "));
JButton fromDateButton = new JButton("...");
fromDateButton.setMaximumSize(new Dimension(100,15));
fromDate.add(fromDateButton);
JPanel toDate = new JPanel();
toDate.setLayout(new BoxLayout(toDate, BoxLayout.X_AXIS));
toDate.add(new JLabel("Until date: "));
JButton toDateButton = new JButton("...");
toDateButton.setMaximumSize(new Dimension(100,15));
toDate.add(toDateButton);
controlPanel.add(Box.createRigidArea(new Dimension(0,10)));
controlPanel.add(fromDate);
controlPanel.add(Box.createRigidArea(new Dimension(0,10)));
controlPanel.add(toDate);
toDate.setAlignmentX(Component.LEFT_ALIGNMENT);
fromDate.setAlignmentX(Component.LEFT_ALIGNMENT);

gui.add(controlPanel, BorderLayout.WEST);

Which produce this GUI (The relevant part is shown):

I want to have a label and a button right next to it. There should be a better way to achieve this. Any suggestions?


texts:
I have a small function that when passed a str that names a file that contains a program; it returns a 2-tuple with the number of the non-empty lines in that program, and the sum of the lengths of all those lines. Here is my current functioning code:

def code_metric(file_name):
    line_count = char_count = 0
    with open(file_name) as fin:
        stripped = (line.rstrip() for line in fin)
        for line_count, line in enumerate(filter(None, stripped), 1):
            char_count += len(line)
    return line_count, char_count

Is there a way to implement this function using functionals such as map, filter, and reduce and small lambdas to pass to these functionals? I could make it work conventionally but having some issue with using functionals. Any help would be great.


texts:
Despite being the clever Java coder I am, I noticed I know way too little about various design patterns. The builder pattern caught my eye as something to learn, as I have certainly seen my fair share of telescopic constructors already.

So, I decided to give it a try. The following is a really simple class represents a cell in a table of data. So far a cell can have text (its contents) and a URL (if it is to be rendered as a hyperlink), but I could see myself adding other parameters as well, so there's an inner static class called CellBuilder as well.

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A class that represents data in a table cell.
 */
public class CellData {
    /** The text that's displayed in the cell. **/
    private final String text;

    /** The URL to which the text should link to, if any. **/
    private final URL url;

    private CellData(CellBuilder builder) {
        this.text = builder.text;
        this.url = builder.url;
    }

    public String getText() {
        return text;
    }

    public URL getUrl() {
        return url;
    }

    /** A builder to avoid telescopic constructors. **/
    public static class CellBuilder {
        private String text = "";
        private URL url = null;

        public CellBuilder text(String text) {
            this.text = text;
            return this;
        }

        public CellBuilder url(String url) {
            try {
                this.url = new URL(url);
            } catch (MalformedURLException ex) {
                Logger.getLogger(CellData.class.getName()).log(Level.SEVERE, null, ex);
            }
            return this;
        }

        public CellData build() {
            return new CellData(this);
        }
    }
}

A new cell would then be created, for example, like this:

CellData cell = new CellData.CellBuilder().text("hello").url("http://www.example.com/foo").build();

Now, I don't know about you, but to me that doesn't look much more easier or cleaner than doing it the traditional way, by passing those arguments to the cell in its constructor. :( Yet another way would be to do it like this:

CellData cell = new CellData();
cell.setText("hello");
cell.setUrl("http://www.example.com/foo");

Why shouldn't I do it like that either? I wonder if this particular use case is still too simple to get the best out of this design pattern, or if I'm doing something else completely wrong?

Notice that this doesn't strictly conform to the architecture presented in Wikipedia, but that's because I read about this way from some other source where it was more like this, and the Wikipedia way with about five classes felt like too complicated for a simple matter like this.


texts:
So I really want to have something similar to discriminated unions in C#.

One way to do it is to use a visitor pattern, but it takes half a life to write all broilerplate code by hands.
There is another way that would allow me writing a bit less code, but it is based on delegates.

Consider the analogue of Options from F#:

public abstract class Optional<TValue>
{
    public abstract TResult Resolve<TResult>(Func<TValue, TResult> someHandler, Func<String, TResult> noneHandler);
}

public class Some<TValue> : Optional<TValue>
{
    public Some(TValue value)
    {
        this.Value = value;
    }
    public TValue Value { get; private set; }
    public override TResult Resolve<TResult>(Func<TValue, TResult> someHandler, Func<String, TResult> noneHandler)
    {
        return someHandler(this.Value);
    }
}

public class None<TValue> : Optional<TValue>
{
    public None(String message)
    {
        this.Message = message;
    }
    public String Message { get; private set; }
    public override TResult Resolve<TResult>(Func<TValue, TResult> someHandler, Func<String, TResult> noneHandler)
    {
        return noneHandler(this.Message);
    }
}

public class Demo {
    public Optional<Uri> ParseAbsoluteUri(String whateverUrl)
    {
        if (Uri.IsWellFormedUriString(whateverUrl, UriKind.Absolute))
        {
            var uri = new Uri(whateverUrl, UriKind.Absolute);
            return new Some<Uri>(uri);
        }
        else
        {
            return new None<Uri>("Given URL is not absolute.");
        }
    }
    public String ProcessUrl(String whateverUrl)
    {
        var uriOpt = this.ParseAbsoluteUri(whateverUrl);
        var result = uriOpt.Resolve(uri => "Hey, your URL \"" + uri + "\" looks nice!", message => "Sorry, the URI that you gave looks bad: " + message);
        return result;
    }
    public void Test()
    {
        Trace.WriteLine(this.ProcessUrl("http://google.com"));
        Trace.WriteLine(this.ProcessUrl("Not url at all"));

        /* output:
            Hey, your URL "http://google.com/" looks nice!
            Sorry, the URI that you gave looks bad: Given URL is not absolute.
         */
    }
}

Each delegate is essentially a class that the C# compiler makes to wrap the pointer to a function. So with the excessive use of such approach will I hit any sort of problems? (Bloating the size of the assembly for example?)
Delegates aren't the fastest things in the galaxy, especially multicasts ones, this approach uses them heavily.
Making a call to a virtual method lessens (if not eliminates at all) a chance for JIT inlining.

So all in all I am a bit scared to go all the way this way due to performance concerns. I would like to know what you think of this.


texts:
I have created a bit of path-finding code in response to this code golf question. Since this is one of my first large bits of code in Groovy that I have written, I would like to see how I could improve it.

def invalid() {
    println "Invalid map."
    System.exit(1)
}

def map =
        """01001E
010110
000P00
1100J1
S00111""".split('\n')

//map = [""]// TODO remove this, this is type checking only
//map.remove(0)
//reader = System.in.newReader()
//line = reader.readLine()
//while (line != '') {
//    map << line
//    line = reader.readLine()
//}

def size = map[0].size()
map.each { if (it.size() != size) invalid() }

def startLocation = [0, 0]
def endLocation = [0, 0]
map.eachWithIndex { it, idx ->
    def startIdx = it.indexOf('S')
    def endIdx = it.indexOf('E')

    if (startIdx != -1) {
        startLocation[0] = startIdx; startLocation[1] = idx
    }
    if (endIdx != -1) {
        endLocation[0] = endIdx; endLocation[1] = idx
    }
}

def validPath = []

testMove = { x, y, visited ->// visited is an array of x y pairs that we have already visited in this tree
    if (visited.contains([x, y]) || y >= map.size() || x >= map[0].size() || x < 0 || y < 0)
        return;

    def chr = map[y][x]
    def newPath = visited + [[x, y]]

    if (chr == 'E') validPath = newPath
    if ('J0S'.contains(chr) && !validPath) {
        testMove(x - 1, y, newPath)
        testMove(x + 1, y, newPath)
        testMove(x, y + 1, newPath)
        testMove(x, y - 1, newPath)
    }
}
testMove(startLocation[0], startLocation[1], [])
if (!validPath) invalid()

println validPath

def orintation = 0
def path = ''
validPath.inject { first, second ->
    def chr = map[second[1]][second[0]]
    def sub = [first[0] - second[0], first[1] - second[1]]
    def newOrin = [[0, 1]: 0, [1, 0]: 1, [0, -1]: 2, [-1, 0]: 3][sub]
    path += ((((orintation - newOrin) == 0) ? '' : (newOrin > 0 ? 'R' : 'L')) + (chr == 'J' ? 'M' : '') + 'F')
    orintation = newOrin
    second
}
println "path: $path"


texts: O(lg n) algorithm for a fibonacci number with c++ template

texts:
I wrote a function to find a specific fibonacci number, which runs in O(lg n). Then I modified it with a template. Though it works, I'm new to template and want to know if I used template correctly. Moreover, I wonder whether someone who has a BigNumber class
can use my function without modify my source code.

#include <iomanip>
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <cstring>

using namespace std;

const int initFibo[5] = {5,3,2,1,1};
template <class U, class V>
void fastFibo(U n, V *tuple) {
    assert(n >= 4);
    if(n <= 5) {
        for(int i = 0; i < 4; i++)
            tuple[i] = initFibo[i + (5 - n)];
        return;
    }
    V tmp[4];
    fastFibo<U, V>(n / 2 + 1, tmp);
    if(n % 2 == 0) { // even
        tuple[0] = tmp[0] * tmp[1] + tmp[1] * tmp[2];
        tuple[1] = tmp[1] * tmp[1] + tmp[2] * tmp[2];
        tuple[2] = tmp[1] * tmp[2] + tmp[2] * tmp[3];
        tuple[3] = tmp[2] * tmp[2] + tmp[3] * tmp[3];
    } else {
        tuple[0] = tmp[0] * tmp[0] + tmp[1] * tmp[1];
        tuple[1] = tmp[0] * tmp[1] + tmp[1] * tmp[2];
        tuple[2] = tmp[1] * tmp[1] + tmp[2] * tmp[2];
        tuple[3] = tmp[1] * tmp[2] + tmp[2] * tmp[3];
    }
}

int main(){
    unsigned long long tuple[4];
    for(int i = 4; i <= 93; i++){
        fastFibo<int, unsigned long long >(i, tuple);
        cout << "Fibo(" << setw(2) << i << ")=" << setw(20) << tuple[0] << endl;
    }
    system("pause");
    return 0;
}

@Yuushi:

"Why does n have to be >= 4?... passing a size and a pointer..." Required by my algorithm, n must be >= 4 and tuple is always an array of size 4 (not n) (After invocation tuple will contains 4 fibonacci numbers: the nth, n-1th, n-2th and n-3th). I thought up an idea to create a method like this:

V fastFibo2(U n){
    if( n < 4 )
        return initFibo[5 - n];
    else{
        V buf[4];
        fastFibo(n, buf)
        return buf[0];
    }
}

However if I create it I don't want user to access the ordinary fastFibo. Is it possible or is there a better solution?


texts: Function that inserts values for an array of fields into a database table

texts:
public function insert($table, $fields = array(), $values = array()) {
    $fields = '`' . implode ( '`,`', $fields ) . '`';
    $values = "'" . implode ( "','", $values ) . "'";
    $sql = "INSERT INTO {$table} ($fields) VALUES($values)";

    if ($this->_pdo->prepare ( $sql )) {
        if ($this->_pdo->exec ( $sql )) {
            return true;
        }
    }
    return false;
}

This is my first PHP OOP PDO insert function I have ever written.  My function is working well, but I believe this is not the best way I would have written.  Can somebody guide me on what I might have missed?


texts:
I'm making a chess game. On the board the columns go from a-h and rows from 8-1. I made this simple function so when someone inputs 'a' for the row it will give me the right row on an array same goes for columns, 7a would be [1][0]. Is there an easier way someone could point out for me?

Thanks in advance.

update:added small working sample of function.

#include <stdio.h>

int getColRow(char input)
{
    int val = 0;

    switch (input)
    {
    //row
    case 97:
        val = 0;
        break;
    case 98:
        val = 1;
        break;
    case 99:
        val = 2;
        break;
    case 100:
       val = 3;
       break;
    case 101:
       val = 4;
       break;
    case 102:
       val = 5;
       break;
    case 103:
       val = 6;
       break;
    case 104:
        val = 7;
        break;
    //col
    case 49:
        val = 7;
       break;
    case 50:
        val = 6;
        break;
    case 51:
        val = 5;
        break;
    case 52:
        val = 4;
        break;
    case 53:
        val = 3;
        break;
    case 54:
        val = 2;
        break;
    case 55:
        val = 1;
        break;
    case 56:
        val = 0;
        break;
    default:
        break;
    }
    return val;
    }

    int main(int argc, char *argv[])
    {
    char a = 'a';
    char b = 'b';
    char c = 'c';
    char d = 'd';
    char e = 'e';
    char f = 'f';
    char g = 'g';
    char h = 'h';

    char one = '1';
    char two = '2';
    char three = '3';
    char four = '4';
    char five = '5';
    char six = '6';
    char seven = '7';
    char eight = '8';

    printf("value of %c is %d ",a,getColRow(a));
    printf("\nvalue of %c is %d ",b,getColRow(b));
    printf("\nvalue of %c is %d ",c,getColRow(c));
    printf("\nvalue of %c is %d ",d,getColRow(d));
    printf("\nvalue of %c is %d ",e,getColRow(e));
    printf("\nvalue of %c is %d ",f,getColRow(f));
    printf("\nvalue of %c is %d ",g,getColRow(g));
    printf("\nvalue of %c is %d \n",h,getColRow(h));

    printf("\nvalue of %c is %d ",one,getColRow(one));
    printf("\nvalue of %c is %d ",two,getColRow(two));
    printf("\nvalue of %c is %d ",three,getColRow(three));
    printf("\nvalue of %c is %d ",four,getColRow(four));
    printf("\nvalue of %c is %d ",five,getColRow(five));
    printf("\nvalue of %c is %d ",six,getColRow(six));
    printf("\nvalue of %c is %d ",seven,getColRow(seven));
    printf("\nvalue of %c is %d \n",eight,getColRow(eight));

    return 0;
}


texts:
I wrote a custom URL encoding function and I'd like to run it past a few other experienced C developers. I have tested it on a few strings, and it has worked on all of them.

This is to be run on iOS devices, so memory and processor use are potentially a small concern.

Do you see any potential problems - UB, wrong return, excessive memory or processor usage, difficulty reading?

Any suggestions for improvement?

NSString *urlEncode(NSString *orig)
{
    static const BOOL safe[0x100] = {
        ['a'...'z'] = YES,
        ['A'...'Z'] = YES,
        ['0'...'9'] = YES,
        ['-'] = YES,
        ['_'] = YES,
        ['.'] = YES,
        ['~'] = YES
    };
    const char *digits = "0123456789ABCDEF";
    const char *cstr = orig.UTF8String;
    int clen = orig.length;
    int nlen = 3*clen;
    char newstr[nlen + 1];

    const char *o = cstr   + clen;
    char *p = newstr + nlen;
    *p = 0;
    while(o > cstr) {
        unsigned char c = *--o;
        if(safe[c]) {
            *--p = c;
        } else {
            *--p = digits[c&0xf];
            *--p = digits[c>>4];
            *--p = '%';
        }
    }
    NSString *str = [NSString stringWithUTF8String:p];
    return str;
}

Yes, newStr could get long, but given that a URL > 2kB is unreliable, I think it's unlikely to be a problem in reality.


texts: Determining if a string can be permuted to a palindrome

texts:
I am going through Elements of Programming Interview by Aziz, Lee and Prakash one of the questions is how to determine if a string can be permuted to a palindrome. For example edified can be permuted to deified and now its a palindrome.

So my first implementation is this:

bool CanFormPalindrome(const string& s) {
    std::unordered_map<char, int> letter_count;
    for(char c : s) {
      letter_count[c]++;
    }

    int odd_letter_count = 0;
    for(std::pair<char, int> letter : letter_count) {
      if(letter.second%2 != 0) {
        odd_letter_count++;
      }
    }

    return odd_letter_count <= 1;
}

After I passed all the tests I saw the book's cleaner and sleeker implementation (compared to my implementation) which is:

bool CanFormPalindrome(const string& s) {
  std::unordered_set<char> char_counter;
  for(char c : s) {
    if(char_counter.count(c)) {
      char_counter.erase(c);
    }
    else {
      char_counter.insert(c);
    }
  }
  return char_counter.size() <= 1;
}

When I saw the time difference the tester timed my test at around 30 ms and the book's implementation at around 100 ms. I am wondering why my implementation is faster than the book's. My suspicion is that the calls to unordered_set's count, erase, and insert probably is the main bottle neck as opposed to just insert it just once and increment the value if it exists.

Another question is if you were to ask this on an interview would you care about the space time complexity over speed? Obviously the unordered_set is far more space efficient than the unordered_map, but if its for greater performance gain can we take up more space?


texts: How can I convert this to a generic method?

texts:
I have this code I used to to pull data from our IBM i into .NET into an object so it is easy to work with (avoiding DataTables).

How can I make it better?
How can I convert all/most of this into a generic reusable method?

Here is an example of a method I have written:

public Customer GetUtilityBillCustomer(int id)
{
    #region SQL Statement
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT ACUSTN, AWEBPN, ANAME, AADD1, AADD2, ACITY, ASTATE, AZIP5, AZIP4, AEMADR, ALOCAT, ");
    sb.Append("(TRIM(WTMETER.MADRSN) || ' ' || TRIM(WTMETER.MADRSA) || ' ' || TRIM(WTMETER.MADRSX)) AS SERVICEADDR, ");
    sb.Append("(AARR1 + AARR2 + AARR3) AS BALANCE ");
    sb.Append("FROM WTCUST, WTMETER ");
    sb.Append("WHERE ALOCAT = MLOCAT AND ACUSTN = @custnumber1 ");
    sb.Append("UNION ");
    sb.Append("SELECT FCUSTN, FWEBPN, FNAME, FADD1, FADD2, FCITY, FSTATE, FZIP5, FZIP4, FEMADR, FLOCAT, ");
    sb.Append("(TRIM(WTMETER.MADRSN) || ' ' || TRIM(WTMETER.MADRSA) || ' ' || TRIM(WTMETER.MADRSX)) AS SERVICEADDR, WTFINAL.FAMTDU AS BALANCE ");
    sb.Append("FROM WTFINAL, WTMETER ");
    sb.Append("WHERE FLOCAT = MLOCAT AND FCUSTN = @custnumber2");
    #endregion

    DataTable dt = new DataTable();
    using (iDB2Connection conn = new iDB2Connection(_connString))
    {
        using (iDB2Command cmd = new iDB2Command(sb.ToString(), conn))
        {
            conn.Open();
            cmd.Parameters.Add("@custnumber1", iDB2DbType.iDB2Decimal).Value = id;
            cmd.Parameters.Add("@custnumber2", iDB2DbType.iDB2Decimal).Value = id;
            using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
            conn.Close();
        }
    }

    #region Fill object from DataTable
    var customer = (from i in dt.AsEnumerable()
                    select new Customer
                    {
                        Id = i.Field<int>("ACUSTN"),
                        Pin = i.Field<int>("AWEBPN"),
                        Name = i.Field<string>("ANAME").Trim(),
                        Address1 = i.Field<string>("AADD1").Trim(),
                        Address2 = i.Field<string>("AADD1").Trim(),
                        City = i.Field<string>("ACITY").Trim(),
                        State = i.Field<string>("ASTATE").Trim(),
                        Zip5 = i.Field<string>("AZIP5").Trim(),
                        Zip4 = i.Field<string>("AZIP4").Trim(),
                        LocationNumber = i.Field<int>("ALOCAT"),
                        ServiceAddress = i.Field<string>("SERVICEADDR").Trim(),
                        BalanceDue = i.Field<decimal>("BALANCE"),
                        Email = i.Field<string>("AEMADR")
                    }).SingleOrDefault();
    #endregion

    return customer;
}

I am thinking along the lines of:

public static DataTable GetData(string connString, string sqlStatement)
{
    DataTable dt = new DataTable();

    using (iDB2Connection conn = new iDB2Connection(connString))
    {
        using (iDB2Command cmd = new iDB2Command(sqlStatement, conn))
        {
            conn.Open();
            cmd.Parameters.Add("@custnumber1", iDB2DbType.iDB2Decimal).Value = id;
            cmd.Parameters.Add("@custnumber2", iDB2DbType.iDB2Decimal).Value = id;
            using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
            conn.Close();
         }
    }

    return dt;
}

But how do I pass in an unknown list of parameters and parameter types? Would I use an array of objects? Other thoughts?


texts: Partition a list of numbers into even and uneven numbers

texts:
Input: An array of integers.

Output: That same array, but with the even numbers at the front and the uneven numbers at the back of the array.

I wrote three different solutions, depending on the needs of the client.

First solution:

// linear time not stable and not in-place
private static void partition1(int[] a){
    // not in place:
    int front = 0;
    int back = a.length -1;
    int[] tmp = new int[a.length];

    for (int t = 0; t < a.length; t++){
        if (a[t] % 2 == 0){
            tmp[front++] = a[t];
        } else { // not even -> must be uneven.
            tmp[back--] = a[t];
        }
    }

    for (int i = 0; i < a.length; i++){
        a[i] = tmp[i];
    }
}

Second solution:

// linear time, stable, not in-place
private static void partition2(int[] a){
    int front = 0;

    // to make it stable, figure out where to start placing the last ones
    int back = 0;
    for (int i = 0; i < a.length; i++){
        if (a[i] % 2 == 0)
            back++;
    }

    int[] tmp = new int[a.length];

    for (int t = 0; t < a.length; t++){
        if (a[t] % 2 == 0){
            tmp[front++] = a[t];
        } else { // not even -> must be uneven.
            tmp[back++] = a[t];
        }
    }

    for (int i = 0; i < a.length; i++){
        a[i] = tmp[i];
    }
}

Third solution:

// linear time, not stable, in-place
private static void partition3(int[] a){
    // invariant: [ even | i ... j | uneven ]

    int front = 0;
    int back = a.length - 1;

    // no tmp array!!
    int tmp;
    while (front < back){
        if (a[front] % 2 == 0){
            front++;
        } else if (a[back] % 2 == 1){
            back--;
        } else { // number at front is uneven and number at back is even
            tmp = a[front];
            a[front] = a[back];
            a[back] = tmp;
            front++;
            back--;
        }
    }
}

Feedback I'm looking for:

Are these variable names OK?
Is the code semantically correct?
Can it be asymptotically faster?
Any other style feedback.


texts:
I'm trying to improve the following code for testability.

public function can_apply_extension()
{

    $search_dates = [
        Carbon::createFromTimestamp(strtotime($this->billing_verified_to))->subMonth(1),
        $this->billing_verified_to
    ];

    $record = ORM::factory('a model')
                 ->where('created_at', 'BETWEEN', $search_dates)
                 ->find();

    if( !$record->loaded() )
    {
        return true;
    }

    return false;

}

Here's how I think I can improve it:

public function can_apply_extension($search_from = null, $search_to = null)
{

    $search_from = is_null($search_from) ? Carbon::createFromTimestamp(strtotime($this->billing_verified_to))->subMonth(1) : $search_from;
    $search_to = is_null($search_to) ? $this->billing_verified_to : $search_to

    $search_dates = [$search_from, $search_to];

    $record = ORM::factory('a model')
                 ->where('created_at', 'BETWEEN', $search_dates)
                 ->find();

    if( !$record->loaded() )
    {
        return true;
    }

    return false;

}

I still have to mock ORM part. I think the only option is that I pass an object as a parameter or make a method that injects the ORM object.

Are there any other better ways? I'm aware of IoC container, but I can't use it in our current environment.

Update: Beside passing ORM as a parameter so that I can just swap it out, I found another workaround.

Since ORM::factory() actually returns an object, I was able to add a method and modify the factory method.

public function testing($bool)
{
    $this->_testing = $bool;
}

public function instead($when_this_passed, ORM $use_this_instead)
{
    $this->_instead_map[$when_this_passed] = $use_this_instead;
}

public function factory($name)
{
    if($this->_testing && array_key_exists($name, $this->_instead_map))
    {
        return $this->_instead_map[$name];
    }
    else
    {
        parent::factory($name);
    }
}


texts:
So I wrote this code a while ago, but i'm trying to optimize my code. Is there anything that I should definitely change here to save memory/time?
The code checks if the neuron is an output or hidden/input neuron, or a constant neuron (the last should stay unaltered).

the input is a decimal, decimal and array with decimals.
this.error is a dictionary containing error values
this.connections contains in, out, and self. Which all are arrays of connections
connection.xtrace is a dictionary in the form of {nodes: [], values : []}, nodes are instances and values are decimals

Here is the code:

  propagate: function(rate, momentum, target) {
    // Error accumulator
    var error = 0;

    momentum = momentum || 0;

    // Output nodes get their error from the enviroment
    if (this.type == 'output'){
      this.error.responsibility = this.error.projected = target - this.activation;
    } else { // the rest of the nodes compute their error responsibilities by backpropagation
      // error responsibilities from all the connections projected from this node
      for (var connection in this.connections.out) {
        var connection = this.connections.out[connection];
        var node = connection.to;
        // Eq. 21
        error += node.error.responsibility * connection.weight * connection.gain;
      }

      // Projected error responsibility
      this.error.projected = this.derivative * error;

      // Error responsibilities from all connections gated by this neuron
      error = 0;

      for(var conn in this.connections.gated){
        conn = this.connections.gated[conn];
        var node = conn.to;
        var influence = node.connections.self.gater == this ? node.old : 0;

        influence += conn.weight * conn.from.activation;
        error += node.error.responsibility * influence;
      }

      // Gated error responsibility
      this.error.gated = this.derivative * error;

      // Error responsibility
      this.error.responsibility = this.error.projected + this.error.gated;
    }

    if(this.type == 'constant') return;

    // Learning rate
    rate = rate || .3;

    // Adjust all the node's incoming connections
    for (var connection in this.connections.in) {
      var connection = this.connections.in[connection];

      var gradient = this.error.projected * connection.elegibility;

      for(var i = 0; i < connection.xtrace.nodes.length; i++){
        var node = connection.xtrace.nodes[i];
        var value = connection.xtrace.values[i];
        gradient += node.error.responsibility * value;
      }

      var deltaWeight = rate * gradient * this.mask + momentum * connection.previousDeltaWeight;

      connection.weight += deltaWeight;

      connection.previousDeltaWeight = deltaWeight;
    }

    // Adjust bias
    this.bias += rate * this.error.responsibility;
  },