texts:
I recently began learning Clojure. In order to get better acquainted with it, I've been tackling Project Euler challenges.

Problem 14 is not really a difficult one. It asks for the number that results in the longest Collatz sequence.

  The following iterative sequence is defined for the set of positive
  integers:

  n → n/2 (n is even) n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following
  sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

  It can be seen that this sequence (starting at 13 and finishing at 1)
  contains 10 terms. Although it has not been proved yet (Collatz
  Problem), it is thought that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

  NOTE: Once the chain starts the terms are allowed to go above one
  million.

Although my solution does solve the problem, I am not sure if it conforms to the Clojure way of doing things, since it seems to be verbose.

Does this conform to functional practices?
Are there any mistakes which result in code being longer than needed?
Is there a way of omitting the loop/recur and doing the same with list functions such as map and apply
Any other suggestions in general?

(ns problem14)

(use '[clojure.test :only (is)])

(defn count-collatz
 "Returns a vector [a b] where b is the
 number that initiated the sequence, and
 a is the number of steps taken to reach 1."
  [input-num]
  (loop [num input-num count 1]
  (if (= num 1)
    (vector count input-num)
    (do (if (= (mod num 2) 0)
      (recur (/ num 2) (inc count))
      (recur (+ (* num 3) 1) (inc count)))))))

;; Test case from the project description.
(is (= (count-collatz 13) [10 13]))

(loop [number 1 peak [0 0]]
    (if (>= number 1e6)
      (str "Longest chain is " (last peak))
      (do (let [result (count-collatz number)]
        (do (if (> (first result) (first peak))
          (recur (inc number) result)
          (recur (inc number) peak)))))))


texts: Crawler for performing reverse search and writing results into a CSV file

texts:
I've written a script which is able to perform reverse search in the website using the Name and Lid from a predefined CSV file. However, when the search is done then it can put the results containing Address and Phone Number adjacent to those Name and Lid creating a new CSV file. It is working errorlessly now. I tried to make the total process clean. Any suggestion to do betterment of this script will be highly appreciated. Here is the code I have tried with:

import csv
import requests
from lxml import html

with open("predefined.csv", "r") as f, open('newly_created.csv', 'w', newline='') as g:

    reader = csv.DictReader(f)
    newfieldnames = reader.fieldnames + ['Address', 'Phone']
    writer = csv.writer = csv.DictWriter(g, fieldnames = newfieldnames)
    writer.writeheader()

    for entry in reader:

        Page = "https://www.yellowpages.com/los-angeles-ca/mip/{}-{}".format(entry["Name"].replace(" ","-"), entry["Lid"])
        response = requests.get(Page)
        tree = html.fromstring(response.text)
        titles = tree.xpath('//article[contains(@class,"business-card")]')

        for title in tree.xpath('//article[contains(@class,"business-card")]'):
            Address= title.xpath('.//p[@class="address"]/span/text()')[0]
            Contact = title.xpath('.//p[@class="phone"]/text()')[0]

            print(Address,Contact)

            new_row = entry
            new_row['Address'] = Address
            new_row['Phone'] = Contact
            writer.writerow(new_row)

Here is the link to the search criteria of "predefined.csv" file.

Here is the link to the results.


texts:
Here's a part of my controller and it's getting quite lengthy (the code works).

Would this code slow down the performance of my website? Can it be cleaned up and be written more efficiently?

def create
  @post = current_user.posts.build(params[:post])

  if @post.save
    if @post.verify
      UserMailer.verify_email(@user).deliver
      redirect_to root_path
    else
      flash[:success] = "Posted"

      if @post.content.to_s.length > 140 and @post.image.present?
        @twitter = Twitter::Client.new
        @twitter.update(@post.content.truncate(120)+"... " +@post.image.path.to_s)
        redirect_to root_path
      elsif @post.content.to_s.length > 140
        @twitter = Twitter::Client.new
        @twitter.update(@post.content.truncate(140))
        redirect_to root_path
      elsif @post.content.to_s.length <= 140 and @post.image.present?
        @twitter = Twitter::Client.new
        @twitter.update(@post.content.truncate(120)+""+@post.image.path.to_s)
        redirect_to root_path
      else @post.content.to_s.length <= 140
        @twitter = Twitter::Client.new
        @twitter.update(@post.content)
        redirect_to root_path
      end
    end
  else
    @feed_items = []
    render 'static_pages/home'
  end
end


texts: Modifying stress markers in Cyrillic words

texts:
This is used to change a Cyrillic word with a stress marker into the same Cyrillic word but with the stress marker separately represented as a number. As I want to return two values I pass two parameters by reference. I assume there is at most only one stress marker per word.

What could I improve here?

function seperateStress($word,&$cleanWord,&$stressLetter){
    $stressLetter=-1;
    $cleanWord="";
    for($i=0;$i<strlen($word);$i++){

        if($word[$i]=="&" ){
            //echo $i."
";
            $stressLetter=$i;

            $i=$i+5;
        }else{
            $cleanWord .=$word[$i];
            //echo $word[$i].":".$i."
";
        }
    }

    //return array($cleansedWord,$stressedLetter);
}

//Sample Test run
$stressWord= "велосипе́ды";
$noStressWord="";
$stressLetter=-1;

seperateStress($stressWord,$noStressWord,$stressLetter);
echo $noStressWord."::".$stressLetter."
";


texts:
I have the following bash script that:

Finds all files with .cfc and .cfm extension and converts them to lowercase
Stores the relative file paths to those files (filenames.txt)
Chops those files to get only the name, excluding the extension (files.txt)
Loops through 1500 files checking for references to any of the other 1500 files and converts those to lower case

#!/bin/bash
# Search for references to JS function is all .cfm and .cfc functions
# Prompt to make sure
while true; do
    read -p "All .cfc and .cfm files in the theradoc/ directory and lower directories will be converted. Do you wish to contiue? (y/n)" yn
case $yn in
    [Yy]* ) make install; break;;
    [Nn]* ) exit;;
    * ) echo "Please answer yes or no.";;
esac
done
echo "Renaming files..."
for f in `find theradoc/ -d -name '*.cfc'`;
    do mv -v $f `echo $f | tr '[A-Z]' '[a-z]'`
done
for f in `find theradoc/ -d -name '*.cfm'`;
    do mv -v $f `echo $f | tr '[A-Z]' '[a-z]'`
done
echo "Indexing file names..."
find theradoc/ -d -name '*.cfc' > filenames.txt
find theradoc/ -d -name '*.cfm' >> filenames.txt
echo "Editing file names..."
sed 's/theradoc.*\///g' filenames.txt > tmp.txt
sed 's/\.cf.*//g' tmp.txt > files.txt
rm tmp.txt
echo "Searching all files..."
a=($(wc filenames.txt))
lines=${a[0]}
count=0
while read fn; do
    echo "$fn | $count/$lines finished..."
    while read f; do
        perl -pi -e "s/$f/$f/gi" "$fn"
    done < files.txt
    count=$((count+1))
done < filenames.txt

Runtime: 4 hours

Hardware: MacBook 16GB RAM

I would definitely like to decrease the runtime of this as it may be needed to run on other systems with the same files.


texts:
I am using the following code to encrypt a file in an SD card in Android:

I want the code to be reviewed for:

Security (prioritize this)
Coding Style
Performance

void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException {
    String myString = getOutputFile();
    File myFile = new File(myString);
    FileInputStream inputStream = new FileInputStream(myFile);
    File encodedfile = new File(path,"filename" + ".mp4");
    FileOutputStream outputStream = new FileOutputStream(encodedfile);
    SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);
    int b;
    byte[] d = new byte[8];
    while((b = inputStream.read(d)) != -1){
        cos.write(d, 0, b);
    }
    cos.flush();
    cos.close();
    inputStream.close();
}


texts:
If I'm working in a 2D environment and have hundreds of objects, brute force collision-checking would be out of the question, but would my method below work?

For example, let's say I have a

std::vector<GameObj*> objectsVector

to hold all objects and a

std::multimap<Point2D, GameObj*> objectsMap

(basically a map which takes a 2D point representing a GameObject's coordinate as a key and the object itself as a value)

to get any object associated with a point. If I want to do collision-checking for an object, I could use a function that looks like this:

void World::checkForCollisions()
{
    for (int i = 0; i < objectsVector; ++i) {
        GameObj* currObj = objectsVector[i];
        for (
                int x = (int)currObj->getX() - (int)currObject->getWidth();
                x < currObj->getX() + 2*currObj->getWidth();
                x++
            )
        {
            for (
                    int y = (int)currObj->getY() - (int)currObject->getHeight();
                    y < currObj->getY() + 2*currObj->getHeight();
                    y++
                )
            {
                pair< multimap<Point2D, GameObj*>::iterator, multimap<Point2D, GameObj*> > \
                  range = objectsMap.equal_range(Point2D(x, y));
                for (
                        multimap<Point2D, GameObj*>::iterator it=range.first;
                        it!=range.second;
                        ++it
                    )
                {
                    if (checkCollision(currObj, it->second))
                        currObj->handleCollision(it->second);
                }
            }
        }
    }
}

Is this even remotely efficient? Because it doesn't seem to be. It basically just scrolls through the vector and checks to see if it collides with nearby objects. Problem is, I have to use 2 containers AND when things move, I have to pretty much reinitialize the entire map, because the keys would be invalid! Is there any way to improve this collision-checking function, or should I scrap the whole thing altogether and use spatial hashes or a quad-tree? Any suggestions would be helpful.


texts:
Aim: Read in the userID, check if the userID has 10-digits and check if it not exists in database, when both right, the program will leave the loop.

This code works on my project, but I think its not the most elegant solution. Have someone any improvements?

InputReader.java

public class InputReader {

    private String userID;

    public void readInput() throws SQLException {

        boolean UserIDExists = false;
        int existsValue = 0;

        try {

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("UserID (10-digits):");

    while(!UserIDExists) {

        this.userID = input.readLine();

        while (this.userID.length() != 10) {

        System.out
                .println("Input must be 10 digits. Type again: :");
        this.userID = input.readLine();

        }

    CustomerInfo customer = new CustomerInfo();
    existsValue = customer.checkCustomer(this.userID);

    if (existsValue == 1) {

        UserIDExists = false;
        System.out.println("UserID exists already. Type again:");

    } else {

        UserIDExists = true;

    }
    }

CustomerInfo.java

public class CustomerInfo {

    private Connection conn = null;
    private ResultSet resultSet = null;

    public CustomerInfo () {

        try {
                conn = null;
                JDBCConnection jdbcConn = new JDBCConnection();
                conn = jdbcConn.openConnection();

        } catch (Exception e) {
                  throw e;
                }
        };

        public int checkUserID (String userID) throws SQLException {
        PreparedStatement pstmt = null;
            String sql = "SELECT * FROM TABL0001 WHERE USERID = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,  userID);
            resultSet = pstmt.executeQuery();

            if (!resultSet.next()){
                return 0;

            }
               return 1;

        }


texts:
Can you improve?

rc = []
for i, j in zip(A_response, B_response):
    rc.append(i)
    rc.append(j)

I use zip and append, but could this be better using list comprehension?


texts: Validating conditions for enabling sign-up button

texts:
On an authentication view, there are some inputs, like password, email, etc and a sign up button which is enabled only if theses inputs are not empty.

So what I have is this function:

func canSignUpButtonBeEnabled() -> Bool {

    let password = self.passwordTextField.text.stringByReplacingOccurrencesOfString(" ", withString: "")

    return (!self.emailTextField.text.isEmpty && !self.passwordTextField.text.isEmpty
            && !self.firstNameTextField.text.isEmpty  && !self.lastNameTextField.text.isEmpty
            && countElements(password) >= 4)

}

And after each character entered by the user, I set on the enable property of my button the result of this function.

So I was wondering if there is a cleaner solution to do it?


texts: Assembly 8086 program to input a 16-bit signed number (in string form) and output its binary equivalent

texts:
I'm working on an exercise using Assembly 8086 which inputs a number (in string form) then output the binary form. Here is what I did (tested on emu8086 by the way):

Convert the string to numeric form: I simply iterated through the string, and for each new value I simply multiply the old value by 10, then add by the new value. But there are some checks for overflow which was annoying: I have to check in both the multiplication and addition part, and since in this part I simply ignored the negative part (for simplicity) I had to check for a special case: a 16-bit signed number goes from \$-2^{15} = -32768\$ to \$2^{15} - 1 = 32767\$, so if the input is -32768 then there would be an error, so I had to check for that case specifically.
From numeric to binary: I simply left-shifted the number (which is now stored in AX) consecutively and printed the most significant bit.

Please give some feedback, because I'm not sure if the overflow part is ok.

;Written by Dang Manh Truong
.stack      100h
.data
base10_string       dw      "-32799$"
biggest_16bits_signed       equ      7FFFh
special_16bits_signed       equ      8000h
special_16bits_signed_str   dw       "1000000000000000$"
error_overflow      dw      "Arithmetic overflow encountered. Abort$"
error_not_a_number  dw      "Not a number. Abort$"
base10      equ     10
tmp         dw      0
is_negative dw      0
.code
main        proc
;Initialization
    mov     ax,@data
    mov     ds,ax

;;;part 1: convert string to value
    mov     ax,0 ;number = 0;
    lea     si,base10_string
;check if positive or negative
    mov     bl,[si]  ;bl = value
    cmp     bl,'+'
    jne     check_if_negative
    add     si,1    ;start from after the "+" sign
    mov     ax,0
    jmp     while_loop
check_if_negative:
    cmp     bl,'-'
    jne     check_if_not_a_number
    mov     ax,1
    mov     is_negative,ax
    mov     ax,0
    add     si,1    ;start from after the "-" sign
    jmp     while_loop
check_if_not_a_number:
    cmp     bl,'0'
    jge     keep_checking
    jmp     not_a_number
keep_checking:
    cmp     bl,'9'
    jle     while_loop
    jmp     not_a_number
while_loop:
    mov     bl,[si]  ;bl = value
    ;check if end of string
    cmp     bl,'$'
    je      end_while
    ;check if not a number
check_:
    cmp     bl,'0'
    jge     keep_checking_
    jmp     not_a_number
keep_checking_:
    cmp     bl,'9'
    jle     add_to_number
    jmp     not_a_number
add_to_number:
    and     bx,000Fh ;'0'-> 0, '1' -> 1,...
    mov     dx,base10
    ;try
    mul     dx       ;number = number*10
    ;catch (Exception ArithmeticOverflow)
    jo      overflow
    ;try
    add     ax,bx    ;number = number*10 + value
    ;catch <Exception ArithmeticOverflow)
    ;jo      overflow
    cmp     is_negative,1
    jne     _perform_check
    cmp     ax,special_16bits_signed
    jne     _perform_check
    jmp     _aftercheck_overflow
_perform_check:
    ;jo      overflow
    cmp     ax,0
    jl      overflow
_aftercheck_overflow:
    add     si,1     ;next value
    jmp     while_loop
end_while:
;is negative?
    cmp     is_negative,1
    jne     begin_part2
    neg     ax
begin_part2:
;;;part 2: print base-2 number
    mov     cx,16
    mov     bx,ax
    mov     ah,2
print_:
    cmp     cx,0
    je      after_print
    shl     bx,1
;if bit == 1
    jnc     print_0
;then print_1
    mov     dl,'1'
    int     21h
    jmp     add_counter
;else print_0
print_0:
    mov     dl,'0'
    int     21h
add_counter:
    dec     cx
    jmp     print_
after_print:

    jmp     return_to_dos
overflow:
    lea     dx,error_overflow
    mov     ah,9
    int     21h
    jmp     return_to_dos
not_a_number:
    lea     dx,error_not_a_number
    mov     ah,9
    int     21h
    jmp     return_to_dos
return_to_dos:
    mov     ah,4ch
    int     21h
main        endp
    end     main


texts: Java background server class that might be called from ui thread

texts:
I have a server communicating over network interface. This server should run on a background thread, so that it does not block the ui thread. The ui thread starts and stops the server. Even starting and stopping should be done from a background thread.

Currently I wrap all public methods of the server class in a thread that gets started immediately:

class Server {

  public void start() {
    new Thread() {
      public void run() {
        handleStart();
      }
    }.start();
  }

  public void stop() {
    new Thread() {
      public void run() {
        handleStop();
      }
    }.start();
  }

  private void handleStart() {
    startLooperThread();
  }

  private void handleStop() {
    stopLooperThread();
  }
}

Is this the proper way to do this or are there any neat alternatives provided by JDK (or any other library)?


texts: All-core MediaWiki website upgrade script

texts:
I wrote the following Bash script to upgrade All-core MediaWiki websites (no added extensions/skins or images - besides logo image).

I already tested the essence of this script and it worked for me; MediaWiki was upgraded from 1.32.0. to 1.33.0 and I can use the site regularly; yet I'd be glad for a review:

#!/bin/sh

date="$(date +%F-%T)"
db_user_name_and_db_name="SOME_IDENTICAL_NAMES" # DB user name and DB name must be the same;
war="SOME_WEB_APPLICATION_ROOT"
domain="SOME_DOMAIN" # As site's directory;
target_url="LINK_TO_LATEST_MEDIA_WIKI_ARCHIVE_DOWNLOAD"

mkdir -p "${war}/mediawiki_general_backups"
mkdir -p "${war}/mediawiki_specific_backups"

zip -r "${war}/mediawiki_general_backups/${domain}-directory-backup-${date}.zip" "${war}/${domain}"
mysqldump -u "${db_user_name_and_db_name}" -p "${db_user_name_and_db_name}" > "${war}/mediawiki_general_backups/${domain}-database-backup-${date}.sql"

files=(
    LocalSettings.php
    robots.txt
    .htaccess*
    ${domain}.png
    googlec69e044fede13fdc.html
)

cd "${war}/${domain}"
cp "${files[@]}" "${war}/mediawiki_specific_backups"

rm -rf "${war}/${domain}"
mkdir "${war}/${domain}"
wget ${target_url} -O - | tar -xzv --strip-components 1 -C ${war}/${domain}

cp -a "${war}/mediawiki_specific_backups"/* "${war}/${domain}"
cd "${war}/${domain}"/maintenance
php update.php

### Sitemap creation ###

mkdir -p "${war}/${domain}/sitemap"

php maintenance/generateSitemap.php \
--memory-limit=50M \
--fspath=/"${war}/${domain}/sitemap" \
--identifier="${domain}" \
--urlpath=/sitemap/  \
--server=https://"${domain}" \
--compress=yes

# Sitemap should be declared in robots.txt / preferred search engine's search console, or both;


texts:
My goal is to use the object literal pattern in TypeScript.

Here is an example of the object literal pattern in JavaScript.

I created a simple example of the object literal pattern in TypeScript. The only change I made compared to plain JavaScript was to declare an interface for the object literal.

See the full working example:
Codepen

I'm curious to know if I'm missing out on any TypeScript features or not following any best practices.

interface square {
    squares: NodeListOf<Element>;
    squareColors: Array<string>;
    squareSizer: (el: HTMLElement) => void;
    squareColorChanger: (el: HTMLElement) => void;
    doSquareClick: (element: HTMLElement, index: number, array: Array<HTMLElement>) => void;
    init: () => void;
}

let squareWidget: square = {

    squares: document.querySelectorAll(".square"),

    squareColors: ["square-is-color-red", "square-is-color-orange", "square-is-color-green"],

    squareSizer: function (el) {
        if (el.dataset.enlarged === "false") {
            el.classList.add("square-is-enlarged");
            el.dataset.enlarged = "true";
        } else if (el.dataset.enlarged === "true") {
            el.classList.remove("square-is-enlarged");
            el.dataset.enlarged = "false";
        }
    },

    squareColorChanger: function (el) {
        for (var i = 0; i < el.classList.length; i++) {
            if (el.classList[i].indexOf("square-is-color") !== -1) {
                el.classList.remove(el.classList[i]);
            }
        }

        var randomColorIndex = Math.floor(Math.random() * (squareWidget.squareColors.length));
        el.classList.add(squareWidget.squareColors[randomColorIndex]);
    },

    doSquareClick: function (element, index, array) {
        element.addEventListener("click", function () {
            squareWidget.squareSizer(element);
            squareWidget.squareColorChanger(element);
        });
    },

    init: function () {
       Array.from(squareWidget.squares).forEach(squareWidget.doSquareClick);
    }
}


texts:
I needed a script to wrap phrases with  tag, they all are separated by commas, for i.e "Alan, Bob, John".

I came to this result:

        $actors = explode(',', $item->casting);

        $item->casting = array_map(function($a) {
            $a = trim($a);
            return ''.$a.'';
        }, $actors);

        echo implode(' ', $item->casting);

I'd like to know is there a better way achieve this result ?


texts: Automatically Sending an Email based on a Google Sheet's cell value

texts:
Would love some feedback on how to improve my code. It might not be as readable as I'd like in places, but it currently works. Note that this code will be adapted to work on a different spreadsheet, so making this extensible would be amazing. Also, is there any reason to put this code into a class? I come from a scripting background, and OOP concepts are new to me.

This is the data that it looks at:

The code gets a row which it uses its index to turn FALSE to TRUE after it sends an email. The email isn't implemented yet, but will be soon. Any suggestions for if there's something other then smtplib on python would be appreciated, as I might want to just send the email without hooking up an account (like mail command on Linux).

import gspread
import pprint
from oauth2client.service_account import ServiceAccountCredentials

def setup_connection(spreadsheet):
    scope = ['https://spreadsheets.google.com/feeds']
    creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
    client = gspread.authorize(creds)
    worksheet = client.open(spreadsheet).sheet1
    return worksheet

def send_email(is_sent, is_passing):
    """
    Takes in two parameters to determine if
    1. the email is sent
    2. did the quiz-taker pass?

    Returns true if the email was sent and false if not. Will probably need to be updated, too!
    """
    if not is_sent:
        print("sending email...")
        if is_passing:
            print("you passed! congratulations :)")
        else:
            print("sorry, but you didn't pass yet! We'd really love to see you at the MakerSpace, so make sure to try again!")
            return True
    else:
        print("email already sent.")
        return False

def main():
    worksheet = setup_connection('CoMotion Quiz Test Automation')
    rows = worksheet.get_all_values()
    index = 0
    for row in rows:
        index = index + 1
        if (row[4] == "FALSE"):
            is_passing = (float(row[0])/30 > 0.8)
            is_sent = False
            if (send_email(is_sent, is_passing)):
                worksheet.update_acell('E' + str(index), "TRUE") # Updates the cell to reflect true

            else:
                print("these are not the droids you\'re looking for...")

main()


texts:
I wrote code which is doing query and insert inside while loop.

    $getall = mysql_query("SELECT `deviceid`,`uid` FROM  `users` WHERE FIND_IN_SET(`bgroup`,  '".$allbrgou."' ) AND `uid`!='".$from."'");
while($mdata = mysql_fetch_assoc($getall)){
        $newto = $mdata['uid'];

        $result = mysql_query("insert into request(rto,rfrom) values ($newto,$from)");

        $message="You get Request From ".$row['name'] ;
        $url = 'https://android.googleapis.com/gcm/send';
        $did=$mdata['deviceid'];

            $fields = array(
                            'registration_ids'  => array($did),
                            'data'              => array( "message" => $message ),
                            );
            $headers = array(
                                'Authorization: key=xxxxxx',
                                'Content-Type: application/json'
                            );

            $ch = curl_init();
            curl_setopt( $ch, CURLOPT_URL, $url );
            curl_setopt( $ch, CURLOPT_POST, true );
            curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
            $result = curl_exec($ch);
            curl_close($ch);

}

This code on shared hosting took 2 min with just 120 records.  Will concatenation and executing insert query fix this performance issue?


texts:
I picked up a programming game, TIS-100. Programming manual can be found on Steam as well, but I have described the relevant syntax in my question.

Basically, you're dealing with some old machine that uses its own variant of assembly. It's a gamification of learning assembly, almost.

The machine consists of nodes. Each node has pipes (UP LEFT DOWN RIGHT) that it can write and read from. When a pipe is read from, the value in the pipe disappears. It also has two registers, ACC and BAK. BAK can only be accessed with the SAV and SWP opcodes. Each node has its own code that it executes. This code is limited to 15 lines of 18 characters per node.

I've already solved this level. The goal is counting sequences:

- SEQUENCE COUNTER -
> SEQUENCES ARE ZERO-TERMINATED
> READ A SEQUENCE FROM IN
> WRITE THE SUM TO OUT.S
> WRITE THE LENGTH TO OUT.L

Short syntax run down (based on commands I used):

MOV <src> <dest> //moves from source to destination. Blocks if source is a pipe and doesn't have a value available. Blocks if dest is a pipe and already has a value.
ADD value //adds to ACC
<label>: //defines a label (for jumps)
JMP <label> //jumps execution to label
JEZ <label> //jumps to label if ACC = 0. JumpifEqualsZero
//there's also JumpifNotZero (JNZ), JumpifGreaterZero (JGZ), JumpifLesserZero (JLZ).
SAV //MOV ACC BAK
SWP //switches values of ACC and BAK

The game describes it like this:

My program is a bit unwieldy to post in full, so I'll limit it to the three main nodes.

This is the node responsible for counting the sequence length:

S: MOV LEFT ACC
JEZ E
SWP
ADD 1
SAV
JMP S
E: SWP
MOV ACC DOWN
MOV 0 ACC
SAV

This is the node responsible for summing sequences:

S: MOV UP ACC
JEZ E
MOV ACC LEFT
SWP
ADD LEFT
SAV
JMP S
E: SWP
MOV ACC DOWN
MOV 0 ACC

And this is the node I abuse as temporary storage:

MOV RIGHT ACC
MOV ACC RIGHT

What I don't like about my code is that it doesn't read very well.

The sequence counter goes like so:

START
read value to ACC
if ACC is 0, then GOTO END
swap ACC and BAK
add 1 to ACC
write ACC to BAK
GOTO START
END
swap ACC and BAK
write ACC as output
set ACC to 0
write ACC to BAK

There's duplication in here, where no matter if you are in the then or the (implicit) else case of the JEZ, you first swap ACC and BAK. Additionally, I'm abusing "swap set write" for altering BAK, but maybe that's the shortest way there is.

For the sequence summer, I don't like how I'm abusing a separate node just for temporary storage.

It works without errors.

For reference, these are histograms showing the scores of people on levels, with mine highlighted via arrow:


texts:
In answering this question on Stack Overflow, I decided to stretch my legs in Haskell a bit to see if I could implement a solution to find the count of lucky triples in a list of ints.

A lucky triple is any triple (j, k, l) where j <= k <= l and l `mod` k == 0 && k `mod` j == 0. A correct implementation counts how many unique combinations of elements of an [Int] are valid lucky triples.

import Data.List (sort)

answer :: [Int] -> Int
answer xs = foldr ((+) . foldr ((+) . length) 0) 0 $ twoStepFactors
  where
    twoStepFactors = map mapFactors $ mapFactors $ sort xs

mapFactors :: [Int] -> [[Int]]
mapFactors xs = mapFactors' xs []
mapFactors' [] acc = acc
mapFactors' (x:xs) acc = mapFactors' xs newAcc
  where
    factors = filter ((==0) . (`mod` x)) xs
    newAcc | null factors = acc
           | otherwise = acc ++ [factors]


texts:
The following code is inside a before insert / before update trigger. Essentially what I have in our app is that when a request type (request.Type__c) is chosen, the scheduler (request.Scheduler__c) should be dynamically set based on a set of default values. However, I also have an administration page which allows users to override the default values by way of a Custom Setting. If the Custom Setting is not empty, that value will be used instead of the default.

public with sharing class ConsultantReqUpdateSchedulerUtilities {

    // this is the method called by our trigger
    public static void AssignSchedulerFromType(List<Consultant_Request__c> requests) {

        for (Consultant_Request__c request : requests) {
            request = AssignScheduler(request);

        }
    }

    public static Consultant_Request__c AssignScheduler(Consultant_Request__c request) {
        // determine what value Type__c is set to to determine
        // what we should set Scheduler__c to
        if (request.Type__c == 'Central - Elementary Core') {
            SetScheduler(request,'Darleen Mcginnis');
        } else if (request.Type__c == 'Central - Per Diem Core') {
            SetScheduler(request,'Darleen Mcginnis');
        } else if (request.Type__c == 'Central - Secondary Core') {
            SetScheduler(request,'Janice Mcshea');
        } else if (request.Type__c == 'East - Elementary Core') {
            SetScheduler(request,'Jacquie Salvatore');
        } else if (request.Type__c == 'East - Per Diem Core') {
            SetScheduler(request,'Darleen Mcginnis');
        } else if (request.Type__c == 'East - Secondary Core') {
            SetScheduler(request,'Janice Mcshea');
        } else if (request.Type__c == 'Sales - Elementary Core') {
            SetScheduler(request,'Becky Hanlon-Faber');
        } else if (request.Type__c == 'Inside Sales - Secondary') {
            SetScheduler(request,'Dawn Halbakken');
        } else if (request.Type__c == 'Inside Sales - Specialized') {
            SetScheduler(request,'Dawn Halbakken');
        } else if (request.Type__c == 'National - Core') {
            SetScheduler(request,'Janice Mcshea');
        } else if (request.Type__c == 'South - Elementary Core') {
            SetScheduler(request,'Darleen Mcginnis');
        } else if (request.Type__c == 'Specialized') {
            SetScheduler(request,'Delonda Morton');
        } else if (request.Type__c == 'West - Core') {
            SetScheduler(request,'Meredith Luiten');
        } else if (request.Type__c == 'TX/Southwest - Core') {
            SetScheduler(request,'Martha Bartlett');
        } else if (request.Type__c == 'South - Secondary Core') {
            SetScheduler(request,'Janice Mcshea');
        } else if (request.Type__c == 'ALEKS') {
            SetScheduler(request,'Melissa Deveikis');
        }

        return request;
    }

    public static void SetScheduler(Consultant_Request__c request, String username) {
        // check for custom settings first
        Scheduler_Settings__c schedulerSettings = Scheduler_Settings__c.getInstance();

        if (schedulerSettings.CEC_Scheduler__c != '') {
            User u = FindUser(schedulerSettings.CEC_Scheduler__c);
            if (u != null) {
                request.Scheduler__c = u.Id;
            }
        } else {
            // else, use the default values passed into this method
            User u = FindUser(username);
            if (u != null) {
                request.Scheduler__c = u.Id;
            }

        }
    }

    public static User FindUser(String username) {

        User u;
        try {
            // find the user based on username
            List<User> userList = [Select Id From User Where Name = :username];
            u = userList[0];

        } catch (Exception e) {
            u = null;
        }

        return u;
    }
}


texts: Mapping key value pairs between two JavaScript objects

texts:
I have two JavaScript objects:

const widgetsObj = {
    inputWidget: "MyInputWidget",
    checkboxWidget: "MyCheckboxWidget",
    geoWidget: "MyGeoWidget"
};

 this.components = {
            "MyInputWidget": MyInputWidget,
            "MyCheckboxWidget": MyCheckboxWidget,
            "MyGeoWidget": MyGeoWidget
        };

The end goal is to map all keys from widgetsObj to all values from this.components. The end object should look like this.

let endObj = {
    inputWidget: MyInputWidget,
    checkboxWidget: MyCheckboxWidget,
    geoWidget: MyGeoWidget
}

Right now, I am doing this like so

let returnObj = {};
        for(const key of Object.keys(widgets)) {
            if(this.components.hasOwnProperty(widgets[key])) {
                returnObj[key] = this.components[widgets[key]];
            }
        }
        return returnObj;

where widgets represents widgetsObj.

Is there a better way to do this rather than look for each value by mapping through the whole object repeatedly?


texts: Insert Emojis Into Outlook Email With VBA Application (For those of us who cant use add-ins)

texts:
I cannot use add ins here so I set out to create an excel application that could get the job done. I suppose that I could easily transport this into outlook?

Basically I want to click one of the icons and have the img inside that icons insert into the email that I am working on.

Question re unit testing: Here it seems like I have to unit test by hand in a sense. I suppose I could write code that simulates the object application environments, ie opens outlook application and then creates multiple popped out emails, no emails, a mix of popped out and inline etc? Then I pass this to each individual function and see that it works?

This Workbook:

Private Sub Workbook_Open()
    Me.Windows(1).WindowState = xlMinimized
    EmjoiControlPanel.Show vbModal
End Sub

EmojiControlPanel:

Option Explicit

Sub Image1_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image1
End Sub

Sub Image2_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image2
End Sub

Sub Image3_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image3
End Sub

Sub Image4_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image4
End Sub

Sub Image5_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image5
End Sub

Sub Image6_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image6
End Sub

Sub Image7_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image7
End Sub

Sub Image8_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image8
End Sub

Sub Image9_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image9
End Sub

Sub Image10_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image10
End Sub

Sub Image11_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image11
End Sub

Sub Image12_Click()
    TransferImg.EmojiEmailTransfer EmjoiControlPanel.Image12
End Sub

TransferIMG:

Option Explicit

Public Sub EmojiEmailTransfer(ByRef picControl As Image)
On Error GoTo Delete
Dim olApp                                       As Outlook.Application
Dim pictureFilePath                             As String

    Set olApp = GetObject(, "Outlook.Application")

    pictureFilePath = "Z:\tempPic"
    SavePicture picControl.picture, pictureFilePath

    If TypeName(olApp.ActiveWindow) = "Inspector" Then
        PoppedOutEmailLoadPicture olApp, pictureFilePath
    ElseIf TypeName(olApp.ActiveWindow) = "Explorer" Then
        NotPoppedOutEmailLoadPicture olApp, pictureFilePath
    End If

Delete:
    DeleteFile pictureFilePath
End Sub

Private Sub PoppedOutEmailLoadPicture(ByRef olApp As Outlook.Application, ByRef pictureFilePath As String)
On Error GoTo CouldNotLoad
    Dim objDoc                                  As Word.Document
    Dim objSelect                               As Word.Selection

    Set objDoc = olApp.ActiveInspector.WordEditor
    Set objSelect = objDoc.Windows(1).Selection

    objSelect.InlineShapes.AddPicture pictureFilePath
    Exit Sub
CouldNotLoad:
End Sub

Private Sub NotPoppedOutEmailLoadPicture(ByRef olApp As Outlook.Application, ByRef pictureFilePath As String)
On Error GoTo CouldNotLoad
    Dim objDoc                                  As Word.Document
    Dim objSelect                               As Word.Selection

    Set objDoc = olApp.ActiveExplorer.ActiveInlineResponseWordEditor
    Set objSelect = objDoc.Windows(1).Selection

    objSelect.InlineShapes.AddPicture pictureFilePath
    Exit Sub
CouldNotLoad:
End Sub

Private Sub DeleteFile(ByRef pictureFilePath As String)
    Dim fso As Object
        Set fso = CreateObject("scripting.filesystemobject")
    If fso.fileexists(pictureFilePath) Then fso.DeleteFile ("" & pictureFilePath & "")
End Sub

RunApp (Assigned to a button in worksheet):

Sub RunApp()
    ActiveWorkbook.Windows(1).WindowState = xlMinimized
    EmjoiControlPanel.Show vbModal
End Sub


texts: Find the available squares for rooks in empty board using boolean arrays

texts:
I will describe two techniques, then the question will be how I can make an algorithm that is more efficient, if possible.
I want to find an efficient way to determine the squares where the pieces on a chess board can go. I want to start with a simple case, and just find the square where two rooks could move in an otherwise empty board. The two rooks are assumed to be "transparent" to one another, since the conditions for the interaction with other pieces will be added at a later stage.
The boards are represented by a collection of 64-components boolean numpy.array.
I start by creating the the board with the two rooks, assumed to be in position 15 and 25 on the 1-D board:
import numpy as np
import time

r_pos=np.zeros(64, dtype=bool)
r_pos[15] = True
r_pos[25] = True

Now I show the first method, which simply consist in setting to True the squares available making the rows and the columns separately. It can be shown that for this method the simulation time required increases with the number of pieces.
t1=time.time()
attack_r=np.zeros(64, dtype=bool)
for piece in np.where(r_pos)[0]:
    attack_r[8 * (piece // 8):8 * (piece // 8 + 1)] = True
    attack_r[piece % 8::8] = True

t2=time.time()
print t2-t1
print attack_a

To better visualize the board we can create a function that converts the 1-D array in the 2-D matrix:
def from_array_to_matrix(v):
    m=np.zeros((8,8)).astype('int')
    for row in range(8):
        for column in range(8):
            m[row,column]=v[row*8+column]
    return m

and thus we can check that we obtained the desired output:
print from_array_to_matrix(attack_r)

The second method creates a certain number of static boards as a template for the moves, and then uses boolean operators to select the proper template on the basis of the rook positions. It is slower, but it has the nice advantage that the simulation time does not depend on the number of pieces:
# create the collection of possible rook
# moves (just all the columns and all
# the rows in separate matrices)

m_rook=np.zeros((16,64), dtype=bool)
for line in range(8):
    m_rook[line,line*8:(line+1)*8]=True

col=0
for line in range(8,16):
    m_rook[line, col % 8::8]=True
    col+=1

% then we use the template to find the available moves

t1=time.time()
attack_r= np.any(m_rook[np.any(np.logical_and(r_pos, m_rook), axis=1)], axis=0)
t2=time.time()
print t2-t1
print from_array_to_matrix(attack_r)

I feel that it should be possible to use some technique that is even faster. Is it possible that using numpy arrays is actually not the best way to go ?


texts: Recursive vs. non-recursive implementations of Fibonacci sequence

texts:
I have 2 functions to get the n-th fibonacci number. The 1st one uses recursive calls to calculate the power(M, n), while the 2nd function uses iterative approach for power(M, n). Theoretically (at least what I think), they should have the same speed O(log n), but why when I run both, the 2nd one is much slower than the 1st one?

def fib_1(n):
    from numpy import matrix
    def power(F, n):
        if n == 0 or n == 1: return matrix('1 1; 1 0', object)

        F = power(F, n >> 1) # n // 2
        F = F * F
        if n % 2 == 0:
            return F
        if n % 2 != 0:
            return F * matrix('1 1; 1 0', object)

    F = matrix('1 1; 1 0', object)
    F = power(F, abs(n)-1)
    return F[0,0] if n > 0 else int((-1)**(n+1)) * F[0,0]

def fib_2(n):
    from numpy import matrix
    def power(F, n):
        M = matrix('1 1; 1 0', object)
        while n > 0:
            if n & 1 == 1:
                M = F * M
            n = n >> 1 # n = n // 2
            F = F * F
        return M

    F = matrix('1 1; 1 0', object)
    F = power(F, abs(n)-2)
    return F[0,0] if n > 0 else int((-1)**(n+1)) * F[0,0]


texts:
I am creating a two-dimensional array, which I am going to process later in ways similar to image MinFilter, procedural labyrinth generation, etc. -- implying using coordinates and neighbors.

Here are two ways I came up with now:

array := make([][]byte, 0, HEIGHT)
for i := 0; i < HEIGHT; i++ {
    array = append(array, bytes.Repeat([]byte{5}, WIDTH))
}

array := make([][]byte, HEIGHT)
for i := range array {
    array[i] = bytes.Repeat([]byte{5}, WIDTH)
}

They are both less straight-forward than the original Ruby code:

array = Array.new(HEIGHT){ Array.new(WIDTH){ 5 } }

But it is the first time I tried Go, so I ask you:

Which of these solutions is better?
And which is faster?
And why?


texts:
This is a PHP database class.  Yes, I know it's using the MySQL functions, which are deprecated, but I shall be updating it to MySQLi soon. Can you please review this code and give any comment on any improvements or changes you think I should make?

<?php

namespace Revolution;
if(!defined('IN_INDEX')) { die('Sorry, you cannot access this file.'); }
class engine
{
    private $initiated;
    private $connected;

    private $connection;

    final public function __construct()
    {
        $this->Initiate();
    }

    final public function Initiate()
    {
        global $_CONFIG;
        if(!$this->initiated)
        {
            $this->setMySQL('connect', mysql_connect);
            $this->setMySQL('pconnect', mysql_pconnect);
            $this->setMysql('select_db', mysql_select_db);
            $this->setMySQL('query', mysql_query);
            $this->setMySQL('num_rows', mysql_num_rows);
            $this->setMySQL('fetch_assoc', mysql_fetch_assoc);
            $this->setMySQL('fetch_array',mysql_fetch_array);
            $this->setMySQL('result', mysql_result);
            $this->setMySQL('free_result', mysql_free_result);
            $this->setMySQL('escape_string', mysql_real_escape_string);

            $this->initiated = true;

            $this->connect($_CONFIG['mysql']['connection_type']);
        }
    }

final public function setMySQL($key, $value)
{
    $this->mysql[$key] = $value;
}

/*-------------------------------Manage Connection-------------------------------------*/

final public function connect($type)
{
    global $core, $_CONFIG;
    if(!$this->connected)
    {
        $this->connection = $this->mysql[$type]($_CONFIG['mysql']['hostname'], $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password']);

        if($this->connection)
        {
            $mydatabase = $this->mysql['select_db']($_CONFIG['mysql']['database'], $this->connection);

            if($mydatabase)
            {
                $this->connected = true;
            }
            else
            {
                $core->systemError('MySQL Engine', 'MySQL could not connect to database');
            }
        }
        else
        {
            $core->systemError('MySQL Engine', 'MySQL could not connect to host');
        }
    }
}

final public function disconnect()
{
    global $core;
    if($this->connected)
    {
        if($this->mysql['close'])
        {
            $this->connected = false;
        }
        else
        {
            $core->systemError('MySQL Engine', 'MySQL could not disconnect.');
        }
    }
}

/*-------------------------------Secure MySQL variables-------------------------------------*/

final public function secure($var)
{
    return $this->mysql['escape_string'](stripslashes(htmlspecialchars($var)));
}

/*-------------------------------Manage MySQL queries-------------------------------------*/

final public function query($sql)
{
    return $this->mysql['query']($sql, $this->connection) or die(mysql_error());
}

final public function num_rows($sql)
{
    return $this->mysql['num_rows']($this->mysql['query']($sql, $this->connection));
}

final public function result($sql)
{
    return $this->mysql['result']($this->mysql['query']($sql, $this->connection), 0);
}

final public function free_result($sql)
{
    return $this->mysql['free_result']($sql);
}

final public function fetch_array($sql)
{
    $query = $this->mysql['query']($sql, $this->connection);

    $data = array();

    while($row = $this->mysql['fetch_array']($query))
    {
        $data[] = $row;
    }

    return $data;
}

final public function fetch_assoc($sql)
{
    return $this->mysql['fetch_assoc']($this->mysql['query']($sql, $this->connection));
}

}
?>


texts:
The following function (function template rather) is to take a vector of any type and write it a file using a filestream object.

template<class T>
void Vec_WriteFile(const vector<T>& vec, ifstream file, char del = '\n')
{
   for (const T& element : vec) file << element << del;
   file << "\b ";
}

This function is very straightforward and simple; however, I'm a student to C++ and would love to learn different ways of doing even the simplest of tasks.


texts: Grouping elements in array by multiple properties

texts:
During work, I was given this task: to group elements with similar properties in the array.

In general, the problem is as follows:

var list = [
    {name: "1", lastname: "foo1", age: "16"},
    {name: "2", lastname: "foo", age: "13"},
    {name: "3", lastname: "foo1", age: "11"},
    {name: "4", lastname: "foo", age: "11"},
    {name: "5", lastname: "foo1", age: "16"},
    {name: "6", lastname: "foo", age: "16"},
    {name: "7", lastname: "foo1", age: "13"},
    {name: "8", lastname: "foo1", age: "16"},
    {name: "9", lastname: "foo", age: "13"},
    {name: "0", lastname: "foo", age: "16"}
];

If I group this elements by lastname and age, I will get this result:

var result = [
    [
        {name: "1", lastname: "foo1", age: "16"},
        {name: "5", lastname: "foo1", age: "16"},
        {name: "8", lastname: "foo1", age: "16"}
    ],
    [
        {name: "2", lastname: "foo", age: "13"},
        {name: "9", lastname: "foo", age: "13"}
    ],
    [
        {name: "3", lastname: "foo1", age: "11"}
    ],
    [
        {name: "4", lastname: "foo", age: "11"}
    ],
    [
        {name: "6", lastname: "foo", age: "16"},
        {name: "0", lastname: "foo", age: "16"}
    ],
    [
        {name: "7", lastname: "foo1", age: "13"}
    ]
];

After some experimentation, I came to the following solution:

    Array.prototype.groupByProperties = function(properties){
        var arr = this;
        var groups = [];
        for(var i = 0, len = arr.length; i<len; i+=1){
            var obj = arr[i];
            if(groups.length == 0){
                groups.push([obj]);
            }
            else{
                var equalGroup = false;
                for(var a = 0, glen = groups.length; a<glen;a+=1){
                    var group = groups[a];
                    var equal = true;
                    var firstElement = group[0];
                    properties.forEach(function(property){

                        if(firstElement[property] !== obj[property]){
                            equal = false;
                        }

                    });
                    if(equal){
                        equalGroup = group;
                    }
                }
                if(equalGroup){
                    equalGroup.push(obj);
                }
                else {
                    groups.push([obj]);
                }
            }
        }
        return groups;
    };

This solution works, but is this a right and best way? It still looks a little ugly to me.


texts:
Reverse a doubly linkedlist. Looking for code review, optimizations and best practices.

public class ReverseDoublyLinkedList<T> implements Iterable<T> {

    private Node<T> first;
    private Node<T> last;
    private int size;

    public ReverseDoublyLinkedList() { };

    public ReverseDoublyLinkedList(List<T> c) {
        for (T item : c) {
            add(item);
        }
    };

    public void add (T t) {
        final Node<T> l = last;
        final Node<T> node = new Node<T>(null, t, null);
        last = node;
        if (first == null) {
            first = node;
        } else {
            l.right = node;
            node.left = l;
        }
        size++;
    }

    private static class Node<T> {
        Node<T> left;
        T item;
        Node<T> right;

        public Node(Node<T> left, T item, Node<T> right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    public void reverse() {
        if (first == null) {
            throw new IllegalArgumentException("The root cannot be null.");
        }

        Node<T> node = first;
        while (node != null) {
            Node<T> temp = node.left;
            node.left = node.right;
            node.right = temp;

            node = node.left;
        }

        Node<T> temp = last;
        last = first;
        first = temp;
    }

    @Override
    public Iterator<T> iterator() {
        return new ListItr();
    }

    private class ListItr implements Iterator<T> {
        private int count;
        private Node<T> currentNode;

        public ListItr() {
             this.currentNode = first;
        }

        @Override
        public boolean hasNext() {
            return count < size;
        }

        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            T item = currentNode.item;
            currentNode = currentNode.right;
            count++;
            return item;
        }

        @Override
        public void remove() {
            currentNode.left.right = currentNode.right;
            currentNode.right.left = currentNode.left;
        }
    }

    public static void main(String[] args) {
        ReverseDoublyLinkedList<Integer> foo = new ReverseDoublyLinkedList<Integer>();
        foo.add(10);
        foo.add(20);
        foo.add(30);

        foo.reverse();

        Iterator<Integer> itr = foo.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}


texts:
In some specific scenarios, I want to run code after the constructor for a class has run (namely: access std::enable_shared_from_this::shared_from_this()).

To solve this without introducing an error prone init method for all classes with this behaviour I have built a generic pattern that allows constructors to "defer" lambdas to run after the constructor has run (example in end of snippet):

// If derived from this subclasses may call enable_defer::defer in their
// constructor to run code directly _after_ their constructor has completed
// This is useful when for example the constructor wants to access the weak_ptr
// from std::enable_shared_from_this in the constructor.
// Note naming convention matching std::enable_shared_from_this & underscores to avoid collisions in subclasses
class enable_defer
{
    // Allowed factories
    template <typename T>
    friend std::shared_ptr<T> make_shared_deferrable();

    template <typename T, typename... Args>
    friend std::shared_ptr<T> make_shared_deferrable(Args&&... args);

    // Allowed implementations
    template <typename T>
    friend class __impl__;

private:
    std::vector<std::function<void()>> defered;
    bool constructed = false;

    // Only friend classes may have access to this type
    // this is because we only want friend classes to be able to implement the interface
    class __Tag__ {};

    virtual void __constructed__(__Tag__ = __Tag__()) = 0;

    // Implementation of enable_defer kept private
    // to make sure only friend factories above may
    // construct implementations
    template <typename T>
    class __impl__ : public T
    {
        static_assert(std::is_base_of<enable_defer, T>::value, "Must be enable_defer");

        // Forward base class constructors
        using T::T;

        virtual void __constructed__(__Tag__) override
        {
            constructed = true;
            for (auto fn : defered)
                fn();
        }
    };

protected:

    void defer(std::function<void()> fn)
    {
        // Make sure defer is only called in constructor
        assert(!constructed);
        defered.push_back(fn);
    }
};

// Create std::shared_ptr from enable_defer
template <typename T>
std::shared_ptr<T> make_shared_deferrable()
{
    auto shared(std::shared_ptr<T>(new enable_defer::__impl__<T>()));
    shared->__constructed__();
    return shared;
}

// Create std::shared_ptr from enable_defer
template <typename T, typename... Args>
std::shared_ptr<T> make_shared_deferrable(Args&&... args)
{
    auto shared(std::shared_ptr<T>(new enable_defer::__impl__<T>(std::forward<Args>(args)...)));
    shared->__constructed__();
    return shared;
}

class Example : public enable_defer, public std::enable_shared_from_this<Example>
{
public:

    Example()
    {
        defer([this]() {
            shared_from_this(); // Works!
        });
    }

    // Factory
    static std::shared_ptr<Example> create()
    {
        return make_shared_deferrable<Example>();
    }
};

Questions:

Are there better ways to accomplish the enforcements of the implementation class and factories?
General improvements
Bugs?
Naming?
General thoughts on this pattern.


texts: Python: check if all array values are same

texts:
I have an example array like:

array = [1, 2, 3, 4, 5, 6]

Every of this numbers refers to an object that has text property. I want to make sure that every of these object has the same text value.
Currently I do it like this:

correct = []
for number in array:
  if(object[number].text == "Sample"):
    correct.append(number)
if correct.length == array.length:
  return True

Is there a more efficient way to do this, like with lambda function or?


texts:
I made a queue that prints out strings a, b, c, and d. It works, but I want to make sure I don't have any unnecessary code. I realized that my main method prints the strings without the queue. Is there any better way to write the main method and Imp method so that it uses my queue class?

    public class Main
{
    //this method reverses the string
    public static void Imp(StringBuffer str)
    {

        int n = str.length();       //str.length recognizes the number of
                                    //characters in n, which is also the stack array
        Queue obj = new Queue(n);   //we set n to a new variable, "obj"

        // Push all characters of string
        // to stack
        int i;
        for (i = 0; i < n; i++)
        obj.push(str.charAt(i));

        // Pop all characters of string
        // and put them back to str
       for (i = 0; i < n; i++)
        {
            char ch = obj.pop();
            str.setCharAt(i,ch);
        }
    }

    public static void main(String args[])
    {
        //create a new string
        //StringBuffer also takes recognizes the amount of characters
        StringBuffer a= new StringBuffer("bob");
        StringBuffer b= new StringBuffer("eat too much");
        StringBuffer c= new StringBuffer("I love greasy food");
        StringBuffer d= new StringBuffer("FORTRAN 77 RULES");

        //call Imp method
        Imp(a);
        Imp(b);
        Imp(c);
        Imp(d);

    //print the reversed string
        System.out.println(a + "\n" + b + "\n" + c + "\n" + d);
    }
}

//this method creates the stack
//This method creates the queue
class Queue {
int size;
    int top;
    int bottom;
    char[] queue;

    Queue(int n)
    {
        top = 0;            //set stack top pointer to 0
        bottom = -1;        //set bottom pointer to less than the top pointer
        size = n;           //set size to variable n
        queue = new char[size]; //make int n convert to char queue by using size
    }

    char push(char x){
            queue[++bottom] = x;    //increment the queue pointer and place x on the bottom of x
            return x;       //return that x value
    }

    char pop(){
            char x = queue[top++];  //get x from the top of the queue and increment the queue
            return x;

    }

    boolean isEmpty()
    {
    boolean empty;      //make variable "empty" a boolean
    empty = false;      //"empty" is set as false
    if (top >= bottom){     //if top is greater than bottom, then the stack is empty
        empty = true;
    }
        return empty;

        }
}


texts: Noughts and Crosses Terminal Game with AI

texts:
I created a game which can play tic-tac-toe with: 0 players (AI vs AI), 1 player (human vs AI) or 2 player (human vs human).
Here is the AI function which wraps around my innermost function. This evaluates all the candidate board positions and returns the best move.

I searched to make sure this has not been implemented before.

Could I have feedback on my Python code in my GitHub repo.

I would be particularly interested in knowing how to make my code clearer to read and understand.
I would be interested to know how I could improve this code, or the code which evaluates a given boardstate. For example I would like to make score_one_gamestate be more elegant.
I have a vague feeling that I could use something instead of creating many deepcopies of the game board in the score_one_gamestate function. But I do not know how to do this.
Additionally I do not know whether attempting this would even be a good idea.

def optimal_ai_move(board: np.array, x_or_o: str, available: list):
    """
    The heart of the robot brain.
    Given a board state, will return the optimal move.
    :param board: numpy array of the board.
    :param x_or_o: which side is the AI playing on? #This isn't exactly true in recursive calls.
    :param available: available[(row, col)] = True, if the space hasn't been taken yet.
    :return: best_move: (row, col). The move with the greatest number of simulated wins.
    """
    possibility_dict = {}
    for candidate_move in available:
        deeper = copy.deepcopy(board)
        deeper[candidate_move] = x_or_o
        available = find_available_moves(deeper)
        possibility_dict[candidate_move] = score_one_gamestate(deeper,
                                                               turn_flipper(x_or_o),
                                                               available,
                                                               x_or_o,
                                                               score_dict=None)

    metric_dict = {candidate_move: (score_dict['wins'] + score_dict['draws']) / sum(score_dict.values())
                   for candidate_move, score_dict in possibility_dict.items()}

    best_move = max(metric_dict, key=metric_dict.get)
    return best_move, possibility_dict

def score_one_gamestate(board: np.array, x_or_o: str, available: list, ai_player_choice: str, score_dict=None,
                        weight=1) -> int:
    if score_dict is None:
        score_dict = {'wins': 0, 'losses': 0, 'draws': 0}
    is_finished = game_over(board)

    if is_finished == ai_player_choice:  # This might be wrong, we want ai_player_choice
        score_dict['wins'] += 1 / weight
        return score_dict
    elif is_finished == turn_flipper(ai_player_choice):
        score_dict['losses'] += 1 / weight
        return score_dict
    elif is_finished == 'draw':
        score_dict['draws'] += 1 / weight
        return score_dict
    else:
        weight *= len(available)
        for candidate_move in available:
            deeper = copy.deepcopy(board)
            deeper[candidate_move] = x_or_o
            available_moves = find_available_moves(deeper)
            score_dict = score_one_gamestate(deeper,
                                             turn_flipper(x_or_o),
                                             available_moves,
                                             ai_player_choice,
                                             score_dict,
                                             weight)
    return score_dict


texts:
I am designing a planetary system simulator. The coordinates used are standard for JPanel (0,0 in the upper left corner).

My model is based on a class Body:

public class Body {
    private double x, y; // position
    private double w, h; // dimensions for drawing
    private double vx = 0, vy = 0; // velocities along x, y axes
    private double ax = 0, ay = 0; // accelerations along x, y axes
    private double mass = 1; // default = 1
    private boolean stationary = false; // stationary body is centered during simulation

    /* ... not showing all the setters and getters */

Because the force of gravity is the same for any two interacting bodies, I designed the methods to take another body as an argument, so we can call planet1.interact(planet2)

Distance calculation:

public double calculateDistX(Body other) {
    double x1 = this.getX();
    double x2 = other.getX();
    return Math.sqrt(Math.pow(x2 - x1, 2));
}

public double calculateDistY(Body other) {
    double y1 = this.getY();
    double y2 = other.getY();
    return Math.sqrt(Math.pow(y2 - y1, 2));
}

public static double calculateDistance(double dist_x, double dist_y) {
    return Math.sqrt(Math.pow(dist_x, 2) + Math.pow(dist_y, 2));
}

Finally, the method that calculates gravitational force:

public void interact(Body other) {
    double x = calculateDistX(other);
    double y = calculateDistY(other);
    double r = calculateDistance(x, y);

    double force = (this.getMass() * other.getMass()) / Math.pow(r, 2);
    double force_x = force * (x / r); // force * cos
    double force_y = force * (y / r); // force * sin

    /* calculate accelerations for both bodies, set vector orientation */
    if (other.getX() > this.getX()) {
        this.setAx(force_x / this.getMass());
        other.setAx(-force_x / other.getMass());
    } else {
        this.setAx(-force_x / this.getMass());
        other.setAx(force_x / other.getMass());
    }

    if (other.getY() > this.getY()) {
        this.setAy(force_y / this.getMass());
        other.setAy(-force_y / other.getMass());
    } else {
        this.setAy(-force_y / this.getMass());
        other.setAy(force_y / other.getMass());
    }

    /* calculate velocities for both bodies */
    this.setVx(this.getVx() + this.getAx());
    this.setVy(this.getVy() + this.getAy());

    other.setVx(other.getVx() + other.getAx());
    other.setVy(other.getVy() + other.getAy());

    /* calculate positions for both bodies */
    this.setX(this.getX() + this.getVx());
    this.setY(this.getY() + this.getVy());

    other.setX(other.getX() + other.getVx());
    other.setY(other.getY() + other.getVy());
}

I don't really know how good/bad this model is. The section in interact that sets the vector orientation looks like it can be simpler, but I can't figure it out.

Also, I have doubts about this method, because calling:

planet1.interact(planet2);
planet1.interact(planet3);
planet2.interact(planet3);

Makes planet2 and planet3 interact AFTER the original position of planet1 and planet2 has changed, and it's not how it's hapenning in reality. I don't know how important that would be, though.


texts: Convert numbers in a string array (#3, #1, #2, #4) to range (#1:#4)

texts:
Updated question: Compress numbers in a string array (#3, #1, #2, #4) to range (#1:#4)

This function takes a string array,

{"foo", "#123", "#124", "bar", "#125", "#126"}

makes a new array with the numbers converted to a range:

{"foo", "#123:126", "bar"}

and returns:

"foo,#123:126,bar"

Note it doesn't and shouldn't change {"#1", "#2"} to {"#1:#2"}

static void Main(string[] args)
{
    var ids = new string[] { "foo", "#12", "#14", "#17", "#13", "#18", "#bar", "#19", "#20", "#25", "#26", "#38", "#39", "baz", "#12", "#13", "#14" };
    Console.WriteLine("foo,#12:#14,#17:#20,#bar,#25,#26,#38,#39,baz,#12:#14");
    Console.WriteLine(Convert(ids));
    Console.Read();
}
static string Convert(IEnumerable<string> arr)
{
    var IDs = arr.ToList();
    var result = new List<string>();
    for (var index = 0; index < IDs.Count; index++)
    {
        var i = IDs[index];
        if (i.StartsWith("#"))
        {
            int fromInt;
            if (int.TryParse(i.Substring(1), out fromInt))
            {
                var plus1 = $"#{fromInt + 1}";
                var plus2 = $"#{fromInt + 2}";
                if (IDs.Contains(plus1) && IDs.Contains(plus2))
                {
                    IDs.Remove(plus1);
                    IDs.Remove(plus2);
                    var toInt = fromInt + 2;
                    while (IDs.Contains($"#{toInt + 1}"))
                    {
                        toInt += 1;
                        IDs.Remove($"#{toInt}");
                    }
                    i = $"#{fromInt}:#{toInt}";
                }
            }
        }
        result.Add(i);
    }
    return string.Join(",", result);
}


texts:
I'm just learning JavaScript and I started this simple to-do list project to practice on. I got most of the way there, but I couldn't get the clear button to work on any dynamically added inputs. I think this has something to do with where/when the selector variable is defined, but I couldn't work out how to fix it. I'm sure some of the code is not the best way to write it, so any recommendations or fixes would be much appreciated!

var add = document.getElementById('add');
var input = document.getElementsByClassName("input-container");
var remove = document.querySelectorAll('.remove');

var addField = function() {
  var field = document.getElementsByClassName("input-container")[0];
  var clone = field.cloneNode(true);
  var latestInput = document.getElementById("list-container").appendChild(clone);
  latestInput.childNodes[1].value = '';
};

var removeField = function() {
  if (input.length > 1) {
    var parent = this.parentElement.parentElement.parentElement;
    var child = this.parentElement.parentElement;
    parent.removeChild(child);
  }
};

add.addEventListener('click', addField);
remove.forEach(function(field) {
  field.addEventListener('click', removeField);
});
@import url('https://fonts.googleapis.com/css?family=Quicksand:300,400,500,700');
@import url('https://fonts.googleapis.com/css?family=Chewy');
* {
  box-sizing: border-box;
  font-family: 'quicksand', 'sans-serif';
}

html,
body {
  background: #E0E6ED;
  width: 100%;
  height: 100%;
  font-family: 'quicksand', 'sans-serif';
}

h1 {
  font-size: 50px;
  color: #E85D75;
  font-family: 'Chewy', cursive;
}

.main-container h1 {
  margin-bottom: 20px;
}

.text-center {
  text-align: center;
}

.text-input {
  width: 100%;
  border: none;
  border-radius: 4px;
  padding: 10px;
  font-size: 12px;
}

.input-container {
  position: relative;
  margin-top: 8px;
}

.input-container:first-child {
  margin-top: 0;
}

.remove-container {
  position: absolute;
  right: -22px;
  top: 0;
  line-height: 35px;
}

input:focus {
  outline: none;
}

.main-container {
  width: 200px;
  position: relative;
  top: 50%;
  margin-left: auto;
  margin-right: auto;
  transform: perspective(1px) translateY(-50%);
}

.plus-container {
  display: block;
  margin-top: 10px;
}

.fa.fa-plus,
.fa.fa-close {
  color: #C0C8D2;
  cursor: pointer;
}

.fa.fa-plus:hover,
.fa.fa-close:hover {
  color: #E85D75;
}

To-Do List

      <input class="text-input" type="text" placeholder="Type something">

https://codepen.io/mrseanbaines/pen/aLyByJ


texts: Could I dispose IDisposable objects that are part of a Thread?

texts:
I have a question about using an IDisposable object in the ThreadStart function. I have a class that derives from ServiceBase:

public class ServiceTest: System.ServiceProcess.ServiceBase
{
    private System.ComponentModel.Container components = null;
    private System.Threading.Thread         m_cProcessThread;

    public ServiceTest()
    {
        this.ServiceName = "ServiceTest";
    }

    static void Main()
    {
        System.ServiceProcess.ServiceBase[] ServicesToRun  = new System.ServiceProcess.ServiceBase[] { new ServiceTest() };

        System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    }
    protected override void Dispose( bool disposing )
    {
        if ( disposing )
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose( disposing );
    }

    protected override void OnStart(string[] args)
    {
        ProcessThread   cThread;

        cThread = new ProcessThread();
        m_cProcessThread = new Thread(new ThreadStart(cThread.InitProcess));
        m_cProcessThread.Start();
    }

    protected override void OnStop()
    {
        m_cProcessThread.Abort();
    }
}

and in the OnStart function I have the ProcessThread object which is an IDisposable object. I was wondering if it is safe to re-write the OnStart function to do this:

    protected override void OnStart(string[] args)
    {
        using (Process cThread = new ProcessThread())
        {
            m_cProcessThread = new Thread(new ThreadStart(cThread.InitProcess));
        }

        m_cProcessThread.Start();
    }

Or will there be any consequences in doing this? I have a bit of an OCD when I see IDisposable objects in C# code that makes me believe that they HAVE to be disposed as soon as you are done lol. Also I don't know if my question title really fits with what I'm asking so if you could come up with a better title then feel free to edit.

Code is targeted at .net 2.0, running on a Windows 2000 server.


texts: Swift function to interpret Roman numerals (ported from JavaScript)

texts:
I have written some Swift for the first time, being competent enough in Javascript and having some experience in Ruby and Python.  For my education, I've written a function that parses a roman numeral string and returns its integer representation, first in Javascript (ES2015+):

const dict = [
  ['CM', 900], ['M', 1000], ['CD', 400], ['D', 500],
  ['XC', 90], ['C', 100], ['XL', 40], ['L', 50],
  ['IX', 9], ['X', 10], ['IV', 4], ['V', 5],
  ['I', 1],
]

function romanToInt (original) {
  let temp = original
  let int = 0

  while (temp.length > 0) {
    let found = false

    for (const [glyph, quantity] of dict) {
      if (temp.startsWith(glyph)) {
        int += quantity
        temp = temp.slice(glyph.length)
        found = true
        break
      }
    }

    if (!found) {
      // e.g. Error parsing roman numeral "MDCCLXXVI," at ","
      throw new Error(`Error parsing roman numeral "${original}" at "${temp}"`)
    }
  }

  return int
}

try {
  romanToInt('MMXIV') // => 2014
} catch (err) {
  console.error(err)
}

and then ported it to Swift 4:

let dict: [( glyph: String, quantity: Int )] = [
    ("CM", 900), ("M", 1000), ("CD", 400), ("D", 500),
    ("XC", 90), ("C", 100), ("XL", 40), ("L", 50),
    ("IX", 9), ("X", 10), ("IV", 4), ("V", 5),
    ("I", 1)
]

enum RomanNumericError: Error {
    case badInput(original: String, temp: String)
}

func romanToInt(original: String) throws -> Int {
    var temp = original
    var int = 0

    while temp.count > 0 {
        var found = false

        for (glyph, quantity) in dict {
            if temp.starts(with: glyph) {
                int += quantity
                temp.removeFirst(glyph.count)
                found = true
                break
            }
        }

        guard found == true else {
            throw RomanNumericError.badInput(original: original, temp: temp)
        }
    }

    return int
}

do {
    try romanToInt(original: "MMXIV") // => 2014
} catch RomanNumericError.badInput(let original, let temp) {
    print("Error parsing roman numeral '\(original)' at '\(temp)'")
}

I'm wondering about how swift-y my code is in terms of design patterns, especially in terms of error handling. In Javascript, throwing and catching errors is a very common control flow design, and I'm wondering if I'm approaching it from the right angle in Swift.


texts: A Maximum Function For Various Type Arbitrary Nested Iterable Implementation in C++

texts:
This is the follow-up question for A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++. Besides the summation case, I am trying to implement a Max function which can find the maximum value in various type (comparable) arbitrary nested iterable things as the further step. The recursive technique is also used here in order to iterate all elements. Some concepts as the constraints for template are as below.
template<typename T>
concept Summable = requires(T x) { x + x; };

template<typename T>
concept Iterable = requires(T x)
{
    x.begin();      // must have `x.begin()`
    x.end();        // and `x.end()`
};

The key implement part about this Max function.
template<typename T> requires Summable<T>
static T Max(T inputNumber);        //  Deal with the base case like "Max(static_cast<int>(1))"

template<class T> requires Iterable<T>
static auto Max(const T& numbers);  //  Deal with the iterable case like "Max(std::vector<long double>{ 1, 1, 1 })"

template<class T> requires Summable<T>
static inline T Max(T inputNumber)
{
    return inputNumber;
}

template<class T>  requires Iterable<T>
static inline auto Max(const T& numbers)
{
    typedef typename std::iterator_traits<typename T::iterator>::value_type
        value_type;

    decltype(Max(std::declval<value_type &&>())) maxValue{};

    maxValue = static_cast<decltype(maxValue)>(Max(numbers.at(0)));
    for (auto& element : numbers)
    {
        if (maxValue < Max(element))
        {
            maxValue = Max(element);
        }
    }
    return maxValue;
}

The std::vector test case to this Max function.
std::vector<int> v{ 1, 2, 3, -1, -2, -3 };
int largest_element = *std::max_element(v.begin(), v.end());
std::cout << largest_element << std::endl;
std::cout << Max(v) << std::endl;

The value of largest_element and the result of Max(v) are the same.
The std::array test case to this Max function.
std::array<long double, 10> testArray;
for (size_t i = 0; i < 10; i++)
{
    testArray[i] = i;
}
std::cout << Max(testArray) << std::endl;

The more complex (std::vector<std::vector<long double>>) case:
std::vector<long double> testVector1;
testVector1.push_back(1);
testVector1.push_back(20);
testVector1.push_back(-100);

std::vector<long double> testVector2;
testVector2.push_back(10);
testVector2.push_back(90);
testVector2.push_back(-30);

std::vector<std::vector<long double>> testVector3;
testVector3.push_back(testVector1);
testVector3.push_back(testVector2);
std::cout << Max(testVector3) << std::endl;

All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++

What changes has been made in the code since last question?
The previous question focus on the summation operation and the main idea in this question is trying to achieve the maximum operation.

Why a new review is being asked for?
In my opinion about this code, there are some problem existed. Although this Max function seems works well, there is a little weird to the usage of Summable concept here. Is it a good idea to replace this Summable into a new concept Comparable? If so, Is there any better idea or suggestion about the design of Comparable? I have ever comes up an idea to the concept Comparable like below.
template<typename T>
concept Comparable = requires(T x) { x > x; };

However, the operator ">" has been defined in std::vector until C++20. This operator > compares the contents lexicographically. This causes the error "ambiguous call to overloaded function".
Moreover, is it a good idea to simplify the initial value assignment maxValue = static_cast<decltype(maxValue)>(Max(numbers.at(0))); into maxValue = Max(numbers.at(0)) (remove the static_cast syntax)?


texts: Solution to LeetCode Next Greater Element Ⅰ in Python

texts:
This is my solution to LeetCode's "Next Greater Element Ⅰ":

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

class Solution:

    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        need, ready, next_greater = set(nums1), set(), {}
        for n in nums2:
            for k in ready:
                if k < n:
                    next_greater[k] = n
            ready = {k for k in ready if k not in next_greater}
            if n in need and n not in next_greater and n not in ready:
                ready.add(n)
        return [next_greater[k] if k in next_greater else -1 for k in nums1]

The nextGreaterElement method accepts 2 lists. Neither list contains duplicates, and nums1 is a subset of nums2. For every num in nums1, it will output the first number greater than num positioned to the right of num in nums2, or -1 is none is found. e.g.:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]

I loop through the keys in ready, and the body of the loop does nothing unless k < n. len(ready) can be very large relative to the number of values that satisfy k < n. This seems like a very common thing so I'm wondering if there's a more explicit/pythonic way to write this?
Or should I be using a different data structure entirely?


texts:
I've tried to solve this challenge about 4 hours during the contest, but all my attempts exceeded the time limit. I tried to solve it with min-heap, but can't pass all the tests. How it can be solved within given time and space requirements?

  Problem statement

  Programmer Alexey likes to work at night and does not like to come to
  work late. In order to precisely wake up in the morning, Alexey every
  evening starts \$N\$ alarm clocks on his phone. Each alarm clock is
  arranged in such a way that it rings every \$X\$ minutes from the time
  at which it was turned on.

  For example, if the alarm clock was started at the moment of time
  \$t_i\$, then it will ring at the moments of time \$t_i, t_i + X, t_i + 2 * X\$ and so on. Moreover, if some two alarms begin to ring at one time, only one of them is displayed.

  It is known that before waking up, Alexey listens every morning to
  exactly \$K\$ alarm clocks, and then wakes up. Determine the point in
  time when Alex wakes up.

  Input format

  Input format The first line contains three integers. \$N, X\$ and \$K\$ \$(1 ≤ N ≤10^5, 1≤X, K≤10^9)\$ - the number of alarms, the frequency of
  calls and the number of alarms that need to be turned off in order for
  Alex to wake up. The second line contains N integers - the points in
  time at which the alarm clocks were entered.

  Requirements

Time limit: 2 seconds
Memory limit: 256Mb

  Examples

  Example 1

  Input

6 5 10
1 2 3 4 5 6

  Output 10

  Example 2

  Input

5 7 12
5 22 17 13 8

  Output 27

  Notes

  In the second example, there are 5 alarm clocks with a frequency of 7
  calls. For example, the first alarm clock will ring at times 5, 12,
  19, 26, 33, etc. If you look at all the alarms at the same time, they
  will ring at the following times: 5, 8, 12, 13, 15, 17, 19, 20, 22
  (2nd and 5th alarm clocks at the same time), 24, 26, 27, 29,…. On the
  12th call Alexey must wake up, What corresponds to the point in time
  27.

My solution

Classified as "time limit exceeded"

import heapq

def main():
    n, x, k = map(int, input().split(" "))
    times = list(map(int, input().split(" ")))

    heapq.heapify(times)

    answers = []

    while k:
        v = heapq.heappop(times)
        heapq.heappush(times, v + x)

        if len(answers) == 0 or answers[len(answers)-1] != v:
            answers.append(v)
            k -= 1

    print(answers[k-1])

if __name__ == "__main__":
    main()


texts:
I've read some resources on implementing NSCopying and copyWithZone, but things are still not very clear. I see many implementations with allocWithZone, which seems to be deprecated, and with autorelease, which seems to be unnecessary with ARC.

I was wondering if I can get away with something more simple. Something like this:

MTSound.h

#import <Foundation/Foundation.h>

@interface MTSound : NSObject <NSCopying>

@property (nonatomic) float frequency;
@property (nonatomic) float amplitude;
@property (nonatomic) float duration;

// Designated Initializer
- (instancetype)initWithFrequency:(float)freq
                        amplitude:(float)amp
                         duration:(float)dur;

+ (instancetype)soundWithFrequency:(float)freq
                         amplitude:(float)amp
                          duration:(float)dur;

@end

MTSound.m

#import "MTSound.h"

@implementation MTSound

// Initializers

- (instancetype)initWithFrequency:(float)freq amplitude:(float)amp duration:(float)dur {
    if (self = [super init]) {
        _frequency = freq;
        _amplitude = amp;
        _duration = dur;
    }
    return self;
}

// Class factory methods

+ (instancetype) soundWithFrequency:(float)freq amplitude:(float)amp duration:(float)dur {
    return [[self alloc] initWithFrequency:freq amplitude:amp duration:dur];
}

// NSCopying protocol

- (id)copyWithZone:(NSZone *)zone {
    return [[self class] soundWithFrequency:self.frequency
                                  amplitude:self.amplitude
                                   duration:self.duration];
}

@end

Is there something wrong with this approach? If so, what's the correct implementation?


texts:
I have written some jQuery that slides open a panel on click, and changes the toggles of the clickable bit from 'Show All' to 'Hide All'.

It works, but I'm trying to figure out what would be the most efficient way to do it, as it seems kind of long to me, and some HTML is repeated.

This is the working version and a working fiddle here:

$(function() {
    //Hide panel with jQuery and create toggle button so subjects will just show if there's no javascript
$("#panelSub").hide();
$('#toggleSubjects').html('
Show All Subjects
');
    //Toggle extra subject panel
    $("#toggleSubjects").click(function(){
        $("#panelSub").slideToggle("slow");
        //Change toggle text for show / hide
            if ($.trim($('.subjectOpen').text()) === 'Show All Subjects') {
            $(this).html('
Hide All Subjects
');
            } else {
            $(this).html('
Show All Subjects
');
                }
            });
            return false;
});


texts: "Hello, world!" program using a class for printing

texts:
Please take a look at my program and let me know how I can improve it.

/*
"   To Print A Line On The Display Screen"
    Date:5th January 2011
    Programmer:Fahad
*/
#include <iostream>
using namespace std;
class Print
{
    public:
        void print_();
};
int main()
{
    Print Obj;
    Obj.print_();
    system( "pause" );
    return 0;
}
void Print::print_()
{
    cout << "I am in print function and the program runs fine." << endl;
}


texts: Add a class to an element when it's loaded

texts:
I want to add a class to only those <p> elements that have an <img>.
So far this is what I have, it works, but I don't think I'm doing it right.

$(".entry-content p img").addClass(function(){
    $(this).parent("p").addClass("no-orphans-ctnr");
});

Here's a Demo/fiddle.

As you can see, I used the .addClass() method twice. I'm not a jQuery/JavaScript developer but that doesn't look right to me.
Please review and help me improve it.


texts:
This is web exercise 3.1.45. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:

Write a program that reads in a list of words from the command line
and prints true if they form a word chain and false otherwise. In a
word chain, adjacent words must differ in exactly one letter, e.g.,
HEAL, HEAD, DEAD, DEED, DEER, BEER.

Here is my program:
public class WordChainChecker
{
    public static boolean checkWordCouple(String word1, String word2)
    {
        int counter = 0;
        int wordLength = word1.length();
        for (int i = 0; i < wordLength; i++)
        {
            if (word1.charAt(i) != word2.charAt(i)) counter++;
        }
        if (counter > 1) return false;
        else             return true;
    }
    public static void main(String[] args)
    {
        String word1 = StdIn.readString();
        String word2 = StdIn.readString();
        boolean truth = true && checkWordCouple(word1,word2);
        while (!StdIn.isEmpty())
        {
            word1 = StdIn.readString();
            truth = truth && checkWordCouple(word1,word2);
            word2 = word1;
        }
        System.out.println(truth);
    }
}

StdIn is a simple API written by the authors of the book. I checked my program and it works.
Is there any way that I can improve my program?
Thanks for your attention.


texts:
I have this class:

public class MapController
{
    private Polyline _currentPolyline; // The line connecting two locations on the map
    private GoogleMap _map;
    private Context _context;

    public MapController(GoogleMap map, Context context)
    {
        _map = map;
        _context = context;
    }

    /**
     * Draws a route on the map.
     *
     * @param directions the Google Map Directions JSON string with the routes
     * @throws JSONException
     */
    public void drawRoute(String directions) throws JSONException
    {
        // First parse the JSON to extract the points into an easily manipulated form
        List<List<HashMap<String, String>>> routes = new DirectionsHelper().parsePathsFromJson(directions);

        // Only one polyline can be shown on the map at a time
        hideRoute();

        ArrayList<LatLng> points;
        PolylineOptions polyLineOptions = null;

        // Traversing through routes
        for (int i = 0; i < routes.size(); i++)
        {
            points = new ArrayList<LatLng>();
            polyLineOptions = new PolylineOptions();
            List<HashMap<String, String>> path = routes.get(i);

            for (int j = 0; j < path.size(); j++)
            {
                HashMap<String, String> point = path.get(j);

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            polyLineOptions.addAll(points);
            polyLineOptions.color(ContextCompat.getColor(_context, R.color.colorPrimary));
        }

        _currentPolyline =  _map.addPolyline(polyLineOptions);
    }

    /**
     * Removes the currently drawn {@link Polyline} from the map.
     */
    public void hideRoute()
    {
        if (_currentPolyline != null)
        {
            _currentPolyline.removeRoute();
        }
    }
}

Is it generally a good practice to call hideRoute() inside the drawRoute() method or does it depend on other factors? For example: should the caller be responsible for clearing the map before drawing the new path or does the caller not care?


texts:
I had to create an executable to search and replace strings in a file. This is to be used in my installer for text file manipulation. I have various placeholders in configuration files that I need to replace with proper values after querying the end user system.

I have written the following code. This being my first real experience with C#, I do not expect the code to be any good. I have come up with this code based upon a couple of hours of reading MSDN and stackoverflow. I needed someone to review this. There is no one greater than the community to do this.

Please review this and let me know what modification are necessary.
I am specifically concerned about the exception handling.
I have included two try-catch blocks.

My logic:

If I have all operations under one try-catch block, the failure of one process will block the execution of all others. That is, if my

text = Regex.Replace(text, args[1], args[2]);

has an exception and if I have

WriteLog(args[0], args[1], args[2], strException, intStatus);

also in the same try block, it will not execute and I will not have any logs.

Also, if I have the

WriteLog(args[0], args[1], args[2], strException, intStatus);

in the catch block, any exception in that method cannot be caught. Yes I can have try-catch in the WriteLog method but I see no problems in my approach too.

So first, I have a try-catch for file manipulation and then another for log write.

Please ignore the log path(hardcoded as D:).

class Program
{
    static int Main(string[] args)
    {
        //args[0] = The file that needs modification
        //args[1] = The string to replace
        //args[2] = The string with which to replace args[1]
        int intStatus = 0;
        string strException = "";

        //Get out immediately if no/improper arguments are found
        if (args.Length < 3)
        {
            intStatus = 1;
            return intStatus;
        }

        try
        {
            StreamReader streamReader = new StreamReader(args[0]);
            String text = streamReader.ReadToEnd();
            streamReader.Close();
            text = Regex.Replace(text, args[1], args[2]);
            StreamWriter streamWriter = new StreamWriter(args[0]);
            streamWriter.Write(text);
            streamWriter.Close();
        }
        catch (Exception ex)
        {
            //text file manipulation failed
            strException = ex.ToString();
            intStatus = 2;
        }

        try
        {
            WriteLog(args[0], args[1], args[2], strException, intStatus);
        }
        catch
        {
            //log write failed
            if (intStatus == 0)
            {
                intStatus = 3; //if intStatus = 1 when we get here, no need to modify the value(its a complete failure)
                               //if intStatus = 0 when we get here, make intStatus = 2 so as to clearly distinguish a "log write failed"
                               //error from a "text file manipulation failed" error
            }
        }

        return intStatus;
    }

    //The new Logger for the exe
    static void WriteLog(string arg0, string arg1, string arg2, string exception, int status)
    {
            string strGrepLogFileName = string.Format("D:\\TempLogs\\Grep-{0:yyyy-MM-dd_hh-mm-ss-tt}.log", DateTime.Now);
            StreamWriter GrepLog = new StreamWriter(strGrepLogFileName, true);
            GrepLog.WriteLine("Argument 1: " + arg0);
            GrepLog.WriteLine("Argument 2: " + arg1);
            GrepLog.WriteLine("Argument 3: " + arg2);
            GrepLog.WriteLine("Status: " + status.ToString());
            GrepLog.WriteLine("Exception: " + exception);
            GrepLog.Close();
    }
}

EDIT 1:
It is an absolute pity that I cannot mark multiple answers.


texts: A task to store user's favorited projects in postgres using python

texts:
I am not happy with two functions calling get_user() since while testing I mock get_user and to test with get_user_returns_null case, it returns Null for both function calls naturally which hints that the structure is not correct. I am using flask-sqlalchemy with postgres models ORM.
 def insert_user(user_details):
    user_record = None
    try:
        user = User(name = user_details['name'], email = user_details['email'])
        db.session().add(user)
        db.session().commit()
        user_record = get_user(user_details)
    except SQLAlchemyError as e:
        db.session().rollback()
    finally:
        db.session().close()
    return user_record

def add_user_favorite(user_details, project_code):
    user_id = None
    user_record = get_user(user_details)

    if user_record is None:
        user_record = insert_user(user_details)

    user_id = user_record['user_id']
    try:
        user_fav = UserFavoriteProject(user_id = user_id, project_code = project_code)
        db.session().add(user_fav)
        db.session().commit()
    except SQLAlchemyError as e:
        db.session().rollback()
    finally:
        db.session().close()

    return is_user_favorite(user_details, project_code)


texts: Extension to BindingList that allows for cancelable notifications of changing and deleting

texts:
This is an extension of the System.ComponentModel.BindingList<T> class that allows for notifications of item changing and deleting. These notifications provided the outgoing item and the incoming item, as well as a Cancel property to cancel the change or deletion.

In additon, it also allows for a bulk addition of items, which is just a loop of AddItem (which will trigger a change notification for each item added).

On top of bulk addition, there is a SetItems which will clear the collection and add all the items provided, but will only fire one Reset notification.

using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace BindingListExtension
{
    public class BindingListEx<T> : BindingList<T>
    {
        public event EventHandler<ListItemRemovingEventArgs<T>> ListItemRemoving;
        public event EventHandler<ListItemChangingEventArgs<T>> ListItemChanging;

        protected override void RemoveItem(int index)
        {
            var args = new ListItemRemovingEventArgs<T>(this[index], index);
            ListItemRemoving?.Invoke(this, args);
            if (args.Cancel) return;
            base.RemoveItem(index);
        }

        protected override void SetItem(int index, T item)
        {
            var args = new ListItemChangingEventArgs<T>(this[index], item, index);
            ListItemChanging?.Invoke(this, args);
            if (args.Cancel) return;
            base.SetItem(index, item);
        }

        public void SetItems(IEnumerable<T> items)
        {
            RaiseListChangedEvents = false;
            Clear();
            AddItems(items);
            RaiseListChangedEvents = true;
            OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        public void AddItems(IEnumerable<T> items)
        {
            if (items != null)
            {
                foreach (T item in items)
                {
                    Add(item);
                }
            }
        }
    }

    public class ListItemRemovingEventArgs<T> : CancelEventArgs
    {
        public ListItemRemovingEventArgs(T oldItem, int index)
        {
            OldItem = oldItem;
        }

        public T OldItem { get; }

        public int Index { get; }
    }

    public class ListItemChangingEventArgs<T> : ListItemRemovingEventArgs<T>
    {
        public ListItemChangingEventArgs(T oldItem, T newItem, int index) : base(oldItem, index)
        {
            NewItem = newItem;
        }

        public T NewItem { get; }
    }
}