texts:
I am working on trying to create a range function in JavaScript that imitates PERL's 'a'..'zz'.

which expands to:

a->z
aa->az
ba->bz
...
za->zz

And so on for every extra character you add to the end of the range( e.g zzz .... ).

I have a working implementation, However, I think that there is a more efficient - and perhaps more idiomatic - solution.

There are two things I would like answers to address:

I would like to reduce the code size - this seems like too many lines for the problem that it solves.
I would like improve the performance - the implementation that I have is very slow for any end string > 5 characters long.

function charRange( start, end ) {
  var current = start;
  var range   = [];

  range.push( current ); //Put the start directly into the range.
  if ( typeof start === typeof end &&
     ( typeof start === "string" )) {
    if ( typeof end !== "string" ) {
        console.log( "ERROR: start and end must both be Strings!" );
    }
  }

  while ( !stringEqual(current.split(""), end.split("")) ) {
    current = next(current);
    range.push( current );
    // process.exit();
  }

  return range;

  function stringEqual( chars, testChars ) {
    var isEqual = 1;
    var sum = 0;
    var testSum = 0;
    var i = 0;
    while ( i < testChars.length ) {
        // console.log(chars);
        // console.log(testChars);
        // console.log(i);

        if ( isEqual && chars[i] !== testChars[i] ) {
            isEqual = 0;
        };
        if ( chars[i] ) {
            sum     += chars[i].charCodeAt(0);
        };
        testSum += testChars[i].charCodeAt(0);
        i++;
    }

    // console.log( sum + " " + testSum );
    return isEqual || (sum < testSum ? 0 : 1);
  }

  function allAreZ( string ) {
    var found = 1;
    var i     = 0;
    while ( i < string.length ) {
        if ( string[i] !== "z" ) {
            found = 0;
            break;
        }
        i++;
    }

    return found;
  }

  function findIncrementIndex( item ) {
    var index = item.indexOf("z");
    var i     = 0;

    while (index === 0) {
        i++;
        index = item.substr(i).indexOf("z");
    }

    index += i;

    return index;
  }

  function next( item ) {
    if ( typeof item === "number" ) {
        return item++;
    } else if ( typeof item === "string" ) {
        var lastCharCode = item.charCodeAt( item.length -1 );
        item = item.toLowerCase();

        if ( lastCharCode === "z".charCodeAt( 0 ) ) {
            if ( allAreZ(item) ) {
                // console.log( "Reached the end, adding a letter");
                return Array(item.length +2).join("a");
            } else {
                var index = findIncrementIndex(item);
                var charCode = item.charCodeAt( index -1 );
                var newChar = String.fromCharCode( ++charCode );
                item = item.replace(/[a-y]z/, newChar + "a").replace(/z+$/, "a");
                // console.log( "Reached the end, next set is: " + item);
                return item;
            }

        } else {
            var newChar = String.fromCharCode( ++lastCharCode );
            // console.log( "Next Character is: " + newChar + " Code: " + lastCharCode + " Input: " + item);
            return item.replace( /\w$/, newChar );
        }
    }
  }
};


texts:
Please see my previous post in the below hyperlink
I've updated my .htaccess file to account for an HSTS, along with many of the recommended changes. See the snippet below. I'd like to stress that implementing an HSTS is not to be taken lightly for anybody else new to it. With that said, I'm looking for advice on what can be done differently from those who have knowledge on .htaccess.
#IMPLEMENT HSTS
<IfModule mod_headers.c>
Header set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</IfModule>

#CUSTOM ERROR PAGES
ErrorDocument 400 /allerror.php
ErrorDocument 401 /allerror.php
ErrorDocument 403 /allerror.php
ErrorDocument 404 /allerror.php
ErrorDocument 405 /allerror.php
ErrorDocument 408 /allerror.php
ErrorDocument 500 /allerror.php
ErrorDocument 502 /allerror.php
ErrorDocument 504 /allerror.php

RewriteEngine On

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

#HOTLINKING PROTECTION
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com(/.*)*$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(css|flv|gif|ico|jpe|jpeg|jpg|js|mp3|mp4|php|png|pdf|swf|txt)$ - [F]

#CONTENT SECURITY POLICY
<FilesMatch "\.(html|php)$">
    Header set Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: 'unsafe-inline'; media-src 'self' data: 'unsafe-inline'; connect-src 'self';"
</FilesMatch>

#REDIRECT FOR DATE PAGE
RewriteRule ^date$ /storage/date-202010 [R=301,L]

#REDIRECT FOR HOME PAGE
RewriteRule ^home$ / [R=301,L]

#PREVENT DIRECTORY BROWSING
Options All -Indexes

#FILE CACHING
    #cache html and htm files for one day
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>
    #cache css, javascript and text files for one week
<FilesMatch "\.(js|css|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
    #cache flash and images for one month
<FilesMatch "\.(flv|swf|ico|gif|jpg|jpeg|mp4|png)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
    #disable cache for script files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>

#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(ht[ap]|ini|log|sh|inc|bak)$">
Require all denied
</FilesMatch>

HSTS Implementation
To note a few things that I've learned while researching HSTS:

An SSL certificate is required
If your sites are available via HTTP, redirect all requests to HTTPS with a 301 Permanent Redirect.
Include the following in your .htaccess file: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload. Max-age must be at least 10886400 seconds or 18 Weeks. Go for the two years value.
Add your domain to a preload list using the first link below.

I encourage everyone to read each source below for more information.

HSTS Preload List Submission
What is HSTS and Why Should I use it? | Acunetix
What is HSTS and should I implement it? | Network Dynamics
Why websites should be using HSTS to improve security and SEO


texts:
I have written the following Javascript class

function InScroll( container, options ) {
    "use strict";

    var isRunning = false;
    // utilities
    var noop = function() {};

    var inter = null;

    if(!container) {
        alert('container element not provided');
        return;
    }
    if(!options.interval) options.interval = 500;

    // save screen info
    var page = {
        contentHeight: $(container).getHeight(),
        pageHeight: document.viewport.getHeight(),
        scrollPosition : 0,
    }

    function scroll() {
        var pos = $(container).select("div.kurz").length;

        if(pos == 0) {
            this.kill();
            return;
        }

        // get scroll position y-axis.
        page.scrollPosition = document.viewport.getScrollOffsets()[1];

        if( !isRunning && (page.contentHeight - page.pageHeight - page.scrollPosition ) < 450) {
            new Ajax.Request(options.url + "?pos=" + pos, {
                onCreate: onCreate,
                onSuccess: append,
                onFailure: error,
                onComplete: onComplete

            });
        }
    }
    function onCreate() {
        isRunning = true;
    }

    function onComplete() {
        isRunning = false;
        page.contentHeight= $(container).getHeight();

    }

    function append( response ) {
        var resp = response.responseText.strip();

        if(resp == "") kill();

        container.innerHTML += resp;
    }

    function error( response ) {
        var resp = response.responseText.strip();
        container.innerHTML += resp;
    }

    function start() {

        if(!container) {
            alert('container element not provided');
            return;
        }

        if(!options || !options.url) {
            alert('content loader script should be set as options.url');
            return;
        }

        (function(that) {
            inter = window.setInterval( function() { that.scroll()}, 50);
        })(this)
    }

    function kill() {
        clearInterval(inter);
        $(options.loader).hide();
    }

    return {
        start: start,
        kill : kill,
        scroll: scroll
    }
}

Here I wanted to expose only the start and kill functions but due to the use of windows.setInterval i had to expose also the scroll function.

Can someone please have a look at the code, and give some suggestion how may I optiomize it?


texts: FizzBuzz implementation using the ternary operator

texts:
This is my first time writing JAVA, and I'm trying to start off on the right track.

Using my C++ knowledge, I was able to understand the syntax for the ternary operator, but I'm not sure how it should be approached properly in JAVA.  I have used Ideone to test this, which include importss that apparently aren't even needed for this program, or so it seems.

I'd like a review over anything there is to offer, even if it involves telling me that starting with Ideone is not the best choice for whatever reasons.

import java.util.*;
import java.lang.*;
import java.io.*;

class BeginnerFizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; ++i) {
            System.out.println(
                (i % 15 == 0) ? "FizzBuzz" :
                (i % 3 == 0) ? "Fizz" :
                (i % 5 == 0) ? "Buzz" :
                i
            );
        }
    }
}


texts:
I was given the challenge of creating a Tic-Tac-Toe game that would print out the board each time. It was fun to make and part B of the challenge was to have others review my code. If you would like to see my code in action, you can do so from here. Any comments or advice on adjustments I could apply to my program would be greatly appreciated.

import random

square_values = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
number_of_turns = 0
no_wins = True

print("Lets play Tic-Tac-Toe!")
player_1_pick = ""
player_2_pick = ""
player_1 = input("Enter a name for player 1 and press enter, leave blank to leave as Player 1: ")
player_2 = input("Enter a name for player 2 and press enter, leave blank to leave as Player 2: ")

#sets the players name
if (player_1 == "" or player_2 == ""):
  if (player_1 == ""):
    player_1 = "Player 1"
  if (player_2 == ""):
    player_2 = "Player 2"
else:
  pass

#assigns X or O to players
if (random.randint(1,2) == 1):
  player_1_pick = input(player_1 + ", choose X or O: ").upper()
  if (player_1_pick == "X"):
    player_2_pick = "O"
  else:
    player_2_pick = "X"
else:
  player_2_pick = input(player_2 + ", choose X or O: ").upper()
  if (player_2_pick == "X"):
    player_1_pick = "O"
  else:
    player_1_pick = "X"

#makes a move
def make_a_move(player, player_pick):
  print("""
     |     |
  {}  |  {}  |  {}
_____|_____|_____
     |     |
  {}  |  {}  |  {}
_____|_____|_____
     |     |
  {}  |  {}  |  {}
     |     |
""" .format(square_values[0], square_values[1], square_values[2], square_values[3], square_values[4], square_values[5], square_values[6], square_values[7], square_values[8]))

  status = True
  while (status == True):
    choice = input(player + " pick a square(" + player_pick + "): ")
    try:
      int(choice)
      if (1 <= int(choice) <= 9):
        if (square_values[int(choice)-1] != "X" and square_values[int(choice)-1] != "O"):
          square_values.remove(choice)
          square_values.insert(int(choice)-1, player_pick)
          status = False
        else:
          print("Square already taken, select another square.")
      else:
        print("Input not an option, choose again.")
    except ValueError:
        print("Input not an option, choose again.")

status_main = True
def check_for_a_win(value1, value2, value3):
  global status_main
  global no_wins
  if (square_values[value1] == "X" and square_values[value2] == "X" and square_values[value3] == "X"):
    status_main = False
    no_wins = False
    if(player_1_pick == "X"):
      print("Player 1 won!")
    else:
      print("Player 2 won!")
  elif (square_values[value1] == "O" and square_values[value2] == "O" and square_values[value3] == "O"):
    status_main = False
    no_wins = False
    if(player_1_pick == "O"):
      print("Player 1 won!")
    else:
      print("Player 2 won!")
  else:
    pass

def func_1(player, pick):
  global number_of_turns
  global status_main
  if (no_wins == True):
    number_of_turns = number_of_turns + 1
    make_a_move(player, pick)
    check_for_a_win(0, 1, 2)
    check_for_a_win(3, 4, 5)
    check_for_a_win(6, 7, 8)
    check_for_a_win(0, 3, 6)
    check_for_a_win(1, 4, 7)
    check_for_a_win(2, 5, 8)
    check_for_a_win(0, 4, 8)
    check_for_a_win(2, 4, 6)
  if (number_of_turns == 9 and status_main == True):
    print("It's a tie :(")
    status_main = False

while (status_main == True):
  func_1(player_1, player_1_pick)
  func_1(player_2, player_2_pick)


texts: Font and color checker chrome extension in JavaScript

texts:
I have written this code for a color and font checker on a webpage.

The code is current and not so good. I would really like if I can get comments, reviews or any better approach for my PoC.

PoC: I want to highlight all the colors or fonts which should not be used on the webpage (the domain is defined by me as of now). I am traversing the DOM and checking the color and font styles and then highlight them if there are values out of my domain.

The current approach is very naive and not optimal because I am traversing and storing element styles, which is bad for duplicated DOM elements.

Any comments are appreciated, please let me know if I should add any more details.

inject.js

var brandColor = [
  "rgb(255, 255, 255)",
  "rgb(0, 0, 0)",
  "rgb(0, 163, 224)",
  "rgb(0, 118, 168)",
  "rgb(1, 33, 105)"
];

var brandFont = ["Open Sans", "Verdana"];
var fontNotMatch;

// generic walkDOM function - iterate DOM
function walkDom(start_element) {
  var arr = []; // we can gather elements here
  var loop = function(element) {
    do {
      // we can do something with element
      if (element.nodeType == 1) {
        // do not include text nodes
        arr.push(element);
      }
      if (element.hasChildNodes()) loop(element.firstChild);
    } while ((element = element.nextSibling));
  };
  loop(start_element);
  //loop(start_elem.firstChild); // do not include siblings of start element
  return arr;
}

var arr = walkDom(document.body);

var stylesContainer = {};
var fontChecker = {};
// iterate through DOM array
for (elem in arr) {
  // get all colors - [need better approach for this as well]
  stylesContainer[arr[elem].tagName] = getComputedStyle(
    arr[elem]
  ).getPropertyValue("color");

  // get all fonts
  fontChecker[arr[elem].tagName] = getComputedStyle(arr[elem]).getPropertyValue(
    "font-family"
  );
}

//console.log(stylesContainer);

// iterate styles
Object.keys(stylesContainer).forEach(element => {
  if (brandColor.indexOf(stylesContainer[element]) > -1) {
    //pass
  } else if (document.querySelector(element).childNodes.length == 1) {
    document.getElementsByTagName(element)[0].style.border = "2px solid red";
    var path =
      "https://example.com/icons/favicon.ico";
    var img = document.createElement("img");
    img.setAttribute("src", path);
    img.setAttribute("width", "20");
    document.querySelector(element).appendChild(img);
  }
  // console.log(stylesContainer[element]);
});

// iterate font family
Object.keys(fontChecker).forEach(element => {
  // Loop through each element and check the font family
  // console.log(fontChecker[element]);
  if (fontChecker[element].indexOf("Open Sans") != 1) {
    fontNotMatch = true;
  }
});

if (fontNotMatch == true) {
  // alert("Incorrect font");

  var f = document.createElement("h3");
  f.classList.add("error");
  f.innerHTML = "hey bhansa";
  document.querySelector("BODY").appendChild(f);

  var pathCSS = chrome.runtime.getURL("demo.css");
  var head = document.getElementsByTagName("head")[0];
  var link = document.createElement("link");
  link.rel = "stylesheet";
  link.type = "text/css";
  link.href = pathCSS;
  head.appendChild(link);
}


texts: Webapp Substrate script for WordPress on Debian-Nginx

texts:
The following script creates a webapp substrate for WordPress webapps/websites on Ubunu-Nginx with PHP-FPM and Mysql environments, with Certbot, while all software is uncustomized.

Such substrate includes, based on the 1 or more domains given as an argument (
/opt/nwsm.sh domain1.tld domain2.tld):

/etc/nginx/sites-available/example.com.conf.
etc/nginx/sites-enabled/ symlink.
Appropriate DB user and instance, named example.com.
Suitable wp-config.php file.

I especially hope to learn how I could shorten this code in at least 10 rows, if at all.

Installing the script

Just copy and paste in Bash and it willl be created under /opt/nwsm.sh.

cat <<-"NWSM" > /opt/nwsm.sh
    #!/bin/sh
    for domain; do
        cat <<-WEBAPPCONF > "/etc/nginx/sites-available/${domain}.conf"
            server {
                root /var/www/html/${domain};
                server_name ${domain} www.${domain};
                location ~*  \.(jpg|jpeg|png|gif|ico|css|js|ttf|woff|pdf)$ {
                    expires 365d;
                }
                location / {
                    index index.php index.html index.htm fastcgi_index;
                    try_files $uri $uri =404 $uri/ /index.php?$args;
                }
                location ~ \.php$ {
                    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                    include fastcgi_params;
                }
            }
        WEBAPPCONF
        ln -s /etc/nginx/sites-available/${domain}.conf /etc/nginx/sites-enabled/

        echo "Please enter database user password for user ${domain}: "
        read -s waps
        echo "Please enter database root password"
        mysql -u root -p <<-MYSQL
            create user "${domain}"@"localhost" identified by "${waps}";
            create database ${domain};
            GRANT ALL PRIVILEGES ON ${domain}.* TO ${domain}@localhost;
        MYSQL

        certbot --nginx -d ${domain} -d www.${domain}
    done

    cd /var/www/html/
    wget http://wordpress.org/latest.tar.gz
    tar xzvf latest.tar.gz && rm latest.tar.gz
    mv wordpress ${domain}

    cp /var/www/html/${domain}/wp-config-sample.php /var/www/html/${domain}/wp-config.php
    echo "1/1: Please enter the password of the site's DB user." && read -s dbup
    sed -i "s/database_name_here/${domain}"/g /var/www/html/${domain}/wp-config.php
    sed -i "s/username_here/${domain}"/g /var/www/html/${domain}/wp-config.php
    sed -i "s/password_here/${dbup}"/g /var/www/html/${domain}/wp-config.php

    chown www-data:www-data /var/www/html/* -R
    find /var/www/html/* -type d -exec chmod 755 {} \;
    find /var/www/html/* -type f -exec chmod 644 {} \;
    systemctl restart nginx.service
NWSM
chmod +x /opt/nwsm.sh

Using the script

Call the script with a domain and tld as an argument, say:

/opt/nwsm.sh example.com


texts:
This is an implementation of heapsort as seen on Programming Pearls, adapted for java List collections. It is working on a copy of the list passed-in on purpose at the moment.

import java.util.ArrayList;
import java.util.List;

public final class HeapSort {

    private HeapSort() {}

    public static <T extends Comparable<T>> List<T> heapSort(List<T> unsortedList) {
        assert unsortedList != null;
        assert unsortedList.size() > 1;
        List<T> sortedList = new ArrayList<T>(unsortedList);
        for (int i = 1; i < sortedList.size(); i++) {
            sortedList = siftUp(sortedList, i);
        }
        for (int i = sortedList.size() - 1; i >= 1; i--) {
            sortedList = swap(sortedList, 0, i);
            sortedList = siftDown(sortedList, i - 1);
        }
        return sortedList;
    }

    private static <T extends Comparable<T>> List<T> siftUp(List<T> unsortedList, int n) {
        assert n > 0;
        for (int i = n;;) {
            if (i == 0) {
                break;
            }
            int p = i / 2;
            if (unsortedList.get(p).compareTo(unsortedList.get(i)) >= 0) {
                break;
            }
            unsortedList = swap(unsortedList, i, p);
            i = p;
        }
        return unsortedList;
    }

    private static <T extends Comparable<T>> List<T> siftDown(List<T> unsortedList, int n) {
        for (int i = 0;;) {
            int c = 2 * (i + 1) - 1;

            if (c > n) {
                break;
            }
            if (c + 1 <= n) {
                if (unsortedList.get(c + 1).compareTo(unsortedList.get(c)) > 0) {
                    c += 1;
                }
            }
            if (unsortedList.get(i).compareTo(unsortedList.get(c)) >= 0) {
                break;
            }
            unsortedList = swap(unsortedList, i, c);
            i = c;
        }
        return unsortedList;
    }

    private static <T> List<T> swap(List<T> list, int firstIndex, int secondIndex) {
        assert list != null;
        assert list.size() > 0;
        assert 0 <= firstIndex;
        assert firstIndex < list.size();
        assert 0 <= secondIndex;
        assert secondIndex < list.size();
        if (firstIndex == secondIndex) {
            return list;
        }
        T tmpT = list.get(secondIndex);
        list.set(secondIndex, list.get(firstIndex));
        list.set(firstIndex, tmpT);
        return list;
    }
}

Should I assert on list size in softDown and siftUp? Is the passing back and forth of list references ok?


texts:
I've written a short implementation of the Eratosthenes' sieve.

def sieve(n):
    l = list(range(2, n + 1))
    out = []
    while len(l) > 0:
        out.append(l[0])
        l = list(filter(lambda n: n % l[0], l))
    return out

Is it lacking in efficiency? Are there any improvements or changes you would make?


texts:
I have implemented for-each as in jQuery, this is the code below,

var $ = (function(){
   var obj = {};
   return obj;
})();

$.each = function(collection,fn){

    if(collection.constructor.name === 'Array'){
        for(var i = 0; i < collection.length; i++){
            fn.call(this,collection[i]);
        }
    }else{
        for(var prop in collection){
            fn.call(this,collection[prop]);
        }
    }

};

$.each([1,2,3,7,8],function(num){
    console.log(num * 2);
});

$.each(['A','B','C'],function(char){
    console.log(char);
});

$.each({
    name : 'Rahul Shivsharan',
    department : 'Computer Science'
},function(value){
       console.log(value);
});

The output of the code is

2
4
6
14
16
A
B
C
Rahul Shivsharan
Computer Science

Please review my jQuery style for-each implementation, and let me know your feedback


texts:
I'm building a game.  It is going well at the moment, but I'm not quite happy with my code because is not working the way I want to, due my low knowledge of C#.  I was wondering if you guys could help me out to improve it by giving me some ideas and tips.

This is how I'm checking if the user has completed the levels.

public partial class MainMenu : PhoneApplicationPage
{
public  MainMenu()
{
    InitializeComponent();
    ReadStar1();
    ReadStar2();

}

private void btnbatland_Click(object sender, RoutedEventArgs e)
{
    NavigationService.Navigate(new Uri("/1star/MainPage.xaml", UriKind.Relative));
}

private async  Task ReadStar1()
{
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

    if (local != null)
    {
        var dataFolder = await local.GetFolderAsync("level");
        var file = await dataFolder.OpenStreamForReadAsync("star1.txt");
        string readtxt;
        using (StreamReader streamReader = new StreamReader(file))
        {
            readtxt = streamReader.ReadToEnd();
        }

        if (readtxt == "star1")
            star2_lock.Visibility = Visibility.Collapsed;
           star1_1.Visibility = Visibility.Collapsed;
    }
}

private async Task ReadStar2()
{
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

    if (local != null)
    {
        var dataFolder = await local.GetFolderAsync("level");
        var file = await dataFolder.OpenStreamForReadAsync("star2.txt");
        string readtxt;
        using (StreamReader streamReader = new StreamReader(file))
        {
            readtxt = streamReader.ReadToEnd();
        }

        if (readtxt == "star2")
            star3_lock.Visibility = Visibility.Collapsed;

    }
}

Sometimes it takes 1-4 seconds to load the MainMenu, then after 1-3 to load the function ReadStar1() and ReadStar2().  What could I do to improve its speed, so that the users don't even notice it has changed?


texts:
I want to know if this stack is implemented properly. Previously I was told a Linked List contains an inner class that represents a node and the outta class that represents the structure. Does that same idea apply to stacks and linked list? I am assuming not because they are so simple. Here is my implementation. Let me know if this is correct.

public class Stack{
  private int size;
  private int[] stack;

  public Stack(int height){
    stack = new int[height];
    size = 0;
  }

  public void push(int value){
    if(size == 0){

      stack[size] = value;
      size++;

    }

    else if(size == stack.length){
      System.out.println("The stack is full. The value cannot be added to the stack");
    }

    else {
    stack[size] = value;
    size++;
    }

  }

  public void pop(){

    if(size == 0){
      System.out.println("The stack is empty. Nothing can be removed from the stack");
    }
    else {
      size--;
      System.out.println(stack[size] + " was removed from the stack");

    }

  }

  public void peek(){

    if(size == 0){
      System.out.println("There is nothing to peek. The stack is empty");

    }
    else
      System.out.println(size);
      System.out.println("The value: " + stack[size -1]+ " is currently at the top of the stack");

  }

  public void isEmpty(){

    if(size == 0)
      System.out.println("The stack is empty");
    else
      System.out.println("The stack is not empty");

  }
}


texts:
The code implements custom iterator, which skips duplicate integers. The array expected is to be sorted.

public class GenericIterator<K> implements Iterator<K> {

    private K[] array; // Array will be set here
    private int index;

    GenericIterator(K[] array) {
        this.array = array;
        index = 0;
    }

    /*
     *
     *
     * (non-Javadoc)
     *
     * @see java.util.Iterator#hasNext() /** Returns <tt>true</tt> if this
     * iterator has more elements when traversing the array in the forward
     * direction. (In other words, returns <tt>true</tt> if <tt>next</tt> would
     * return an element rather than throwing an exception.)
     *
     * @return <tt>true</tt> if the array iterator has more elements when
     * traversing the array in the forward direction.
     */

    @Override
    public boolean hasNext() {
        return !(array.length == index);
    }

    /*
     *
     *
     * (non-Javadoc)
     *
     * @see java.util.Iterator#hasNext()
     *
     * /** Returns the next element in the array. This method may be called
     * repeatedly to iterate through the array, or intermixed with calls to
     * <tt>previous</tt> to go back and forth. (Note that alternating calls to
     * <tt>next</tt> and <tt>previous</tt> will return the same element
     * repeatedly.)
     *
     * @return the next element in the array.
     *
     */

    @Override
    public K next() {

        K outputElement = array[index++];
        if (index == 0) {
            index++;
        }

        while (hasNext()) {
            if (array[index] == array[index - 1]) {
                index++;
            } else {
                break;
            }
        }
        return outputElement;

    }
}


texts: Dynamic context.Set load and update/insert with using dynamic field in C# entity framework

texts:
I am writing an importer service. I have different sources and at the end I would like to push them into database tables.

For different db tables, I am using different dbset in the context. I also am aware for each db what is the primary key (it could be different, because other naming conversation).

I would like to resolve the issue, and refactor this code into 1 common, where I just have to name the Entity DbSet, and give the primary key, and everything is just working smooth with the given configuration:

var fmResultIds = fmResultset.Resultset.Records.Select(r => r.Fields.First(f => f.Name == primaryKeyName).Value).ToArray();
switch (config.Value.GetTableName())
{
    case "FmCompanyIntegration1":
        // The FMCompanyIntegration1 should be a parameter
        var allsql1 = context.Set<FmCompanyIntegration1>()
            .Where(t => true)
            //The issue here, the primary key should be a parameter
            .Where(t => fmResultIds.Contains(t.CoId))
            .Take(100000)
            .ToDictionary(kvp => kvp.CoId, kvp => kvp);
        //this is taking care to update/insert the record. We do not have to delete anything
        foreach (var record in fmResultset.Resultset.Records)
        {
            var entity = allsql1.FirstOrDefault(r => r.Key == record.Fields.First(f => f.Name == primaryKeyName).Value).Value;
            if (entity != null)
            {
                // LoadRecord is not a problem, because all entity is coming from the same base class, which has this function defined
                entity.LoadRecord(record);
                context.Entry(entity).State = EntityState.Modified;
            }
            else
            {
                // here I also have to dynamically create the class...
                entity = new FmCompanyIntegration1();
                entity.LoadRecord(record);
                context.Entry(entity).State = EntityState.Added;
            }
        }
        break;
    // !!!!!!!!!!!!!!!!!!!
    // THE GOAL IS TO get rid of this part of the code, and use only a dynamic context.Set creation instead
    // !!!!!!!!!!!!!!!!!!!
    // This is an unwanted duplication
    //
    case "FmBookBackyard1":
    default:
        var allsql2 = context.Set<FmBookBackyard1>()
            .Where(t => true)
            // Again I know what is the primary key field name... Or I am ready to extend any reasonable class to give it back
            .Where(t => fmResultIds.Contains(t.BkRecordId))
            .Take(100000)
            .ToDictionary(kvp => kvp.BkRecordId, kvp => kvp);
        //this is taking care to update/insert the record. We do not have to delete anything
        foreach (var record in fmResultset.Resultset.Records)
        {
            var entity = allsql2.FirstOrDefault(r => r.Key == record.Fields.First(f => f.Name == primaryKeyName).Value).Value;
            if (entity != null)
            {
                entity.LoadRecord(record);
                context.Entry(entity).State = EntityState.Modified;
            }
            else
            {
                entity = new FmBookBackyard1();
                entity.LoadRecord(record);
                context.Entry(entity).State = EntityState.Added;
            }
        }
        break;
}
context.SaveChanges();


texts:
Below there is a function eating all strings and convert it to Unicode. It works fine. But is it the best way to do so? Is there maybe already an existing function for it?

The reason was a German Windows version which prints German ä ö ü - error-messages which are retrieved from popen/communicate etc. There must have been someone before me with the same issue.

# python2.7
def all_eating_unicode_converter(input_string):
    test1 = 'äöü'
    test2 = b'\xe4\xf6\xfc'
    test3 = u'äöü'
    """
    Converts every input to unicode. tested with testcases abouve!
    :param input_string: may be a string or unicode or bytes.
    :return: returns unicode
    """

    l.debug("type: %s\n message:%s" % (type(input_string), input_string))
    if type(input_string) is not unicode:
        # i don't need to decode unicode. because it already is!
        output_string = input_string.decode("utf-8")  # converts bytes to unicode
    else:
        output_string = input_string
    return output_string


texts: The logic for re.match() , sys.exit(1) does not make sense, plus why can't i use return True if the re.match regex matches

texts:
The whole idea behind this ,is the user enters :
1. hg commit -m "NO-TIK" and is able to submit the changeset
2. hg commit -m "NO-REVIEW" also does the same as # 1
3. hg commit -m "JIRA-123 blah blah" is also submitted as long as there is a valid issue "JIRA-123" otherwise the commit is reverted with the message "%s does not exist"%ticket
4. hg commit -m "plain english without ANY of the above, reverts the changes , so the above 3 rules MUST be observed.

#!/usr/bin/env python

import re, os, sys, jira, subprocess
from optparse import OptionParser
import warnings
from collections import namedtuple

def verify_commit_text(tags):
    for line in tags:
        if re.match(r'[^\NO-TIK]',line):
            sys.exit(1)
        elif re.match(r'[^\NO-REVIEW]', line):
            sys.exit(1)
        elif re.match(r'[a-zA-Z]+-\d+', line):
            # Validate the JIRA ID
            m = re.search("([a-zA-Z]+-\d+)",line)
            m_args = m.group(1)
            m_args = [m_args]
            if CheckForJiraIssueRecord(m_args):
                sys.exit(1)
            else:
                print >> sys.stderr, ("%s does not exist"%m_args)
        else:
            sys.exit(0)

def CheckForJiraIssueRecord(my_args):
    # turn off stdout
    #sys.stdout = open(os.devnull)
    #sys.stderr = open(os.devnull)
    com = jira.Commands()
    logger = jira.setupLogging()
    jira_env = {'home':os.environ['HOME']}
    command_name = "cat"
    server = "http://jira.server.com:8080/rpc/soap/jirasoapservice-v2?wsdl"
    options = namedtuple('Options', 'user password')('user','password')
    jira.soap = jira.Client(server)
    jira.start_login(options, jira_env, command_name, com, logger)
    issue = com.run(command_name, logger, jira_env, my_args)
    if issue:
        return True

if __name__ == '__main__':
    commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"'))
    if commit_text_verified:
        sys.exit(0)
    else:
        print >> sys.stderr, ('[obey the rules!]')
        sys.exit(1)


texts:
I just finished my working code, but still want to improve it.

I want to transform this input:

<item>asdf</item>
<item>asdf</item>
<item>asdf</item>

to this output:

<string name="x1">asdf</string>
<string name="x2">asdf</string>
<string name="x3">asdf</string>

My current code:

   static void Main(string[] args)
        {
            String content;

            using (StreamReader reader = new StreamReader("arrays2.xml"))
            {
                content = reader.ReadToEnd();
            }

            int counter = 0;
            int startIndex = 0;
            while ((startIndex = content.IndexOf("<item>", startIndex)) != -1)
            {
                counter++;
                content = content.Substring(0, startIndex) + "<string name=\"rule" + counter + "\">" + content.Substring(startIndex + 6);
            }

            content = content.Replace("</item>", "</string>");

            using (StreamWriter writer = new StreamWriter("arrays2_formatted.xml"))
            {
                writer.Write(content);
            }
            Console.WriteLine(content);

        }

I think the bottleneck is in the content assignment within the loop, as a lot of String instance are created and thrown away.

However, is there a completely different way to do this efficiently?


texts: Creating a TCP Listener and receiving data

texts:
I am very new to network programming and I'm thinking I have probably misconstrued the creation of an appropriate TCP listener. The code I have below works perfectly, but I have a feeling it's a "hack and slash" miracle and could come apart easily when set into my production environment. What can I do to improve this receive message?

Objective

The application should be able to receive a string and parse it into an xml string. Later, after a set of validation and data collection is completed, a response will be sent back to the client.

Receive Message

private static void ReceivePortMessages()
{
    int requestCount = 0;
    tcpListener.Start();
    Debug.Print(" >> Server Started");
    tcpClient = tcpListener.AcceptTcpClient();
    Debug.Print(" >> Accept connection from client");

    while (true)
    {
        try
        {
            requestCount = requestCount++;
            NetworkStream networkStream = tcpClient.GetStream();
            byte[] bytesFrom = new byte[10025];
            networkStream.Read(bytesFrom, 0, (int)tcpClient.ReceiveBufferSize);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
            dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));

            XmlDocument xm = new XmlDocument();
            xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
            XmlElement root = xm.DocumentElement;
            string rootName = root.FirstChild.Name;
            RouteInboundXML(rootName, dataFromClient, sw);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            Debug.Print("ReceivePortMessages: Remote client disconnected. " + ex.ToString());
            tcpClient.Close();
            tcpListener.Stop();
            ReceivePortMessages();
            return;
        }
        catch (Exception ex)
        {
            Debug.Print("ReceivePortMessages: " + ex.ToString());
            tcpClient.Close();
            tcpListener.Stop();
            ReceivePortMessages();
            return;
        }
        Debug.Print(" >> exit");
    }
}

Send Message

private void SendReply(string reply)
{
    try
    {
        NetworkStream networkStream = _TcpClient.GetStream();
        string serverResponse = reply;
        Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
        networkStream.Write(sendBytes, 0, sendBytes.Length);
        networkStream.Flush();
        Debug.Print(" >> " + serverResponse);
    }
    catch (ArgumentOutOfRangeException ex)
    {
        Debug.Print("SendReply: Remote client disconnected. " + ex.ToString());
        _TcpClient.Close();
        _TcpListener.Stop();
        ReceivePortMessages();
        return;
    }
}


texts:
This was an assignment from "The Odin Project". This is my first program using JSON. I've been told I need work on structuring my classes, any advice will be appreciated!

https://github.com/jmooree30/Hangman/upload/master

require 'json'
load 'display.rb'

class Hangman
  attr_accessor :name
  @name = name

  def initialize
    puts "What is your name?"
    @name = gets.chomp
    puts "
################################################
                   HANGMAN
################################################
               _________
              |
              |       |
              |       O
              |      /|\\
              |       |
              |      / \\
              |
              -----------------
Welcome #{@name} to Hangman. The computer will generate
a 5-12 letter random word. You will try to guess
that word one letter at a time. Try to solve the
puzzle before time runs out!
\n
"

  end
end

class Gameplay
  attr_accessor :array, :filestuff, :random_word, :cipher, :random_word2, :counter
  def initialize
  @array = []
  @filestuff = File.foreach('5text.txt') do |x|
      chomped = x.chomp
      @array << chomped if (chomped.length >= 5 and chomped.length <= 12)
    end
  @random_word = @array.sample
  @cipher = @random_word.gsub(/[a-z]/, '*').split(//)
  @random_word2 = @random_word.split(//)
  @counter = 5
  puts "Would you like to load a saved game? Y/N"
  saved_game = gets.chomp
  if saved_game == "Y"
    game_file = File.read("saved.json")
    data = JSON.parse(game_file)
    @filestuff = data["filestuff"]
    @random_word = data["random_word"]
    @cipher = data["cipher"]
    @random_word2 = data["random_word2"]
    @counter = data["counter"]
  end
  puts @cipher.join
  puts "Enter a letter."

  def to_json
    JSON.generate({filestuff: @filestuff, random_word: @random_word, cipher: @cipher, random_word2: @random_word2})
  end

  def save_game(string)
    File.open("saved.json", "w") do |game_file|
  game_file.write(string)
    end
  end

  def choice(n)
    @random_word2.each_with_index do |i,index|
      if i == n
        @cipher[index] = i
      end
    end
      if n == @random_word2.join.to_s
        puts "You win"
        puts "would you like to start another game? Y/N"
        new_game = gets.chomp
        if new_game == "Y"
          Hangman.new
          else exit
        end
      end
      if @random_word2.include?(n) == false
        @counter -= 1
        display
        puts "#{@counter} guesses remaining."
      end
      if @counter == 0
        puts "would you like to start another game? Y/N"
        new_game = gets.chomp
        if new_game == "Y"
          else exit
        end
      end
      if n == "1"
          save_game(to_json)
        end
        puts @cipher.join
        puts "Want to save? Press 1 to save."
  end

  @counter = 5
  while @counter > 0
    choice(gets.chomp)
  end

 end
end
Hangman.new
Gameplay.new


texts: Check if a string is palindrome or two strings are the opposite of each other

texts:
I made a function which checks if a word is the opposite of each other (ex: word and drow) and then realized that with minor changes it could also be used to detect if a word is palindrome. They both return bools, false means they aren't opposite/it isn't palindrome, true means they are/it is.
First function:

bool opposite(std::string& first, std::string& second) {
    size_t size = first.size();
    if (size != second.size()) {
        return false;
    }

    for (size_t left = 0, right = size - 1; first[left] == second[right]; ++left, --right) {
        if (left == size) {
            return true;
        }
    }
    return false;
}

Second function:

bool palindrome(std::string& word) {

    for (int left = 0, right = word.size() - 1; word[left] == word[right]; ++left, --right) {
        if (right < 0) {
            return true;
        }
    }
    return false;
}

In the second function I decided to use int because size_t is unsigned, I could use left == first.size() in the if statement, but that would mean calling size() twice which I think would slow me down. The other option would be storing the value returned by first.size() in a size_t (let's call it size), using it to initialize right and changing the condition to left == size, but that would mean keeping an extra size_t variable around.

I already tested them, they work, but the question is, are there improvements I can make to speed them up?


texts: Generalized PHP function for editing data in a table

texts:
I've got some legacy code which I need to maintain and its got this function which works perfectly fine, but I'm trying to understand if it is working using acceptable coding practices or not... I am trying to understand if it is safe and secure to operate the site with the function as-it-is.

The function would be called as:

$this->editData('users',"activation_key",$_GET['key']);

The actual function (unedited):

function editData($table_name,$fldname,$fldval,$other='',$lang_flag=0)
{

    $link = $this->my_connect();
    $this->my_select_db($this->DATABASE_NAME,$link);
$arr_types =  array("TR_", "TN_", "TREF_", "PHR_", "PHN_", "IR_", "IN_", "MR_", "MN_", "TNEF_", "TRC_", "TNC_", "TRFN_", "TNFN_","TNURL_","TRURL_");
    if (!empty($GLOBALS["HTTP_POST_VARS"])) {
        reset($GLOBALS["HTTP_POST_VARS"]);
        while (list($k,$v)=each($GLOBALS["HTTP_POST_VARS"]))
        {

            for($p=0;$p<count($arr_types);$p++)
            {
                if(stristr($k,$arr_types[$p])!="")
                {
                    $k = str_replace($arr_types[$p],"",$k);
                }
            }
            ${strtolower($k)}=$v;
            //echo "
 k =$k -- v = $v";
        }
    }
    if (!empty($_POST)) {
        reset($_POST);
        while (list($k,$v)=each($_POST))
        {

            for($p=0;$p < count($arr_types);$p++)
            {
                if(stristr($k,$arr_types[$p])!="")
                {
                    $k = str_replace($arr_types[$p],"",$k);
                }
            }
            ${strtolower($k)}=$v;
            //echo "
 k =$k -- v = $v";
        }
    }
    if (!empty($GLOBALS["HTTP_GET_VARS"])) {
        reset($GLOBALS["HTTP_GET_VARS"]);
        while (list($k,$v)=each($GLOBALS["HTTP_GET_VARS"]))
        {

            for($p=0;$p < count($arr_types);$p++)
            {
                if(stristr($k,$arr_types[$p])!="")
                {
                    $k = str_replace($arr_types[$p],"",$k);
                }
            }
            ${strtolower($k)}=$v;
            //echo "
 k =$k -- v = $v";
        }
    }
    if (!empty($_GET)) {
        reset($_GET);
        while (list($k,$v)=each($_GET))
        {

            for($p=0;$p < count($arr_types);$p++)
            {
                if(stristr($k,$arr_types[$p])!="")
                {
                    $k = str_replace($arr_types[$p],"",$k);
                }
            }
            ${strtolower($k)}=$v;
            //echo "
 k =$k -- v = $v";
        }
    }
     $result=$this->my_query("show fields from $table_name",$link);
    $query="update $table_name SET   ";
     while ($a_row = $this->my_fetch_array($result)) {
        $field="$a_row[Field]";

            if($field!=$fldname)
            {
                if(isset($$field))
                {
                       $query.="`".$field."`=";

                       $query.="'".$this->removeQuotes($$field,$lang_flag)."' , ";
                }
                else
                {
                    if(isset($GLOBALS["$field"]))
                    {
                        //echo "
 var ".$GLOBALS["$field"];
                        $query.="`".$field."`=";
                        $query.="'".$this->removeQuotes($GLOBALS["$field"],$lang_flag)."' , ";

                    }
                }
            }
     }
     $query = substr($query,0,-2);
    $query.=" where `$fldname`='$fldval' $other";
    $query  ;
    //echo $query;
     $result=$this->my_query($query,$link);
     $this->my_free_result($result);
     $this->my_close($link);
     return $result;
}


texts: Left or right padding a string with the specified character

texts:
Can I improve performance of below method? Is there anything I need to optimize or any redundancy I need to remove to make it more efficient? It's a simple method used to pad strings by left or right.

public static String padString(String input, boolean leftPad, char padChar, int maxLength) {
    String output = CommonBaseConstants.EMPTY_STRING;
    final int defaultSize = 8;
    String filledStr = null;
    if (CommonBaseConstants.CHAR_ZERO == padChar) {
        filledStr = StringUtils.getZeroes(defaultSize);
    }
    else if (CommonBaseConstants.CHAR_SPACE == padChar) {
        filledStr = StringUtils.getSpaces(defaultSize);
    }

    if (null != filledStr && null != input) {
        if (maxLength > input.length()) {
            StringBuilder value = new StringBuilder();
            int remainder = maxLength % defaultSize;
            if (0 != remainder) {
                value.append(filledStr, 0, remainder);
            }

            int loopSize = (maxLength - remainder) / defaultSize;
            for (int index = 0; index < loopSize; index++) {
                value.append(filledStr);
            }

            output = value.toString();
            if (leftPad) {
                output = output.substring(0, maxLength - input.length()) + input;
            }
            else {
                output = input + output.substring(0, maxLength - input.length());
            }
        }
        else {
            output = input;
        }
    }

    return output;
}


texts: Doing an ROP style bind for two functions on the same input in a pipeline

texts:
I am working on understanding Railway Oriented Programming (Scott Wlaschin style) in F#.  In my example I want to create a pipeline which does some calculation, applies two different functions to the output of that initial calculation, then hands off a tuple of its results to a final function.

In real code the 'initial calculation' might be getting some data, the 'two different functions' might produce a textual summary and a chart of the data, and the final function might be rendering some output containing both the text and the chart.

I've invented a bind2 function to achieve this, but I can't help thinking that if this was a good idea it would already be common practice and must appear (in disguise) in existing libraries such as Scott's.

Please let me know how I would achieve what I want in an idiomatic style.

Here's my code.  All above bind2 is taken broadly from Scott's code, the remainder is my bind2 function and a simple demo.

type Result<'S, 'F> =
| Success of 'S
| Failure of message : 'F list

let bind f x =
    match x with
    | Success s -> f s
    | Failure f -> Failure f

let bind2 (f1 : 'A -> Result<'B, 'F>)
          (f2 : 'A -> Result<'C, 'F>) (x : Result<'A, 'F>) : Result<'B * 'C, 'F> =
    match x with
    | Success _ ->
        let r1, r2 = (bind f1) x, (bind f2) x
        match r1, r2 with
        | Success s1, Success s2 ->
            Success(s1, s2)
        | Failure f1, _ ->
            Failure f1
        | _, Failure f2 ->
            Failure f2
    | Failure f -> Failure f

let demo1 (a: int) : Result<int, string> =
    Success a

let demo2 (a: int) : Result<string, string> =
    a |> string |> Success

let demo3 (a: int) : Result<string, string> =
    a |> (*) -1 |> string |> Success

let demo4 (s1 : string, s2 : string) =
    sprintf "%s - %s" s1 s2 |> Success

let Demo =
    bind demo1
    >> bind2 demo2 demo3
    >> bind demo4


texts:
I made a code for a health system for the game I'm creating. I made it myself and I wanted some criticism on how to make it better. Thanks for viewing.

## Health system
import time
SH = 100
PA = True
while PA == (True):
  DMG = input("How much damage would you like to take?" )
  Output = int(SH) - int(DMG)
  if Output == (80):
    print("You took 20 damage!")
    print(" --------------")
    print("|■■|■■|■■|■■|  |")
    print(" --------------")
  elif Output == (60):
    print("You took 40 damage!")
    print(" --------------")
    print("|■■|■■|■■|  |  |")
    print(" --------------")
  elif Output == (40):
    print("You took 60 damage!")
    print(" --------------")
    print("|■■|■■|  |  |  |")
    print(" --------------")
  elif Output == (20):
    print("You took 80 damage!")
    print(" --------------")
    print("|■■|  |  |  |  |")
    print(" --------------")
  elif Output == (0):
    print("You took 100 damage!")
    print(" --------------")
    print("|  |  |  |  |  |")
    print(" --------------")
    print("You died!")
  else:
    print("That isn't a command")

  PA = input("Would you like to play again? |Y/N| ")
  if PA == ("Y"):
    PA = True
  elif PA == ("N"):
    PA = False
    print("The program will now close")
    time.sleep(5)
  else:
    print("That is not a command...")


texts: HackerEarth: Find array index with cumulative sum till there matching a given target

texts:
The problem was like this:

Given an array:

[1, 2, 1, 3, 4]

where each index value shows the production of that particular day. So, at index 0, production is 1, index 1 - production is 2, so on...

Then we're given some targets (N numbers of them). For a given target T, we've to find the index till which the cumulative production matches the target.

For e.g., a target of 4 will be achieved by index 2 (1 + 2 + 1 = 4 >= 4). Similarly, a target of 10 will be achieved by index 4 (1 + 2 + 1 + 3 + 4 = 11 >= 10). Basically, the target is achieved for index i, if cumulative sum till that index is greater than target. We've find the minimum index for each target.

For the above array, sample input and output would be:

4, 2, 10
2, 1, 4

My idea for the problem is: While reading the array as input, I pre-process the array to store cumulative at each index. So, I'll convert the above array to:

[1, 3, 4, 7, 11]

and then for the given target, I'll find the minimum value in array greater than that target (can easily be done using binary search).

Assuming the total number of targets input is Q and size of initial array is T, my algorithm would be O(Qlog(T)), which seems to be quite fine. But, it failed with TLE for input #5 on hackerearth.

Then I thought of maintaining a target cache (Map<Long, Integer>), which I'll populate after reading each array element. That map will store the index of each possible target till the maximum value.

For the above array, the map which I build would be like:

{1=0, 2=1, 3=1, 4=2, 5=3, 6=3, 7=3, 8=4, 9=4, 10=4, 11=4}

So, for each target, I can just do map.get(target), to get the index. For this solution, pre-processing numbers, and building map should be O(maxTarget), where maxTarget is the maximum value a target can get. And then fetching result is just O(1). But again, this also failed with TLE.

I'm completely out of thought to modify this to make the last input pass. Here's my code for 2nd approach (map):

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

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    int T = Integer.parseInt(line);

    String input = br.readLine();
    StringTokenizer tokenizer = new StringTokenizer(input, " ");

    long[] numbers = new long[T];
    Map<Long, Integer> targetCache = new HashMap<Long, Integer>();

    int i = 0;
    while (tokenizer.hasMoreTokens()) {
        int nextTarget = Integer.parseInt(tokenizer.nextToken());
        long previousTarget = i == 0 ? 0 : numbers[i - 1];
        numbers[i] = previousTarget + nextTarget;
        long currentCumulativeTarget = numbers[i];
        for (long j = previousTarget + 1; j <= currentCumulativeTarget; j++) {
            targetCache.put(j, i);
        }
        i++;
    }
    System.out.println(targetCache);

    int Q = Integer.parseInt(br.readLine());
    for (int x = 0; x < Q; x++) {
        long target = Long.parseLong(br.readLine());
        Integer index = targetCache.get(target);
        // If target can't be matched, print -1
        System.out.println(index == null ? -1 : index);
    }
}

How can the above solution be optimized further? Any leads? BTW, I can't test the solution, as that was the part of a interview test, and I can't see that question again.


texts:
Usually when I see tutorials about Observer Pattern I see an unique method called notify, but I'm wondering. What if I have different methods that can be called in different moments but needs to notify the others when this happen? Like events, am I doing this wrong? or still begin the observer pattern?

#include <iostream>
#include <algorithm>
#include <vector>

class Observer
{
public:
    virtual void notifyBefore() = 0;
    virtual void notifyAfter() = 0;
};

class Subject
{
public:
    void attachObserver(Observer * observer)
    {
        observers.push_back(observer);
    }

    void detachObserver(Observer * observer)
    {
        auto index = std::find(observers.begin(), observers.end(), observer);
        if (index != observers.end())
        {
            observers.erase(index);
        }
    }

    virtual void notifyBefore()
    {
        for (auto current : observers)
        {
            current->notifyBefore();
        }
    }

    virtual void notifyAfter()
    {
        for (auto current : observers)
        {
            current->notifyAfter();
        }
    }
private:
    std::vector<Observer *> observers;
};

class ConcreteObserver : public Observer
{
public:
    void notifyBefore()
    {
        std::cout << "You called me before..." << std::endl;
    }

    void notifyAfter()
    {
        std::cout << "You called me after..." << std::endl;
    }
};

class ConcreteSubject : public Subject
{
public:

};

int main()
{
    auto subject = new ConcreteSubject;
    subject->attachObserver(new ConcreteObserver);

    subject->notifyBefore();

    for (int i = 0; i < 5; ++i)
        std::cout << i << std::endl;

    subject->notifyAfter();
}


texts: C++ sum and averaging functions for arrays and argument sets

texts:
Here are two sets of variadic C++ functions to do fast summing and averaging of arrays (plain & std::array) or argument sets, (re)written as part of my generic toolbox.

The sum functions are pretty generic, the averaging ones operate on floating point based types only (the integer counterparts are application specific).

Usage example:

std::array<volatile float, 5> arr1 { 1.1f, 1.2f, 1.3f, 1.4f, 1.5f };
volatile float arr2[] { 1.1f, 1.2f, 1.3f, 1.4f, 1.5f };

volatile float res1 = sum(arr1);
volatile float res2 = avg(arr2, sizeof(arr2)/sizeof(arr2[0]));
volatile auto res3 = avg(1.2f, 1.4f, 1.6);

Live demo at: https://godbolt.org/g/DMHv7Y

The sum functions:

#include <cstdint>
#include <utility>
#include <type_traits>
#include <array>

/**
 * Return the sum of all values in the provided `std::array`.
 * @param  arr std::array
 * @return     sum
 */
template <typename T, size_t S>
inline constexpr auto sum(const std::array<T, S> arr) {
    std::remove_cv_t<std::remove_reference_t<T>> t = 0;
    for (const auto v : arr) {
        t += v;
    }
    return t;
}

/**
 * Return the sum of all values in the provided plain array.
 * @param  arr Array
 * @param  l   length
 * @return     sum
 */
template <typename T, typename = typename std::enable_if<std::is_pointer<T>::value, void>::type>
inline constexpr auto sum(const T arr, size_t l) {
    std::remove_cv_t<
        std::remove_reference_t<
            decltype(arr[0])>> t = 0;
    for (size_t i = 0; i < l; i++) {
        t += arr[i];
    }
    return t;
}

/**
 * Return the sum of all values. Tries to use the common type for the return value.
 * @param  ts Arguments to sum
 * @return    sum
 */
template <typename... Ts,
          typename = typename std::enable_if<!std::is_pointer<std::common_type_t<Ts...>>::value, void>::type>
inline constexpr auto sum(Ts&&... ts) {
    std::common_type_t<Ts...> t = 0;
    for (const auto val : std::initializer_list<std::common_type_t<Ts...>>{ts...}) {
        t += val;
    }
    return t;
}

The averaging functions:

#include <cstdint>
#include <utility>
#include <type_traits>
#include <array>

/**
 * Return the average of all values in the provided `std::array`.
 * @param  arr std::array
 * @return     average
 */
template <typename T, size_t S, typename = typename std::enable_if<std::is_floating_point<T>::value, void>::type>
inline constexpr auto avg(const std::array<T, S> arr) {
    std::remove_cv_t<std::remove_reference_t<T>> t = 0;
    for (const auto v : arr) {
        t += v;
    }
    return t / S;
}

/**
 * Return the average of all values in the provided array.
 * @param  arr array
 * @param  l   length
 * @return     average
 */
template <typename T, typename = typename std::enable_if<std::is_pointer<T>::value && std::is_floating_point<std::remove_pointer_t<T>>::value, void>::type>
inline constexpr auto avg(const T arr, size_t l) {
    std::remove_cv_t<
        std::remove_reference_t<
            decltype(arr[0])>> t = 0;
    for (size_t i = 0; i < l; i++) {
        t += arr[i];
    }
    return t / l;
}

/**
 * Return the average of all arguments. Tries to use the common type for the return value.
 * @param  ts Arguments to sum
 * @return    average
 */
template <typename... Ts,
          typename = typename std::enable_if<!std::is_pointer<std::common_type_t<Ts...>>::value && std::is_floating_point<std::common_type_t<Ts...>>::value, void>::type>
inline constexpr auto avg(Ts&&... ts) {
    std::common_type_t<Ts...> t = 0;
    for (const auto val : std::initializer_list<std::common_type_t<Ts...>>{ts...}) {
        t += val;
    }
    return t / sizeof...(Ts);
}

The generic patterns here can of course be used to create all kinds of data processing tools. I'd love to know if/how I can improve them.


texts:
So I received a comment on my previous question that suggested creating a Dictionary of my menus to store the data in.  So that got me thinking, all I am doing is going back to the first instance of MenuItem in the ItemList that has a Menu of Back[0].Menu.  So why not just iterate through there and open the menu when I find it?

So, here is my final code:

public void GoBack()
{
    NavButtonUsed = true;

    Forward.Insert(0, Back[0]);
    Back.RemoveAt(0);

    if (Back[0].Title.StartsWith(" ") && CurrentItem.Menu != Back[0].Menu)
    {
        foreach(MenuItem mi in ItemList)
        {
            if (mi.Menu == Back[0].Menu)
            {
                CurrentItem = ItemList[ItemList.IndexOf(mi)];
                break;
            }
        }
    }

    CurrentItem = ItemList[ItemList.IndexOf(Back[0])];
    NavButtonUsed = false;
}

Everything else stayed the same as in my previous question, please check that for details.


texts:
I'm creating a website that parses in currency rates of the three major cities listed below in the $cities array.

<?php

// Feed URL's //
$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';

// Define arrays //
$cities = array(
    'London',
    'New York',
    'Paris'
);

$currencyCode = array(
    'GBP',
    'USD',
    'EUR'
);

// Arguments parsed onto theMoneyConverter URL to set position of the <item> tags declared in the XML document
$currencySource = array(
    $theMoneyConverter . $currencyCode[0] . '/rss.xml?x=15',
    $theMoneyConverter . $currencyCode[1] . '/rss.xml?x=16',
    $theMoneyConverter . $currencyCode[2] . '/rss.xml?x=56'
);
?>

Above is my configuration script that a developer will use if they wish to drop a city or add a new one.  Notice in my $currencySource array that I add arguments to the end of each URL.  For example, at index 0 in the array I add ?x=15.  This argument corresponds to the <item> element from the original source feed from themoneyconvert.com.  In the case of ?x=15, this would be the 15th <item> element from the XML document.

The XML document to confirm this.  The 15th  element contains the following element just to clarify:

<item>
<title>EUR/GBP</title>

The following is stored in a separate script called getCurrency.php:

function get_currency_rate($currencySource) {

      try {
        $xml = new SimpleXmlElement(file_get_contents($currencySource));
    } catch (Exception $e) {
        echo 'Caught exception: An error has occured. Unable to get file contents';
    }

    $vars = parse_url($currencySource, PHP_URL_QUERY);
    parse_str($vars);
    switch ($x) {
        case 15:
            get_rate($xml, 15); //EUR 15
            get_rate($xml, 56); //USD 56
            break;
        case 16:
            get_rate($xml, 16); //GBP 16
            get_rate($xml, 15); //EUR 15
            break;
        case 56: default :
            get_rate($xml, 15); // EUR 15
            get_rate($xml, 56); // USD 56
            break;
    }
}

// Get and return currency rate
function get_rate(SimpleXMLElement $xml, $x) {

    $currency['rate'] = $xml->channel->item[$x]->description;

    echo $currency['rate'], '<br />';
}

I call the get_currency_rate() function from my user interface like such:

echo get_currency_rate($currencySource[$index])

After getting the file contents I extract the argument that I added to the URL from the configuration file listed above and store it as a variable $x.  The XML feed and variable $x are parsed into the get_rate function().

The whole process doesn't seem very maintainable and particular readable.  Adding a new city into the equation would become a nightmare for another developer.  Can anyone think of any other alternatives?


texts: Flatten an array of arbitrarily nested arrays of integers

texts:
Write a piece of functioning code that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].

* tests use Jasmine can be found  http://jsbin.com/harofo/4/edit?html,js,output
* @input  array
* @output array
*/

function flatten(arr) {
    // this function is called in recursion mode
    let result = [];
    if (arr && arr.length > 0) {
        arr.forEach(function(value) {
            if(Array.isArray(value)) {
                result = result.concat(flatten(value));
            } else {
                result.push(value);
            }
        });
    }
    return result;

};


texts: Checking if a number is prime in NASM Win64 Assembly

texts:
I'm just learning Assembly. This program is a simple attempt to determine if a given number is prime or not.

Compiled as follows using VS2019 x64 Native Tools Command Prompt:

> nasm -g -fwin64 isprime.asm

> cl /Zi isprime.obj msvcrt.lib legacy_stdio_definitions.lib

isprime.asm

bits 64
default rel

extern printf
extern scanf

section .data

    number: dq 0
    isPrime: dq 1
    counter: dq 0

    question: db "Which number would you like to check? ", 0
    fmt: db "%d", 0
    numberIsPrime: db "%d is prime", 10, 0
    numberIsNotPrime: db "%d is not prime", 10, 0

section .text

global main
main:
    push rbp
    mov rbp, rsp

    sub rsp, 32
    mov rcx, question
    call printf
    add rsp, 32

    sub rsp, 32
    mov rdx, number
    mov rcx, fmt
    call scanf
    add rsp, 32

    mov rcx, [number]
    mov [counter], rcx

continue_prime_check:
    dec qword [counter]
    cmp qword [counter], 2
    jge not_reached_1_yet
    jmp prime_check_ended

not_reached_1_yet:
    mov rax, [number]
    cdq
    mov rbx, [counter]
    idiv rbx
    cmp edx, 0
    je evenly_divisible
    jmp not_evenly_divisible

evenly_divisible:
    mov qword [isPrime], 0

not_evenly_divisible:
    jmp continue_prime_check

prime_check_ended:
    cmp qword [isPrime], 1
    je number_was_prime
    jmp number_wasnt_prime

number_was_prime:
    sub rsp, 32
    mov rdx, [number]
    mov rcx, numberIsPrime
    call printf
    add rsp, 32
    jmp end_if

number_wasnt_prime:
    sub rsp, 32
    mov rdx, [number]
    mov rcx, numberIsNotPrime
    call printf
    add rsp, 32

end_if:
    mov rbp, rsp
    pop rbp
    ret


texts: Calculating e^x by math.h and by own means

texts:
For this program, the user needs to enter an exponent and the program will calculate \$e\$ (Euler's number) to the power of the exponent the user inputs.

This is done by two ways:

By the math.h library
By a for loop (Series)

Then the program calculates the difference of these two functions (which we now call \$d\$) and calculates \$n\$.

\$n = \frac{d}{0,001}\$

#include <math.h>
#include <stdio.h>

main()
{
int a, exponent, h;
float math, iteraties, c, stdio, z, verschil;

    char stop='n';
    while (stop!='j')
    {

      printf("vul exponent in:\t\t");
      scanf("%d",&exponent);
      syntax: math= exp(exponent);
      c=1.0;
      h=0;
      stdio=1.0;
      a=0;
      for (iteraties=1.0; a<1; iteraties++)
      {
        h=h+1;
        Syntax: z= pow(exponent,h);

        c=c*iteraties;
        stdio=stdio+(z/c);
        verschil=math-stdio;
        if(verschil<0.01)
        {
            a=2;
        }
      }
      printf("\nexp (%d) uit math.h is:\t\t%f",exponent, math);
      printf("\nexp (%d) m.b.v. de reeks is:\t%f",exponent,stdio);
      printf("\nhet verschil is: \t\t%f", verschil);
      printf("\naantal iteraties is:\t\t%.f", iteraties);

      printf("\n\nstoppen n/j\t\t\t");
      getchar();
      scanf("%c",&stop);
    }

}


texts:
I am relatively new to programming and have been recommended to work through the many tasks in order, in order to better my skills. For some reason, problem 42 had me stumped for a while:

  The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

  By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.

  Using words.txt, a 16K text file containing nearly two-thousand common English words, how many are triangle words?

The following is my beginner-level code, and I was wondering whether any of you wonderful people would help me improve it and give me some tips for the future.  In retrospect, I should have probably reused some code from problem 22 since they involve the same skills.

def calculate_total(word):
    alphabet = {'a':1, 'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
    total = 0
    index = 1
    while word[index] != '"':
        total += alphabet[word[index].lower()]
        index += 1
    return total

def gen_triangles(limit):
    triangles = [0, 1]
    index = 1
    while triangles[index] <= limit:
        triangles.append(((index ** 2) + index) // 2)
        index += 1
    return sorted(list(set(triangles)))

def binary_search(aList, itemToFind, first, last):
  if last < first:
    #print(itemToFind + "not in list")
    return False
  else:
    midpoint = (first + last)//2
    if aList[midpoint] > itemToFind:
      return binarySearch(aList, itemToFind, first, midpoint - 1)
    else:
      if aList[midpoint] < itemToFind:
        return binarySearch(aList, itemToFind, midpoint + 1, last)
      else:
        #print(str(itemToFind) + " Found at position: " + str(midpoint))
        return True

def solution():
    myFile = open('Words.txt', 'r')
    wordsArray = myFile.read().split(',')
    for i in range(0, len(wordsArray)):
        wordsArray[i] = calculate_total(wordsArray[i])

    triangles = gen_triangles(max(wordsArray))

    wordTriangles = []
    lengthTriangles = len(triangles) - 1

    for i in range(0, len(wordsArray)):
        #print('i:', i, 'current index:', wordsArray[i])
        if binarySearch(triangles, wordsArray[i], 0, lengthTriangles) == True:
            wordTriangles.append(wordsArray[i])

    print(len(wordTriangles))

solution()

I have been teaching myself some computing theory and have seen that Python's built-in searching keyword in performs a linear search on the array so I decided to branch out and see if I can make my own binary search, which seemed to have worked :D

What was a surprise to me was that this actually runs really quickly. To all of you guys, though, this is probably a huge mess, but hey, that's why I'm here!


texts:
Given the following definition of Cons:

data Cons a = Cons a (Cons a)
             | Empty
             deriving Show

I implemented a flatten function.

It's mean to work exactly like concat :: [[a]] -> [a], but for Cons.

flatten :: Cons (Cons a) -> Cons a
flatten Empty                = Empty
flatten (Cons (Empty) ys)    = flatten ys
flatten (Cons (Cons x xs) ys) = Cons x (flatten (Cons xs ys))

Test data:

test1 :: Cons (Cons Int)
test1 = Cons (Cons 5 Empty) Empty

test2 :: Cons (Cons Int)
test2 = Cons (Cons 5 (Cons 10 Empty)) Empty

test3 :: Cons (Cons Int)
test3 = Cons (Cons 5 (Cons 10 (Cons 20 Empty))) test2

Some tests:

ghci> flatten test1
Cons 5 Empty

ghci> flatten test2
Cons 5 (Cons 10 Empty)

ghci> flatten test3
Cons 5 (Cons 10 (Cons 20 (Cons 5 (Cons 10 Empty))))


texts: Properly updating multiple MongoDB documents with Angular

texts:
In the app I'm creating, when a user upvotes a post, the post should be upvoted, as well as the user that wrote the post. But this updates two MongoDB documents. This presents a number of issues. I'll first provide an overview of the code and then list the issues.

A user clicks on an upvote button, which calls the vm.upvote function below. This in turn calls a function in the postService.js also below, which is where the AJAX request is made to update the database.

The code in the success block reloads the post data (which is already done initially) so that the information (number of upvotes) on the page updates immediately. If I don't add this, it won't do so. Is there a better way to accomplish this?

postController.js

vm.upvote = function() {

  Post.upvotePost(vm.post._id)
      .success(function(data) {

        Post.get($routeParams.post_id)
          .success(function(data) {
            vm.post = data;
            Post.getUserId(vm.post.authorId)
              .success(function(data) {
                vm.post.userData = data;
              });

          });
      });
  };

Even though this is a post factory, this function should probably be in a user factory since it is retrieving data relating to the user. Is it acceptable to have this here?

postService.js

postFactory.getUserId = function(id) {
    return $http.get('/api/users/' + id);
};

postFactory.upvotePost = function(id) {
    return $http.put('/api/posts/' + id + '/upvote')
}

The main issue here is that I am again nesting database calls. I first add an upvote to the post Model and depending on whether the user has already upvoted it or not (clicking the button twice, unupvotes), the user model is called and a counter is either incremented or decremented accordingly. This isn't modular. Again, is there a better way?

api.js

apiRouter.route('/posts/:post_id/upvote')
  .put(function(req, res) {
    Post.findById(req.params.post_id, function(err, post) {
      var index = post.likes.indexOf(req.decoded._id);
      if (index === -1) {
        post.likes.push(req.decoded._id);

        User.findById(post.authorId, function(err, user) {
          user.upvotes += 1;
          user.save(function(err) {
            // I can't place anything here since it can only return one error message.
          });
        });

      } else if (post.likes.length === 1 && post.likes[0] === req.decoded._id) {
          post.likes = [];

          User.findById(post.authorId, function(err, user) {
            user.upvotes -= 1;
            user.save(function(err) {
              // I can't place anything here.
            });
          });

      } else {
          var left = post.likes.slice(0, index);
          var right = post.likes.slice(index+1, post.likes.length);
          post.likes = left + right;

          User.findById(post.authorId, function(err, user) {
            user.upvotes -= 1;
            user.save(function(err) {
            });
          });

      };

      post.save(function(err) {
        if (err) res.send(err);
      });

      res.json({ "Post upvoted!" });

    });
});


texts: Thread Safe Service to Perform Tasks in a Queue

texts:
In answering a question on SO, I provided this example.  The intention was to provide a thread safe service that queues requests to make directories.  I figured I could definitely use some review on my use of threading, singletons and general Java skills.

package mkdir;

import java.io.File;
import java.util.concurrent.ConcurrentLinkedQueue;

public class MkDirService implements Runnable {

    private static MkDirService service;
    private static ConcurrentLinkedQueue<File> pendingDirs;

    private MkDirService() {
        pendingDirs = new ConcurrentLinkedQueue<File>();
    }

    public static MkDirService getService() {
        if (service == null) {
            service = new MkDirService();
            new Thread(service).start();
        }
        return service;

    }

    public void makeDir(File dir) {
        pendingDirs.add(dir);
    }

    @Override
    public void run() {
        while (true) {
            while (!pendingDirs.isEmpty())
            {
                File curDir = pendingDirs.poll();
                if (curDir !=null && !curDir.exists()) {
                    curDir.mkdir();
                }
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}


texts:
Using Python's Beautiful Soup, I analyze a number of html files (internally: soup). They are all a little different and my target comes in four different tags - or not at all. In two cases, my target may not be there but the tags may exists. In this case I find a ↵ .

Here I got a very ugly code to check for them:

#1: in

if len(soup.find_all("div", {"class":"section ack"})) > 0:
    thanktag = soup.find("div", {"class":"section ack"})
#2: in

elif len(soup.find_all("li", {"class":"fn-con"})) > 0:
    thanktag = soup.find("li", {"class":"fn-con"})
#3: in next-to-last

elif len(soup.find_all("li", {"class":"fn"})) > 1:
    thanktag = soup.find_all("li", {"class":"fn"})[-2]
#4: in first

    if "↵" in clean_string(thanktag.text):
        thanktag = soup.find_all("li", {"class":"fn"})[0]
#5: doesn't exist at all
if 'thanktag' in globals() and not "↵" in clean_string(thanktag.text):
    do_something()

For example, my code doesn't adhere to DRY. How could I make the code more pythonic/less redundant?


texts: Constructing MongoDB document from a dict with character code-to-integer translation

texts:
I have an class definition:

class ScoreDetail(Document):
    location            = StringField(help_text = "province")
    school              = StringField(help_text = "school")
    spec                = StringField(help_text = "major")
    bz                  = IntField(help_text = "1: Bachelor, 2: Academy, 0: exception")
    wl                  = IntField(help_text = "1: w, 2: l, 0: exception")
    batch               = StringField(help_text = "batch")
    score               = IntField(help_text = "score")
    average_score       = FloatField(help_text = "average score")
    average_score_rank  = FloatField(help_text = "rank of average score")
    low_score           = IntField(help_text = "the lowest score")
    low_score_rank      = IntField(help_text = "rank of the lowest score")
    high_score          = IntField(help_text = "highest score")
    high_score_rank     = IntField(help_text = "rank of the highest score")
    score_number        = IntField(help_text = "people in this score")
    spec_number         = IntField(help_text = "people in the major")
    rank                = IntField(help_text = "rank")
    year                = IntField('year')

Now I have a dict named item, like this:

{
  "school": u"Peking University",
  "average_score": u"255",
  "low_score_rank": u"195466",
  "wl": u"w",
  "batch": u"4",
  "score_number": u"1",
  "average_score_rank": u"178199",
  "low_score": u"150",
  "high_score": u"464",
  "score": u"150",
  "spec_number": u"62",
  "rank": u"195466",
  "year": u"14",
  "high_score_rank": u"60631",
  "spec": u"E-commerce",
  "bz": u"z",
  "location": u"US"
}

I want construct a ScoreDetail object from this dict, so I do this:

wl_map = {'w': 1, 'l': 2}
bz_map = {'b': 1, 'z': 2}
item['wl'] = wl_map[item['wl']]
item['year'] = '20' + item['year']
item['bz'] = bz_map[item['bz']]

s = ScoreDetail(
        school=item['school'],
        average_score=item['average_score'],
        low_score_rank=item['low_score_rank'],
        wl=item['wl'],
        batch=item['batch'],
        score_number=item['score_number'],
        average_score_rank=item['average_score_rank'],
        low_score=item['low_score'],
        high_score=item['high_score'],
        score=item['score'],
        spec_number=item['spec_number'],
        rank=item['rank'],
        year=item['year'],
        high_score_rank=item['high_score_rank'],
        spec=item['spec'],
        bz=item['bz'],
        location=item['location']
        )

Now I want to know these two things:

Can I simplify this code?
As you can see, this is a mongoengine schema. It inherits Document, so it can make '1' to int, '150' to float as default, but if I were not to use MongoEngine, this is just a common class. How can I make some type conversion as default?


texts:
I have a filter method that receives a list composed of dictionaries. You must discard dictionaries that have their handle or their citizen_number elements off the filtered result as well as concatenate any lists inside that dictionary. In addition to that, in case an element on that main list is a Noneit should be skipped and all the None dictionary elements should be replaced by a zero. This is the solution that I have come up with to do so

def citizens(citizen_list):
    filtered_list = []
    try:
        for citizen in citizen_list:
            if citizen:
                for item in citizen:
                    if not item:
                        citizen[item] = 0
                if (citizen['handle'] == 0 or citizen['citizen_number'] == 0):
                    continue
                if (citizen['organizations'] is not None):
                    citizen['organizations'] = ', '.join(
                        org['sid'] for org in citizen['organizations'])
                else:
                    citizen['organizations'] = 0
                for item in citizen:
                    if(type(citizen[item]) is list):
                        citizen[item] = ', '.join(citizen[item])
                filtered_list.append(citizen)
        return(filtered_list)
    except Exception:
        print(citizen)
        raise

Note that the list concatenation for the organizationsfield must be done before the general one and in that particular way. I feel this code just looks awfully hacked together, how can I make this better?


texts: Script to determine the outcome(s) of any number of dice rolls

texts:
I think this code has far to many if else clauses and not enough abstraction via functions. I would like to break the code down into a series of small functions, or methods if i decide to go OOP, but I'm not sure of the best way to do so. If you brilliant Pythonista's could guide me in the write direction I would appreciate it.

Here is the GitHub repo if you would like to fork it repo

'''
script to determine the outcome(s) of any number of dice rolls
By Andrew Smith (2015)
'''

from random import randint

def dice_roller(dice, rolls, sides):
    '''
    Add doc string here.
    '''
    show_di = '|   |'
    show_di_1 = '| * |'
    show_di_2 = '|* *|'
    show_di_3 = '|***|'
    show_di_t = ' ___ '
    show_di_b = ' --- '
    roll_counter = 0
    di_counter = 0

    while roll_counter < rolls:
        roll_counter += 1
        di_counter = 0
        print " "

        while di_counter < dice:
            di_counter += 1
            num_side = randint(1, sides)
            print "Roll %r, Di %r: %r" % (roll_counter, di_counter, num_side)
            if num_side <= 6: # print di symbol if di is six-sided
                if num_side == 1:
                    print show_di_t
                    print show_di_1
                    print show_di
                    print show_di_b
                elif num_side == 2:
                    print show_di_t
                    print show_di_1
                    print show_di_1
                    print show_di_b
                elif num_side == 3:
                    print show_di_t
                    print show_di_1
                    print show_di_2
                    print show_di_b
                elif num_side == 4:
                    print show_di_t
                    print show_di_2
                    print show_di_2
                    print show_di_b
                elif num_side == 5:
                    print show_di_t
                    print show_di_2
                    print show_di_3
                    print show_di_b
                elif num_side == 6:
                    print show_di_t
                    print show_di_3
                    print show_di_3
                    print show_di_b
    print " "
#-------------------------------------------------------------------------------

TITLE = """
 __________________
| Dice Roller v1.1 |
| by Andrew Smith  |
|__________________|
"""

MENU = """
Enter the number of dice to roll, the number
of rolls, and the number of sides per di in the
following format: #dice #rolls #sides

--- or ---

Select from the following presets:

a. 3 man attack (Risk)
b. 2 man attack or defend (Risk)
c. 1 man attack or defend (Risk)

--- or ---

Type 'menu' to repeat this menu

--- or ---

Type 'quit' to quit
        """

def main():
    '''
    Explain this function.
    '''
    print TITLE
    print MENU
    again = 0

    while again != 1: # prompts the user until 'quit' is entered
        roll_choice = raw_input("> ")
        if roll_choice.isalpha(): # if input starts with a letter
            if roll_choice == 'a':
                dice_roller(3, 1, 6)
            elif roll_choice == 'b':
                dice_roller(2, 1, 6)
            elif roll_choice == 'c':
                dice_roller(1, 1, 6)
            elif roll_choice == 'menu':
                print MENU
            elif roll_choice == 'quit':
                again = 1
            else:
                print "Invalid choice.\n"

        elif roll_choice[0].isdigit(): # if input starts with a number
            choices = roll_choice.split()
            size = len(choices)
            if size == 3:
                one = int(choices[0])
                two = int(choices[1])
                three = int(choices[2])
                dice_roller(one, two, three)
            else:
                print "Invalid Choice.\n"
        else:
            print "Invalid choice.\n"

if __name__ == '__main__':
    main()


texts: Verify credit card number with Luhn's algorithm

texts:
#include <stdio.h>
    #include <cs50.h>

int main(void){

     long long card;
     int i;
     int otherdigs;
     int multiply;
     int sum = 0;
     int sumofothers = 0;
     int finaladd;
     int length;
     int card_length;
     long long get_card;

     get_card = get_long_long(" Enter credit card: ");
     card = get_card;

     for (i = 0; i < 16; i++)
     {

       sumofothers += card % 10;

       card /= 10;
       otherdigs = card % 10;
       card /= 10;

       if (otherdigs*2 < 10)
        {
         multiply = otherdigs * 2;
         sum += multiply;
         }

       else
         {
          otherdigs = otherdigs*2-9;
          sum += otherdigs;
         }

       }

      finaladd = sum + sumofothers;

      if (finaladd % 10 == 0)
      {
        for (length = 0; length < 14; length++)
        {
            get_card /= 10;
        }

        if ( get_card >= 51 && get_card < 56 ) {

            printf("MasterCart\n");
        }

        else if ( get_card >= 3 && get_card < 4)
        {
            printf("AmericanExpress\n");
        }

        else if ( get_card < 0 || (get_card/10 >= 4 && get_card/10 < 5) )
        {
            printf("VIZA\n");
        }

        else {

            printf(" Sorry, We Don't Support This Payment Company\n");
        }
      }

      else
      {
        printf("This credit card is not valid \n");
      }

      return 0;

}

I recently took cs50 online course and this is my solution to pset1 ( Credit )
This is my very first program that I actually thought through and did it all myself.
The goal is to get the card number from user and check if it's valid ( Luhn’s Algorithm )

I know the style is awful and the code is very messy too, but your opinion is very important to me... I spent maybe 5,6 hours for this. The question is do you think I can code? Become a programmer ? I mean do I have the right mind for it ? ( since this is my first without guide code )
BTW, I have no prior programming experience (only read some pages of K&R 2 years ago),

I even don't know half of c syntax yet. I know talent is a myth and all, but based on this code, do you think I'm any good at this?


texts: Performance of Codility MaxCounter challenge solution

texts:
I'm doing some of the Codility challenges using Ruby. The current challenge is "The MaxCounter," which is described as:

  Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.

See the link above for more details. I managed to get a solution. The performance, however, scored 0, being that some operations timed out. How can I improve my algorithm to perform better?

def solution(n, a)
  counter = (0..n-1).to_a.map{|z| z = 0}
  for value in a
    counter.map!{|x| x = counter.max} unless value <= n
    counter[value-1] += 1 unless value == n+1
  end
  counter
end

Update - my second and third attempts, still fails on performance

2nd

def solution(n, a)
  counter = (0..n-1).to_a.map{|z| z = 0}
  a.each{|x| counter.map!{|c| c = counter.max} unless x <= n; counter[x-1] +=1 unless x==n+1;}
  counter
end

3rd

def solution(n, a)
  counter = (0..n-1).to_a.map{|z| z = 0}
  a.each{|x| counter[x-1] +=1 and next unless x==n+1; counter.map!{|x| x = counter.max};}
  return counter
end


texts: Is it proper to use nested loops a lot in python?

texts:
I have a project and I am trying to do a complex cryptographic method. Is it normal to use nested loops a lot? Or Did I miss something?

I intend to create a method which tries all strings to find password. For example, It should create each of these one by one: ('A','A') ('B', 'A') ('A', 'B') ('B', 'B') ('A', 'AA' ) ('A', 'AB') ('B', 'AA') ('B', 'AB') ('A', 'BA') ('B', 'BA') ('A', 'BB') ('B', 'BB') , (triple permutations), (quadruple permutations).. and it goes...

def rulefinder():
    global externalrul1
    global externalrul2
    rul2 = uniquestring1[0]
    rul1 = uniquestring1[0]
    for n in range (0,3):
     for m in range (0, len(uniquestring1)):
      for z in range(0, n+1):
        for k in range (0,3):
            for i in range(0, len(uniquestring1)):
                for o in range(0, k+1):
                    for y in range (0,  len(uniquestring1)):
                        rul2 = rul2[:-1] + uniquestring1[y]
                        for x in range (0, len(uniquestring1)):
                            rul1= rul1[:-1] + uniquestring1[x]
                            code=""
                            for cha in Genx1:
                                if cha==uniquestring1[0]:
                                    code +=codereplacer(rul1)
                                elif cha==uniquestring1[1]:
                                    code +=codereplacer(rul2)
                            print(code)
                            print(uniquestring1[0],rul1)
                            print(uniquestring1[1],rul2)
                            print(LastString)
                            if code == LastString:
                                axiom1=uniquestring1[0]
                                axiom2=uniquestring1[1]
                                externalrul1=rul1
                                externalrul2=rul2
                                print('rules are found')
                                print("First RULE:", uniquestring1[0], rul1)
                                print("Second RULE:", uniquestring1[1], rul2)
                                findsubgeneration(code, axiom1, rul1, axiom2, rul2)
                                return
                    rul1 = rul1[:o] + uniquestring1[i] + rul1[(o + 1):]
            rul1 += codereplacer(uniquestring1[i])
        rul2 = rul2[:z] + uniquestring1[m] + rul2[(z + 1):]
        rul1 =""
     rul2 += codereplacer(uniquestring1[m])


texts:
Challenge:
Resolve git conflict by resolveGitConflict(linesArray, resolveMode), where
linesArray is an array of strings
Example:
[
    "context1",
    "context2",
    "<<<<<<<",
    "my changes1",
    "=======",
    "their changes1",
    ">>>>>>>",
    "context3",
    "context4",
    "<<<<<<<",
    "my changes2",
    "=======",
    "their changes2",
    ">>>>>>>",
    "context5",
    "context6"
]

resolveMode -  a string indicate:

m: Keep only current branch's changes
t: Keep only other branch's changes
tm: Keep both changes, but put other branch's changes before current branch's changes
mt - Keep both changes, but put other branch's changes after current branch's changes
none - Keep no changes

Review
We have three solutions for that challenge. Please compare  all of them and tell which one is better.
Solution 1
const resolveGitConflict = (linesArray, resolveMode, t = []) =>
  linesArray.reduce((p, c) => p.concat(
    t.length ?
      c === '>>>>>>>' ?
        (c = [].concat(resolveMode[0] ? t.splice(+(resolveMode[0] === 't'), 1)[0].concat(resolveMode[1] ? t[0] : []) : [])) &&
        (t = []) && c
      : c === '=======' ? t[1] = [] : t[+!!t[1]].push(c) && []
    : c === '<<<<<<<' ? t[0] = [] : [c]
  ), [])

Solution 2
function resolveGitConflict(linesArray, mode) {
    var [changes, curMode] = [{m: [], t: []}, ''];
    return linesArray.map(line => {
        var newLines = [];
        if (line === '<<<<<<<' || line === '=======')
            curMode = line === '<<<<<<<'? 'm' : 't';
        else if (line === '>>>>>>>') {
            newLines = Array.from(mode).map(c => changes[c] || []).flat(1);
            [changes.m, changes.t, curMode] = [[], [], ''];
        } else
            (changes[curMode] || newLines).push(line);
        return newLines;
    }).flat(1);
}

Solution 3
function resolveGitConflict(lines, mode) {
  return lines.reduce((p, c) => {
    let last = p[p.length-1]
    if(typeof last === 'object' ) {
      if(c === '>>>>>>>') last = [].concat(last[mode[0]] || [], last[mode[1]] || [])
      else if(c === '=======') last.t = []
      else last[last.t ? 't' : 'm'].push(c)
      return p.slice(0, -1).concat(last)
    } else if(c === '<<<<<<<') c = {m: []}
    return p.concat(c)
  }, [])
}


texts: Counting instances of a string in a binary / unicode file using regex

texts:
(Originally posted on Stack Overflow)

I need to run through a number of bespoke files (I'm unsure if they are unicode / ascii or binary so have attached a snapshot through notepad++).  I'd like to count the number of instances of a simple string.

I've managed to get this working using the CreateObject("ADODB.Stream") method but I'd like to speed this up.

Below is the working code in excel, setup as a function.

Function CountPRODSinNielsenDBs(StrFilename As String, RngThisCell)

'StrFilename = "C:\Nielsen Databases\UBINCCCS.hed"

'used to disable the function whilst editing other parts of the sheet
'prefer this approach over setting calculation to manual
If Range("Active") = 0 Then
CountPRODSinNielsenDBs = RngThisCell.Value
Exit Function
End If

Const adTypeText = 2
Set ADStream = CreateObject("ADODB.Stream")
With ADStream
    .Type = adTypeText
    .Open
    .LoadFromFile StrFilename
    .Charset = "us-ascii"
    strText = .ReadText()
End With

' Now do our regex search...
Set rgxp = CreateObject("VBScript.RegExp")
With rgxp
    .Pattern = "\x00P[0-9]{39}"
    .Global = True
    .IgnoreCase = True
    Set matches = .Execute(strText)
End With

CountPRODSinNielsenDBs = matches.Count
'Debug.Print matches.Count

End Function

This function works ok as is and so I just left the default setting for .charset to ascii and adTypeText to 2 as it seemed to work with the regex matching process.

However, it's a little slow and I believe that the OpenAsTextStream method should be quicker:

Const ForReading = 1
Const TristateFalse = 0
Dim strSearchThis
Dim objFS
Dim objFile
Dim objTS
Dim strText
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.GetFile(StrFilename)
strText = objFile.OpenAsTextStream(ForReading, TristateFalse).readall

However the regex returns zero matches so I began wondering if in fact this approach can't handle the data as it's not actually ascii or some other format.

Please can someone take a look at this pic to help me understand what type of datatype this might be and whether I can speedup the searching and counting of the instances?

There are many files and each one runs into the MB's you see.

Alternate link to the Notepad++ screenshot


texts: Makefile to build and debug a C++ console app

texts:
I had to create this makefile to build and debug a C++ console app. I just need some hints and tips on how I can organize my makefile.

CC=g++
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=helloWorld.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=helloWorld

all: $(SOURCES) $(EXECUTABLE)

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: helloWorld

clean:
    rm *o helloWorld

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@