texts:
This is my first project I am attempting in Python, and my first time on Stack Exchange, so please be kind.
The game uses a text file with lots of words. I was wondering how to improve the game by having different difficultly levels. E.g. easy for 1-4 letters, medium for 5-8 letters, hard for 9+ letters in the word.
All the code in print_graphics() was pre-made, so I have to figure out a way to incorporate it into the code I was writing.
I was also thinking it might look neater if it didn't keep printing new iterations of the hangman after each body part is added, but I'm not sure how I could do that without massively changing the text.
I couldn't figure out how to attach the input file so I've linked it instead.
import random
from IPython.display import clear_output
from termcolor import colored

def print_graphics(wrong_guesses):
    # list of possible body parts
    body_parts = ['  O     |', '  |     |',' /|     |', ' /|\    |', ' /      |', ' / \    |']

    # how many lines to print
    lines = 4 if wrong_guesses != 0 else 5

    # check number provided is usable
    if 0 <= wrong_guesses <= 6:
        print('  +-----+')  # print top of frame
        print('  |     |')

        # print the correct body parts for current state
        if wrong_guesses > 0:
            if wrong_guesses > 1:
                print(body_parts[0])
                lines -= 1
            if wrong_guesses > 4:
                print(body_parts[3])
                lines -= 1
            print(body_parts[wrong_guesses-1])

        for i in range(lines):
            print('        |')  # print the lines

        print('==========')  # print the floor

with open("wordlist.txt") as file:
  words = file.read().split()
  word = random.choice(words)

guessed_word = []
guessed_letters = []
max_guesses = 5
length_word = len(word)
alphabet = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []
body_parts = ['  O     |', '  |     |',' /|     |', ' /|\    |', ' /      |', ' / \    |']

def start():
  print("\033[1;34m"+"Welcome to hangman! You have 6 tries to guess the correct word, enter a letter to get started", "\033[0;30m")
start()

def intro():
  for character in word:
    guessed_word.append("_")
  print("The word you are guessing has", length_word, "characters")
  print_graphics(0)
intro()

def play(word):
  wrong_guesses = 0
  while wrong_guesses <6:
    guess = input("Guess a letter or word: ")

    if guess in guessed_letters:
      print("\033[1;31m"+"Whoops! You have already guessed this letter. Don't worry, you still have", 6-wrong_guesses, "guesses remaining" "\033[0;30m")
    if guess not in alphabet:
      print("\033[1;31m"+"Character invalid. Please enter a letter", "\033[0;30m")

    elif guess in alphabet and guess not in guessed_letters:
      if guess in word:
        print("\033[1;3;32m"+"Well done", guess.upper(), "is correct!", "\033[0;30m")
        guessed_letters.append(guess)
        for i in range(0, length_word):
          if word[i] == guess:
            guessed_word[i] = guess
        print(guessed_word)
        if not "_" in guessed_word:
          print("\033[1;3;32m"+"Congratulations, you beat the Hangman!", "\033[0;30m")
          break

      elif guess not in word:
        wrong_guesses += 1
        print(print_graphics(wrong_guesses))
        print(guessed_word)
        print("\033[1;31m"+guess.upper(), "is not correct. You have", 6-wrong_guesses, "guesses left", "\033[0;30m")
        guessed_letters.append(guess)
    if wrong_guesses == 6:
      print("\033[1;31m"+"Bad luck! You have been beaten by the Hangman. The word you were trying to guess was", word, "\033[0;30m")

play(word)
print("\033[1;3;35m"+"Game over, thank you for playing :)")


texts: Bulk File Rename; Improved Safety and Performance

texts:
A function that funnels all filenames into a file and opens that file in vim. The user then changes the names, saves, and quits. Finally the function renames the files in the folder with the new names provided in the file.

This is the update to this previous version. The update makes it impossible to destroy files, and improves performance. This is the answer that helped develop this version.

bulkrename() {
    trap 'rm -f $RENAMETMP' EXIT

    # Make array of file names
    local OLDFILENAMES=( *$@ )

    # Pipe array items into file seperated by new lines
    local RENAMETMP=$(mktemp)
    printf '%s\n' "${OLDFILENAMES[@]}" > $RENAMETMP && nvim $RENAMETMP

    # If user exits nvim with failure, stop the script
    local exitcode=$?; [[ $exitcode = 0 ]] || return $exitcode

    # Place new names into an array
    local IFS=$'\n'
    local NEWFILENAMES=( $( command cat $RENAMETMP ) )

    # After user has edited the names, check for matching line count
    if [[ ${#OLDFILENAMES[@]} -ne ${#NEWFILENAMES[@]} ]]; then
        echo "Lines Mismatch" && return 1
    fi

    # Also check for naming conflicts
    for ((old = 1; old <= ${#OLDFILENAMES[@]}; old++)); do
        for ((new = 1; new < $old; new++)); do
            if [[ ${NEWFILENAMES[old]} = ${NEWFILENAMES[new]} ]] || \
            [[ ${OLDFILENAMES[old]} = ${NEWFILENAMES[new]} ]]; then
                echo "File Naming Confict" && return 1
            fi
        done
    done

    # Rename the files
    for ((name = 1; name <= ${#NEWFILENAMES[@]}; name++)); do
        command mv -Tnv "${OLDFILENAMES[name]}" "${NEWFILENAMES[name]}"
    done
}


texts: JavaScript function to get DOM elements by any attribute

texts:
I needed to write a function today in JavaScript that would return all elements based on a given attribute.

e.g retrieve all elements that have an id attribute in them.

The function I wrote for this is as follows:

function getElements(attrib) {
    // get all dom elements
    var elements = document.getElementsByTagName("*");
    // initialize array to put matching elements into
    var foundelements = [];

    // loop through all elements in document
    for (var i = 0; i < elements.length; i++) {
        // check to see if element has any attributes
        if (elements[i].attributes.length > 0) {
            // loop through element's attributes  and add it to array if it matches attribute from argument
            for (var x = 0; x < elements[i].attributes.length; x++) {
                if (elements[i].attributes[x].name === attrib) {
                    foundelements.push(elements[i]);
                }
            }
        }
    }
    return foundelements;
}

Looking at this, I am sure it could be written a great deal better. Any feedback would be much appreciated!


texts: Code kata featuring: fetch, promises, Array.sort, Array.reduce, Array.map, String.localeCompare

texts:
I just finished a kata and would love to get some constructive feedback regarding code quality, readability, organization.

Objectives

fetch members of polish parliament (poslowie)
group them by occupation
sort occupations by number of members and occupation name
get top 5 entries
print result on the screen

Sample result

Code

(function() {
    'use strict';

    const POSLOWIE_ENDPOINT = 'https://api-v3.mojepanstwo.pl/dane/poslowie/';

    fetch(POSLOWIE_ENDPOINT)
        .then(response => response.json())
        .then(data => data.Dataobject)
        .then(sumByOccupation)
        .then(occupationsMap => {
            return occupationsMap
                .sort(compareByCountAndName)
                .slice(0, 5);
        })
        .then(printToScreen)
        .catch(e => console.error(e));

     function sumByOccupation(poslowie) {
        return Array.from(
            poslowie
                .map(posel => posel.data['poslowie.zawod'])
                .reduce((map, occupation) => {
                    const numberOfEntries = map.get(occupation) || 0;
                    return map.set(occupation, numberOfEntries + 1);
                }, new Map())
        ).map(([occupation, count]) => {
            return {occupation, count};
        });
     }

     function compareByCountAndName(a, b) {
        return b.count - a.count || (a.occupation).localeCompare(b.occupation);
     }

     function printToScreen(data) {
        console.table(data);
     }
})();


texts: Change-making problem with specific constraints

texts:
I am a new Pythoner.  I have solved a OJ project with Python. Can you tell me how can I solve it more Pythonically?

Problem Description: There are n coin denominations, each with an unlimited supply of coins. Use them to make a given total amount m.
Requirements:

Every denomination must be used
The number of coins of small denominations must be greater than the number of large denomination coins
The total number of coins must be minimum
If there is no combination of conditions to meet the conditions 1 and 2, the output "NA"

Input parameters:

coin types n: 2 < n < 10
The total amount m:  m < 1000
The largest denomination is less than 20

Program input: First line: the total amount requested Second row: each
coin denomination (in half-space separated)
Program output: First line: total number of coins Second row: the
number of small to large denomination of each coin (in half-space
separated)
Sample input:
20
1 2 5

Sample output:
9
4 3 2

#!/bin/bash/env python3
import copy

def coinChange():
    amount, coins = int(input()), list(sorted(map(int, input().split(sep=' '))))
    min_package = [x for x in range(len(coins), 0, -1)]
    min_sum = sum(map(lambda x, y:x * y, min_package , coins))

    if amount < min_sum:
        print('NA')
        return

    dp, dp[0] = [amount + 1] * (amount + 1), 0
    packages = [[0] * len(coins)] * (len(dp))
    for i in range(len(dp)):
        for j, coin in enumerate (coins):
            if coin <= i:
                last = i - coin
                package = copy.deepcopy(packages[last])
                if dp[i] > dp[last] + 1 and (j == 0 or package[j - 1] > package[j] + 1):
                    dp[i], package[j], packages[i] = dp[last] + 1, package[j] + 1, package
            else:
                break

    if dp[-1] > amount or packages[-1][-1] < 1:
        print('NA')
    else:
        print(sum(packages[-1]))
        print(' '.join([str(x) for x in packages[-1]]))

if __name__ == '__main__':
    coinChange()


texts:
Including the full module, but the method I'm interested in is createIndex, feels more complicated than I think it should be.  Still new at both node and elasticsearch

/*jslint node: true */
'use strict';

var EsConnect = require('./EsConnect');
var inet = require('inet');

function NetFlowStorage(es, logger, config) {
    var esCon = new EsConnect(es, logger, config);

    this.host = config.get('ElasticSearchConfig.elasticsearch_host');
    this.shards = config.get('ElasticSearchConfig.elasticsearch_shards');
    this.replicas = config.get('ElasticSearchConfig.elasticsearch_replicas');
    this.index_name = config.get('Application.index_name');
    this.client = esCon.connect();
    this.log = logger;

}

// setup index
NetFlowStorage.prototype.createIndex = function createIndex(callback) {
    // don't create if already created
    this.client.indices.exists({
        index: this.index_name

    }, function (error, exists) {

        if (exists === true) {
            this.log.info('index already exists, not creating again');
        } else {
            var storageObj = this;
            this.log.info('creating index');

            this.client.indices.create({
                    index: this.index_name,
                    body: {
                        index: {
                            number_of_shards: this.shards,
                            number_of_replicas: this.replicas
                        },
                        mappings: {
                            raw_flow: {
                                properties: {
                                    timestamp: {
                                        type: 'date',
                                        format: 'epoch_millis'
                                    },
                                    ipv4_dst_addr: {
                                        type: 'ip'
                                    },
                                    ipv4_src_addr: {
                                        type: 'ip'
                                    }
                                }
                            }
                        }
                    }
                },
                // istanbul ignore next
                function (error, response, status) {
                    if (error) {
                        storageObj.log.info(error + ' ' + status + ' ' + response);
                        throw new Error('index creation failed: ' + error);
                    }

                    if (typeof (callback) === 'function') {
                        return callback();
                    }
                });
        }
    }.bind(this));
};

// Store the actual flow
NetFlowStorage.prototype.storeFlow = function storeFlow(flow) {
    flow.timestamp = Date.now();
    var storageObj = this;
    this.client.index({
        index: this.index_name,
        type: 'raw_flow',
        body: {
            ipv4_src_addr: flow.ipv4_src_addr,
            ipv4_dst_addr: flow.ipv4_dst_addr,
            ipv4_next_hop: flow.ipv4_next_hop,
            input_snmp: flow.input_snmp,
            output_snmp: flow.output_snmp,
            in_pkts: flow.in_pkts,
            in_bytes: flow.in_bytes,
            first_switched: flow.first_switched,
            last_switched: flow.last_switched,
            ipv4_src_port: flow.ipv4_src_port,
            ipv4_dst_port: flow.ipv4_dst_port,
            tcp_flags: flow.tcp_flags,
            protocol: flow.protocol,
            src_tos: flow.src_tos,
            in_as: flow.in_as,
            out_as: flow.out_as,
            src_mask: flow.src_mask,
            dst_mask: flow.dst_mask,
            timestamp: flow.timestamp
        }
    },
    // istanbul ignore next
    function (error, response, status) {
        if (error) {
            storageObj.log.info(error + ' ' + status + ' ' + response);
        }
    });
};

module.exports = NetFlowStorage;


texts: Simple overlapped IO single threaded client

texts:
I wanted to make a single threaded network client that only uses a single connection to a server.  IOCP seems like overkill but overlapped IO with event notification I think is the most performant of the myriad of choices available.  However I haven't found any examples of such so this is my version.  I'm still in learning mode so while the code seems to work fine, there are probably gotchas, inefficiencies and potential errors which I'm hoping will be pointed out to me by those of greater learning than I.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <winsock2.h>

#define DATA_BUFSIZE 4096
#define ERROR_END0 {WSACleanup(); return 1;}
#define ERROR_END1 {closesocket(s); WSACleanup(); return 1;}

int main(int argc, char *argv[])
{
    WSADATA wsa;
    struct hostent *he;
    char *hostname = "my.echo.server.com";
    short port = 12345;

    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)  { printf("Failed. Error Code : %d", WSAGetLastError()); ERROR_END0; }
    puts("Initialised.");

    if ((he = gethostbyname(hostname)) == NULL) { printf("gethostbyname failed : %d", WSAGetLastError()); ERROR_END0; }
    printf("%s resolved to : %s\n", hostname, inet_ntoa(*((struct in_addr *) he->h_addr)));

    struct sockaddr_in sockAddr = { AF_INET, htons(port) };
    memcpy(&sockAddr.sin_addr, he->h_addr, he->h_length);

    SOCKET s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
    if(s == INVALID_SOCKET) { printf("Could not create socket : %d" , WSAGetLastError()); ERROR_END0; }
    puts("Socket created.");

    if (WSAConnect(s , (SOCKADDR*)&sockAddr , sizeof(sockAddr), NULL, NULL, NULL, NULL) ==  SOCKET_ERROR)   { puts("connect error"); ERROR_END1; }
    printf("Connected\n\n");

    WSAEVENT EventArray[2];
    WSAOVERLAPPED TXOverlapped = {0}, RXOverlapped = {0};

    TXOverlapped.hEvent = EventArray[0] = WSACreateEvent();
    RXOverlapped.hEvent = EventArray[1] = WSACreateEvent();

    char txBuffer[DATA_BUFSIZE], rxBuffer[DATA_BUFSIZE];
    DWORD numBytes, Flags = 0;
    strcpy(txBuffer, "hello world");
    WSABUF txBuff = {sizeof("hello world"), txBuffer}, rxBuff = {sizeof(rxBuffer), rxBuffer};
    if ((WSASend(s, &txBuff, 1, &numBytes, 0, &TXOverlapped, NULL) == SOCKET_ERROR) && (WSAGetLastError() != WSA_IO_PENDING))   { printf("WSASend() failed with error %d\n", WSAGetLastError()); ERROR_END1; }
    if ((WSARecv(s, &rxBuff, 1, &numBytes, &Flags, &RXOverlapped, NULL) == SOCKET_ERROR) && (WSAGetLastError() != WSA_IO_PENDING)) { printf("WSARecv() failed with error %d\n", WSAGetLastError()); ERROR_END1; }

    while(TRUE)
    {
        DWORD Index = WSAWaitForMultipleEvents(2, EventArray, FALSE, WSA_INFINITE, FALSE);
        WSAResetEvent( EventArray[Index] );
        if(Index == 0)
        {
            WSAGetOverlappedResult(s, &TXOverlapped, &numBytes, FALSE, &Flags);
            if (numBytes == 0)  { printf("Closing socket %d\n", (int) s); ERROR_END1; }
            txBuffer[numBytes] = 0;
            printf("TX Bytes SENT: %d\n\n%s\n\n", (int) numBytes, txBuffer);
        }
        else if(Index == 1)
        {
            WSAGetOverlappedResult(s, &RXOverlapped, &numBytes, FALSE, &Flags);
            if (numBytes == 0)  { printf("Closing socket %d\n", (int) s); ERROR_END1; }
            rxBuffer[numBytes] = 0;
            printf("RX Bytes RECEIVED: %d\n\n%s\n\n", (int) numBytes, rxBuffer);

            ZeroMemory(&RXOverlapped, sizeof(WSAOVERLAPPED));
            RXOverlapped.hEvent = EventArray[1];
            if ((WSARecv(s, &rxBuff, 1, &numBytes, &Flags, &RXOverlapped, NULL) == SOCKET_ERROR) && (WSAGetLastError() != WSA_IO_PENDING)) { printf("WSARecv() failed with error %d\n", WSAGetLastError()); ERROR_END1; }
        }
    }
    shutdown(s,SD_BOTH);
    closesocket(s);
    WSACleanup();
    return 0;
}


texts: K&R 2.6 Exercise setbits(x,p,n,y) function

texts:
Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

#include <stdio.h>

unsigned setbits(unsigned x, int p, int n,unsigned y);

int main(void){
    unsigned result=setbits(0, 4, 3, ~0);
    printf("%d\n",result);
    return 0;
}

unsigned setbits(unsigned x, int p, int n,unsigned y){
    unsigned ybits = y & ~(~0 << n);
    unsigned helper = ~(~0 << n);
    unsigned result = (x | (helper << (p+1-n))) & ((ybits << (p+1-n)) | (~(helper << (p+1-n))));
    return result;
}

Output:

  28


texts:
This is a simple attempt by me to test whether two words are anagrams or not:

#include <stdio.h>
#include <ctype.h>

#define CH_LEN 15
#define N 26

int main(void) {
    char track_letters[N] = {0};
    char first_word[CH_LEN];
    char sec_word[CH_LEN];
    printf("Enter first word: ");
    int i;
    for(i = 0; i < CH_LEN; i++) {
        first_word[i] = getchar();
        if(first_word[i] == '\n')
            break;
        if(!isalpha(first_word[i]))
            --i;

        track_letters[(tolower(first_word[i]) - 'a')]++;

    }
    printf("Enter second word: ");
    for(i = 0; i < CH_LEN; i++) {
        sec_word[i] = getchar();
        if(sec_word[i] == '\n')
            break;
        if(!isalpha(sec_word[i]))
            --i;
        track_letters[(tolower(sec_word[i]) - 'a')]--;

    }
    for(i = 0; i < CH_LEN; i++) {
        if(track_letters[i] != 0) {
            printf("The words are not anagrams");
            return 0;
        }
    }
    printf("The words are anagrams");

    return 0;
}

You can use any method of C (structure, pointers, functions etc.).


texts: What is best using of OOP in Java in this example

texts:
I created example for simple calculator depending on Scanner object to ask from user to choose any of the four standard Math Operations, I divided it on two class (SelectOperation and MathematicOperations) , I want to know new ideas for best way of using of OO programming in this example

this class MathematicOperations

import java.util.Scanner;

public class MathematicOperations {
    private static Scanner in;

    public static void Sum() {
        in = new Scanner(System.in);
        System.out.print("Enter the first No :");
        int x = in.nextInt();
        System.out.print("Enter the secound No :");
        int y = in.nextInt();
        int result = x + y;
        System.out.println(result);
        in.close();
    }

    public static void Sub() {
        in = new Scanner(System.in);
        System.out.print("Enter the first No :");
        int x = in.nextInt();
        System.out.print("Enter the secound No :");
        int y = in.nextInt();
        int result = x - y;
        System.out.println(result);
        in.close();
    }

    public static void Mul() {
        in = new Scanner(System.in);
        System.out.print("Enter the first No :");
        int x = in.nextInt();
        System.out.print("Enter the secound No :");
        int y = in.nextInt();
        int result = x * y;
        System.out.println(result);
        in.close();
    }

    public static void Div() {
        in = new Scanner(System.in);
        System.out.print("Enter the first No :");
        int x = in.nextInt();
        System.out.print("Enter the secound No :");
        int y = in.nextInt();
        if (y == 0)
            System.out.println("Cannot dived by zero");
        else {
            int result = x / y;
            System.out.println(result);
            in.close();
        }
    }
}

this class SelectOperation

 import java.util.Scanner;

    public class SelectOperation {
        private static Scanner scn;
        private static int num;

    public SelectOperation() {
        scn = new Scanner(System.in);
        System.out.print("1.Sum : , 2.Sub : , 3.Mul : , 4.Div :");
        num = scn.nextInt();

        switch (num) {
        case 1:
            MathematicOperations.Sum();
            break;
        case 2:
            MathematicOperations.Sub();
            break;
        case 3:
            MathematicOperations.Mul();
            break;
        case 4:
            MathematicOperations.Div();
            break;
        default:
            System.out.println("Invalid Operation");
            break;
        }
        scn.close();
    }
}

this Main class

public class Main {

        public static void main(String[] args) {
            new SelectOperation();

        }

    }


texts:
I've recently started looking into encryption in python and I came across with pycryptodome library. I made this simple program that encrypt/decrypt a file using AES-GCM. Could someone take a look if I implemented the encryption and authentication correctly? For sake of simplicity, I'm posting only the encryption and makeKey functions.

import os
import struct
import secrets
import hahslib
from Cryptodome.Cipher import AES

def makeKey(password, salt):
    key = hashlib.pbkdf2_hmac('sha512',password.encode('ascii'), salt, 1000000)
    return key[:32]

def encrypt(password, inputFileName):
    #creates the needed variables for encryption
    salt = secrets.token_bytes(16)
    key = makeKey(password, salt)
    nonce = secrets.token_bytes(AES.block_size)
    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    #put the file size, salt and nonce in outputfile
    fileSize = os.path.getsize(inputFileName)
    with open("output", "wb") as outputFile:
        outputFile.write(struct.pack('<Q', fileSize))
        outputFile.write(salt)
        outputFile.write(nonce)
        #beginning of encryption itself
        chunkSize = 64 * 1024
        with open(inputFileName, "rb") as inputFile:
            while True:
                chunk = inputFile.read(chunkSize)
                if len(chunk) == 0:
                    outputFile.write(cipher.digest())
                    break
                outputFile.write(cipher.encrypt(chunk))


texts:
I'm using this PHP to modify A elements in a DOM fragment (a vBulletin $post['message'] if that matters) so that links to external sites always open new tabs. This is actually the default in vBulletin but it's not always reliable. Anyway, the code works, but looking at the loop makes me think it could be done better. Any suggestions?

$as = $doc->getElementsByTagName('a');
for ( $i = $as->length; --$i >= 0; ) {
    $a = $as->item($i);
    $aParts = parse_url ( strtolower ( $a->getAttribute('href') ) );
    if ( $aParts['host'] !== $localDomain ) {
        $a->setAttribute ( 'title', @$a->getAttribute ('title') . " [external link to {$aParts['host']}]" );
        $a->setAttribute ( 'target', '_blank' );
    }   // if
} // for


texts: Writing binding providers in CoffeeScript?

texts:
In his KnockoutJs 1.3 beta post, Steve Sanderson has an example of using Binding providers ("5. Binding providers (and hence external bindings)") where he makes a comment in the JSFiddle JavaScript tab that says "// This syntax would be way more succinct with CoffeeScript".

How would this actually be accomplished?

// This syntax would be way more succinct with CoffeeScript
ko.bindingConventions.conventions(".person-editor", {
    ".person-editor"  : { 'with': myViewModel.person },
    ".first-name"     : function(person) { return { value: person.firstName } },
    ".last-name"      : function(person) { return { value: person.lastName } }
});

ko.bindingConventions.conventions("#weather-list", {
    "#weather-list"    : { 'with': myViewModel.weather },
    ".cities-list"     : function(weather) { return { foreach: weather.cities } },
    ".city"            : function(item) { return { text: item.city } },
    ".temp"            : function(item) { return { text: item.temperature } },
    ".add-city"        : { click: function() { this.addItem() } }
});


texts:
For today, I tackled this coding challenge question:
Given a binary tree, write a method to recursively traverse the tree in the preorder manner. Mark a node as visited by adding its data to the list - Arraylist  preorderedList

ArrayList<Integer> preorderedList = new ArrayList<Integer>();
public void preorder(TreeNode root) {

   if(root == null){
       return;
   }
    preorderedList.add(root.data);
    if(root.left != null){
        preorder(root.left);
    }
     if(root.right != null){
        preorder(root.right);
    }

}


texts: Generating filters to remove query variables from a URL

texts:
This function takes a URL structure which is most often a query string (but sometimes not) and generates filters to remove query variables from the URL.

If you're looking at an archive like

  http://example.com/?genre=rock&band=deep-purple

you'll get the following output:

[ROCK X] [DEEP PURPLE X]

so you can remove those "filters".

I have a lot (too much maybe) of nested structure-- if anyone has any general optimization or refactoring pointers for me I'd really appreciate it!

<?php
function event_filters() {
    $output = '';
    $filterclear = get_bloginfo('wpurl').'/events';
    $filterclass = 'filter-clear cp block fl search-tag tdn pr con ic-right ic-x c2h btn bg1 c2';
    $queryString = $_SERVER['QUERY_STRING'];
    $home = get_bloginfo('wpurl');

    parse_str($queryString, $params);
    $filter_count = count($params);

    // IF IS SINGLE DAY VIEW
    if(tribe_is_day()) {
        $day_title = ucwords(strftime( '%e de %B ', strtotime( get_query_var('eventDate') )));
        $output .= ''.$day_title.'';
    }

    foreach ($params as $key => $term) {
        $tags = explode(' ',$term);
        $tag_count = count($tags);

        $term = get_term_by('slug', $term, $key);
        $term_name = $term->name;

        if($filter_count == 1 && $tag_count <= 1) {
            // IF IS ONE KEY AND ONE TERM
            $output .= ''.$term_name.'';
        } else {
            if($tag_count > 1) {
                foreach($tags as $tag) {
                    // IF THERE IS MORE THAN ONE TERM PER KEY, LOOP THROUGH EACH TERM
                    $the_tag = get_term_by('slug', $tag, $key);
                    $tag_name = $the_tag->name;

                    $filterclear = str_replace($tag, '', $queryString);
                    $filterclear = str_replace(array('=+', '++', '+&'), array('=', '+', '&'), $filterclear);

                    if(substr($filterclear, -1) == '+'){
                        $filterclear = substr($filterclear,0,-1);
                    }

                    $output .= ''.$tag_name.'';
                }
            } else {
                // OR ELSE THERES JUST ONE TERM PRESENT
                $filterclear = remove_query_arg($term,$queryString);
                $output .= sprintf("%s", $filterclear, $term_name);
            } // END TAG_COUNT
        } // END FILTER_COUNT
    } // END FOR EACH

    return $output;
}
?>


texts: Calculate average round cell value from each 2D array cell

texts:
I am try to practice the leetcode and hit the following question 'image smooth'. Basically the question is to calculate average the around cell value from a 2D array. I have following code. But if there is better way to do it at least better performance?

def imageSmoother(M):
    """
    :type M: List[List[int]]
    :rtype: List[List[int]]
    """
    import numpy as np
    from math import floor
    m_np = np.array(M)
    tol_r, tol_c = m_np.shape
    mx = np.zeros(shape=(tol_r, tol_c), dtype=int)
    for r in range(0, tol_r):
        for c in range(0, tol_c):
            row = slice(max(0, r-1), min(tol_r, r + 2))
            col = slice(max(0, c-1), min(tol_c, c + 2))
            total = m_np[row, col].sum()
            x, y = m_np[row, col].shape
            mx[r, c] = floor(total/(x * y))
    return mx.tolist()


texts: Attempt on basic input validation and functional programming in a POSIX shell

texts:
In spite of all the POSIX shell disadvantages, I am still sticking with it and I love its portability.
Recently, I was searching for a way of code re-use, which turns out to be functional programming and input validation = Yes, in a POSIX shell script.

Let me begin with the simpler.
is_integer() + is_exit_code()
is_integer ()
{
    case "${1#[+-]}" in
        (*[!0123456789]*) return 1 ;;
        ('')              return 1 ;;
        (*)               return 0 ;;
    esac
}

is_exit_code ()
{
    is_integer "$1" &&
    case "$1" in
        ([+-]*) return 1 ;;
    esac &&
    [ "$1" -le 255 ]
}

Here, I continue on with further chained functions.
print_error() + print_error__exit()
print_error ()
{
    if ! { [ $# -eq 2 ] && [ -n "$1" ] && [ -n "$2" ]; } then
        printf '%b\n' "Some longer error message."
        exit 1
    fi
    printf '%b\n' \
        "${color_red}Error occurred$tput_reset" \
        "Error heading: $color_yellow$1$tput_reset" \
        "Error message: $2"

} >&2

print_error__exit ()
{
    if ! { [ $# -eq 2 ] && [ -n "$1" ] && [ -n "$2" ]; } &&
       ! { [ $# -eq 3 ] && [ -n "$1" ] && [ -n "$2" ] && is_exit_code "$3" && [ "$3" -ge 1 ]; } then
        printf '%b\n' "Some longer error message."
        exit 1
    fi
    print_error "$1" "$2"
    exit "${3:-1}"
} >&2

So, in this bare example, the chains go up like this:

print_error__exit ()  print_error ();

print_error__exit ()  is_exit_code ()  is_integer ().

Despite I am quite confident, these examples work as they should, one never knows, a maybe different point of view would shed a different light on my process.


texts: Applying a set of styles both with a media query and with nested rules

texts:
I am working on an application which responds to different screen resolutions. At a certain minimum DPI, we want to apply a set of styles. We also want to apply that same set of styles if the class hidpi is present on the root html element. Our project uses LESS.

This is the code I inherited. I've replaced the styles with some placeholders for the sake of this question (so don't mind the colors):

@media all and (min-resolution: 96dpi) {
  .foo {
    color: "maize";
  }
  .bar {
    color: "blue";
  }
}

html.hidpi {
  .foo {
    color: "maize";
  }
  .bar {
    color: "blue";
  }
}

Attempt at reducing duplication

As you can see, the code between the media query and html.hidpi is exactly the same, so I figured I should be able to reduce duplication. I came up with a solution using a mixin:

.mixinHidpi() {
  .foo {
    color: "maize";
  }
  .bar {
    color: "blue";
  }
}

@media all and (min-resolution: 96dpi) {
  .mixinHidpi();
}

html.hidpi {
  .mixinHidpi();
}

Can any more be done to reduce duplication? Are there any problems with the way I'm doing things now? In particular, I've only ever seen very simple examples of using mixins, so I'm not sure if I'm using them in the way they are supposed to be used.


texts:
While I'm training to get better at C, I tried my hand at making a doubly linked list implementation.

linkedlist.h

#ifndef LINKED_LIST_H_
#define LINKED_LIST_H_

#include <stdlib.h>

typedef struct node {
    void* data;
    struct node *next;
    struct node *prev;
} node;

typedef node* pnode;

typedef struct List {
    pnode head, tail;
} *List;

List init_list();
void push_back(List, void*);
void* pop_back(List);
void push_front(List, void*);
void* pop_front(List);
void foreach(List, void (*func)(void*));
void free_list(List);
void clear(List);
int size(List);

#endif /* LINKED_LIST_H_ */

linkedlist.c

#include "linkedlist.h"

List init_list() {
    List list = (List)malloc(sizeof(struct List));
    list->head = NULL;
    list->tail = NULL;
    return list;
}

void push_back(List list, void* data) {
    pnode temp = (pnode)malloc(sizeof(struct node));
    temp->data = data;
    temp->next = NULL;
    temp->prev = NULL;

    if(!(list->head)) {
         list->head = temp;
         list->tail = temp;
    } else {
        list->tail->next = temp;
        temp->prev = list->tail;
        list->tail = list->tail->next;
    }
}

void push_front(List list, void* data) {
    pnode temp = (pnode)malloc(sizeof(struct node));
    temp->data = data;
    temp->next = NULL;
    temp->prev = NULL;

    if(!(list->tail)) {
         list->head = temp;
         list->tail = temp;
    } else {
        list->head->prev = temp;
        temp->next = list->head;
        list->head = list->head->prev;
    }
}

void* pop_front(List list) {
    if(!(list->tail)) return NULL;
    pnode temp = list->head;

    if(list->head == list->tail) {
        list->head = list->tail = NULL;
    } else {
        list->head = list->head->next;
        list->head->prev = NULL;
    }
    void* data = temp->data;
    free(temp);
    return data;
}

void* pop_back(List list) {
    if(!(list->head)) return NULL;
    pnode temp = list->tail;

    if(list->tail == list->head) {
        list->tail = list->head = NULL;
    } else {
        list->tail = list->tail->prev;
        list->tail->next = NULL;
    }
    void* data = temp->data;
    free(temp);
    return data;
}

void free_list(List list) {
    while(list->head) {
        pop_back(list);
    }

    free(list);
}

void clear(List list) {
    while(list->head) {
        pop_back(list);
    }
}

void foreach(List list, void(*func)(void*)) {
    pnode temp = list->head;

    if(temp) {
        while(temp) {
            (*func)(temp->data);
            temp = temp->next;
        }
    }
}

int size(List list) {
    int i = 0;
    pnode temp = list->head;
    while(temp) {
        i++;
        temp = temp->next;
    }

    return i;
}

Can you please point out any flaws, errors, stupid mistakes, general improvements, which can make this code better and "C'ish"?


texts:
What I have here is a relatively simple endpoint for a small site I'm making. Idea is to take:

title
content
tags

and create an entry in the database. It works properly.
I threw this together as something that should work and tried to make it clean (like with the error list that gets returned) but clearly I'm doing this all by hand. Are there best practices for writing these API-style endpoints that I'm not following?
I looked under the hood at a few sites (such as SO) and noticed they are using JSON as encoding for the response. That's why I used it too.
On the input validation front, is my system decently robust or is it too flimsy?
I also tried to make the code safe by catching any exceptions that might pop up. If there's something I've overlooked please let me know.
@main.route('/createpost', methods=['POST'])
@login_required
def createpost():
resp = {
    'success': False
}

err = []

u = current_user.id  # 2458017363
title = request.values.get('title')
_tags = request.values.get('tags')  # JSON btw
content = request.values.get('content')
# _attachments = request.files.getlist('file')
# attachments = []

# for f in _attachments:
#     if f.filename.rsplit('.', 1)[1].lower() not in ALLOWED_EXTENSIONS:
#         filepath = os.path.join(UPLOAD_DIR, secure_filename(f.filename))
#         f.save(filepath)
#         attachments.append(filepath)
#     else:
#         err.append('File ' + f.filename + "is not permitted!")

if not title or len(title) > 100:
    err.append('Your title must exist and be less than 100 characters.')

try:
    tags = json.loads(_tags)
    if not tags or len(tags) > 3:
        err.append('Choose between 1-3 tags so people know what your post is about!')
except Exception:
    err.append('Choose between 1-3 tags so people know what your post is about!')

if not content or len(content) < 50:
    err.append('Your content must be at least 50 characters.')

if err:
    resp['error'] = err
    print('err')
    return Response(json.dumps(resp), mimetype='text/json')

# PROVIDED EVERYTHING IS CORRECT

while True:
    try:
        dbentry = Post(id=snowflake(),
                       author_id=u,
                       title=bleach.clean(str(title)),
                       tags=bleach.clean(str(_tags)),
                       content=bleach.clean(str(content)).encode(),
                       )

        db.session.add(dbentry)
        db.session.commit()
    except IntegrityError:
        continue
    break

resp['success'] = True
return Response(json.dumps(resp), mimetype='text/json')

imports are as follows:
# main.py
import json
import os

import bleach
from sqlalchemy.exc import IntegrityError

from .models import Post # sqlalchemy model for posts
from flask import Blueprint, render_template, request, Response
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename

from . import db
from .utils import snowflake  # random number generator
# (hence why i have a while loop around the db entry creation since there is a
# miniscule chance it will give the same number again)


texts:
I am looking for some guidance and optimization pointers for my custom JavaScript function which counts the bytes in a string rather than just chars. The website uses UTF-8 and I am looking to maintain IE8 compatibility.

/**
 * Count bytes in string
 *
 * Count and return the number of bytes in a given string
 *
 * @access  public
 * @param   string
 * @return  int
 */
function getByteLen(normal_val)
{
    // Force string type
    normal_val = String(normal_val);

    // Split original string into array
    var normal_pieces = normal_val.split('');
    // Get length of original array
    var normal_length = normal_pieces.length;

    // Declare array for encoded normal array
    var encoded_pieces = new Array();

    // Declare array for individual byte pieces
    var byte_pieces = new Array();

    // Loop through normal pieces and convert to URL friendly format
    for(var i = 0; i <= normal_length; i++)
    {
        if(normal_pieces[i] && normal_pieces[i] != '')
        {
            encoded_pieces[i] = encodeURI(normal_pieces[i]);
        }
    }

    // Get length of encoded array
    var encoded_length = encoded_pieces.length;

    // Loop through encoded array
    // Scan individual items for a %
    // Split on % and add to byte array
    // If no % exists then add to byte array
    for(var i = 0; i <= encoded_length; i++)
    {
        if(encoded_pieces[i] && encoded_pieces[i] != '')
        {
            // % exists
            if(encoded_pieces[i].indexOf('%') != -1)
            {
                // Split on %
                var split_code = encoded_pieces[i].split('%');
                // Get length
                var split_length = split_code.length;

                // Loop through pieces
                for(var j = 0; j <= split_length; j++)
                {
                    if(split_code[j] && split_code[j] != '')
                    {
                        // Push to byte array
                        byte_pieces.push(split_code[j]);
                    }
                }
            }
            else
            {
                // No percent
                // Push to byte array
                byte_pieces.push(encoded_pieces[i]);
            }
        }
    }

    // Array length is the number of bytes in string
    var byte_length = byte_pieces.length;

    return byte_length;
}


texts: Programming Pearls -- Column 1: Sorting unique numbers with bitfield

texts:
I've implemented a simple program to sort an input of unique  numbers given as decimals on a separate line.  The idea is, since all numbers are unique, to use a (long) bitfield where a 1 on index n represents that the number n is in the sorted list.  The algorithm thus consists of these phases (as described in the book):
/* phase 1: initialize set to empty */
    for i = [0, n)
        bit[i] = 0
/* phase 2: insert present elements into the set */
    for each i in the input file
        bit[i] = 1
/* phase 3: write sorted output */
    for i = [0, n)
        if bit[i] == 1
            write i on the output file

In order to (re-)freshen my Rust, I chose to implement this in Rust, to be an efficient replacement for sort(1) when given the -n option, assuming unique input.  Thus the program can be called as:
$ bitfield # sorts stdin, writes to stdout
$ bitfield foo # sorts foo, writes to stdout
$ bitfield foo - bar # sorts foo, stdin, bar, writes to stdout

As with the exercise, I assume n (MAXNUM) to be 10,000,000:
use std::io::*;
use std::fs::File;
use std::env;

const MAXNUM: usize = 10_000_000;
const _MAXLINES: usize = 1_000_000;

fn fill(src: impl BufRead, bitfield: &mut[u8; MAXNUM >> 3]) -> Result<()> {
    for line in src.lines() {
        let num = line?.parse::<usize>().unwrap();
        if num > MAXNUM {
            return Err(Error::new(ErrorKind::Other, "number too large!"));
        }

        bitfield[num >> 3] |= 1 << (num & 0b111);
    }

    return Ok(());
}

fn print_sorted(bitfield: &[u8; MAXNUM >> 3], dest: impl Write) -> Result<()> {
    let mut dest = BufWriter::new(dest);

    for (i, byte) in bitfield.iter().enumerate() {
        for bit in 0..=0b111 {
            if byte & (1 << bit) != 0 {
                write!(&mut dest, "{}\n", (i << 3) | bit)?;
            }
        }
    }

    return Ok(());
}

fn main() -> Result<()> {
    let mut bitfield: [u8; MAXNUM >> 3] = [0; MAXNUM >> 3];

    let args: Vec<_> = env::args().skip(1).collect();
    if args.is_empty() {
        fill(stdin().lock(), &mut bitfield)?;
    }

    for arg in args {
        if arg == "-" {
            fill(stdin().lock(), &mut bitfield)?;
        } else {
            let f = match File::open(&arg) {
                Err(e) => {
                    eprintln!("{}: {}", &arg, e);
                    continue;
                }
                Ok(f) => BufReader::new(f),
            };
            fill(f, &mut bitfield)?;
        }
    }
    print_sorted(&bitfield, stdout())?;

    return Ok(());
}

To test, I used GNU/shuf(1), time(1), and cmp(1):
$ shuf -i 1-10000000 -n 1000000 > foo
$ time ./target/release/bitsort foo > bar
0.19s user 0.03s system 97% cpu 0.221 total
$ time sort -n foo > bar2
1.56s user 0.06s system 291% cpu 0.556 total
$ cmp bar bar2

Ideas?


texts: Decorator Pattern in PHP Simple implementation

texts:
I am learning decorator design pattern in PHP. Please see what i am doing is correct or wrong, would appreciate your review, feedback, comments, suggestions.

<?php
/**
 * NotifierService interface is used as abstraction for Notification Mechanism
 *
 * It can be later implemented as EmailNotifierService, PushNotifierService, or
 * any other Notification SErvice
 */
interface NotifierService {

    public function Notify();
}

/**
 *  EmailNotifierService - is Email Decorator
 *  here the EmailSending is Implemented, and it can be used wherever it is
 *  required, Different Unique services that doesn not have common behaviours
 *   are utilised using decorator patterns
 */
class EmailNotifierService implements NotifierService {

    public function __construct(){

        $this->to = 'Praveen@gmail.com' ;//$toarr;
        $this->from  = 'Napoleon@gmail.com' ;//$from;
        $this->msg   = 'This is a test message';//$msg
    }

    /**
     * [sendMail Actual Implementation of Sending Email is put here]
     * Kept simple for demo purposes
     */
    private function sendMail(){

        echo "Sending Email To" .PHP_EOL;
        print_r($this->to);

        echo "From: " .PHP_EOL;
        print_r($this->from);

        echo "Msg: " .PHP_EOL;
        print_r($this->msg);
    }

    /**
     * [Notify - Implementation of the interface method - Notify]
     */
    public function Notify(){
        echo "Notify function called" .PHP_EOL;
        $this->SendMail();
    }
}

class User implements NotifierService{

    var $users = [];
    var $notifierservice;

    //Passing NotifierService Object, So that we can utilise its service
    public function __construct(NotifierService $notifierservice){

        echo "New User constructed";
        $this->notifierservice = $notifierservice;
    }

    /**
     * [adduser This function creates a new user, like new user signup,
     * Whenever a new user signup, a Email is sent to the Website Admin]
     * @param  [Username] $u Username
     */
    public function adduser($u){
        $this->users[]=$u;
        $this->Notify();// Calls the Notification
    }

    public function Notify(){
        $this->notifierservice->Notify();
    }

}
// New User is created, EmailNotificationService is wrapped in it
// So that whenever a new user is created, Admin gets an Email
$u1 = new User(new EmailNotifierService());
$u1->adduser('Ramkumar');


texts:
This is part of a two-part post (Part 2).

Here, I have two recent projects that parse a file. The first uses a loop that's kind of hard to follow, and the second uses "modes" to decide what to do.

Project 1: A "bookmark manager" for managing URLs easier than a text editor.

The data structures:

typedef struct {
    char *text;
    int length;
} string;

typedef struct {
    string *path;
    string *title;
} url;

typedef struct {
    url **urls; // An array of pointers to urls
    int length;
    int sel_url;
    int modified;
    char *filename;
} urllist;

For the data, I am considering using a linked list instead of an array.

The parser:

void parse_file(char *fname, urllist *ul){
    /* Dumb char-by-char parser that follows the syntax "URL[Title]"
     * [Title] is optional. If left unspecified, then the url is used as
     * a title instead.
     *
     * There's some basic idiot-proofing:
     *
     * 1. Empty lines are ignored (lazy-ignore)
     *    Rather, '\n' and ' ' are skipped if they begin a line.
     *    " http://google.com" is still valid; it'll just take two
     *    iterations to extract anything from it
     *
     * 2. lines beginning in '[' or '#' are fully ignored (full-ignore).
     *    So you can write comments like "#this" or "[this]". The
     *    'comment char' has to be the first character on the line. If
     *    there is a space before it, for example, the parser will think
     *    it's a url.
     */
    int c;
    url *u;
    FILE *f = fopen(fname, "r");

    while(1){
        c = fgetc(f);
        if(c == -1){ /* Check EOF */
            break;
        }
        if(c != '\n' && c != ' ' && c != '[' && c != '#'){
            /* Thanks to the EOF check, I have to add the first char
             * NOW, while I still have it. This is also an opportunity
             * for a sanity check */
            u = new_url();
            string_push_char(u->path, c);
        } else if(c == '#' || c == '['){ /* full-ignore */
            while((c = fgetc(f)) != '\n');
            continue;
        } else { /* lazy-ignore */
            continue;
        }
        while(1){ /* Step through individual line */
            c = fgetc(f);
            if(c == '\n'){
                /* Line ends without title, copy path to title */
                string_copy(u->title, u->path);
                break;
            }
            if(c == '['){
                /* Title specified. */
                while(1){ /* Get it. */
                    c = fgetc(f);
                    if(c == ']'){
                        while(fgetc(f) != '\n');
                        break;
                    }
                    string_push_char(u->title, c);
                }
                break;
            }
            string_push_char(u->path, c);
        }
        url_push(ul, u);
    }
    fclose(f);
}

It works, but I feel like it could be done better. As I said earlier, it's hard to follow. You can tell because it's littered with comments, which I personally try to avoid unless describing a block of code as a whole.

An example file

# Cool sites
http://google.com/search?q=help+with+bananas[Google: banana help]
http://stackoverflow.com[Stack Overflow]

# YouTube stuff
http://youtube.com

Result

[Google: banana help                  ]
 Stack Overflow
 http://youtube.com

http://google.com/search?q=help with bananas


texts: Bash script prepares virtual environment

texts:
I have a few Flask projects that I want to install, each in their own virtual environment. The approach is derived from this tutorial. The steps to create the VE's are very similar, so they're easy to automate. So I wrote this, as a first step. It seems to work OK:

#! /bin/bash

if [ $# -lt 2 ]
  then
    echo -e "mkve.sh - make virtual environment\nUsage: mkve.bash project_name user_name"
    exit
fi

echo project name: $1
echo project user: $2

# create the webapp user and its home directory, and give it ownership
sudo useradd --system --gid webapps --shell /bin/bash --home /mnt/u1/$1 $2
sudo mkdir -p /mnt/u1/$1
sudo chown $2 /mnt/u1/$1

# become the webapp user, create a virtual environment, start it, and install gunicorn and flask
sudo su $2 -c "cd ~; virtualenv ./venv"
sudo su $2 -c "cd ~;. venv/bin/activate; pip install gunicorn flask"

echo -e "Done! Start with:\n$ sudo su - $2\n$ . venv/bin/activate"
echo -e "Or undo the whole kaboodle with:\n$ sudo userdel -r $2"

# at this point, manual configuration is necessary, which is different for each project.

I'm fairly new to bash programming, so I'm open to suggestions.
Is this good practice at all?
Any serious pitfalls I have overlooked?
Any room for improvement?


texts: Delete Entry from SQL-Table and confirm the deletion to a CommandSender in a spigot plugin

texts:
I'm working on a spigot plugin, that deals with messages to from players on a server to the admin's. It's the same plugin this question relates to: SQL structure to save coordinates for spigot plugin . I've got a command, which allowes access to the inbox, and does all kinds of operations on the data. One of these operations is deleting an entry by it's ID.
I've got a simple SQL query to delete it, and want to display a message, depending on if the message could be deleted or not. Therefore I wrote this method in my Command-Class:
private void deleteMessage(CommandSender sender, int messageId) {
    int deleted = DatabaseMethods.deleteMessage(messageId);

    if (deleted == 0) {
        sender.sendMessage(MessageManager.couldNotBeFound(messageId));
    } else {
        sender.sendMessage(MessageManager.deletedMessage(messageId));
    }
}

and this is the method that accesses the database:
public static int deleteMessage(int messageId) {
    try (final PreparedStatement ps = BasePluginAPI.getDatabaseConnection()
            .prepareStatement("delete from MELDUNG where ID = ?")) {
        ps.setInt(1, messageId);
        return ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
        return 0;
    }
}

I don't know if this is the best way to approach it. I have two main questions:

Is an early return better for the first method? Or is it just a question of personal taste?
Can the SQL-handling be improved? Should maybe the method return a boolean instead of an int?

Besides these specific questions, of course general feedback is very welcome as well! :)


texts:
Yes, another FizzBuzz! I know you guys may be tired of these but I think it's a tradition stepping stone for beginners on this site.

Here are some notes on my thinking:

I tried to keep it as flexible as possible where the logic is deducted from the variables as much as possible. So one could potentially make a user input form on a website and let the user select all the values (numbers and words), and the code just does it.
I tried to avoid magic numbers as much as I know how. Not sure if 0 counts as a magic number.
I did not feel the need to add any comments as I feel it is self-explanatory. If you feel otherwise, please let me know.

Here is a link to PhpFiddle for your convenience.

<?php
$counter = 1;
$stopper = 100;
$fizzWord = 'Fizz';
$fizzNumber = 3;
$buzzWord = 'Buzz';
$buzzNumber = 5;

for ($counter = 1; $counter <= $stopper; $counter++) {
    if ((($counter %($fizzNumber * $buzzNumber) == 0))) {
        echo $fizzWord . $buzzWord;
    }
    elseif (($counter % $fizzNumber) == 0) {
        echo $fizzWord;
    }
    elseif (($counter % $buzzNumber) == 0) {
        echo $buzzWord;
    }
    else {
        echo $counter;
    }
echo "<br>\n";
}
?>


texts: How to enumerate the internal nodes and leaves of a tree more elegantly?

texts:
Might there be a simpler way to write this code?  I'd like to learn to write code more efficiently.

def leaves_and_internals(self):
    """(BTNode) -> ([object], [object])
    Return a pair of lists: (list of all the items stored in the leaves of
    the subtree rooted at this node, list of all the items stored in the
    internal nodes of the subtree rooted at this node).
    """
    leaves = []
    internal = []

    if self.left is None and self.right is None:
        leaves.append(self.item)
    else:
        internal.append(self.item)
    if self.left:
        subleaf, subinternal = self.left.leaves_and_internals()
        leaves.extend(subleaf)
        internal.extend(subinternal)
    if self.right:
        subleaf, subinternal = self.right.leaves_and_internals()
        leaves.extend(subleaf)
        internal.extend(subinternal)

    return (leaves, internal)


texts:
I wrote this in order to solve the fractional knapsack problem. Any feedback is appreciated.

def get_optimal_value(capacity, weights, values):
    value = 0.
    if sum(weights) <= capacity:
        return sum(values)
    if len(weights) == 1:
        value = values[0]/float(weights[0])*capacity
    densities = [(v/float(w), w) for (v,w) in zip(values, weights)]
    densities = sorted(densities, key=lambda density:density[0], reverse=True)
    fraction = 0.
    #print(densities)
    for i in range(len(weights)):
        fraction = sum([f for (d,f) in densities[0:i]])
        #print(i, fraction, capacity)
        if fraction >capacity and i >0:
            value = sum([d*f for (d,f) in densities[0:i-1]]) + densities[i][0]*(1.0000000-densities[i][1]/float(capacity))*capacity
        if fraction == capacity and i >0:
            value = sum([d*f for (d,f) in densities[0:i]])

    return value


texts: Red-black tree not matching performance of Java's TreeMap

texts:
This program is for constructing a symbol table where a key is a word and value is the frequency of the word in a text file and finding the word with maximum frequency.

I did it in two ways:

First I used Java's inbuilt TreeMap, which uses a red-black tree as internal data structure.

Then I made my own implementation of red-black tree and did the same thing.But I was lot disappointed when my program came whole lot slower in accomplishing the task. I ran both the programs several times. But still the minimum time of TreeMap was lesser than my own program time by at least 1 million of nano seconds. Also it won every time when I computed average time taken by both. This much time lag makes me ask whether I can improve my implementation of red-black tree about which I am really skeptical.

First method:

import java.util.*;
import java.io.*;
class TREEMAP_APP
{
 public static void main(String []args)throws IOException
 {
     BufferedReader br = new BufferedReader(new FileReader("book.txt"));
     TreeMap<String , Integer> tm = new TreeMap<String , Integer>();
     String S="";
     String []arr;
     String line;
     int max=0;
     long st=System.nanoTime();
     while((line=br.readLine())!=null)
     {
         arr=line.split(" ");

         for(String k:arr)
          if(!tm.containsKey(k))
           tm.put(k,1);
          else
          {
            tm.put(k,tm.get(k)+1);
            if(tm.get(k)>max)
            {S=k;max=tm.get(k);}
          }
     }
     long ft=System.nanoTime()-st;
     System.out.println("time taken is "+ft);
     System.out.println("the word that occurs for the maximum no of times is and it occurs for");
     System.out.println(S+"    "+max);
    }
}

Red-black tree:

import java.io.*;
class REDBLACK
{
 int max=0;String S="";
 public Node insert(Node x,String key)
 {
     if(x==null)
     {
         return new Node(key,1,'R',null,null);
     }
     else if(key.compareTo(x.key)>0)
     {
         x.right=insert(x.right,key);
     }
     else if(key.compareTo(x.key)<0)
     {
         x.left=insert(x.left,key);
     }
     else {x=new Node(key,x.value+1,x.color,x.left,x.right);}

     if(isRed(x.right)&&!isRed(x.left))   x=rotate_left(x);
     else if(isRed(x.left)&&isRed(x.left.left)) x=rotate_right(x);
     else if(isRed(x.left)&&isRed(x.right)) flip_color(x);
     return x;
 }
 public boolean isRed(Node x)
 {
     if(x==null) {return false;}
     if(x.color=='R')
     return true;
     else return false;
 }
 public Node rotate_left(Node x)
 {
     Node y=x.right;
     x.right=y.left;
     y.left=x;
     y.color=x.color;
     x.color='R';
     return y;
 }
 public Node rotate_right(Node x)
 {
     Node y=x.left;
     x.left=y.right;
     y.right=x;
     y.color=x.color;
     x.color='R';
     return y;
 }
 public void flip_color(Node x)
 {
     x.color='R';
     x.left.color='B';
     x.right.color='B';
 }
 public static void main(String []args)throws IOException
 {
   REDBLACK tree1=new REDBLACK();
   Node root=null;
   BufferedReader br=new BufferedReader(new FileReader("book.txt"));
   String []arr;
   String line;
   int max=0;
   long st=System.nanoTime();
   while((line=br.readLine())!=null)
   {
       arr=line.split(" ");
       for(String s:arr)
        root=tree1.insert(root,s);
   }
   long ft=System.nanoTime()-st;
     System.out.println("time taken is "+ft);
   System.out.println("the word with maximum freq is "+Node.S+" and its freq is "+Node.max);
 }
 public void iot(Node x)
 {
     if(x==null)
      return;
     iot(x.left);
     System.out.println(x.key+" "+x.value);
     iot(x.right);
 }
}

class Node
{
 String key;int value;char color;
 Node left,right;static int max=0;static String S="";
 Node(String key,int value,char color,Node l,Node r)
 {
     this.key=key;
     if(value>max)
     {max=value;S=key;}
     this.value=value;
     this.color=color;
     this.left=l;
     this.right=r;
 }
}


texts:
I am challenging myself to try to attempt to write a function that is as efficient, portable and failsafe as possible. The function is very simple and just converts a string (or wstring) to lowercase.

Are there any improvements you think I could make and any errors I have done?

#ifdef UNICODE
typedef std::wstring tstring;
typedef std::wstring::npos tnpos;
#else
typedef std::string tstring;
//typedef std::string::npos tnpos;  // throws compiler error?!
#endif

tstring toLower(const tstring& str)
{
    // Alternative 1: Returns a copy of a local string so not that efficient.

    unsigned int len = str.length();    // use unsigned int so I only have 4 bytes as opposed to 16 for int
    tstring lower(len, 'a');            // ensure string is correct size to avoid dynamic resizing. Reserve at construction; performing 2 steps at once defintion and reserving - is faster right?
    // or use lower.reserve(len);

    for (unsigned int i=0; i<len; i++)  // iterate using indexes. Maybe iterators could be more fail safe/efficient/etc.?
        lower[i] = tolower(str[i]);

    return lower;
}

void toLower(const tstring& inStr, tstring& outStr)
{
    // Alternative 2: Have user define string and pass by reference (this would be faster?)

    unsigned int len = inStr.length();  // use unsigned int so I only have 4 bytes as opposed to 16 for int. Store length in local variable because we look it up again in the below for loop
    outStr.resize(len);                 // ensure string is correct size to avoid dynamic resizing.

    for (unsigned int i=0; i<len; i++)  // iterate using indexes. Maybe iterators could be more fail safe/efficient/etc.?
        outStr[i] = tolower(inStr[i]);
}


texts:
I'm working with Codeigniter and I have a jQuery file to add some functionalities. But I think I'm doing it in a wrong way.

$(function() {
    var list = '../indoamericana/intranet/employeesList/';
    var home = '../indoamericana/administrar/callHome/';
    var profile = '../indoamericana/user/';
    var addUser = '../indoamericana/user/addUSer';

    $(document).on('click', '#documentacion', function(e) {
        var head = $('iframe').contents().find('head');
        head.append($('<link/>', {
            rel: 'stylesheet',
            href: '/indoamericana/webroot/css/style.css',
            type: 'text/css' }));
        head.append($('<link/>', { rel: 'stylesheet',
            href: '/indoamericana/webroot/css/custom.css',
            type: 'text/css' }));
        e.preventDefault();
    });

    $(document).on('click', 'a[data-target=#ajax]', function(ev){
        var target = $(this).attr("href");
        $("#ajax").load(target, function() {
            $("#ajax").modal("show");
        });
        ev.preventDefault();
    });

    var loadPage = function(page){
        $(".page-content").load(page);
    };

    $(".sub-menu .menu-item, .module-item").click(function(event) {
        $(".page-content").load($(this).data('target'));
        $("title").text( $( this ).text() );
    });

    $( document ).on( 'click', '.page-sidebar-menu li', function(e) {
        $( this ).addClass('active');
        $( this ).siblings().removeClass('active');
    });

    var last_clicked = '';
    var order = 'asc';

    $(document).on('click', '#admin-support a i', function(e){
        var index = $( this ).attr('data-sort');
        if( last_clicked == index )
            order = ( order == 'asc' ) ? order = 'desc' : order = 'asc';
        last_clicked = index;
        var page  = '../indoamericana/soporte/allSupports/' + index + '/' + order;
        $(".page-content").load(page);
    });
});

I'm calling this file (call-functionalities.js) in a script type of my 'head':

<script src="webroot/scripts/call-functionalities.js" type="text/javascript"></script>

I don't want to use anonymous functions. I have seen some pages that use

jQuery(document).ready(function() {
  App.init();
  Index.init();
});


texts: Groovy: find all elements in a list equal to the max element

texts:
Is there any simpler way to find all elements in a list that are equal to the max element.

List v = [ 1,2,3,4,5,5  ]
def max = v.max()
def maxs = v.findAll { it == max }

Thanks!


texts:
Here is my solution to Grading Students courtesy of HackerRank. My code passes all tests in the testing suite but I feel like there could be a better implementation of it. But nonetheless, what are some pros/cons of my current implementation?
Thank you for answering.

def gradingStudents(grades):
    rounded_grades = []
    for grade in grades:
        if grade < 38:
            rounded_grades.append(grade)
        else:
            if grade % 5 == 0:
                rounded_grades.append(grade)
            else:
                difference = 0
                new_grade = grade
                while grade % 5 != 0:
                    difference += 1
                    new_grade += 1
                    if new_grade % 5 == 0:
                        break
                if difference < 3:
                    rounded_grades.append(new_grade)
                else:
                    rounded_grades.append(grade)
    return rounded_grades


texts: Updating one model field based on the associated model's field

texts:
I'm wondering if there is any way we can optimize the following code.
Scenario is Library's active field should be true if it has any available book.

class Book < ApplicationRecord
  belongs_to :library
  scope :available, -> { where.not(deleted: true) }

  after_commit :update_library_active, on: [:update, :create]

  def update_library_active
    self.library.update_active_status
  end

end

class Library < ApplicationRecord
  has_many :books

  def update_active_status
    self.update(active: books.available.present?)
  end

end


texts:
I'm a beginner to PHP and I've written a function that validates a U.K National Insurance Number. The function works by checking whether the given number against the format below;

  The National Insurance Number ($NINO) is made up of 3 components in the
  format AAnnnnnnA. The 3 components are the prefix, numeric body and
  suffix.

  Prefix

  The first two alpha characters, validated as follows:

  • The prefix must not be BG, GB, NK, KN, TN, NT or ZZ

  • The prefix must not contain D F I Q U or V

  • The second character of the NINo prefix must not be O

  Numeric body

  The 8 numeric characters of the NINO, validated as follows:

  • Must be numeric in the range 000000 – 999999

  Suffix

  The final alpha character; validated as follows:

  • Must be in the range A – D

<?php

function validateNI($NINO) {
    $NILength = strlen($NINO);

    if (!($NILength < 10 | $NILength > 10)) {
        $NIParts = str_split($NINO, 2);

        if(!(preg_match("/[^!@#$%^&*]*(BG|GB|NK|TN|NT|ZZ|D|F|I|Q|U|V)[^!@#$%^&*]*/i", $NIParts[0]))) {

            $NIPartsSplit = str_split($NIParts[0]);

            if(preg_match("/[^!@#$%^&*]*(O)[^!@#$%^&*]*/i", $NIPartsSplit[1])) {
                echo "Invalid National Insurance Number.";
            } else {
                $NIPartsNum = $NIParts[1].$NIParts[2].$NIParts[3];

                if (is_numeric($NIPartsNum)) {

                    if(preg_match("/[^!@#$%^&*]*(A|B|C|D)[^!@#$%^&*]*/i", $NIParts[4])) {
                        echo "Valid National Insurance Number.";
                    } else {
                        echo "Invalid National Insurance Number.";
                    }
                } else {
                    echo "Invalid National Insurance Number.";
                }
            }

        } else {
            echo "Invalid National Insurance Number.";
        }

    } else {
        echo "Invalid National Insurance Number.";
    }
}

validateNI("AA1220091A");

?>

I'm looking for advice on how I can reduce the overall lines of code (including the use of regex) as well as increasing the efficiency and simplicity of my code.


texts:
I have implemented a custom concurrent queue on top of GCD which offers two additional pieces of functionality:

Limit the maximum number of concurrently executing tasks.
Give manual control over which enqueued task is scheduled for execution next.

An OperationQueue could of course address the former but gives no control over the latter. Being able to influence the order in which the queue executes its task is however beneficial for the purposes of my app (anticipating and delaying expensive tasks that are likely to get cancelled), hence my attempt at this implementation.
I have multiple concerns:

The fact that this is one class providing two distinct pieces of functionality seems like a red flag. Implementing this in two separate types, possibly with one subclassing the other, would probably be better. But I can't see a straightforward way to untangle this without overcomplicating things.

Needing three queues and a semaphore to coordinate everything isn't great. Am I trying to be too clever?

Looking through some of the libdispatch guidelines, particularly this post by the maintainer, has me wondering if this entire use case is a bit of an anti-pattern anyway (specifically regarding the use of semaphores to wait for asynchronous work). Is it simply a bad idea to try retrofitting this kind of functionality onto GCD?

Given my initial requirements (i.e. limited bandwidth and custom scheduling order), is this approach remotely reasonable? If so, how could it be improved?
Thanks in advance!
final class Queue {

    let count: Int

    private let block: (Range<Int>) -> Int

    private let semaphore: DispatchSemaphore

    private let objectQueue: DispatchQueue

    private let semaphoreQueue: DispatchQueue

    private let workItemQueue: DispatchQueue

    private var workItems = Array<DispatchWorkItem>()

    init(count: Int, qos: DispatchQoS = .default, block: @escaping (Range<Int>) -> Int) {
        self.count = count

        self.block = block

        self.semaphore = .init(value: count)

        self.objectQueue = .init(label: "object-queue", qos: qos)

        self.semaphoreQueue = .init(label: "semaphore-queue", qos: qos)

        self.workItemQueue = .init(label: "workitem-queue", qos: qos, attributes: [.concurrent])
    }

}

extension Queue {

    func async(execute work: @escaping () -> ()) {
        objectQueue.async { [self] in
            let workItem = DispatchWorkItem(flags: [.inheritQoS]) {
                work()

                semaphore.signal()
            }

            workItems.append(workItem)

            semaphoreQueue.async {
                semaphore.wait()

                objectQueue.async {
                    let index = block(workItems.indices)

                    let workItem = workItems.remove(at: index)

                    workItemQueue.async(execute: workItem)
                }
            }
        }
    }

    func async(execute workItem: DispatchWorkItem) {
        async { workItem.perform() }
    }

}

Edit
The block closure selects the index of the next-to-be-scheduled work item. Its argument Range is guaranteed to be non-empty.
The work items are in the same order in which they were enqueued. block isn't intended to relate to specific work items but rather to make a decision between choosing ones that have been awaiting execution for a while vs. ones that just arrived in the queue.
I use it in this specific way:
let count = max(1, ProcessInfo.processInfo.activeProcessorCount - 2)

let queue = Queue(count: count) { indices in
    let value = sqrt(.random(in: 0 ..< 1))

    let index = Int(value * Double(indices.count))

    return indices[index]
}

In this configuration the queue picks work items at random, skewing towards newer ones. This might seem counterintuitive, but when dealing with a lot of expensive tasks which are subject to likely cancellation (in my case loading resources for display in a collection view while scrolling), this results in a measurable performance improvement.


texts: Temporal kernel filtering on video frames coming in a loop

texts:
I have a video which I read in a loop frame by frame. For every frame, I want to do temporal kernel filtering, the coefficients of which come from the input variable model (a dictionary). The temporal kernel is an array that has size of 15. So, basically, for every frame we apply this function. The variables scale, clip_size are constants. Firstly I add borders across the obtained frame. Then I start a buffer of size (15,240,320) where (240,320) is the clip size. Variable bindex is used to write the buffer. The buffer variable will store only last 15 modified frames, hence bindex needs to be updated at every function iteration. Variable sindex is used to traverse through the buffer and apply the buffer, hence it has to be returned too.  Since the input_frames are coming from a video in a loop, I had to make some variables be both inputs and outputs. Is there a way to speed this up? Any better way to do this?

def filtered_output(input_frame,model, Buffer,bindex,sindex,scale,clip_size):
    # padding is required
    top=model['item'][0]
    bot=model['item1'].shape[1]-top-1
    left=model['item'][1]
    right=model['item1'].shape[0]-left-1
    # NewDepth = 15
    # clip_size is [240,320]
    # In the external loop, bindex = 0, sindex =0 in the beginning
    # We now create a copy of our current frame, with appropriate padding
    frame2= cv2.copyMakeBorder(input_frame,top,bot,left,right,cv2.BORDER_CONSTANT,value=0.5)
    Buffer[bindex] = scipy.signal.convolve2d(frame2, model['item1'], boundary='symm', mode='valid')
    sindex = (bindex+1) % NewDepth # point to oldest image in the buffer
    temp=np.zeros(tuple(clip_size),dtype=float)
    temp = model['TempKern'][0]*Buffer[sindex]

    sindex = (sindex+1) % NewDepth
    for j in range(1, NewDepth) :  # iterate from oldest to newest frame
        temp = temp + model['TempKern'][j]*Buffer[sindex]
        sindex = (sindex+1) % NewDepth
    bindex = (bindex+1) % NewDepth
    temp=np.nan_to_num(temp)
    output_frame = ApplyCubicSpline(model['CubicSplineCoeffs'],temp)*scale
    return output_frame, Buffer,bindex,sindex

My question is whether we can make this function faster somehow (not that it is slow)? If yes, how? Is it the best practice to use bindex, sindex as both inputs and outputs to the function? Are there any alternatives?


texts: Removing folders from my rails app with rake

texts:
I'm trying to remove the tmp/letter_opener folder. Everything works fine, just wondering if there's a better way to write it. My next step is to write some tests, to double check that I can only accept those inputs (currently failing)

#my_rake_task.rake

namespace :cleanup do

desc 'Deletes the emails inside tmp/letter_opener folder.'
task letter_opener_emails: :environment do

start_time = Time.current
Rails.logger.info "Task starting at #{start_time}."
puts "Task starting at #{start_time}."

print 'About to remove the tmp/letter_opener folder. Press [Nn] to abort. Press [Yy] to continue.'
option = STDIN.gets.strip

case option #[FIXME]: Not deleting the folders
  when /[^Nn]/ then FileUtils.rm_r(Dir.glob('tmp/letter_opener/*'))
    puts 'Directory contents removed'
  when /[^Yy]/ then 'Exiting the task now.'
    # abort_message
end
end


texts:
I'm willing to listen to any advice you have for improving it.

from collections import defaultdict

import nltk
import numpy as np

seq, freq, sample = [t for ts in [[None] + nltk.casual_tokenize(line) + [None] for line in open("file.txt").readlines()] for t in ts], defaultdict(lambda: defaultdict(int)), lambda curr: np.random.choice(list(freq[curr].keys()), p=[x/sum(freq[curr].values()) for x in freq[curr].values()])
for a, b in zip(seq[:-1], seq[1:]): freq[a][b] += 0 if a is None and b is None else 1
curr = sample(None)
while curr != None: _, curr = print(curr, end=" "), sample(curr)


texts: Logfile parser for Team Fortress Classic video game

texts:
I'm currently working on a logfile parser for a pretty old videogame called Team Fortress Classic, which can be compared to Counter-Strike 1.6 and is available on Valve's Steam platform.

I started out trying to make a collection of nicknames for each player. Every player joining the server has a unique ID, the STEAM_ID.
Once a player joins the server I can parse the ID off the logfile:

L 07/08/2013 - 19:25:40: "Marcus<47><STEAM_0:1:111><>" entered the game

So the STEAM_ID for the joining player would be STEAM_0:1:111, for the database I strip off the static prefix STEAM_ and only add 0:1:111 to the steam_id field in the database to keep the size smaller.

Now a player can change his in-game nickname from let's say Marcus to sucraM. I thought about making a one-to-many relationship between the tables players and aliases, adding the nickname the player was first seen with to the players table as a primary nickname to easier keep track of the player (later that would be useful i.e. when a known player joins the server with a new nickname I could print a line "new_nickname is also known as primary_nickname" to tell everyone who they are actually dealing with) and using a foreign key field player_id_fk in the aliases-table to be able to add several aliases for one players.id.

The database structure I created looks like the following;

players table:

CREATE TABLE players (
    id SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    steam_id VARCHAR(15) UNIQUE,
    name VARCHAR(15)
) ENGINE = 'InnoDB';

aliases table:

CREATE TABLE aliases (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    player_id_fk SMALLINT UNSIGNED,
    name VARCHAR(31),
    FOREIGN KEY (player_id_fk) REFERENCES players(id) ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE = 'InnoDB';

Populating the tables with dummy data:

INSERT INTO players (id, steam_id, name) VALUES
    (NULL, '0:1:111', 'Marcus'),
    (NULL, '0:1:222', 'Benjamin');
INSERT INTO aliases (id, player_id_fk, name) VALUES
    (NULL, (SELECT id FROM players WHERE steam_id = '0:1:111'), 'Marcus The Great'),
    (NULL, (SELECT id FROM players WHERE steam_id = '0:1:111'), 'sucraM'),
    (NULL, (SELECT id FROM players WHERE steam_id = '0:1:222'), 'Benjamin The Weirdo');

Finding a player by steam_id and return his primary nick and known aliases:

SELECT players.steam_id, players.name, group_concat(aliases.name separator ', ') AS aliases
FROM players
INNER JOIN aliases
ON players.id = aliases.player_id_fk
WHERE players.steam_id = '0:1:111'

Hence I'm a novice to relational databases I have a few questions:

Am I using one-to-many the right way?
Can the layout be improved in any form?
If I'm going to print all known player names and their aliases to a website I might have to split aliases (group_concat() part in SELECT query) by separator ", " - now if a player is using the alias/name "Hello, its me!" this will be a problem as the alias/primary nickname will be split into "Hello" and "its me!".

Of course I could use a separator that is very unlikely to used by any player in their nicknames but I consider that method pretty unclean. I'm sure there has to be a query which would print steam_id, primary nick (players.name) and all the players' aliases so I can just iterate through them, I just can't figure out how to achieve this.

Any suggestions?


texts: Unsubscribing Facebook admins and regular users from notifications

texts:
What is the best way to DRY this code up?

class NotificationsController < ApplicationController
  before_filter :load_user

  def unsubscribe
    if @facebook_admin && @facebook_admin.auth_key == params[:auth_key]
      @facebook_admin.update_notification_settings(params[:type] => false)
    elsif @user && @user.auth_key == params[:auth_key]
      @user.update_notification_settings(params[:type] => false)
    end
  end

  private

  def load_user
    if params[:type].present?
      if params[:facebook_admin_id].present?
        @facebook_admin = FacebookAdmin.find_by_id(params[:facebook_admin_id])
      elsif params[:user_id].present?
        @user = User.find_by_id(params[:user_id])
      end
    end
  end
end


texts: Get the value of the name attribute of each element with class="class"

texts:
I need a function to get the value of the name attribute of each element with class="class". I was wondering what is the best way to do this, performance-wise.

Currently I'm using jQuery and doing it like this:

$("#Button").click(function() {
    var myElements = $(".class");
    for (var i=0;i<myElements.length;i++) {
        alert(myElements.eq(i).attr("name"));
    }
});

Alert is just to show what it does, of course. For the following HTML:

<input type="checkbox" class="class" name="1">
<input type="checkbox" class="nope" name="2">
<input type="checkbox" class="class" name="3">

It would issue:

alert("1")
alert("3")

I was wondering if using pure Javascript would be faster, or if there is any other (better) way of doing it. I apologize if this question is not on this website's scope, please move it to Stackoverflow if that's the case.


texts:
I created a method that takes a string value with a fixed length of 9 characters and extracts three values, house (4 characters), level (2), door (3). If the input value has another length than 9 then the method should return nil.

I found several ways to implement the method, but which implementation should I prefer and why?

def extract(value)
  return nil unless value.length == 9
  [value[0..3].to_i, value[4..5].to_i, value[6..8].to_i]
end

require 'scanf'

def extract(value)
  return nil unless value.length == 9
  value.scanf('%4d%2d%3d')
end

def extract(value)
  value.match(/^(\d{4})(\d{2})(\d{3})$/).captures.map(&:to_i) rescue nil
end

p extract('123456789')
#=> [1234, 56, 789]
p extract('123456789012')
#=> nil


texts: MVVM model letting the user select a directory in a testable manner

texts:
My application needs to let the user select a folder from somewhere on their local machine. Below are the interface and model pair that I have written to let the user do so.

public interface IFolderPicker
{
    //  Methods
    //  =======

    string Show();
}

using Microsoft.WindowsAPICodePack.Dialogs;
using WinForms = System.Windows.Forms;

public class FolderPicker : IFolderPicker
{
    //  Constants
    //  =========

    private const string SelectATargetFolder = "Select a target folder";
    private const string CDrive = @"C:\";

    //  Variables
    //  =========

    private readonly bool isPlatformSupported;
    private readonly WinForms.FolderBrowserDialog xpFolderBrowserDialog;
    private readonly CommonOpenFileDialog vistaFolderBrowserDialog;

    //  Constructor
    //  ===========

    public FolderPicker()
    {
        isPlatformSupported = CommonFileDialog.IsPlatformSupported;

        xpFolderBrowserDialog = new WinForms.FolderBrowserDialog
        {
            Description = SelectATargetFolder
        };

        vistaFolderBrowserDialog = new CommonOpenFileDialog
        {
            Title = SelectATargetFolder,
            IsFolderPicker = true,
            DefaultDirectory = CDrive,
            AllowNonFileSystemItems = false,
            EnsurePathExists = true,
            Multiselect = false,
            NavigateToShortcut = true
        };
    }

    //  Deconstructor
    //  =============

    ~FolderPicker()
    {
        xpFolderBrowserDialog.Dispose();
        vistaFolderBrowserDialog.Dispose();
    }

    //  Methods
    //  =======

    public string Show()
    {
        if (isPlatformSupported)
        {
            return SelectWinVistaOrLaterFolder();
        }
        else
        {
            return SelectWinXPFolder();
        }
    }

    private string SelectWinXPFolder()
    {
        WinForms.DialogResult result = xpFolderBrowserDialog.ShowDialog();

        switch (result)
        {
            case WinForms.DialogResult.OK:
            case WinForms.DialogResult.Yes:
                return xpFolderBrowserDialog.SelectedPath;

            default:
                return null;
        }
    }

    private string SelectWinVistaOrLaterFolder()
    {
        CommonFileDialogResult result = vistaFolderBrowserDialog.ShowDialog();

        switch (result)
        {
            case CommonFileDialogResult.Ok:
                return vistaFolderBrowserDialog.FileName;

            default:
                return null;
        }
    }
}

My reasoning for this design is that now the 3 readonly variables can be mocked in unit tests via reflection, while this isn't an ideal way of doing it, it's better than nothing.

While I am looking for all feedback, my focus here is on the WinForms.FolderBrowserDialog and the CommonOpenFileDialog. They both implement the IDisposable interface and my concern is that I might not be implementing that properly?
I believe that I could make the IFolderPicker interface extend the IDisposable interface and then call the two .Dispose() methods from within the inherited Dispose method but I was hoping I could insulate the rest of my program from these two classes as much as possible - is disposing of them in the deconstructor like this also valid?

Originally I had both these classed being instantiated in their respective Select...() methods in a using block. But while also not being mock-able, it meant they were being newed up each time the method was called - is this current implementation better than that?


texts: C# Asp.net core middleware for redirecting URLs

texts:
I wrote a small middleware for redirecting between WWW URLs.
The most important thing that I want to change is to make it super fast.
Here's what it is doing:
If the host is localhost or mywebsite.com without any subdomains and without www, it will redirect to www.localhost or www.mywebsite.com.
If the host starts with www. AND has subdomains, it will redirect to a url without www.
using System;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Builder;

using Microsoft.Extensions.Logging;

namespace Website.Middlewares
{

    public class WWWRedirectionMiddleware
    {
        private readonly RequestDelegate _next;

        private string _domain;
        private int _https_port;

        public WWWRedirectionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {

            var request = context.Request;
            var response = context.Response;

            var host = request.Host;

            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                _domain = "localhost";
                _https_port = 5001;
            }
            else
            {
                _domain = "seaoftools.com";
                _https_port = 80;
            }

            // Redirect to www domain if url is home page
            if (host.Host.Equals(_domain, StringComparison.OrdinalIgnoreCase))
            {
                host = new HostString("www." + host.Host, _https_port);

                var redirectUrl = UriHelper.BuildAbsolute(
                    "https",
                    host,
                    request.PathBase,
                    request.Path,
                    request.QueryString);

                response.Redirect(redirectUrl, true);
                return;
            } // Redirect to non-www domain if url is with a subdomain
            else if (host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase)
                     && Regex.Replace(host.Host, @"www.|" + _domain, String.Empty) != String.Empty)
            {
                host = new HostString(host.Host.Replace("www.", String.Empty), _https_port);

                var redirectUrl = UriHelper.BuildAbsolute(
                    "https",
                    host,
                    request.PathBase,
                    request.Path,
                    request.QueryString);

                response.Redirect(redirectUrl, true);
                return;
            }

            await _next(context);
        }
    }

}

What should I change to make the middleware run faster?


texts:
I am having problem with a simple Hanoi tower program.  I need to do something to reduce its time.

#include <stdio.h>
#include <fstream>

using namespace std;

int hanojus(int n, char a, char b, char c) {

    ofstream fr("hanoj.out",ios::app);
    if (n == 1)
        fr<<a<< " -> " <<c<<endl;
    else {
         hanojus(n-1, a, c, b);
         fr<<a<< " -> " <<c<<endl;
         hanojus(n-1, b, a, c);
        }
}
int main()
{
    ifstream fd("hanoj.in");
    int sk;
    fd>>sk;
    hanojus(sk, 'A', 'B', 'C');
}


texts:
Here is a method that takes two lists (l1 and l2) and pairs up elements that "match". As you can see at the end of the code block these lists consist of matching elements but in different indexes. The method pairUp outputs matching elements paired up, and discards those without a pair.

I spent way too much time writing this method, and it feels clumsy and complex, not scala idiomatic.

How could I have done this simpler? and could I make it faster?

case class A(serial:Int) {
  def matches(b:B):Boolean = this.serial == b.serial
}
case class B(serial:Int)

import scala.annotation.tailrec
@tailrec def pairUp(
  list1:List[A],
  list2:List[B],
  i:Int=0,
  pairs:List[(A, B)]=List.empty[(A,B)]
):List[(A,B)] = {
  if (list1.isEmpty || list2.isEmpty) return pairs
  else {
    if (i == list2.length)  // this list1 element has no match
      return pairUp(
        list1.tail,         // so discard
        list2,
        0, // reset counter
        pairs)
    else {
      if (list1.head matches list2.head) // these elements match
        return pairUp(
          list1.tail,
          list2.tail,
          0,
          pairs :+ ((list1.head, list2.head)))
      else
        return pairUp(
          list1,
          list2.tail :+ list2.head, // list2 element to back
          i + 1,
          pairs)
    }
  }
}

val l1 = List(0, 1, 2, 3, 4, 5).map(A(_))
val l2 = List(1, 3, 0, 2, 4).map(B(_))

val pairs = pairUp(l1, l2)
// List((A(0),B(0)), (A(1),B(1)), (A(2),B(2)), (A(3),B(3)), (A(4),B(4)))
println(pairs)


texts:
I am currently creating a word search program using C. I have created 5 different arrays for subjects containing 15 different words from each. I must also create a program that creates a 2D grid of letters that contain 6 words from a subject chosen by the user prior. The words must go horizontally and vertically.

So far this is the code that I have. Can anyone tell me if I'm on the right track or if I'm completely wrong?

/* ICP-1029 - Assignment 1 */
/* WordSearch Puzzle Porgram */
/* Callum Fawcett */
/* Version 1 */

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

int main()
{
    const char *animalArray[20];

    animalArray[0] = "lynx";
    animalArray[1] = "kitten";
    animalArray[2] = "cheetah";
    animalArray[3] = "ape";
    animalArray[4] = "doe";
    animalArray[5] = "reindeer";
    animalArray[6] = "whale";
    animalArray[7] = "baboon";
    animalArray[8] = "skunk";
    animalArray[9] = "dugong";
    animalArray[10] = "elephant";
    animalArray[11] = "anteater";
    animalArray[12] = "chameleon";
    animalArray[13] = "lizard";
    animalArray[14] = "horse";

    const char *colourArray[20]:

    colourArray[0] = "red";
    colourArray[1] = "green";
    colourArray[2] = "blue";
    colourArray[3] = "black";
    colourArray[4] = "pink";
    colourArray[5] = "yellow";
    colourArray[6] = "brown";
    colourArray[7] = "orange";
    colourArray[8] = "purple";
    colourArray[9] = "black";
    colourArray[10] = "white";
    colourArray[11] = "cyan";
    colourArray[12] = "maroon";
    colourArray[13] = "magenta";
    colourArray[14] = "grey";

    const char *videogameArray[20];

    videogameArray[0] = "fortnite";
    videogameArray[1] = "fifa";
    videogameArray[2] = "hytale";
    videogameArray[3] = "soma";
    videogameArray[4] = "prey";
    videogameArray[5] = "destiny";
    videogameArray[6] = "titanfall";
    videogameArray[7] = "woldenstein";
    videogameArray[8] = "battlefield";
    videogameArray[9] = "fallout";
    videogameArray[10] = "tekken";
    videogameArray[11] = "skyrim";
    videogameArray[12] = "dishonored";
    videogameArray[13] = "uncharted";
    videogameArray[14] = "anthem";

    const char *sportsArray[20];

    sportsArray[0] = "basketball";
    sportsArray[1] = "football";
    sportsArray[2] = "cricket";
    sportsArray[3] = "wrestling";
    sportsArray[4] = "fencing";
    sportsArray[5] = "rowing";
    sportsArray[6] = "volleyball";
    sportsArray[7] = "baseball";
    sportsArray[8] = "hockey";
    sportsArray[9] = "racing";
    sportsArray[10] = "golf";
    sportsArray[11] = "bobsleigh";
    sportsArray[12] = "curling";
    sportsArray[13] = "snowboarding";
    sportsArray[14] = "bowling";

    const char *countryArray[20];

    countryArray[0] = "england";
    countryArray[1] = "ireland";
    countryArray[2] = "china";
    countryArray[3] = "wales";
    countryArray[4] = "bangladesh";
    countryArray[5] = "maldives";
    countryArray[6] = "slovenia";
    countryArray[7] = "uruguay";
    countryArray[8] = "colombia";
    countryArray[9] = "samoa";
    countryArray[10] = "jamaica";
    countryArray[11] = "malta";
    countryArray[12] = "bulgaria";
    countryArray[13] = "armenia";
    countryArray[14] = "gamnbia";

}

char **create2DArray(); //function prototype
#define WIDTH 16
#define HEIGHT 16
char** myArray; //global array
void main()
{
    myArray = create2DArray();
}
//Creates a 2D array of WIDTH * HEIGHT and returns a pointer to it
char **create2DArray(){
         int i,j;
         char **array = (char **) malloc(sizeof(char *) * WIDTH);

         for(i=0; i<WIDTH; i++)
            array[i] = (char *) malloc(sizeof(char) * HEIGHT);

         for(i=0; i<WIDTH; i++)
            for(j=0; j<HEIGHT; j++)
         // array[i][j] = 65 + rand() % 25;
            array[i][j] = '.';
    return array;
}


texts: Loading and comparing files containing 3D data

texts:
I have written a program to compare two 3D raw data equal or different. But I think the time consuming would be reduced if I use the STL. How to improve the program? The complete and varifiable code is showed as follows:

#include <cstdio>
#include <string>
#include <iostream>
#include <assert.h>
#include <cstdlib>

using namespace std;

int LoadSample(std::string path_sample, unsigned char*& raw_data, int* w_h_d) {

    FILE *fp;
    if (  fopen_s(&fp, path_sample.c_str(),"rb") )
        return 1;

    int width = 0;
    int height = 0;
    int depth = 0;

    fread(&width,4,1,fp);
    fread(&height,4,1,fp);
    fread(&depth,4,1,fp);

    w_h_d[0] = width;
    w_h_d[1] = height;
    w_h_d[2] = depth;

    raw_data = (unsigned char*)malloc(width*height*depth*sizeof(unsigned char));
    fread(raw_data,height*width*depth,1,fp);
    fclose(fp);

    return 0;
}

int CompareData(unsigned char*& data_train, int* train_w_h_d, unsigned char*& data_test, int* test_w_h_d) {

    if (train_w_h_d[0] == test_w_h_d[0] && train_w_h_d[1] == test_w_h_d[1] && train_w_h_d[2] == test_w_h_d[2]) {

        std::cout<< "Size is equal!\n";

        int all_num = train_w_h_d[0]*train_w_h_d[1]*train_w_h_d[2];
        int count = 0;
        for(int i = 0; i < all_num; i++) {
            if(data_train[i] == data_test[i])
                count++;
        }

        if(all_num == count)
            return 1;

    }
    return 0;
}

int main(){

    string root_path = "F:\\SZU\\Projects\\Fetal_Face\\data\\";
    string filepath_train = root_path + "train\\";
    string filepath_test = root_path + "test\\detect_data\\";

    unsigned char* data_train = NULL;
    unsigned char* data_test = NULL;

    int num_train = 127;
    int num_test = 80;
    int train_w_h_d[3] = {0, 0, 0};
    int test_w_h_d[3] = {0, 0, 0};
    for (int i = 0; i < num_train; i++)
        for (int j = 1; j <= num_test; j++) {

            char num_i[10], num_j[10];
            _itoa_s(i, num_i, 10);
            _itoa_s(j, num_j, 10);
            std::string file_train = filepath_train + "data_" + num_i + ".raw";
            std::string file_test = filepath_test + "data_" + num_j + ".raw";

            if( LoadSample(file_train, data_train, train_w_h_d) )
                std::cout<< "Error: load train data.\n";

            if ( LoadSample(file_test, data_test, test_w_h_d) )
                std::cout<< "Error: load test data.\n";

            if( CompareData(data_train, train_w_h_d, data_test, test_w_h_d) ) {
                std::cout<< "Same data: " << i << "-- train\t\t" << j << " -- test\n"<<std::endl;
                system("PAUSE");
            }
            else{
                std::cout<< i << "-- train\t\t" << j << " -- test is difference." <<std::endl;
            }

            delete[] data_train;
            data_train = NULL;
            delete[] data_test;
            data_test = NULL;
    }

    return 0;
}

The code can run correctly but I want to improve the efficiency by the STL. My compiler is VS2008.

So, how to revise it? By the way, what and where is potential error or something be able to develop in my code.


texts: Force attribute value on potentially non-existent or locked PyNode

texts:
I am working in Maya using PyMEL (my goal is to leverage PyMEL to create more readable, object-oriented, Pythonic code than if I'd used maya.cmds). I need to set an attribute value on an arbitrary node. The attribute may not exist or, if it does exist, may be locked. I found that setAttr with force=True did not account for all these scenarios, so I made my own.

import pymel.core as core

def _maya_force_attribute(self, pynode, name, value, data_type="string", keyable=False, lock=False):

    if pynode.hasAttr(name):
        pynode.setAttr(name, lock=False)
        pynode.deleteAttr(name)

    pynode.addAttr(name, dataType=data_type)
    pynode.setAttr(name, value, keyable=keyable, lock=lock)

What I discovered (I think) is that when using set/add/deleteAttr, you can't often use multiple flags at the same time.

Is there a command sequence or a command/flag combo that achieves the same result more directly?


texts: Update user country based on IPv4 decimal address

texts:
I have UserSignatures, a table with clientIPs, some of which have CountryIds that are null and need to be filled in.

A second table, IpLookups, stores IPs, and a third table Country has the needed CountryId. This is workaround at the moment, because we don't fill CountryIp yet.

declare @var1 int,@var2 int,@var3 int,@ind int = 0;

SELECT * INTO #Temp
FROM [dbo].[UserSignatures]
where CountryId is null

SELECT @var1 = count(*) FROM #Temp;

while (@ind < @var1  )
begin
      select @var3 = Id from #Temp order by Id OFFSET @ind ROWS FETCH NEXT 1 ROW ONLY;

      select @var2 = CONVERT(BIGINT, PARSENAME(u.ClientIp, 1)) * POWER(256, 0)
  + CONVERT(BIGINT, PARSENAME(u.ClientIp, 2)) * POWER(256, 1)
  + CONVERT(BIGINT, PARSENAME(u.ClientIp, 3)) * POWER(256, 2)
  + CONVERT(BIGINT, PARSENAME(u.ClientIp, 4)) * POWER(256, 3) from [dbo].[UserSignatures] u
  where u.Id = @var3

      update [dbo].[UserSignatures]
        set CountryId = (
        SELECT c.Id FROM dbo.IpLookups lo with(NOLOCK)
          inner join
        [dbo].[Countries] c with(nolock)
        on
        c.Code = lo.CountryIsoCode
         WHERE
        @var2
          BETWEEN lo.[From] AND lo.[To]
        )
        where Id = @var3

      SET @ind = @ind+1;
end

DROP table #Temp

Is there any way to simplify this?