texts: Is this PHP Email Form Secure from injections or other abuses?

texts:
I am new to PHP and put this contact page together using the w3Schools.com example as a guide along with a couple other sources. As far as I can tell, it works fine, but before I put it up on my page I would like to know if there is any potential for abuse. Any feedback is appreciated.

<!DOCTYPE html>

<?php include 'header.php'; ?>

<?php
require_once "Mail.php";
function spamCheck($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

if (isset($_REQUEST['email'])) {
    $mailcheck = spamCheck($_REQUEST['email']);
    if ($mailcheck == false) {
        echo "Invalid Input";
    } else {
        $from = $_REQUEST['email'];
        $body = "From\n" . $from . "\n\n"  .  $_REQUEST['message'];
        $to = "<REMOVED>";
        $subject = "$_REQUEST['subject'];
        $host = "<REMOVED>";
        $port = "<REMOVED>";
        $username = "<REMOVED>";
        $password = "<REMOVED>";
        $headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);
        $smtp = Mail::factory('smtp',array ('host' => $host,
             'port' => $port,
             'auth' => true,
             'username' => $username,
             'password' => $password));
        $mail = $smtp->send($to, $headers, $body);
        if (PEAR::isError($mail)) {
            echo("
" . $mail->getMessage() . "
");
        } else {
            echo("
Message successfully sent!
");
        }
}

} else {
    echo "
Send me an email if you like.

<form method='post' action='contact.php'>

Your Email: <input name='email' type='text'>
    Subject: <input name='subject' type='text'>

Message:

    <textarea name='message' rows='15' cols='40'>
    </textarea>

    <input type='submit'>

    </form>";
}
?>

<?php include "footer.php"?>


texts:
def json_response(response):
    assert response.code == 200, 'bad http response'
    return json.loads(response.body)

def custom_json_response(response):
    response = json_response(response)
    assert 'answer' in response, 'invalid custom json'
    return response['answer']

The code looks straightforward but I wonder if there any chance to rewrite it to achieve the following:

Replace json_response direct call with composition.
Code should not become a message from Sirius: everybody should still be able to understand it just without any efforts.
It should be robust (composition type safety) yet easy extensible.

Any ideas?


texts:
I'm implementing transpose in Haskell.

-- transpose [[1,2,3],[4,5,6],[7,8,9]]
-- [[1,4,7],[2,5,8],[3,6,9]]

Please give it a look. Note that I'm trying not to use any built-in functions (excluding map and ++):

transpose' :: [[a]] -> [[a]]
transpose' ys
   | null $ filter (not . null) ys = []
   | otherwise = [flatten' $ map head' ys] ++ transpose' (map tail' ys)

head' :: [a] -> [a]
head' []     = []
head' (x:xs) = [x]

tail' :: [a] -> [a]
tail' []     = []
tail' (x:xs) = xs

flatten' :: [[a]] -> [a]
flatten' as = foldl (\acc x -> acc ++ x)  [] as

Side note - I know that I could look at the Haskell source, but I appreciate the comments & thoughtful insights here.


texts:
This project is from the subreddit for beginner Python projects:

  The goal of the project is to create a program that allows the user to choose a time and date, and then prints out a message at given intervals (such as, every 3 seconds) that tells the user how much longer there is until the selected time. If the chosen time has passed, the program lets the user know. When selecting the month, the user has the option of entering the month name or number.

Is there a simple and succinct way to remove the microseconds from being printed out? And is there a better way to set up the while loop?

import datetime
import time

# a simple program that allows the user to pick a time and the program counts down
# until that time has been reached

month_strings = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec',]

# This function creates a datetime object chosen by the user and compares
# this object to the current time and counts down until that chosen time
def count_down():

    year = int(raw_input('What is the year of the date? '))
    month = raw_input('What is the month of the date? ')
    # this part allows the user to type in the month as a string or integer
    if len(month) < 3:
        month = int(month)
    else:
        month = (month_strings.index(month[0:3].lower()) + 1)
    day = int(raw_input('What is the day of the month? '))
    hour = int(raw_input('What is the hour according to a 24 hour clock? '))
    minute = int(raw_input('At which minute? '))
    second = int(raw_input('At which second? '))

    chosen_time = datetime.datetime(year,month,day,hour,minute,second)

    print 'The time you chose is: ' + chosen_time.__str__()

    current_time = chosen_time.now()
    # If the time has passed, let the user know and exit the program
    if chosen_time < chosen_time.now():
        print 'This time has passed.'
        exit()

    else:
        # This loop prints how much time is left until the chosen time every 3 seconds
        while True:
            time_difference = (chosen_time - chosen_time.now())
            print str(time_difference) + ' until the time.'
            time.sleep(3)
            if chosen_time <= chosen_time.now():
                break
        print "It's time!"
        exit()

if __name__ == '__main__':
    count_down()


texts: Providing JavaScript Configuration (Laravel config() style)

texts:
This may be better suited on Stackoverflow, in which case, please let me know and I will move it over...

Background

Consider the following file structure:

/config
│   index.js
│   app.js
│   api.js
│   ...

The purpose of the above is to provide global configuration throughout a static frontend application, including within the webpack build configuration.

My original intention was to provide a global function called config which would behave much like the Laravel config function.

For example:

config('app.name') would return the name property from the app.js configuration file

Instead, my solution simply provides an object which is used like so:

config.app.name
config.api.url

My Code

The way I am doing this is extremely simple:

/config/index.js

module.exports = {
    app: require('./app'),
    company: require('./company'),
    api: require('./api'),
    locales: require('./locales')
};

/config/app.js

module.exports = {
    name: 'Foobar',
    // etc...
};

Example Usage

import config from './config';

console.log(config.app.name);

My Question

Whilst I am not bothered whether /config provides an object, or a function, I am unsure as to whether the solution I have put together is the cleanest way of achieving this...

I appreciate this question might be considered 'subjective' but does anyone have any alternative ways in which they would go about doing this?


texts: Reading transactions from a file and writing them to a database table

texts:
I am learning Node.js and I would like to see if I'm using it correctly:

var mysql = require('mysql');
var fs = require('fs');

var connectionProps = JSON.parse(fs.readFileSync('connection.json', 'utf8'));

var connection = mysql.createConnection({
  host: connectionProps.host,
  user: connectionProps.user,
  password: connectionProps.password,
  database: connectionProps.database
});

connection.connect();

function checkErr(err) {
  if (err) {
    connection.end();
    throw err;
  }
}

connection.query('SELECT * FROM TRANSACTION_TYPE', function(err, rows, fields) {
  checkErr(err);

  var typeNameToId = {};

  for (var i = 0; i < rows.length; i++) {
    typeNameToId[rows[i].NAME] = rows[i].ID;
  }

  fs.readFile(process.argv[2] + '.csv', 'utf8', function(err, content) {
    checkErr(err);

    var data = [];
    var lines = content.split(/\r\n?|\n/);

    for (var i = 0; i < lines.length; i++) {
      if (lines[i].trim() === '') {
        continue;
      }

      data.push(lines[i].split(','));
      var typeName = data[data.length - 1][2];
      data[data.length - 1][2] = typeNameToId[typeName];
      var dateTokens = process.argv[2].split('-');
      data[data.length - 1].push(new Date(dateTokens[0], dateTokens[1] - 1, dateTokens[2]));
    }

    connection.query(
      'INSERT INTO TRANSACTION (DESCRIPTION, AMOUNT, TRANSACTION_TYPE_ID, TRANSACTION_DATE) VALUES ?',
      [data],
      function(err) {
        connection.end();

        if (err) {
          throw err;
        }
      }
    );
  });
});


texts: Java sort by selection: which is better in regards to readability and efficiency?

texts:
Which algorithm do you think is better in regards to readability and efficiency?

selection():

public static int[] selection(int[] tab) {
    int minor;
    int aux;
    for (int i=0; i<tab.length-1; i++) {
        minor = tab[i];
        for (int j=i+1; j<=tab.length-1; j++) {
            if (tab[j] < minor) {
                aux = tab[j];
                tab[j] = minor;
                minor = aux;
            }
        }
        tab[i] = minor;
    }
    return tab;
}

otherSelection():

public static int[] otherSelection(int A[]) {
    int i, j, minor, pos, tmp;
    for (i = 0; i < A.length - 1; i++) {
        minor = A[i];
        pos = i;
        for (j = i + 1; j < A.length; j++){
            if (A[j] < minor) {
                minor = A[j];
                pos = j;
            }
        }
        if (pos != i){
            tmp = A[i];
            A[i] = A[pos];
            A[pos] = tmp;
        }
    }
    return A;
}


texts: x64 Assembly zeroing an array (8 bytes at a time)

texts:
Is there a better way of implementing this other than using simd instructions?

What is the best way of dealing with arrays not divisible by 8, as in the code where if there are less than 8 bytes left to zero they just get zeroed 1 by 1?

Maybe it is faster to check how many bytes there are left and then zero them 2 bytes or 4 bytes at a time?

Does the checking outweigh the cost of doing them 1 by 1?

This is just a test for me to try to learn assembly so any, even small, improvements and tips are greatly appreciated.

Thank you

.code
ZeroArray proc
    cmp edx, 0
    jle Finished ; Check if count is 0

    cmp edx, 8
    jl SetupLessThan8Bytes ; Check if counter is less than 8

    mov r8d, edx ; Storing the original count
    shr edx, 3   ; Bit shifts the counter to the right by 3 (equal to dividing by 8), works because 2^3 is equal to 8
    mov r9d, edx ; Stores the divided count to be able to check how many single byte zeros the program has to do

MainLoop:
    mov qword ptr [rcx], 0 ; Set the next 8 bytes (qword) to 0
    add rcx, 8             ; Move pointer along the array by 8 bytes
    dec edx                ; Decrement the counter
    jnz MainLoop           ; If counter is not equal to 0 jump to MainLoop

    shl r9d, 3   ; Bit shifts the stored divided counter to the left by 3 (equal to multiplying by 8), 2^3 again
    sub r8d, r9d ; Subs the counts from eachother, if it equals zero all bytes are zeroed, otherwise r8d equals the amount of bytes left
    je Finished

SetFinalBytesLoop:
    mov byte ptr [rcx], 0 ; Sets the last byte of the array to 0
    inc rcx
    dec r8d
    jnz SetFinalBytesLoop

Finished:
    ret

SetupLessThan8Bytes:
    mov r8d, edx ; Mov the value of edx into r8d so the same code can be used in SetFinalBytesLoop
    jmp SetFinalBytesLoop

ZeroArray endp
end


texts: Optimizing mathematical index calculation function

texts:
I have made a function which calculates the index of a point to which an arbitrary point on a polygon made of XY points belong.

This is a visual representation:

And this is the function I made:

stock GetNodeIndexFromPolygonIndex(polygonid,Polygon_Size)
{
    new polid = (polygonid - (polygonid % 2));
    new mid = Polygon_Size/2;
    if(polid > mid)
    {
        polid /= 2;
        return (mid - (++polid));
    }
    else
    {
        polid /= 2;
        if(polid == 0)
        {
            return 0;
          }
        return --polid;
    }
}

Is there anything I can optimize here?  This function is going to be called ~2000 times in the worst case in one run on a single threaded application. I would like this to be as optimal as possible.  Is it already?


texts: Pythonic solution to display multi-dimensional tuple as a tree

texts:
I would like to show the tree-like structure contained in a multi-dimensional tuple by using the set of graphical glyphs that exist in Unicode fonts (e.g. \u2500, \u2502, \u2514 and others). Here is an example of the kind of output, I'm talking about:

>>> showtree('(01, (02,  03, 04), 05, ((06, 07), 08), (09, (10, 11), (12, 13), 14), 15)')
┬─01
├─┬─02
│ ├─03
│ └─04
├─05
├─┬─┬─06
│ │ └─07
│ └─08
├─┬─09
│ ├─┬─10
│ │ └─11
│ ├─┬─12
│ │ └─13
│ └─14
└─15

Ideally, empty items, multi-words items, extra spaces around commas or parenthesis, as well as unbalanced parenthesis should be managed correctly, as in the following example:

>>> showtree('( A, B multi-word item , (C,D), ( E  , ,  F ), G  )'))
┬─A
├─B multi-word item
├─┬─C
│ └─D
├─┬─E
│ ├─
│ └─F
└─G

I came up with a solution that works quite well (the examples above have been generated with it) but the implemented algorithm is not very elegant, and the code not very pythonic :

def showtree(string):
    """display multidimensional tuple as a tree"""
    glyphs = ['\u252C\u2500','\u251C\u2500','\u2514\u2500','\u2502 ']
    tree, glyph, item = [], [], []
    for char in string:
        if char in ',)' and item:                                   # add glyph prefix and current item to tree
            tree.append(glyph + [''.join(item).strip()]); item = []
        if char == ',':                                             # update glyph prefix for new item in sublist
            glyph = [glyphs[3]] * (len(glyph)-1) + [glyphs[1]]
        elif char == ')':                                           # update glyph prefix for last item in sublist
            tree[-1][-2] = glyphs[2]; glyph = glyph[:-1]
        elif char == '(':                                           # update glyph prefix for first item in sublist
            glyph.append(glyphs[0])
        else:                                                       # other chars are simply added to current item
            item.append(char)
    return '\n'.join(''.join(node) for node in tree)

So I would like to get some ideas for an improved implementation, maybe using regular expressions or other advanced parsing techniques. Thank you very much for any hint...


texts: JavaScript/HTML web application - user interface logic

texts:
I am writing a JavaScript/HTML driven web application. For the user interface, I am not completely sure that my JavaScript is 'OK'. Mainly, I switch between "modes" by assigning a placeholder variable to a new function, which changes what the onclick event does for items in a table (either open, edit, or move them).

Am I breaking any code styles? Is my script hard to follow or understand? Is it unconventional for me to assign bookmarkEventMapping to another function later on in my code, using it as a placeholder? What can I do differently? Can you recommend any material that I could read to write clearer JavaScript?

(Please note that this is a WIP)

var bookmarkEventMapping = function() {};//placeholder
/*
    ...
    more JavaScript, which creates &lt;li&gt; elements
    that all have onclick events, example:
        element.addEventListener(
            "click",
            function(e) { bookmarkEventMapping(e); }
        );
    ...
*/
function initModeMenu() {//called in &lt;body&gt; onload event
    var modeNames = ["normal","edit","move"];//the order in HTML menu
    for(var i = 0; i &lt; 3; i++) {,
        var node = document.getElementById("modeMenu").children[i];
        bookmarkActions[ modeNames[i] ].node = node;
        node.dataset["action"] = modeNames[i];
        node.addEventListener(
            "click",
            function() {
                bookmarkActions.setCurrentMode( this.dataset["action"] );
            }
        );
    }
    bookmarkActions.setCurrentMode("normal");
}
var bookmarkActions = {
    "currentMode":"normal",
    "setCurrentMode":function(modeName) {
        var prevMode = bookmarkActions.currentMode;
        bookmarkActions[ prevMode ].exitMode();
        bookmarkActions[ prevMode ].node.classList.remove("selected");
        bookmarkEventMapping = bookmarkActions[ modeName ].eventMapping;
        bookmarkActions[ modeName ].node.classList.add("selected");
        bookmarkActions.currentMode = modeName;
    },
    "normal":{
        "initMode":function() {
        },
        "exitMode":function() {
        },
        "eventMapping":function(ev) {
        }
    },
    "edit":{
        "initMode":function() {
        },
        "exitMode":function() {
        },
        "eventMapping":function(ev) {
            if(ev.type == "click")
            {
                bookmarkActions.edit.selectBookmark( ev.target );
            }
        },
        "selectBookmark":function(itemNode) {
            itemNode.dataset['bookmarkItemId'];
            itemNode.classList.add("editing");//.remove later
        }
    },
    "move":{
        "initMode":function() {
        },
        "exitMode":function() {
        },
        "eventMapping":function(ev) {
        }
    }
};

Below is a relevant snippet of HTML from the

<menu id="modeMenu">

Normal

Edit

Move

</menu>


texts:
If you came here because of the title, chances are your server isn't down. But if by some miraculous reason it is:
A while ago, I posted a program that would ssh and ping all the servers at work. I got some very good feedback and went ahead and rolled with it.
Here's what I came up with:

It now is much more readable, in my opinion
Pings the servers after SSHing into them
Then if it finds one of the servers to be offline, or errors out connecting, writes data to a .txt file containing the server name, and the user who deployed the program.

I of course will be leaving some information off due to security.
Source code:
#!/usr/local/bin/ruby

require 'rubygems'
require 'net/ssh/gateway'
require 'work/mail/gem'
require 'etc'

def mail_error(e)
  x = AD::Mail.new
  x.from        = "email@email.email"
  x.to          = "email@email.email"
  x.subject     = "Server Loading Error"
  x.body        = e.message
  x.send
end

def scanning_all_servers(server)
  begin
    check = Net::SSH.start(server, @username, :password => @password)
    cmd = "ping -c 1 #{server}"
    check.exec!(cmd)
  rescue => e
    mail_error(e)
    :error
    write_data(server)
  end
end

def server_status(server)
  result = scanning_all_servers(server)

  message_server_online = /1 received, 0% packet loss/i
  message_server_offline = Regexp.union('0 recieved, +1 errors', 'Connection closed')

  result =~ message_server_online  ? :online  :
  result =~ message_server_offline ? :offline : :error
end

def status_message(server, status)
  status == :online  ? "server online: #{server}"  :
  status == :offline ? "[#{Time.now}] SERVER OFFLINE: #{server}" :
                       "[#{Time.now}] Error loading server: #{server}."
end

def write_data(server)
  x = "[#{Time.now}]: Server: #{server} down. Checked by #{@username}. ------------"
  if File.exist?("path/to/log")
     File.open("path/to/log", "a+"){ |s| s.write(x) }
  else
    new_file = File.new("path/to/log", "w")
    new_file.puts(x)
    new_file.close
  end
end

@username = Etc.getlogin
@password = nil

server_list = %w(all of our servers)

server_list.each do |server|
  status = server_status(server)
  puts status_message(server, status)
end

Example of usage:

server online: server
server online: server
SERVER OFFLINE: server
server online: server
server online: server
server online: server
server online: server
server online: server
Error loading server: server
server online: server
server online: server
server online: server
server online: server
server online: server
server online: server
server online: server
server online: server
server online: server
server online: server
server online: server

Example of log:

[2015-12-14 06:11:41 -0600]: Server: server down. Checked by user. ------------
[2015-12-14 06:11:45 -0600]: Server: server down. Checked by user. ------------

What I would like to know:

Is there any better ways to write data to files?
Is there also more readable syntax to use here?


texts: JavaScript: Find the number in an array which is closest to an given number

texts:
It's actually an exercise from an Assembly-course I'm doing:

  Find closest number.

Add the following into the data section:

nums  dd  23h,75h,111h,0abch,443h,1000h,5h,2213h,433a34h,0deadbeafh

This is an array of numbers.

Write a program that receives a number x as input, and finds the dword
inside the array nums, which is the closest to x. (We define the distance
between two numbers to be the absolute value of the difference: |a-b|).

Example:

For the input of 100h, the result will be 111h, because 111h is closer to
100h than any other number in the nums array. (|100h - 111h| = 11h).

Full exercise-sheet on GitHub.

Because it's easier for me to develop the algorithm in more familiar JavaScript and because it's a nice exercise I have done it in JavaScript first. Now the only thing left to do is to find an Assembly-specific way.

Anyway: Here's the JavaScript-code I've written to solve the task.

let nums = [ 0x23, 0x75, 0x111,
             0xabc, 0x443, 0x1000,
             0x5, 0x2213, 0x433a34,
             0xdeadbeaf
           ];
let given = 0x100; // { 256 }10

// --- The Relevant Part --------------------------------------
function findIndexClosestNumber(arrayToSearch, compareNumber) {
  'use strict';
  let closest = compareNumber;
  let indexClosest = 0;

  arrayToSearch.forEach((currentNumber, index) => {
    let currentDistance =
      Math.abs(compareNumber - currentNumber);

    if (currentDistance < closest) {
      indexClosest = index;
      closest = currentDistance;
    }
  });

  return indexClosest;
}
// -------------------------------------------------------------

// ------ Testing & Demo ---------------------------------------
console.log(findIndexClosestNumber(nums, given));

nums.length = 0;

for (let i = 0; i <= 90; i += 10) {
  nums.push(i);
}

console.log(nums);

for (let i = 0; i < 10; i++) {
  var randomNumber = Math.floor((Math.random() * 100));

  console.log('%s gives index %s', randomNumber,
    findIndexClosestNumber(
      nums, randomNumber));
}

Can I expect my implementation to solve the task in a correct way?
Was it a good idea to initialize the closest-variable with the value of the compareNumber-parameter?
Was it a good idea to check for currentDistance < closest? Or should I have used currentDistance <= closest?

Currently the first occurrence-index is returned in case the number is contained multiple times. Using <= it would return the last occurrence-index.

I'm not sure what's the better practice.

Any other comments concerning structure, naming, used methods, algorithm appreciated too.

And if someone knows a cool JavaScript specific way to solve the task: That would interest me too. ;)


texts: Releasing retained objects inside dealloc

texts:
When releasing objects that might have been retained during the app's lifetime, how do you check if the object really exists and prevent releasing a nil object?

Here's how I'm doing it:

- (void)dealloc{
    if(account_)
        [account_ release];
    account_ = nil;
    [super dealloc];
}


texts: BingWallpapers: Fetches and applies the image of the day from Bing as the wallpaper

texts:
I have written a small desktop program nabeelomer/BingWallpapers in Haskell. This is my first time writing Haskell.

I was wondering how I can make the code use more functional programming features/idioms/patterns.

Any other suggestions on how to improve the code are also welcome.

-- Copyright (C) Nabeel Omer 2017
-- See the LICENSE file for the license
--

import Network.HTTP.Conduit
import System.Process
import qualified Data.ByteString.Lazy.Char8 as L8
import GHC.IO.Exception

main :: IO ()
main = do
    -- using http://muzzammil.xyz/git/bing/
    metadata <- get "http://cdn.muzzammil.xyz/bing/bing.php?format=text&cc=IN"

    -- Guaranteed by the API
    putStrLn $ (split '>' $ (lines $ L8.unpack metadata)!!1)!!1
    let url = (lines $ L8.unpack metadata)!!0
    picture <- get $ (split '>' url)!!1

    L8.writeFile "/dev/shm/Bing-Wallpaper" picture
    exitcode <- setWallpaper "/dev/shm/Bing-Wallpaper"

    print exitcode
    return ()

-- From StackOverflow
split :: Eq a => a -> [a] -> [[a]]
split d [] = []
split d s = x : split d (drop 1 y) where (x,y) = span (/= d) s

get :: String -> IO L8.ByteString
get url = simpleHttp url

setWallpaper :: String -> IO GHC.IO.Exception.ExitCode
setWallpaper uri = system $ "gsettings set org.gnome.desktop.background picture-uri file://" ++ uri


texts:
Given the Josephus Problem.

  Josephus Problem

  N people (numbered 1 to N) are standing in a circle. Person 1 kills Person 2 with a sword and gives it to Person 3. Person 3 kills Person 4 and gives the sword to Person 5. This process is repeated until only one person is alive.

  Task:
  (Medium) Given the number of people N, write a program to find the number of the person that stays alive at the end.
  (Hard) Show each step of the process.

  (The description from Sololearn application)"

This is my code. The forEachRemaining method solution is correct? I have to do something with this inherited method, but it has no meaning.

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

class CyclicIterator implements Iterator {

private final List list;
private Iterator iterator;

public CyclicIterator(List list) {
    this.list = list;
    initIterator(list);
}

private void initIterator(List list) {
    this.iterator = list.iterator();
}

@Override
public boolean hasNext() {
    return !list.isEmpty();
}

@Override
public Object next() {
    if (!this.iterator.hasNext())
        initIterator(list);
    return this.iterator.next();
}

@Override
public void remove() {
    this.iterator.remove();
}

@Override
public void forEachRemaining(Consumer action) {
    throw new UnsupportedOperationException("This method has no meaning in CyclicIterator class!");
}
}

public class JosephusProblem {

public static void main(String[] args) {
    execution(0);
    execution(1);
    execution(2);
    execution(4);
    execution(6);
}

private static void execution(int members) {
    if (members < 1) {
        System.out.println("The parameter (members) has to be bigger than 0!");
        return;
    }
    if (members == 1) {
        System.out.println("There is olny one person, so he is the survivor. Peaceful version! :)");
        return;
    }
    LinkedList<Integer> list = new LinkedList();
    for (int index = 0; index < members; index++)
        list.add(index + 1);
    Iterator<Integer> it = new CyclicIterator(list);
    System.out.println("For " + members + " members: ");
    while (members-- > 1) {
        System.out.print(it.next() + " kills " + it.next() + ", ");
        it.remove();
    }
    System.out.println("\n The survivor: " + it.next());
}

}


texts: Code review for a collection manipulation tool in Javascript

texts:
As I was working with .NET, I started wondering how I would implement the LINQ methods syntax in Javascript. So here is my first try; is there a more elegant, or more performant, way to write this code?

// usage : the functions take a predicate function as input and modify the array accordingly
var collection;
(function() {
    "use strict";

    var Collections = function(array) {
        this.array = array;
    };

    Collections.prototype = {
        //The predicate should return a boolean value
        //Keeps all elements that match the given function
        where: function(predicate) {
            var newArray = [];
            this.each(function(index, item) {
                if (predicate(item)) {
                    newArray.push(item);
                }
            });
            this.array = newArray;
            return this;
        },
        //The predicate should return a boolean value
        //Returns true if one element or more matches the predicate
        any: function(predicate) {
            var newArray = [];
            this.each(function(index, item) {
                if (predicate(item)) {
                    newArray.push(item);
                }
            });
            return newArray.length > 0;
        },
        //The predicate should return an object
        //Replaces all elements by the object generated by the predicate
        select: function(predicate) {
            var newArray = [];
            this.each(function(index, item) {
                newArray.push(predicate(item));
            });
            this.array = newArray;
            return this;
        },
        //Returns the current (modified) array
        getArray: function() {
            return this.array;
        }
    };

    collection = function(array) {
        return new Collections(array);
    };
} ());

And here is an exemple of use:

var myArray = [{name: 'chicken', size: 1}, {name: 'cat', size: 2},
{name: 'dog', size: 3}, {name: 'horse', size: 4}, {name: 'skunk', size: 2}];
var newArray = collection(myArray)
    .where(function(animal){
        return animal.size == 2
    })
    .select(function(animal){
        return {
            animalName: animal.name,
            category: 'mammal',
            size: 'small'
        }
    })
    .getArray()
// new array : [{animalName: 'cat', category: 'mammal', size: 'small}, {animalName: 'skunk',
// category: 'mammal', size: 'small'}]


texts:
I wrote a simple prime sieve in Python. But it ended up looking... ugly. I included a few of the most basic optimizations. When posting this question SE suggested a bunch of questions on the same topic, which lead me to some improvements. But few were in generator form.

It's the optimizations' fault.
Unfortunately I can't continue an outer loop from an inner loop, like I can in JavaScript. I very much disagree with Guido here, as it makes the inner loop clunky.

from itertools import count

def sieve():
    primes = [2]
    for candidate in count(start=3, step=2):
        cont = False
        n = 0
        while primes[n]**2 <= candidate:  # You only need to check up to the square root of a number.
            if candidate % primes[n] == 0:
                cont = True  # outer
                break
            n = n + 1
        if cont:
            cont = False
            continue
        yield primes[-1]
        primes.append(candidate)

Can we make this more concise without changing the basic logic?
For example this is extremely concise, but it doesn't have some of the optimizations my code does.

For fun, I wrote the same logic in Javascript. This looks cleaner due to being able to continue an outer loop. But the lack of negative indices is a step backwards.

  function* sieve() {
    let primes = [2]
    counter: for (let candidate = 3;; candidate+=2) {
        for (let n = 1; primes[n]**2 <= candidate; n++)
            if (candidate % primes[n] == 0)
                continue counter
        yield primes[primes.length - 1]
        primes.push(candidate)
    }
}


texts: Check if a given linked list is palindrome

texts:
I am solving interview questions from here.

Problem :Given a singly linked list, determine if its a palindrome. Return 1 or 0 denoting if its a palindrome or not, respectively.
Notes:Expected solution is linear in time and constant in space.
For example,
List 1-->2-->1 is a palindrome.
List 1-->2-->3 is not a palindrome.

How can this solution be improved ?
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def __init__(self,seq):
        """prepends item of lists into linked list"""
        self.head = None
        for item in seq:
            node = ListNode(item)
            node.next = self.head
            self.head = node

    def list_palin(self):
        """ Returns 1 if linked list is palindrome else 0"""
        node = self.head
        fast = node
        prev = None
        ispal = True

        # prev approaches to middle of list till fast reaches end or None
        while fast and fast.next:
            fast = fast.next.next
            temp = node.next   #reverse elemets of first half of list
            node.next = prev
            prev = node
            node = temp

        if fast:  # in case of odd num elements
            tail = node.next
        else:    # in case of even num elements
            tail = node

        while prev and ispal:
            # compare reverse element and next half elements
            if prev.val == tail.val:
                tail = tail.next
                prev = prev.next
                ispal = True
            else:
                ispal = False
                break

        if ispal :
            return 1
        else :
            return 0
# Test Cases
listpal_1 = Solution([7, 8, 6 ,  3 , 7 ,3 , 6, 8, 7])
assert listpal_1.list_palin()
listpal_2 = Solution([6 , 3 , 7, 3, 6])
assert listpal_2.list_palin()
listpal_3 = Solution([3, 7 ,3 ])
assert listpal_3.list_palin()
listpal_4 = Solution([1])
assert listpal_4.list_palin()


texts: Compile a string into a callable object in C++: a simple JIT based on system, dlopen and dlsym

texts:
Today I discovered that it is possible to dynamically load code at runtime via dlopen and dlsym (and similar utilities on Windows as well). So the obvious next step was to call the compiler through system to build a piece of code into a shared object, which is then loaded to obtain a function pointer. All wrapped in a template class which becomes callable once "compiled".
The code is pretty much at an embryo state (less than 100 lines including the example), but it works and shows the idea, therefore I would love to hear your opinion.
This thing looks sooo simple and yet sooo powerful that I would really be surprised to be the first one having thought about it.
// compile with something like: g++ -std=c++20 jit.cpp -ldl

#include <dlfcn.h>
#include <cstdlib>
#include <iostream>
#include <filesystem>

template< class >
class JitFunc;

template< class R, class... Args >
class JitFunc<R(Args...)> {
  public:
  using Func = R(Args...);
  using result_type = R;

  private:
  std::string soName;

  void * dlso = nullptr;
  Func * func = nullptr;

  public:
  // remember to call compile() anytime you modify these strings
  std::string name;                 // the function name, which should also be found in the source
  std::string source;               // the source code, remember to use extern "C"
  std::string cxx = "/usr/bin/g++"; // the compiler executable
  std::string soPath = "/tmp";      // where to store the shared object (ideally a ramdisk)
  std::string flags;                // custom compiler flags which you may need

  JitFunc(std::string funcName):
    name(std::move(funcName))
  {}

  ~JitFunc() {
    close();
    removeSo();
  }

  result_type operator()(Args && ... args) const {
    return func(std::forward<Args>(args)...);
  }

  void compile() {
    close();
    removeSo();

    soName = soPath + "/jit_" + name + ".so";
    std::string cmd = cxx;
    auto push = [&cmd](std::string s) { cmd += " "; cmd += std::move(s); };
    push(flags);
    push("-shared -fPIC -o");
    push(soName);
    push("-xc++ - << EOF\n");
    push(source);
    push("\nEOF\n");

    std::system(cmd.c_str());

    dlso = dlopen(soName.c_str(), RTLD_NOW);
    if (!dlso) throw std::runtime_error(dlerror());
    func = (Func*) dlsym(dlso, name.c_str());
    if (!func) throw std::runtime_error(dlerror());
  }

  void close() {
    if (dlso) {
      dlclose(dlso);
      dlso = nullptr;
      func = nullptr;
    }
  }

  void removeSo() {
    if (!soName.empty()) {
      std::filesystem::remove(soName);
      soName.clear();
    }
  }

};

int main() {
  JitFunc<int(int)> f("timestwo");
  f.source =
R"CODE(
#include <iostream>
extern "C" {
int timestwo(int a) { std::cout << "hello from timestwo" << std::endl; return 2*a; }
}
)CODE"; // using a string literal to avoid having to escape all the double quotes

  f.compile();
  std::cout << f(2) << std::endl;

  return 0;
}


texts:
First time writing a "game" in a sense. Used a functions approach, it's simple, looking for a review of the way it's written and of course looking for how should it be written. Also using random for first time (I know I'm a nube).

#Number Guess Game

import random

def gameNumber():
     while True:
        difficulty = input("Type: E, M, H for easy, medium, or hard number range:\n").lower()

        if difficulty == 'e':
            return random.randint(0,20)

        elif difficulty == 'm':
            return random.randint(0,50)

        elif difficulty == 'h':
            return random.randint(0,100)

        else:
            print("Incorrect input")

def numberGuessGame():
    number = gameNumber()
    while True:
        try:
           guess = int(input("Your guess: "))
           if number == guess:
               print("Correct guess!\n")
               return numberGuessGame() if input("play again?(y/any key to exit) ").lower() == 'y' else 0
           print("Too High" if number < guess else "Too Low")
        except ValueError:
            print("must be an integer value\n")

def main():
    numberGuessGame()

if __name__ == '__main__':
    main()


texts: Will this converstion to/from fixed point cause me to lose precision?

texts:
I have a situation where I have a fixed point number that I want to convert to and from a floating point number.  Specifically it is the SANE_Fixed type from the SANE API.  Here is the what the documentation says (I grabbed the bits I think are relavant):

  SANE_Fixed is used for variables that can take fixed point values in the range -32768 to 32767.9999 with a resolution of 1/65535.

#define SANE_FIXED_SCALE_SHIFT  16
typedef SANE_Word SANE_Fixed;

  The macro SANE_FIXED_SCALE_SHIFT gives the location of the fixed binary
  point. This standard defines that value to be 16, which yields a
  resolution of 1/65536.

  SANE_Word: A word is encoded as 4 bytes (32
  bits). The bytes are ordered from most-significant to
  least-significant byte (big-endian byte-order).

So, over the wire I get 4 bytes which I convert into a .Net int like this (you can guess what GetByte and SendByte do):

public int GetWord()
{
    int value = 0;
    value += (GetByte() << 24);
    value += (GetByte() << 16);
    value += (GetByte() << 8);
    value += (GetByte() << 0);
    return value;
}

Then I want to convert that int into a floating point number (I went for decimal) like this:

public decimal ToFloating(int source)
{
    decimal value = source / ((decimal)(1 << 16));
    return value;
}

And I will also need to go back the other way so I would convert to fixed like this:

public int ToFixed(decimal source)
{
    decimal value = source * ((decimal)(1 << 16));
    return (int)value;
}

And then convert to four bytes like this to send it like so:

public void SendWord(int word)
{
    SendByte((word >> 24) & 0xff);
    SendByte((word >> 16) & 0xff);
    SendByte((word >> 8) & 0xff);
    SendByte((word >> 0) & 0xff);
}

So, here is my question:

This seems a pretty simplistic implementation to me and I read lots of stuff on the internet about creating custom fixed point classes and whatnot but, given the constraints of my scenario, is this a safe approach to take?  Could I lose precision and is the maths correct?


texts: Simple react app to fetch and display data

texts:
This is my first react app and it was for a job interview challenge. The app is really simple and it works, but although I don't think I'm gonna get it, could I have some feedback about what is wrong and how could I improve it?

***I already submitted this, so is not cheating, I just need to know how can I be better

The way requests are being made is correct?
Should planetas object be populated this way? Is there a better approach? (thats how I managed to make it work)
planetas.films was taking too long to be loaded and giving me a map is undefined problem, is my conditional render bad?
And anything else you find to be wrong

service:

import axios from 'axios'

const PLANETS_URL = 'https://swapi.co/api/planets'
const FILMS_URL = 'https://swapi.co/api/films'

const GetPlanets = async () => {
    let planetas = {}

    await axios.get(`${PLANETS_URL}`)
        .then((p) => {

            planetas = p.data.results

            return axios.get(`${FILMS_URL}`)
        }).then((f) => {

        planetas.forEach((pv, i) => {
            pv.films.forEach((pf, j) => {
                f.data.results.forEach((el, k) => {
                    if(pf === el.url){
                        pv.films[j] = el
                    }
                })
            })
        })
        })
        .catch((e) => {
            console.error(e);
        })

    return planetas
}

export default GetPlanets

component:

import React, { useState, useEffect } from 'react'
import GetPlanets from '../services'
import { Loader, Container, Name, Info, Button } from '../components'

export default function Planetas () {

  const [ counter, setCounter ] = useState(1)
  const [ planetas, setPlanetas ] = useState([])
  const [ toShow, setToShow ] = useState({})

  useEffect( () => {

    const fetchPlanetas = async () => {
      const planetas = await GetPlanets()

      setPlanetas(planetas)
      setToShow(planetas[0])
    };
    fetchPlanetas()
  }, [])

  const handleClick = () => {
    if(counter === (planetas.length - 1)){
      setCounter(0)
      setToShow(planetas[counter])
    } else {
      setCounter(counter + 1)
      setToShow(planetas[counter])
    }
  }

  if(typeof toShow.films !== 'undefined') {
    return (
      <Container>
        <Name>{toShow.name}</Name>
        <Info>

Population: {toShow.population}

Climate: {toShow.climate}

Terrain: {toShow.terrain}

        Featured in Films:

        {toShow.films.map((film, key) => (

{film.title}

           ))}

        </Info>
        <Button onClick={handleClick}>Next</Button>
      </Container>
     )
  } else {
    return(
      <Loader>Loading...</Loader>
    )
  }
}


texts: Returning a description based on a minimum and a maximum value

texts:
I need to return a "human readable" description based on a minimum and a maximum value. Note that the minimum is included in the condition, but the maximum is excluded -- so for instance if the parameters are 6 and 9, the valid values are 6, 7 and 8, but not 9. The maximum value is also nullable.

I started out with nested switch statements, but I quickly abandoned them because they were unreadable and would be hard to maintain. Instead I kept the original switch, but moved each nested switch to its own method.

Note that the code currently supports only a handful of cases, but these are the ones currently needed. Though it is possible others will need to be added in the future and thus I'd like to have something that would be easy to maintain.

The code as featured below doesn't feel "mature" to me, but I don't see another solution right now. Perhaps the Strategy Pattern could be a solution, but it feels a bit overkill for this purpose.

internal class InterpretationRetriever
{
    public static string Execute(int minimum, int? maximum)
    {
        switch (minimum)
        {
            case 0:
                return MinimumIsZero(maximum);
            case 1:
                return MinimumIsOne(maximum);
            case 3:
                return MinimumIsThree(maximum);
            case 5:
                return MinimumIsFive(maximum);
            case 6:
                return MinimumIsSix(maximum);
            case 9:
                return MinimumIsNine(maximum);
            case 10:
                return MinimumIsTen(maximum);
            default:
                return null;
        }
    }

    private static string MinimumIsZero(int? maximum)
    {
        if (!maximum.HasValue)
        {
            return "Zero or more";
        }

        switch (maximum)
        {
            case 1:
                return "Less than one";
            case 3:
                return "Less than three";
            case 5:
                return "Less than five";
            default:
                return null;
        }
    }

    private static string MinimumIsOne(int? maximum)
    {
        if (!maximum.HasValue)
        {
            return "One or more";
        }
        return null;
    }

    private static string MinimumIsThree(int? maximum)
    {
        if (!maximum.HasValue)
            return null;

        switch (maximum)
        {
            case 6:
                return "From three to five";
            default:
                return null;
        }
    }

    private static string MinimumIsFive(int? maximum)
    {
        if (!maximum.HasValue)
            return null;

        switch (maximum)
        {
            case 10:
                return "From five to nine";
            default:
                return null;
        }
    }

    private static string MinimumIsSix(int? maximum)
    {
        if (!maximum.HasValue)
            return null;

        switch (maximum)
        {
            case 9:
                return "From three to eight";
            default:
                return null;
        }
    }

    private static string MinimumIsNine(int? maximum)
    {
        if (!maximum.HasValue)
        {
            return "Nine or more";
        }
        return null;
    }

    private static string MinimumIsTen(int? maximum)
    {
        if (!maximum.HasValue)
        {
            return "Ten or more";
        }
        return null;
    }
}


texts:
This is the code I wrote to compute the newton's square root of a number.

I aimed for extreme clarity over efficiency and I have put an abundant docstring at the start of the newton_sqrt function where I describe the main formula and explain all the parameters.

This function is not meant to be fast (standard library is 4x times faster and more accurate), I wrote just to learn some good math coding techniques in Python.

This was written in Python 3 but is fully compatible with Python 2.
I created constants for the error messages. Is that a good practice? Or should I just write the errors down verbatim when need occurs?
I chose n / 2 as my initial guess. Do you know a better initial guess?
Are all the option parameters that I am using necessary or should I delete some of them?

from __future__ import division
import time

def newton_sqrt(n,x0=None,tolerance=10 ** (-3),max_iter=15,epsilon=10 ** (-5)):
    """
   This function computes the sqare root of a number
   using Newton's method.
   After chosing a starting approximate value for x runs:
   x = x - f(x) / derivative_of_f(x)
   After a given number of iterations or if the result is good enough
   the programme will stop and return x.

   Parameters:
       Compulsory:
           @ n: the number of which the square root must be taken.
       Optional:
           @ x0: the initial approximation of n.
           @ tolerance: the maximum error permitted.
           @ max_iter: the maximum number of iterations.
           @ epsilon: a number so small that dividing by it would break
           @        the programme, giving vastly inapproximate results.
   """
    DIVISION_BY_TINY_DERIVATIVE_ERROR = """The derivative of f is {} and therefore under the {} limit chosen.
   Dividing by it would give a result with a vast error."""
    NOT_ENOUGH_ACCURACY_IN_ITER_ERROR = """Solution of {} accuracy for {} was not found in {} iterations"""

    if x0 is None:
        x0 = n / 2

    f = lambda x: x ** 2 - n
    fprime = lambda x: 2 * x  # The derivative of f(x)

    for i in range(max_iter):
        y = f(x0)
        yprime = fprime(x0)
        if(abs(yprime) < epsilon):
            raise Exception(DIVISION_BY_TINY_DERIVATIVE_ERROR.format(
            yprime, epsilon))
        x1 = x0 - y / yprime
        if(abs(x1 - x0) / abs(x1) < tolerance):
            return x1
        x0 = x1

    raise Exception(NOT_ENOUGH_ACCURACY_IN_ITER_ERROR.format(
    tolerance,n,max_iter))

def test_and_timing(max_):
    start = time.time()
    n_sqrt = [newton_sqrt(i) for i in range(1, max_)]
    print("Newton's sqrt took {} seconds to execute for i 1:{}".format(
        time.time() - start, max_))

    start = time.time()
    b_sqrt = [i ** 0.5 for i in range(1, max_)]
    print("Built-in sqrt took {} seconds to execute for i 1:{}".format(
        time.time() - start, max_))

    print("""Sum of all newton sqrts is: {}
   Sum of all built-in sqrts is: {}""".format(sum(n_sqrt), sum(b_sqrt)))

if __name__ == "__main__":
    test_and_timing(100000)


texts:
rule 1: length must be between 8 and 50 chars.
rule 2: at least 3 of the 4 following rules:
--------2a: at least one upper case
--------2b: at least one lower case
--------2c: at least one numeral
--------2d: at least one non-alphanumeric.

I have a function which will take in two Strings (the password and the confirmation) and then return a boolean depending on if it verified. It also sets a label on my JavaFX screen to the error or confirmation message. It works fine, but the code seems cumbersome. any thoughts?

public boolean validatePassword(String newPass, String confirmPass)
{
    if (newPass == null ||
        confirmPass == null ||
        newPass.length() == 0 ||
        confirmPass.length() == 0 )
    {
        responseLabel.setText("");
        return false;
    }

    boolean equalsRule = newPass.equals(confirmPass);
    boolean lengthRule = newPass.length() >= 8 && newPass.length() <= 50;

    boolean upperRule = !newPass.equals(newPass.toLowerCase());
    boolean lowerRule = !newPass.equals(newPass.toUpperCase());
    boolean numeralRule = newPass.matches("(.*)[0-9](.*)");
    boolean nonAlphaRule = newPass.matches("(.*)[^A-Za-z0-9](.*)");

    int ruleCount = (upperRule ? 1 : 0) + ( lowerRule ? 1 : 0) + ( numeralRule ? 1 : 0) + (nonAlphaRule ? 1 : 0);

    if (ruleCount >= 3 && equalsRule && lengthRule)
    {
        responseLabel.setText("Password set successfully.");
        responseLabel.setTextFill(Color.GREEN);
        return true;
    }
    else
    {
        if (!equalsRule)
        {
            responseLabel.setText("Passwords must match.");
        }
        else if (ruleCount < 3 || !lengthRule)
        {
            responseLabel.setText("Password does not follow instructions above.");
        }
        responseLabel.setTextFill(Color.RED);
        return false;
    }
}


texts: Traversing a tile-based 2D-array map using keyboard controls

texts:
I've produced the beginnings of an RPG-style game using HTML5 and canvas. So far you can use the keyboard controls WASD to move an avatar around a simple tile-based map. The map is constructed of individual 'room' maps which form a larger 'world' map. The use of a 'world' map allows the avatar to walk off the screen and onto a new map. If the avatar has reached the 'edge' of the 'world', it will behave as though it has encountered a non-traversable tile.

So far I'm happy with how it works, but I am aware that the code itself has a lot of duplication and I'd like to refactor it to be more DRY. So far, what has stopped me doing this is confusion over how best to efficiently pass values between different functions without having tons of global variables.

One example of what I mean is my keyDownHandler function. I created variables such as nextTileNorth (and so on) to let me calculate the nature of the grid tile onto which the avatar is attempting to move. There is a lot of repeated behaviour which I think should be in a separate function, but then how would I pass on the nextTileNorth (etc) information to the new function without further repeating myself?

I have included the keyDownHandler function below, but in line with the rules of Code Review I am happy to receive feedback on any aspects of the code, which can be found in this JSFiddle.

function keyDownHandler(event) {
    var keyPressed = String.fromCharCode(event.keyCode);

    var nextTileSouth;
    (currentMap[currentRowTile + 1] === undefined) ? nextTileSouth = undefined : nextTileSouth = currentMap[currentRowTile + 1][currentColumnTile];

    var nextTileNorth;
    (currentMap[currentRowTile - 1] === undefined) ? nextTileNorth = undefined : nextTileNorth = currentMap[currentRowTile - 1][currentColumnTile];

    var nextTileEast = currentMap[currentRowTile][currentColumnTile + 1];
    var nextTileWest = currentMap[currentRowTile][currentColumnTile - 1];

    if (keyPressed == "W") {

        worldDirection = 'N';
        // if the next tile is undefined (because we're at the edge of the screen) ...
        if (nextTileNorth === undefined) {
            drawNewMap();
        } else {
            // otherwise, check if we can continue to move forward (is the next tile traversable?)
            if (traversableTiles.indexOf(nextTileNorth) > -1) {
                isMoving = true;
            } else {
                // if we're blocked by a non-traversable tile, stop moving
                isMoving = false;
            }
        }
    } else if (keyPressed == "D") {

        worldDirection = 'E';
        if (nextTileEast === undefined) {
            drawNewMap();
        } else {
            if (traversableTiles.indexOf(nextTileEast) > -1) {
                isMoving = true;
            } else {
                isMoving = false;
            }
        }
    } else if (keyPressed == "S") {

        worldDirection = 'S';

        if (nextTileSouth === undefined) {
            drawNewMap();
        } else {
            if (traversableTiles.indexOf(nextTileSouth) > -1) {
                isMoving = true;
            } else {
                isMoving = false;
            }
        }
    } else if (keyPressed == "A") {

        worldDirection = 'W';

        if (nextTileWest === undefined) {
            drawNewMap();
        } else {
            if (traversableTiles.indexOf(nextTileWest) > -1) {
                isMoving = true;
            } else {
                isMoving = false;
            }
        }
    }

    for (var i = 0; i < avatarContainer.length; i++) {
        avatarContainer[i].facing = worldDirection;
        avatarContainer[i].isMoving = isMoving;
    }
}


texts: Construct A String Using StringBuilder from a List using elements index

texts:
I am a java beginner and want to build a string from elements in a list using its elements index, the code runs fine yet i want to learn if there are other ways to improve upon it.Below is my sample code and I'm welcomed to suggestions.

String buildObject(List<Integer> obj){
    StringBuilder name = new StringBuilder();
   for(int i = 0; i < obj.size(); i ++){
       int m = obj.size() - 1;//will be nine
       if(i == 0 && i < 2){
           name.append(obj.get(0))
                   .append(" & ")
                   .append(obj.get(1));
       }else if (i >= 2 && i != m) {
           name.append(", ");//between second and before last value
            name.append(obj.get(i));
       }else if(i == m){//last value
           name.append(" and ")
                   .append(obj.get(m));
       }

   }
  return name.toString();
   }


texts:
I'm using QScintilla in my project.  There's no good FindQScintilla.cmake out there, so I'm writing one myself.  However, I don't really know what I'm doing.  This is my attempt; it works, but I don't know how it'll work in reality:

find_path(QSCINTILLA_INCLUDE_DIR
  NAMES Qsci qsciglobal.h
  PATHS "${Qt5Core_INCLUDE_DIRS}" /usr/include/x86_64-linux-gnu/qt5
  PATH_SUFFIXES Qsci
)

find_library(QSCINTILLA_LIBRARY
  NAMES qt5scintilla2 libqt5scintilla2
  PATHS ${Qt5Core_LIBRARIES}
)

include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(
  QScintilla
  FOUND_VAR QSCINTILLA_FOUND
  REQUIRED_VARS QSCINTILLA_INCLUDE_DIR QSCINTILLA_LIBRARY
  VERSION_VAR QSCINTILLA_VERSION
)

if(QSCINTILLA_LIBRARY AND QSCINTILLA_INCLUDE_DIR)
  set(QSCINTILLA_LIBRARIES ${QSCINTILLA_LIBRARY})
  set(QSCINTILLA_INCLUDE_DIRS ${QSCINTILLA_INCLUDE_DIR})
endif()

mark_as_advanced(QSCINTILLA_INCLUDE_DIR QSCINTILLA_LIBRARY)

My development environment is Ubuntu 16.04, but I want this package to work on all major platforms.

More specifically:

Am I missing anything?
How will this hold up on different operating systems?

I'm targeting Windows, Mac, and Linux, though if there's a quick and easy way I can target another OS then I'll do that too.


texts: Checking if two byte arrays are the same

texts:
I have a method to compare two byte arrays. The code is Java-style, and there are many if-elses.

def assertArray(b1: Array[Byte], b2: Array[Byte]) {
  if (b1 == null && b2 == null) return;
  else if (b1 != null && b2 != null) {
    if (b1.length != b2.length) throw new AssertionError("b1.length != b2.length")
    else {
      for (i <- b1.indices) {
        if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
      }
    }
  } else {
    throw new AssertionError("b1 is null while b2 is not, vice versa")
  }
}

I have tried as following, but it's not simplified the code much:

(Option(b1), Option(b2)) match {
    case (Some(b1), Some(b2)) => if ( b1.length == b2.length ) {
       for (i <- b1.indices) {
        if (b1(i) != b2(i)) throw new AssertionError("b1(%d) != b2(%d)".format(i, i))
       }
    } else {
       throw new AssertionError("b1.length != b2.length")
    }
    case (None, None) => _
    case _ => throw new AssertionError("b1 is null while b2 is not, vice versa")
}


texts:
I'm just getting into bash and sh scripting.  I mostly just stub out little convenience or exercise scripts for myself, but I recognize I may be flaunting best practices at times.

My question is specifically related to best practices (or just common sense) when using rm inside a shell script.  My googles have only turned up suggestions to alias rm to rm -i or somesuch.

Anyway, enough talk, here's the script (note: the rm appears at the very end of the script):

#!/bin/sh -e
# Format output of alias print dump into more readable format

if [ -f "TEMP.AWK" ]; then
    echo "Somehow 'TEMP.AWK' already exists"
    exit 1
fi

cat ${HOME}/.zshrc | grep -e '^alias' | awk -F'=' 'BEGIN {
        print "ALIAS                         | COMMAND";
        print "---------------------------------------";
    }
    {

        # replace all multi-spaces with a single space
        gsub(/\s+/, " ", $0);

        col1Len  = 20;
        col2Len  = 60;
        aliasLen = length($1);
        cmdLen   = length($2);

        tab1len  = col1Len - aliasLen;
        tab2len  = col2Len - cmdLen;

        printf " " $1 " "

        for (i = 0; i < tab1len; i++)
            printf "-"

        print " " $2

    } END {
        print "---------------------------------------";
    }' > TEMP.AWK

cat TEMP.AWK | grep --color -e '[#].*'

rm TEMP.AWK

Any other feedback would not go unappreciated.


texts:
This script uses robocopy purge with list command to out what would be purged it then parses that log file and checks each file and only deletes files older than 7 days. Is there way it could be simplified to maybe use less log files in the process?

$Log = "D:\IT\Backups\Logs\list.txt"
$extrafile = "D:\IT\Backups\Logs\extrafile.txt"
$extradir = "D:\IT\Backups\Logs\extradir.txt"
$extraparsed = "D:\IT\Backups\Logs\extraparsed.txt"
$purged = "D:\IT\Backups\Logs\purged.txt"
$now = Get-Date
$days = "7"
$Lastwrite = $now.AddDays(-$days)
$datetime = get-date -f MM-dd-yy-hhmmtt

If (Test-Path "D:\IT\Backups\Logs\list.txt"){
        Remove-Item "D:\IT\Backups\Logs\list.txt"
}

robocopy "\\10.10.10.9\tcart" "\\192.168.1.44\tcartbkup" /e /Purge /R:1 /W:1 /l /TEE /FP /LOG:"D:\IT\Backups\Logs\list.txt" /MT:16

If (Test-Path $extradir){
        Remove-Item $extradir
}

If (Test-Path $extrafile){
        Remove-Item $extrafile
}

If (Test-Path $extraparsed){
        Remove-Item $extraparsed
}
If (Test-Path $purged){
        rename-item $purged -newname ("purged-" + $datetime + ".txt")
}

Get-Content $Log | Select-String "EXTRA File" | Out-File $extrafile -Width 5000
Get-Content $Log | Select-String "EXTRA Dir" | Out-File $extradir -Width 5000

cat $extradir | %{$_.Substring(28)} | Out-File $extraparsed
cat $extrafile | %{$_.Substring(38)} | Out-File $extraparsed -Append

$files = Get-Content $extraparsed | Select-String "\\" | ForEach-Object {(Get-Item "$_")} | Where {ForEach-Object {($_.LastWriteTime -le "$Lastwrite")}}

foreach ($file in $files)
    {
        if ($File -ne $NULL)
            {
             Write-Host "Deleting File $File" -ForegroundColor "DarkRed"
             Write-Output "Deleting File $File" | Out-File $purged -Append
             Remove-Item $file.FullName -Recurse | Out-Null
             }
             else
             {
             Write-Host "No More files to delete" -ForegroundColor "Green"
             Write-Output "No More files to delete" | Out-File $purged -Append
             }
     }


texts:
I am writing a small game and as a part of it I load json config with colors definitions in a format of strings #00ff00.

Then I am using this function to convert these strings to SDL Color structure. I am assuming that all color strings are a valid hex colors (between 6-7 chars, depending if # (hash) is provided at the beginning).

template <class T>
inline unsigned int toIntFromHexString(const T& t) {

    unsigned int x;
    std::stringstream ss;
    ss << std::hex << t;
    ss >> x;
    return x;

}

inline SDL_Color stringToSDLColor(std::string colorString) {

    SDL_Color color;

    if (colorString[0]=='#') {
        colorString.erase(0,1);
    }

    std::string stringR = colorString.substr(0,2);
    std::string stringG = colorString.substr(2,2);
    std::string stringB = colorString.substr(4,2);
    std::string stringA = colorString.substr(6,2);

    color.r = toIntFromHexString(stringR);
    color.g = toIntFromHexString(stringG);
    color.b = toIntFromHexString(stringB);
    if (stringA.length()>0) {
        color.a = toIntFromHexString(stringA);
    }

    return color;

}

What can be adjusted in the implementation?


texts: Authenticate users based on both user role, and requested operation

texts:
I have a function that checks if a user can perform an operation based on access to a specific URL.

The function parameters are the requested URL: url, and user level: lv. The conf object has stored access levels for comparison with the users access level.

function isAuthenticated(url, lv){
    let conf = config.getConfig();

    // Role Editor
    if((url === "/RoleEditor" || url === "/SaveRoles") && lv > conf.roleEditor)
        return true;
    // Queue
    if(url === "/WriteQueueData" && lv > conf.queuedata)
        return true;
    // Listener
    if((url === "/startListener" || url === "/stopListener" || url === "restartListener" || url === "/ListenerConfig" || url === "/SaveListenerConfig") && lv > conf.listener)
        return true;
    // Client details
    if(url === "/ClientInfo" && lv > conf.clientDetails)
        return true;
    // User information
    if(url === "/UserManagement" && lv > conf.userOverview)
        return true;
    // User Edit
    if((url === "/EditUser" || url === "/EditUserToDb") && lv > conf.userEdit)
        return true;

    //
    // Another 6 of this comparisons
    //
    return false;
}

This seems inefficient. For example, if the url is "/RoleEditor" but the power level is too low, all other comparisons are still being made. This could be fixed by changing to this:

if((url === "/RoleEditor" || url === "/SaveRoles"))
    if(lv > conf.roleEditor)
        return true;
    else
        return false;

But that feels even worse (more redundant).

Is there a better way to do this?


texts: Perfect-forwarding while implementing emplace

texts:
I am trying to write a class similar to std::set, and I was wondering if I handled the perfect forwarding right in implementing the emplace member function below. Basically, I forwarded calls to my class to a member set. But I wasn't sure whether I used std::forward enough.

Also, is there an easy way to tell when something is not forwarded as desired, and values are copied instead?

#include <set>
using namespace std;

template<typename T>
class myset {
  std::set<T> m_s;
  typedef typename std::set<T>::iterator iterator;
  int cnt;
public:
  template <class... Args>
  pair <iterator,bool> emplace ( Args&&... args ) {
    pair<iterator,bool> p = m_s.emplace(std::forward<Args>(args)...);
    if (p.second) //true if a new element was inserted
      cnt ++; //house keeping
    return p;
  }
};

int main() {myset<int> s;}


texts:
My code returns the correct answer the first duplicate is 3 (represented as int f) . I am struggling finding a more efficient way to find the first duplicate?

My constraints are \$ 1 ≤ a.length ≤ 10^5, 1 ≤ a[i] ≤ a.length \$ .

class Program
{
  static void Main(string[] args)
  {
    int[] a = {2, 3, 3, 1, 5, 2};

    int f = FirstDuplicate(a);

    Console.ReadLine();
   }
public static int FirstDuplicate(int[] a)
{

    int[] answer = new int[2];
    answer[0] = -1;
    answer[1] = a.Length;
    for (int i = 0; i < a.Length - 1; i++)
        for (int j = i; j < a.Length; j++)
            if (a[i] == a[j] && i != j)
            {
                if (i < answer[1])
                {
                    answer[0] = a[i];
                    answer[1] = j;
                    break;

                }
            }

    return answer[0];
  }
}


texts: Removing final elements of a path to a file

texts:
I have the use case of needing to find the parent path of a sub path for which I have written the following function:

#! /usr/bin/env python3

from os.path import sep

def pathbase(main, sub):
    if main.endswith(sub):
        parent = main[:-len(sub)]

        while parent.endswith(sep):
            parent = parent[:-1]

        return parent

    else:
        raise ValueError('Main path does not end on sub-path')

path1 = '/foo/bar/spamm/eggs'
path2 = 'spamm/eggs'

print(pathbase(path1, path2))

But I find that this is awfully verbose and that I re-invented the wheel with it.
Also it breaks if the paths have an unequal amount of trailing slashes, so my method would need to normalize both paths first, which would make it even more verbose.
Is there already some library method which does that, that I may have overlooked?

Edit: Due to the problems regarding the undesired partial node-match mentioned in some answers and comments I refactored the method to this:

from os.path import basename, dirname, normpath

def pathbase(main, sub):
    """Extract basename of main
    relative to its sub-path sub
    """

    norm_main = normpath(main)
    norm_sub = normpath(sub)

    while basename(norm_main) == basename(norm_sub):
        norm_main = dirname(norm_main)
        norm_sub = dirname(norm_sub)
    else:
        if basename(norm_sub):
            raise ValueError('"{sub}" is not a sub-path of {main}'.format(
                sub=sub, main=main))

    return norm_main


texts: Regular Expression replace specific characters

texts:
Does anyone know of a better / cleaner way to write the following:

GetSafeTagName(txtUserInput.text);

public static string GetSafeTagName(string tag)
{
    tag = tag.ToUpper()
    .Replace("'","`")
    .Replace('"','`')
    .Replace("&", "and")
    .Replace(",",":")
    .Replace(@"\","/"); //Do not allow escaped characters from user
    tag = Regex.Replace(tag, @"\s+", " "); //multiple spaces with single spaces
    return tag;
}

Thanks!


texts:
I am quite new to scripting, and here is my first code I wrote. The goal of the code is to extract a parent ID based on a child ID. I would appreciate some constructive criticism and aggressive checkup. The codes works and does what it's supposed to do. But how can I make it more pythonic? more passionate?

import codecs

import numpy as np
import pandas as pd

def import_file(path):
    '''imports the .csv files as a pandas dataframe
    Args:
        path (csv file): Takes in the path for the .csv file

    Returns:
        Returns a pandas dataframe
        '''
    with codecs.open(path, "r", encoding='utf-8', errors='ignore') as fdata:
        df = pd.read_csv(fdata)
    return df

def appends_address_before_name(file):
    '''Appends the address before the name ID name
    Returns:
        Returns the file, with address appened to column name.
        '''
    file['ID'] = [address + str(col) for col in file['ID']]
    return file

def create_parent_name(file, column_name: str):
    '''This will create a parent name based on the ID column

    Args:
        file: takes in the dataFrame created from appends_address_before_name function

        column_name: Takes in the column name where the parent name
        will be extracted from.The logic is to split it on the last dot.
        [[parentname].[+ childname]]

    Returns:
        Returns a pandas dataframe with a new column called parentID
        '''
    file['parentID'] = [
        x.rsplit('.', 1)[0] if '.' in x else x[:-1] for x in file[column_name]
    ]

    return file

address = 'New_Jersey_'
file_1 = import_file(r'C:\humans.csv')
file_2= appends_address_before_name(file=file_1)
file_3= create_parent_name(file=file_2 , column_name = 'ID')

print(file_3)

The input CSV is a column of values separated with decimal places like the following:

ID

99.99.9
100.42.3

Example output

parentID

New_Jersey_99.99
New_Jersey_100.42

Furthermore, I feel like the way I am passing variables between the functions at the end of the code seems quite basic and terrible. What can I improve in the above code and how can I improve it ?

A screenshot of the code working


texts:
Project Euler problem 83 asks:

  In the 5 by 5 matrix below,

131   673 234 103 18
201   96  342 965 150
630   803 746 422 111
537   699 497 121 956
805   732 524 37  331

  the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is

131 → 201 → 96 → 342 → 234 → 103 → 18 → 150 → 111 → 422 → 121 → 37 → 331

  and is equal to 2297.

  Find the minimal path sum, in matrix.txt (right click and 'Save
  Link/Target As...'), a 31K text file containing a 80 by 80 matrix,
  from the top left to the bottom right by only moving right and down.

I have solved the project euler problem 83 using uniform cost search. This solution takes about 0.6s to solve. I want to know if anyone can get the code to run relatively faster without changing the general outline of the program.

import bisect
f = open('matrix.txt')
matrix = [[int(i) for i in j.split(',')] for j in f]

def uniformCostSearch(startNode):
    frontier = []
    frontier.append(startNode)
    closedSet = set()
    while not len(frontier) == 0:
        currentNode = frontier.pop(0)
        if currentNode.x == 79 and currentNode.y == 79:
            return currentNode.priority
        else:
            if not (currentNode.x, currentNode.y) in closedSet:
                closedSet.add((currentNode.x, currentNode.y))
        possibleMoves = currentNode.neighbors()
        for move in possibleMoves:
            if not (move.x, move.y) in closedSet:
                try:
                    index = frontier.index(move)
                    if move.priority < frontier[index].priority:
                        frontier.pop(index)
                        bisect.insort_left(frontier, move)
                except ValueError:
                    # move is not in frontier so just add it
                    bisect.insort_left(frontier, move)
    return -1

class Node:
    def __init__(self, x, y, priority=0):
        self.x = x
        self.y = y
        self.priority = priority

    def neighbors(self):
        tmp = [Node(self.x + 1, self.y), Node(self.x, self.y + 1),
               Node(self.x - 1, self.y), Node(self.x, self.y - 1),]
        childNodes = []
        for node in tmp:
            if node.x >= 0 and node.y >= 0 and node.x <= 79 and node.y <= 79:
                node.priority = self.priority + matrix[node.y][node.x]
                childNodes.append(node)
        return childNodes

    def __eq__(self, node):
        return self.x == node.x and self.y == node.y

    def __ne__(self, node):
        return not self.x == node.x and self.y == node.y

    def __cmp__(self, node):
        if self.priority < node.priority:
            return -1
        elif self.priority > node.priority:
            return 1
        else:
            return 0


texts:
I wrote a simple slack bot, which is able to save links (command: "save name link") and print them (command: "get name"). Optionally, a delay in minutes and seconds can be specified (command: "get name XmXs"). I would appreciate any feedback.

import os
import re
from time import sleep
from threading import Thread
from slackclient import SlackClient

BOT_NAME = 'klausbot'
BOT_ID = ''
slack_client = SlackClient(os.environ['SLACK_BOT_TOKEN'])

links = {}
save_pattern = re.compile('^save\s(?P<name>[a-zA-Z]+)\s(?P<link>\S+)$')
get_pattern = re.compile('^get\s(?P<name>[a-zA-Z]+)\s?((?P<minutes>\d+)m)?\s?((?P<seconds>\d+)s)?$')

def get_bot_id():
    api_call = slack_client.api_call('users.list')
    if api_call.get('ok'):
        users = api_call.get('members')
        for user in users:
            if 'name' in user and user.get('name') == BOT_NAME:
                global BOT_ID
                BOT_ID = '<@{}>'.format(user.get('id'))

def parse_message(message):
    text = message['text']
    if text.startswith(BOT_ID):
        text = text.split(BOT_ID)[1].strip().lower()
        if save_pattern.match(text):
            handle_save_command(message, save_pattern.match(text))
        elif get_pattern.match(text):
            handle_get_command(message, get_pattern.match(text))
        else:
            post_message('Command not found', message['channel'])

def handle_save_command(message, match):
    name = match.group('name')
    link = match.group('link')
    links[name] = link
    response = '{} saved to {}'.format(link, name)
    post_message(response, message['channel'])

def calculate_time(match):
    minutes = match.group('minutes') or 0
    seconds = match.group('seconds') or 0
    return int(minutes) * 60 + int(seconds)

def handle_get_command(message, match):
    name = match.group('name')
    if name not in links:
        error_message = '{} not found'.format(name)
        post_message(error_message, message['channel'])
    else:
        sleep_time = calculate_time(match)
        sleep(sleep_time)
        post_message(links[name], message['channel'])

def handle_messages_read(messages):
    if messages and len(messages) > 0:
        for message in messages:
            if message and 'text' in message:
                parse_message(message)

def post_message(message, channel='#general'):
    slack_client.api_call(
        'chat.postMessage',
        channel=channel,
        text=message,
        as_user=True
    )

if __name__ == '__main__':
    if slack_client.rtm_connect():
        print('KlausBot started and running')
        get_bot_id()
        while True:
            messages = slack_client.rtm_read()
            handle_message_thread = Thread(target=handle_messages_read, args=(messages,))
            handle_message_thread.start()
            sleep(0.1)
    else:
        print('Could not connect')


texts: This perl script renames all files in a directory to have an equal amount of digits

texts:
I took a lot of pictures with my camera and I wanted to make a time-lapse out of them. The camera saved the pictures as picture1, picture2 ... picture956 etc. but the time-lapse software I'm using only accepts numbers of equal length like this: picture001, picture002, picture003 etc.

I thought Perl would be a good fit for this kind of problem so I gave it a shot. This is a shorter and translated version of the original code so if anything is unclear I can change it to the longer version.

use strict;
use warnings;
use diagnostics;

print "Give the path to the directory where the pictures are stored:\n";
my $filename = <STDIN>;

chomp $filename;
chdir $filename or die "Couldn't change the directory: $!\n";
my @files  = <*>;
#gives a list of all filehandles in the given directory

my $amount_of_digits = int( log($#files)/log(10) +1);
#how many digits should the new number have?
#Example: If there are 400 files -> 3 digits per file: 001, 002 etc

foreach my $file (@files){
    next if($file =~ /^\.$/);
    next if($file =~ /^\.\.$/);
    #skip the . and .. files
    print "$file\n";
    if ($file =~ /(\d+)/){
        my $amount_of_padded_zeroes = $amount_of_digits - length($1);
        if($amount_of_padded_zeroes > 0){
            my $new_number =  '0' x $amount_of_padded_zeroes . $1;
            (my $new_name = $file) =~ s/$1/$new_number/;
            print "Changing name too: $new_name\n";
            rename ($file, $new_name) or die "Couldn't rename the file: $!";
        }
    }
}

print "Program completed. Press any key to continue.\n";
my $einde = <STDIN>;

The code works but I wanted to know if there is a better/cleaner/shorter/more Pearlesque way to do this. I'm learning Perl for uni so any feedback is welcome. I suspect this problem is so trivial in Perl that there might be readable one-liners that are able to replace all of this.


texts:
I have a Game model that is "static". Containing game information and such, and users can comment on all games.

Games model

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}

And then I have a Comment model. This has a User relation and a Comments relation.

public function commentable()
{
    return $this->morphTo();
}

public function user()
{
    return $this->belongsTo(User::class);
}

What I want to do is to fetch the 10 games sorted by the latest comment top, be able to display who made the comment, and when.

I have this query that seems to do the job, but it makes an absurd amount of queries. Can I somehow keep the queries to a minimum?

    $games = Game::join('comments', 'games.id', '=', 'comments.commentable_id')
    ->where('comments.commentable_type', Game::class)
    ->latest('comments.created_at')
    ->groupBy('games.id')
    ->take(10)
    ->withCount('comments')
    ->get()->each(function($games){
        $games->comment = $games->comments()->orderBy('created_at', 'desc')->first();
        $games->user = User::find($games->comment->user_id);
        return $games;
    });


texts: getint that properly handles + or - signs

texts:
As written, getint treats a + or - not followed by a digit as a valid representation of zero. Fix it to push such a charachter back on the input.

Before the for I check if the charachter after the + or - is a number. If it is, the function will store the representation of that number in *pn. If it is not, it will push back that characther back on the input - such that, everytime the getint is called it will
read that charachter and push it back.

Here is my solution:

int getint(int *pn) {
    int c, sign;
    while(isspace(c = getch()))
        ;
    if(!isdigit(c) && c != EOF && c != '+' && c != '-') {
        ungetch(c);
        return 0;
    }

    sign = (c == '-') ? -1 : 1;
    if(c == '+' || c == '-')
        c = getch();

    if(!isdigit(c)) {
        ungetch(c);
        return 0;
    }

    for(*pn = 0; isdigit(c); (c = getch()))
        *pn = 10 * *pn + (c - '0');
    *pn *= sign;
    if(c != EOF)
        ungetch(c);
    return c;
}


texts:
using System;
 using System.Collections.Generic;
 using System.Configuration;
 using System.Data;
 using System.Data.SqlClient;
 using System.Linq;
 using System.Web;

 namespace WebApplication1.App_Code
{
public class SqlHelper
{

    public string connstring;
    public SqlConnection con;
    public SqlCommand cmd;

    public SqlHelper(){}

    public SqlHelper(string sp)
    {
        connstring = ConfigurationManager.AppSettings["constr"];
        con = new SqlConnection(connstring);
        cmd = new SqlCommand(sp, con);
        cmd.CommandType = CommandType.StoredProcedure;
    }

}

public class Result : SqlHelper
{
    public Result(string sp) : base(sp)
    {
    }

    public bool ExecuteResultWithParameter(Dictionary<string, string> parameter)
    {

        bool result = true;
        try
        {
            foreach (var item in parameter)
            {
              cmd.Parameters.AddWithValue("@" + item.Key, item.Value);
            }
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception Ex)
        {
            result = false;
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
        return result;
    }

    public DataSet ReturnResultWithParameter(string sp, Dictionary<string, string> parameter)
    {

        DataSet dt = new DataSet();
        try
        {

         foreach (var item in parameter)
        {
            cmd.Parameters.AddWithValue("@" + item.Key, item.Value);
        }
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            sda.Fill(dt);
        }

        }
        catch (Exception Ex)
        {

        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
        return dt;
    }

    public DataSet ReturnResultWithoutParameter()
    {
        DataSet dt = new DataSet();
        try
        {

            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {

                sda.Fill(dt);
            }
        }
        catch (Exception Ex)
        {

        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }

        return dt;
    }

}

 }

I have written SQL helper class for my project and I want to improve the above code.also can someone suggest a suitable design pattern for the same.


texts:
I created a simple linked list to test what I've learned so far and if I manage everything correctly. If you see syntax errors is't because of copy-paste. I just want to know if i'm making everything in the right way without
having leak and memory problems.

Node class

#include "Node.h"

//Constructor.
Node::Node(int v)
:next(nullptr), value(v)
{
}

//Deconstrucor (not in use).
Node::~Node()
{
}

//Set next.
void Node::set_next(Node *new_node)
{
    this -> next = new_node;
}

//Set previous.
void Node::set_prev(Node *new_node)
{
    this -> prev = new_node;
}

//Set value.
void Node::set_value(int v)
{
    this -> value = v;
}

//Get next.
Node *Node::get_next()
{
    return this -> next;
}

//Get previous.
Node *Node::get_prev()
{
   return this -> prev;
}

//Get value
int Node::get_value()
{
    return this -> value;
}

LinkedList class

#include "LinkedList.h"
#include "Node.h"
#include <new>
#include <iostream>

//Constructor.
LinkedList::LinkedList()
:head(nullptr), tail(nullptr), moving_ptr(nullptr)
{
}

//Deconstrucor (not in use).
LinkedList::~LinkedList()
{
}

//Append a new item on the list.
void LinkedList::append(int v)
{

    //Allocate a new node.
    Node *new_node = new (std::nothrow)Node(v);

    //If memory is full, exit the program.
    if (new_node == nullptr){
        std::cout << "Memory is full, program will exit." << std::endl;
        exit(0);
    }

    //If this is the first node.
    if (head == nullptr || tail == nullptr)
        {
            head       = new_node;
            tail       = new_node;
            moving_ptr = new_node;
        }

    //Append other node.
    else
        {
            tail -> set_next(new_node); //Link it after the tail of the list.
            new_node -> set_prev(tail); //Set the previous node.
            tail = new_node;            //Update the tail pointer.
        }
}

//Remove a node from the list.
bool LinkedList::remove_item(int v)
{

    //Starting node.
    Node *curr = head;

    //----Find the node that contains v----//
    while (curr != nullptr)
    {

        //Found.
        if (curr -> get_value() == v)
            break;

        //Keep going.
        else
            curr = curr -> get_next();
    }
    //----Find the node that contains v----//

//The item was not found into the list.
if (curr == nullptr)
    return false;

//Make necessary links!!!
curr -> get_prev() -> set_next( curr -> get_next() );

//Delete current node.
delete curr;

return true;
}

//Get the next item.
int LinkedList::nextItem()
{

    //Temp that hold current value.
    int temp = moving_ptr -> get_value();

    //Move to the next node.
    moving_ptr = moving_ptr -> get_next();

    //Return the value.
    return temp;
}

//Return true if moving_ptr is not null.
bool LinkedList::hasNext()
{
    return moving_ptr != nullptr;
}

//Reset moving_ptr.
void LinkedList::reset()
{
    moving_ptr = head;
}

Am I handling everything correctly? I also tried to fill all my memory with an infinite loop to see what happens and everything run's smoothly. The program terminates when memory is full.


texts: which for loop has better performance in javascript?

texts:
I can't find out which loop is better performance than another, if you know help me.

I try about loops in js and performance in this site
and this is code snippet, you can run and check.

const array1 = [];

for (let i = 0; i <= 50000; i++) {
  array1.push(i);
}

//for...
var forT0 = performance.now()

for (let element = 0; element < array1.length; element++) {
  console.log(element);
}

var forT1 = performance.now()
console.log("Call to doSomething took " + (forT1 - forT0) + " milliseconds.")

//for...in
var forInT0 = performance.now()

for (const element in array1) {
  console.log(element);
}

var forInT1 = performance.now()
console.log("Call to doSomething took " + (forInT1 - forInT0) + " milliseconds.")

//for...of
var forOfT0 = performance.now()

for (const element of array1) {
  console.log(element);
}

var forOfT1 = performance.now()
console.log("Call to doSomething took " + (forOfT1 - forOfT0) + " milliseconds.")

//forEach
var forEachT0 = performance.now()

array1.forEach(element => console.log(element));

var forEachT1 = performance.now()
console.log("Call to doSomething took " + (forEachT1 - forEachT0) + " milliseconds.")


texts: Using a list-matrix to supply indices to N-dimensional array

texts:
I am working on a partial differential equations project where some N-dimensional objects are required. I got stuck in padding one N-dim object with a copy of each of its dimensions. Here is the function:

padreplicate <- function(a, padSize) {
    # A: is a N-dimensional array
    # padSize: is a vector that defines the padding
    # Pad an array by replicating values.
    numDims <- length(padSize)
    idx <- vector("list", numDims)
    for (k in 1:numDims) {
        M <-  dim(a)[k]       # 32
        onesVector <-  matrix(1, 1, padSize[k])
        idx[[k]] <- c(onesVector, 1:M, M * onesVector)
    }
    do.call( `[`, c(list(a), idx))
}

The first argument is the N-dim object; it could be a matrix, a 3D array or higher dimensional array.

An example for a 2D object or matrix would be:

# pad a matrix 4x3 with c(1,1)
set.seed(123456)
mx = matrix(sample.int(9, size = 9*100, replace = TRUE), nrow = 4, ncol = 3)
mx
  #       [,1] [,2] [,3]
  # [1,]    8    4    9
  # [2,]    7    2    2
  # [3,]    4    5    8
  # [4,]    4    1    6
padreplicate(mx, c(1,1))

The padded matrix looks like this:

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

For a 3-D array the input array and the padded array.

ar = array(sample.int(9, size = 9*100, replace = TRUE), dim = c(3, 3, 1))
ar
padreplicate(ar, c(1,1,1))

# input 3x3x1 array
, , 1

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

   # padded 5x5x3 array
, , 1

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

, , 2

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

, , 3

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

These are all correct results from my unit tests.

My question is this: "is there a better way of doing this N-dim padding operation in R or a package that address N-dimensional arrays?


texts:
I have the below regex to match email address with atleast one @ and one .

[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}

Am wondering can it be simplified further to match email address with atleast one @ and one .?


texts:
Requirements:

I have to design a database to store tick data of 350 stocks. Inside this database queries will be executed to transform tick data and retrieve OHLC candles of 1 minute, 1 hour, 1 day.

There are on average 15 tick rows inserted each second for every stock and each table is initially populated with an average of 6 million tick data (from a minimum of 100k to a peak of 50 million).

There are no delete queries to be supported efficiently.

SELECT queries need to filter the time of the candles, but I would like to support huge bulks of 600k rows in case a whole year of 1 minute candles is requested.

Initial target is to support at least 5 concurrent queries on the same stock or 20 concurrent queries in total.

Implementation:

The implementation I have chosen is to use one PostgreSQL (10) database and store tick data in tables split by stock. Index on trade_id and trade_time.

In order to transform tick data in OHLC candles, I thought to use MATERIALIZED VIEW for each type of candle (1m, 1h, 1d) refreshed concurrently every 24 hours in sequence for all the tables. The reason is to avoid the database to compute every time the transformation from tick data to candles, but to be able to retrieve the candles during the refresh. The views have index on date.

-- Tick data <pair>
CREATE TABLE IF NOT EXISTS :title (
    "trade_time" bigint NOT NULL,
    "trade_id" bigint NOT NULL,
    "first_trade_id" bigint NOT NULL,
    "last_trade_id" bigint NOT NULL,
    "price" TEXT NOT NULL,
    "quantity" TEXT NOT NULL,
    "is_buyer_mm" BOOLEAN NOT NULL,
    "is_best_match" BOOLEAN NOT NULL
) WITH (
  OIDS=FALSE
);

CREATE INDEX IF NOT EXISTS trade_idx ON :title (trade_id);
CREATE INDEX IF NOT EXISTS trade_timex ON :title (trade_time);

-- Tick data materialized view <pair>_tick (last day trades)
CREATE MATERIALIZED VIEW IF NOT EXISTS :tick AS
SELECT trade_id,
price::numeric,
quantity::numeric,
TIMESTAMP WITH TIME ZONE 'epoch' + trade_time * INTERVAL '1 ms' AS trade_time,
first_trade_id,
last_trade_id,
is_buyer_mm,
is_best_match
FROM :title
WHERE TIMESTAMP WITH TIME ZONE 'epoch' + trade_time * INTERVAL '1 ms' < CURRENT_DATE
ORDER BY trade_time;

CREATE INDEX IF NOT EXISTS trade_idx ON :tick (trade_id);
CREATE INDEX IF NOT EXISTS trade_timex ON :tick (trade_time);

-- 1m materialized view <pair>_1m
CREATE MATERIALIZED VIEW IF NOT EXISTS :minute AS
SELECT
date_trunc('minute', a.trade_time) dt,
(array_agg(a.price ORDER BY trade_time ASC))[1] o,
MAX(a.price) h,
MIN(a.price) l,
(array_agg(a.price ORDER BY trade_time DESC))[1] c,
SUM(a.quantity) vol,
count(*) ticks
FROM :tick AS a
GROUP BY date_trunc('minute', a.trade_time);

CREATE INDEX IF NOT EXISTS dtx ON :minute (dt);

-- 1h materialized view <pair>_1h
CREATE MATERIALIZED VIEW IF NOT EXISTS :hour AS
SELECT
date_trunc('hour', a.trade_time) dt,
(array_agg(a.price ORDER BY trade_time ASC))[1] o,
MAX(a.price) h,
MIN(a.price) l,
(array_agg(a.price ORDER BY trade_time DESC))[1] c,
SUM(a.quantity) vol,
count(*) ticks
FROM :tick AS a
GROUP BY date_trunc('hour', a.trade_time);

CREATE INDEX IF NOT EXISTS dtx ON :hour (dt);

-- 1d materialized view <pair>_1d
CREATE MATERIALIZED VIEW IF NOT EXISTS :day AS
SELECT
date_trunc('day', a.trade_time) dt,
(array_agg(a.price ORDER BY trade_time ASC))[1] o,
MAX(a.price) h,
MIN(a.price) l,
(array_agg(a.price ORDER BY trade_time DESC))[1] c,
SUM(a.quantity) vol,
count(*) ticks
FROM :tick AS a
GROUP BY date_trunc('day', a.trade_time);

CREATE INDEX IF NOT EXISTS dtx ON :day (dt);

Problems:

For each stock I add, the sizes of the views are more or less the same as the size of the table itself
50 million rows make use of 4.5GB

Honestly, I still have to benchmark the throughput of my design, but I feel that there could be better implementations.

Ideal:

Looking at various similar questions about OHLC series I found these ideas:

Switch to ZFS to reduce size of database
Change database (NoSQL, InfluxDB, BerkeleyDB)
Use redis to cache queries (Integration with PostgreSQL is not very straightforward)


texts: Running some code every day at certain times

texts:
I am currently developing a windows service in C# which is supposed to run a data import every day at configurable times. For this purpose I have created a class "ExecutionTime" which contains the attributes "Hour" and "Minute" to specify a time when the data import should be executed. When the service is started, the configured times are parsed into one ExecutionTime object each and those objects are then added to a list "executionTimes". I also created a class "Scheduler" which is responsible for checking if the data import should be executed and executing it once one of the configured times is reached.

I have already created a possible solution but I am not sure if my solution is considered "good practice" or if there are any edge cases when my code will not work the way it should. Could I therefore please get some feedback on my idea? Is it good? Can it still be improved?

My idea is to run the following code inside a while-loop:

DateTime now = DateTime.Now;

foreach (ExecutionTime executionTime in executionTimes)
{
    if (now.Hour == executionTime.Hour && now.Minute == executionTime.Minute
        && (lastExecutionTime.Hour < executionTime.Hour || lastExecutionTime.Minute < executionTime.Minute || lastExecutionTime < DateTime.Today))
    {
        PerformImport();
        lastExecutionTime = now;
    }
}

Thread.Sleep(1000);

Please do not suggest using scheduled tasks as a solution because that is not up for discussion, I have to implement this in a windows service.

I have already asked this question on StackOverflow but someone recommended to ask it here instead.

Thanks a lot in advance!


texts:
I've solved this question. Wasn't sure if I was suppose to use a dictionary in this case, as the question was to use a dynamic array, but I didnt know how else to do it. Was wondering if I can get feedback on my code or if there's a better way to approach it:

import Foundation

// reads input for N(number of sequences) and Q(number of queries)
let input = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
let numOfSequences = input[0]
let numOfQueries = input[1]
var lastAns = 0
var seqDictionary = [Int: [Int]]()

// loop through numOfQueries
for _ in 0..<numOfQueries {
    // each query is given in format [1, x, y] or [2, x, y]
    let query = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
    // check to see if query[0] is 1 or 2
    switch query[0] {
    case 1:
        // formula for seqDictionaryIndex
        // ^ is the XOR operator
        let seqDictionaryIndex = ((query[1] ^ lastAns) % numOfSequences)
        // since we initalized an empty dictionary, we gotta set the first key to a value to start the array so we can start appending
        guard seqDictionary[seqDictionaryIndex] != nil else { seqDictionary[seqDictionaryIndex] = [query[2]] ; continue }
        seqDictionary[seqDictionaryIndex]?.append(query[2])
    case 2:
        let seqDictionaryIndex = ((query[1] ^ lastAns) % numOfSequences)
        // calculate the size of the particular sequence in seqDictionary
        let size = seqDictionary[seqDictionaryIndex]?.count
        // formula for finding index in particular sequence in seqDictionary
        let index = query[2] % size!
        // set last answer to that element at the index calculated above
        lastAns = seqDictionary[seqDictionaryIndex]![index]
        print(lastAns)
    default: break
    }
}


texts: Candy splitting - lower memory usage needed

texts:
I just did CodeChief's candy splitting task here and my code is working even with a lot of test cases and big numbers, but it uses way too much memory. When I checked my submission, it was 1342M, which is a lot.

import java.util.ArrayList;
import java.util.Scanner;

class Candies {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int candieStuds;
    int candieT;

    int testCases = in.nextInt();
    ArrayList<String> answ = new ArrayList<String>();
    for(int tCase = 0; tCase < testCases; tCase++){
        int candies = in.nextInt();
        int studs = in.nextInt();
            candieStuds = candies/studs;
        candieT  = candies%studs;
        StringBuilder str = new StringBuilder();
        str.append(candieStuds);
        str.append(" ");
        str.append(candieT);
        answ.add(str.toString());

    }
   for(int listInd = 0; listInd < answ.size(); listInd++){
       System.out.println(answ.get(listInd));
   }
   in.close();
}}

Can someone point out what I should use so I can have the same performance but use less memory?