texts: Intro to Java - determine valid unique numbers

texts:
This is an assignment for an intro to Java course.  It works with the test case given, but I would like to know if there is anything / a lot of things that should be different or could be better.

Specification:

  Write a Java application that accepts 5 “valid” numbers from the user.

  A valid number is between 50 and 100 inclusive.  If the user enters a
  number outside of the valid range, an error message should indicate
  this.  An invalid number is not counted as one of the 5.  The user
  might enter 50 invalid numbers, and the program will keep asking for
  numbers between 50 and 100.

  If the user enters a number that they have previously entered, this is
  counted as one of the 5.  A message appears that it is not unique.  A
  unique number is a valid number that has not been entered up to this
  point.  A non-unique number is a valid number that has already been
  entered.

  After each valid number  is entered, the count of the unique numbers
  entered so far is printed, and all of the unique numbers are printed
  on a single line.  (see example)

  When the user has entered 5 valid numbers, a message appears informing
  the user of how many unique, valid numbers were entered, and the
  unique numbers are printed again.

package partB;

import java.util.Scanner;

public class PartB {

    public static void main(String[] args) {

        int[] validNumber;
        int[] uniqueNumber;
        int input, numberOfUnique = 0;
        boolean validCheck, uniqueCheck;
        validNumber = new int[5];
        uniqueNumber = new int[5];

        Scanner userInput = new Scanner(System.in);

        for (int i = 0; i < validNumber.length; i++) {

            System.out.print("\nEnter an integer: \t");
            input = userInput.nextInt();

            validCheck = isValid(input);

            while (validCheck == false) {
                System.out.print("\nEnter an integer: \t");
                input = userInput.nextInt();
                validCheck = isValid(input);
            }

            if (validCheck == true) {

                uniqueCheck = isUnique(validNumber, input);
                validNumber[i] = input;
                if (uniqueCheck == true) {
                    numberOfUnique++;
                    uniqueNumber[i] = input;
                    System.out.println("Unique so far: \t\t" + numberOfUnique);
                    outputStatements(uniqueNumber);

                } else if (uniqueCheck == false) {
                    System.out.println(input + " is valid, but not unique");
                    System.out.println("Unique so far: \t\t" + numberOfUnique);
                    outputStatements(uniqueNumber);
                }
            }
        }
        System.out.println();
        System.out.println("You entered " + numberOfUnique
                + " unique valid numbers!");
        outputStatements(uniqueNumber);
    }

    public static boolean isValid(int validParameter) {
        boolean result;

        if (validParameter >= 50 && validParameter <= 100) {
            result = true;
        } else {
            result = false;
            System.out.println("The number " + validParameter
                    + " is out of the valid range.");
        }
        return result;
    }

    public static boolean isUnique(int[] array, int uniqueParamter) {
        boolean result = true;

        for (int i = 0; i < array.length; i++)
            if (array[i] != 0) {
                if (array[i] == uniqueParamter) {
                    result = false; // is NOT unique
                    break;
                } else {
                    result = true; // is unique

                }
            }
        return result;
    }

    public static void outputStatements(int[] array) {

        for (int i = 0; i < array.length; i++) {
            if (array[i] != 0) {
                System.out.print(array[i] + " ");
            }
        }
        System.out.println();
    }
}


texts:
I have some old RAR files and I know the general format of passwords I used to use, so I have generated a dictionary file combining those words in a variety of ways. The dictionary file is 500mb and I've wrote a python program to use the dictionary.

The issue is that the program has been running all night and is only 1% of the way in. I've now divided the dictionary file up and I am now running multiple instances of the program, but each instance is running pretty slow.

I would love any advice on how to improve the speed. I'm very new to Python, which will be obvious by my code (but I'm really enjoying Python).

import itertools
import sys, traceback
import os

with open('dictionary.txt') as infile:
    words = [line.strip() for line in infile]
    for word1 in itertools.product(words, repeat=1):
        fword = word1[0]
        print "Attempting: " + fword

        # open unrar and test password
        output = os.popen("unrar.exe x protected.rar -p" + fword)
        outstring = output.read()
        slng = len(outstring)

        # unrar.exe returns "All OK" for correct password
        validate = outstring.find("All OK", 0, slng)
        if validate != -1:
            print "Found password: " + fword
            with open('correct_password.txt', 'w') as outfile:
                outfile.write(fword)
            sys.exit(0)
        else:
            # continue searching
            print "invalid password"

raw_input("Password was not in this dictionary!")

Sample dictionary.txt

FableLand
FableWay
FableTree
FableSpirit
FableApple


texts:
I am trying to process concurrent AJAX requests with vanilla JavaScript. Below is the sample code I've been working with

function getInfoViaConcurrency(ids) {
  let infoPromiseArr = ids.map(id=> { infoPromiseArr.push(getInfoViaAjax(id)); });

  return Promise.all(infoPromiseArr).then(values => { return values; });
}

function getInfoViaAjax(id) {
  return new Promise((resolve, reject) => {
    let  xhr = new XMLHttpRequest();
    xhr.open('GET', `API URL`);
    xhr.onload = function() {
      if (xhr.status === 200) {
        resolve(JSON.parse(xhr.responseText));
      }
      else {
          reject(xhr.status);
      }
    };
    xhr.send();
  })
}

Does using promise.all suffice to promote concurrency? can someone suggest any improvements?


texts: Implement function in doubly linked list

texts:
The following is the entire function for implementing a doubly linked list. Can anyone show me if there is a better way to write these functions, especially the delete_at function please?

#include<stdio.h>
#include<stdlib.h>
typedef struct linked_list
{
    int point;
    struct linked_list *p_node;
    struct linked_list *n_node;
}node;

node *create_head_node(node *, int);
node *insert_head(node *, int);
void insert_tail(node *, int);
node *insert_at(node *, int, int);
int count_node(node *);
void print_list(node *);
node *delete_tail(node *);
node *delete_head(node *);
node *delete_at(node *, int);

node *create_head_node(node *head, int point){
    head->point=point;
    head->p_node=NULL;
    head->n_node=NULL;
    return head;
}
node *insert_head(node *head, int point){
    if (head==NULL){
        printf("no head exist");
        return 0;
    }
    node *temp=(node*)malloc(sizeof(node));
    temp->point=point;
    temp->p_node=NULL;
    temp->n_node=head;
    head->p_node=temp;
    head=temp;
    return head;
}
void insert_tail(node *head, int point){
    if (head==NULL){
        printf("no head exist");
        return;
    }
    node *p=head;
    node *temp=(node*)malloc(sizeof(node));
    temp->point=point;
    temp->n_node=NULL;
    while (p->n_node!=NULL)
    {
        p=p->n_node;
    }
    p->n_node=temp;
    temp->p_node=p;
}
node *insert_at(node *head, int point, int pos){
    if (head==NULL){
        printf("no head exist");
        return 0;
    }
    int count=count_node(head);
    while (pos>count)
    {
        printf("choose %d positions to add. choose again: ", count); scanf("%d", &pos);
    }
        node *p=head;
        for (int i = 0; i < pos; i++)
        {
            p=p->n_node;
        }
        node *temp=(node*)malloc(sizeof(node));
    temp->point=point;
    temp->n_node=p;
    temp->p_node=p->p_node;
    if(p->p_node!=NULL) p->p_node->n_node=temp;
    p->p_node=temp;
    return head;
}
int count_node(node *head){
    node *p=head;
    int count=0;
    while (p!=NULL)
    {
        count++;
        p=p->n_node;
    }
    free(p);
    return count;
}
void print_list(node *head){
    if (head==NULL){ printf("nothing to print"); return;}
    node *p=head;
    while (p!=NULL)
    {
        printf("%d ", p->point);
        p=p->n_node;
    }
}
node *delete_head(node *head){
    if (head==NULL){
        printf("no head exist\n");
        return 0;
    }
    node *p=head;
    // head->p_node=NULL;
    if(p->n_node!=NULL){
        head=p->n_node;
        free(p);
    }
    else head=NULL;
    return head;
}
node *delete_tail(node *head){
    if (head==NULL){
        printf("no head exist\n");
        return 0;
    }
    node *p=head;
    while (p->n_node!=NULL)
    {
        p=p->n_node;
    }
    if (p->p_node!=NULL){
        p->p_node->n_node=NULL;
        free(p);
    }
    else head=NULL;
    return head;
}
node *delete_at(node *head, int pos){
    int count=count_node(head);
    if(head==NULL){
        printf("no head exist");
        return 0;
    }
    while (count<pos)
    {
        printf("choose %d positions to delete. choose again", count); scanf("%d", &pos);
    }

    node *p=head;
    if(pos==0) head=delete_head(head);
    else if(pos==count-1) head=delete_tail(head);
    else{
        for (int i = 0; i < pos; i++)
        {
            p=p->n_node;
        }
        p->p_node->n_node=p->n_node;
        p->n_node->p_node=p->p_node;
        free(p);
    }
    return head;
}


texts: Check WiFi Connectivity and internet connectivity in Background thread - with a return value

texts:
I have written this class to check internet connectivity on Android, while there are many instances when WiFi is connected is taken as an implication that internet is connected as well. I wanted to have a method which actually checks if internet is connected. One issue was to run the internet code in a background thread and while doing so - return a value, so I used a future task, below is the code:

public class CheckWiFi {
public static String TAG = "Check Internet";

public static boolean isWiFiConnected(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    return ni != null;
}

public static Boolean isNetworkConnected(Context ctx) {

    ExecutorService service = Executors.newFixedThreadPool(10);

    FutureTask<Boolean> task1 = new FutureTask<Boolean>(new CheckConnection(ctx));
    service.submit(task1);
    try {
        return task1.get();
    } catch (java.util.concurrent.ExecutionException ex) {
        ex.printStackTrace();
        return false;
    } catch (InterruptedException ex) {
        ex.printStackTrace();
        return false;
    }

}

public static class CheckConnection implements Callable {
    Context ctx;

    public CheckConnection(Context ctx) {
        this.ctx = ctx;
    }

    @Override
    public Boolean call() {
        if (isWiFiConnected(ctx)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection)
                        (new URL("http://clients3.google.com/generate_204").openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.e(TAG, "Error checking internet connection", e);
            }
        } else {
            Log.d(TAG, "No network available!");
        }
        return false;
    }

}

}

What are your thoughts about it?

Also that I am getting a warning:

Unchecked assignment: 'network.CheckWiFi.CheckConnection' to 'java.util.concurrent.Callable<java.lang.Boolean>'


texts:
Implementation:

This works based on this observation:

$$a^n = a^{n/2} * a^{n/2}$$

BigInteger Pow(BigInteger x,int n)
{
    if(n == 0) return 1;
    else if(n % 2 == 0) {
        var val = Pow(x,n/2);
        return val * val;
    }
    else return x * Pow(x,n-1);
}

How can I improve this? Is there a more efficient algorithm?


texts:
I'm still learning c#, and I need my code to only run less than 2 seconds to be accepted.
I have a look and say sequence and after the last number is found, the code sums it all up, and it takes so long if the element in the sequence is big.

Example:

Input: 2

Output: takes less than a second

Input: 50

Output: takes 4 or so seconds.

I have only tried doing is changing foreach loops into for loops. I don't know what else to change.
Anyone can point me in the right direction? Thanks all.

namespace SumOfLookAndSaySequence
{
    class Program
    {

        static void Main(string[] args)
        {
            string input = Console.ReadLine();

            if (Int32.TryParse(input, out int nthTerm) && nthTerm > 0)
            {
                string lastSequence = GetSequence(nthTerm).Last();
                char[] digits = lastSequence.ToCharArray();
                int[] itemToSum = new int[digits.Length];
                int result = 0;
                for(int i = 0; i < digits.Length; i++)
                {
                    itemToSum[i] = int.Parse(digits[i].ToString());
                    result = result + itemToSum[i];
                }
                Console.WriteLine(lastSequence);
                Console.WriteLine(result);
            }

        }

        static IEnumerable<string> GetSequence(int nthTerm)
        {
            List<string> sequence = new List<string>() { "1" };

            for(int i = 1; i < nthTerm; i++)
            {
                sequence.Add(GetNextNumberSequence(sequence[i - 1]));
            }

            return sequence;
        }

        static string GetNextNumberSequence(string number)
        {
            StringBuilder stringBuilder = new StringBuilder();

            int count = 1;
            char digit = number[0];

            for(int i = 1; i < number.Length; i++)
            {
                if(number[i] == digit)
                {
                    count++;
                }
                else
                {
                    stringBuilder.Append(string.Concat(count, Char.GetNumericValue(digit)));

                    count = 1;
                    digit = number[i];
                }
            }

            stringBuilder.Append(string.Concat(count, digit));

            return stringBuilder.ToString();
        }
    }
}


texts: Determining a digit on a given position in the A002260 sequence

texts:
This is my solution to this SO question, which can formulated as

take the sequence A002260, i.e., 1, 1, 2, 1, 2, 3, ...
concatenate all its digits
find the digit at a given position (1-based)]

What bothers me is that my solution is rather complicated and fails near Long.MAX_VALUE due to overflow. I also wonder if this could be done in an error-proof way, since I ran through quite some off by one errors.
There's the code, a test and a demo.
public class Ogen {
    /** The length of the number {@code n} (in decimal representation) */
    int length(long n) {
        return LongMath.log10(n, RoundingMode.DOWN) + 1;
    }

    /**
     * The total number of digits in the sequence {@code 1, 2, ..., n}, i.e.,
     * the sum of {@code length(i)} of all positive {@code i} up to and including {@code n}.
     * */
    long cumulativeLength(long n) {
        if (n==0) return 0;
        long result = 0;
        final int maxLength = length(n);
        for (int numberLength=1; numberLength<=maxLength; ++numberLength) {
            // all numbers between min and max have the length numberLength
            final long min = LongMath.pow(10, numberLength-1); // 1, 10, 100, ... highest power of 10 not greater than n
            final long max = Math.min(10*min - 1, n); // 9, 99, 999, ..., n
            final long countOfDifferentNumbers = max - min + 1;
            result += numberLength * countOfDifferentNumbers * 1;
        }
        return result;
    }

    /**
     * The total number of digits in the sequence {@code 1, 1, 2, 1, 2, 3, ..., 1, ..., n}, i.e.,
     * the sum of {@code cumulativeLength(i)} of all positive {@code i} up to and including {@code n}.
     */
    long doublyCumulativeLength(long n) {
        if (n==0) return 0;
        long result = 0;
        final int maxLength = length(n);
        for (int numberLength=1; numberLength<=maxLength; ++numberLength) {
            // all numbers between min and max have the length numberLength
            final long min = LongMath.pow(10, numberLength-1); // 1, 10, 100, ... highest power of 10 not greater than n
            final long max = Math.min(10*min - 1, n); // 9, 99, 999, ..., n
            final double avg = 0.5 * (min+max);
            final double averageNumberOfOccurrences = n - avg + 1;
            final long countOfDifferentNumbers = max - min + 1;
            result += numberLength * countOfDifferentNumbers * averageNumberOfOccurrences;
        }
        return result;
    }

    /**
     * The biggest number {@code n} such that the sequence {@code 1, 1, 2, 1, 2, 3, ..., 1, ..., n} ends before
     * position {@code pos}, i.e., such that {@code doublyCumulativeLength(n) < pos}.
     */
    long fullSequenceBefore(long pos) {
        long lo = 0;
        // find upper bound
        long hi = (long) (Math.sqrt(pos)) / 2;
        while (doublyCumulativeLength(hi) < pos) {
            lo = hi;
            hi += 1 + (hi >> 4);
        }
        // binary search
        while (hi>lo+1) {
            final long mid = (hi+lo) / 2;
            if (doublyCumulativeLength(mid) >= pos) {
                hi = mid;
            } else {
                lo = mid;
            }
        }
        assert doublyCumulativeLength(lo) < pos;
        assert doublyCumulativeLength(lo+1) >= pos;
        return lo;
    }

    public char digitAt(long pos) {
        pos -= doublyCumulativeLength(fullSequenceBefore(pos));
        long lo = 0;
        long hi = pos;
        while (hi>lo+1) {
            final long mid = (hi+lo) / 2;
            if (cumulativeLength(mid) >= pos) {
                hi = mid;
            } else {
                lo = mid;
            }
        }
        pos -= cumulativeLength(lo);
        return String.valueOf(lo+1).charAt((int) pos - 1);
    }
}


texts:
Project Euler #7:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?

Here is my solution:
public class PrimeFinder {

    public static void main(String[] args) {
        long time = System.nanoTime();
        int result = getNthPrime(10001);
        time = System.nanoTime() - time;
        System.out.println("Result: " + result
                + "\nTime used to calculate in nanoseconds: " + time);
    }

    private static int getNthPrime(int n) {
        int max = (int) (1.4 * n * Math.log(n));
        boolean[] isPrimeArray = new boolean[max + 1];
        for (int i = 2; i <= max; i++) {
            isPrimeArray[i] = true;
        }
        for (int i = 2; i * i <= max; i++) {
            if (isPrimeArray[i]) {
                for (int j = i; i * j <= max; j++) {
                    isPrimeArray[i * j] = false;
                }
            }
        }
        // Find the nth prime
        int nthPrime = 0;
        int index = 0;
        for(boolean isPrime : isPrimeArray) {
            if(isPrime) {
                nthPrime++;
            }
            if(nthPrime == n) {
                return index;
            }
            index++;
        }
        throw new IllegalArgumentException("n is not valid");
    }
}

It simply performs a sieve, and then find the 10001st true.
Output:

 Result: 104743
 Time used to calculate in nanoseconds: 13812289

Questions:

This obviously is not efficient. How can I improve it?
Are there any bad practices?


texts: nginx serve static - images, js, css and proxy node.js server

texts:
I'm building a server for serving static content, and uploading images there.

Everything works, but I'm not expert in nginx and server configuration, so maybe someone sees some improvements for this.

Here is my nginx config:

server {
    listen 80;

    server_name localhost;

    location / {
        proxy_pass http://localhost:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    location ~ \.(gif|jpg|png)$ {
        gzip_static off;
        root /var/www/assets;
    }

    location ~ \.(css|js)$ {
        gzip_static on;
        root /var/www/assets;
    }
}

Users will upload and save images on this server, and I added node.js server for that with 1 view: app.get('/upload', function (req, res) {...});

That's why I'm proxying server here:

location / { proxy_pass http://localhost:8080; ....

location ~ \.(gif|jpg|png)$ {`

I will serve images on this server
location ~ \.(css|js)$ {

I will serve js & css already gzipped on this server


texts:
I have created this model for Codeigniter. It's working fine, but I need to know if it can be more optimized.

class Basic_Function_Model extends CI_Model
{

    var $msg_invalid_array;
    var $msg_no_table;

    function __construct()
    {
        parent::__construct();
        $this->msg_invalid_array    =   "Data must be provided in the form of array";
        $this->msg_no_table         =   "Table does not exist in database";
        $this->load->database();
    }

    public function insertInDatabase($table, $insertData, $mode = "single")
    {
        if( !is_array($insertData) ) {
            return $this->msg_invalid_array;
        }

        if( !$this->validateTable($table) ) {
            return $this->msg_no_table;
        }

        if( $mode == "batch" ) {
            return $this->db->insert_batch($table, $insertData);
        } else {
            $this->db->insert($table, $insertData);
            return $this->db->insert_id();
        }
    }

    public function updateInDatabase($table, $updateData, $conditionData)
    {
        if( !is_array($updateData) || !is_array($conditionData) ) {
            return $this->msg_invalid_array;
        }

        if( !$this->validateTable($table) ) {
            return $this->msg_no_table;
        }

        if( $this->db->update($table, $updateData, $conditionData) )
            return $this->db->affected_rows();
        else
            return false;
    }

    public function deleteFromDatabase($table, $conditionData)
    {
        if( !is_array($conditionData) ) {
            return $this->msg_invalid_data;
        }

        if( !$this->validateTable($table) ) {
            return $this->msg_no_table;
        }

        return $this->db->delete($table, $conditionData);
    }

    public function insertOnDuplicateKeyUpdate($table, $tableData)
    {
        if( !is_array($tableData) ) {
            return $this->msg_invalid_data;
        }

        if( !$this->validateTable($table) ) {
            return $this->msg_no_table;
        }

        foreach( $tableData as $column => $value )
        {
            $columnNames[] = $column;
            $insertValues[] = "'".$value."'";
            $updateValues[] = $column." = '".$value."'";
        }
        $this->db->query("insert into $table(".implode(', ', $columnNames).") values(".implode(', ', $insertValues).") on duplicate key update ".implode(', ', $updateValues));
        return $this->db->insert_id();
    }

    private function validateTable($tableName)
    {
        $result = $this->db->list_tables();

        foreach( $result as $row ) {
            if( $row == $tableName )    return true;
        }
        return false;
    }
}


texts: Querying a list of jobs on a server using EJBs

texts:
Inspired by this question, I have a Java Enterprise application running in Glassfish 2.1 and a Java SE client that communicates with the server application.

For this I have a bean that maintains a collection of jobs that is set by the server and the client then asks if his job is in the current list of jobs known to the bean.

I want to ask if this code is good.

The client uses this interface:

import javax.ejb.Remote;
@Remote
public interface GeneratorCancelledRemote {
    public boolean isJobCancelled(String jobId);
}

The server uses this interface:

import java.util.Collection;
import javax.ejb.Local;
@Local
public interface GeneratorCancelledLocal {
    public void setJobs(final Collection<String> jobs);
}

And here's the implementation:

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import javax.ejb.Stateless;
@Stateless
public class GeneratorCancelled implements GeneratorCancelledLocal, GeneratorCancelledRemote {
    private Collection<String>  jobs;
    public void setJobs(final Collection<String> jobs) {
        this.jobs = Collections.synchronizedSet(new HashSet<String>());
        this.jobs.addAll(jobs);
    }
    @Override
    public boolean isJobCancelled(final String jobId) {
        return jobs != null && jobs.contains(jobId);
    }
}

Obviously access to the collection of jobs has to be synchronized somehow. Is the use of Collections.synchronizedSet the best way to do this? The EJB gurus around here shun on the use of synchronized in an EE context.

I found this (in German), which also explains that synchronized is not allowed in EJB.


texts: BF interpreter in Python that uses recursion to handle loops

texts:
I wrote a Brainfuck interpreter in Python and I'm wondering how to simplify it.

I handle separately loop commands and the others. A recursive function deals with loops.

import sys
array = [0] # byte array
ptr = 0 # data pointer

Read and execute commands except loop

def readNoLoop(char):
  global ptr
  # Increment/Decrement the byte at the data pointer
  if char=='+':
    array[ptr] += 1
  elif char=='-':
    array[ptr] -= 1
    if array[ptr] < 0:
      raise ValueError("Negative value in array")
  # Increment/Decrement the data pointer
  elif char=='>':
    ptr += 1
    while(ptr>=len(array)-1):
      array.append(0)
  elif char=='<':
    ptr -= 1
    if ptr < 0:
      raise ValueError("Negative value of pointer")
  # Output the byte at the data pointer
  elif char=='.':
    sys.stdout.write(chr(array[ptr]))
  # Store one byte of input in the byte at the data pointer
  elif char==',':
    array[ptr] = ord(sys.stdin.read(1))

Recursive function to deal with loops

def interpret(charChain):
  it = 0
  loopBegin = []
  while(it<len(charChain)):
    if charChain[it]=='[':
      loopBegin.append(it)
    elif charChain[it]==']':
      subChain = charChain[loopBegin[-1]+1:it]
      while(array[ptr]>0):
        interpret(subChain)
      loopBegin.pop()
    else:
      readNoLoop(charChain[it])
    it+=1

Main

if __name__ == "__main__":
  # Brainfuck program to print "Hello World!"
  code = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'
  try:
    interpret(code)
  except:
    raise

My main concern is to know if it's possible to have a simpler code without recursion.


texts: LPTHW - ex48 - Handling exceptions and unit testing

texts:
This is my solution to the exercise 48 of Learn Python the hard way by Zed Shaw. Please visit the link for testing suite and requirements.

I'm worried about my the word banks I have created (COMPASS, VERBS, etc...) as this seems a duplication from the testing code.

I'm also afraid my handling might have gone overboard as all I needed it for was finding out which string items could be converted to integers.

1 COMPASS= ['north','south','east','west']$
2 VERBS = ['go', 'kill', 'eat']$
3 STOPS = ['the', 'in', 'of']$
4 NOUNS = ['bear', 'princess']$
5   $
6 import string$
7 def scan(sentence):$
8     action = []$
9     #TODO: it seems there might be a way to  combine these if statments$
10     for word in sentence.split(' '):$
11         lword = string.lower(word)$
12         try:$
13             if lword in COMPASS:$
14                 action.append(('direction', word))$
15             elif lword in VERBS:$
16                 action.append(('verb', word))-$
17             elif lword in STOPS:$
18                 action.append(('stop', word))$
19             elif lword in NOUNS:$
20                 action.append(('noun', word))$
21             elif int(lword):$
22                 action.append(('number', int(word)))$
23         except:$
24             action.append(('error', word))$
25     return action$
26 $


texts:
I wrote this Sundaram's sieve in Coffeescript to quickly generate prime numbers up to limit:

sieve_sundaram = (limit) ->
    numbers = (n for n in [3...limit+1] by 2)
    half = limit / 2
    start = 4

    for step in [3...limit+1] by 2
        for i in [start...half] by step
            numbers[i-1] = 0
        start += 2 * (step + 1)

        if start > half
            result = (n for n in numbers when n > 0)
            result.shift 2
            return result

See equivalent Javascript code.

Is it possible to rewrite it in functional paradigm? I'm concerned mainly with the need to change the numbers array and increment start variable. If external library (like underscore.js) is needed, it's acceptable. JavaScript solutions are also acceptable.


texts: Improving performance in generating an Excel file

texts:
I am using this code to write more than 170,000 rows to an Excel document. All in all, the file generation process takes about 3 minutes total. (I've already shaved off about ten minutes by shaving off overhead in the form of Apache POI and an unnecessary ArrayList) I'd like to shave off some more time, but I'm currently out of ideas.

public File generateDelimitedFile(String sql, String outputFilename, String delimiter, String bodyStringDelim) throws SQLException, IOException{
    File output = new File(outputFilename);

    try (

        Connection connection = DriverManager.getConnection(connectionUrl);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql)
    ) {

        resultSet.setFetchSize(excelFetchSize);
        ResultSetMetaData meta = resultSet.getMetaData();
        int columnCount = meta.getColumnCount();

        StringBuilder headerBuilder = new StringBuilder();
        for (int i = 1; i < columnCount + 1; i++ ) {
            String name = meta.getColumnName(i);
            headerBuilder.append(name);
            if (i != columnCount) {
                headerBuilder.append(delimiter);
            }
        }
        FileUtils.writeStringToFile(output, headerBuilder.toString(), true);

        while(resultSet.next()) {
            StringBuilder lineBuilder = new StringBuilder();

            for (int column = 1; column <= columnCount; column++) {
                String value = resultSet.getString(column);
                if (value != null) {
                    if(bodyStringDelim != null){
                        lineBuilder.append(bodyStringDelim);
                    }
                    lineBuilder.append(value);
                    if(bodyStringDelim != null){
                        lineBuilder.append(bodyStringDelim);
                    }
                }

                if (column != columnCount) {
                    lineBuilder.append(delimiter);
                }
            }

            FileUtils.writeStringToFile(output, lineBuilder.toString(), true);
        }
        logger.info("Writing data to file");

    } catch (SQLException ex) {
        logger.error("Error generating file from SQL", ex);
        throw ex;
    } catch (IOException ex) {
        logger.error("Error writing file", ex);
        throw ex;
    }

    return output;
}


texts: Fetching busy students and their latest product

texts:
I use SQL Server 2014 and I have three tables:

Student (ID, Name, Age)
Product  (ID, Name)
StudentProduct (StudentID, ProductID, Date)

TABLE Student(ID, Name, Age) >>
ID  Name    Age
1   Adam    20
2   Bob     17
3   Ben     18
4   Joseph  18
5   Jon     18

TABLE Product (ID, Name) >>
ID  Name
1   SQLServer
2   Visual Studio
3   Idea
4   Eclipse

TABLE StudentProduct (StudentID, ProductID, Date) >>
StudentID   ProductID     Date
1           1             25.05.2016 0:00:00
1           4             26.06.2016 0:00:00
1           3             27.06.2016 0:00:00
1           2             28.06.2016 0:00:00
2           1             29.07.2016 0:00:00

I've written a query to get all students who meet these criteria

Are older than 19
Participate in developing more than 3 products

Both criteria should be checked in a single query.

The desired result should then contain the

Age of the student
Name of student
Name of the last developed product (using StudentProduct.Date)

Result should be:

Age   StudentName      ProductName
20    Adam             Visual Studio

My query is:

select e.age, e.name ,
(select top 1 p.Name from Product p
inner join StudentProduct peOut on p.ID = peOut.ProductID
where peOut.StudentID = e.ID
order by peOut.Date desc)
from Student e where e.age > 19
and exists (select pe.StudentID, count(1) from StudentProduct pe
where pe.StudentID = e.ID group by pe.StudentID
having count(1) > 3)

How can I improve the efficiency of my query?


texts:
I have Products table which looks like this:

I have some data in this table and I want to filter it depending on this columns (Filtering with columns type of string isn't problem). For this I have the code (in ASP.NET Core Web API Project) shown below. I know it's not a good approach. I have another table which has more foreign keys, so it will be more difficult to do this kind of work on it.

In SearchProduct action method I am getting the product object, which properties have specific values. For example, If Name="Box", then I want to get products from the product list, which Name is "Box" too.

The consumer of this service is WPF application, where I have the window, where the controls (textboxes and comboboxes{ for productType and ProductUnit}) are placed and the user will be able to search data with any criteria. For example, if he wants to search only with Name, he will write something only in Name textbox. If he wants to search product which name is "Box" and also the productType is "A", then he will write "Box" in name textbox and will choose A type in comboBox.

P.S When product is added in this table, if user doesn't write anything in the Name textbox for example, the value of Name will be "" and not null.

    [HttpPost("SearchProduct")]
    public IEnumerable<Product> SearchProduct([FromBody]Product product)
    {
        IEnumerable<Product> data;

        if(product.ProductTypeID != null && product.ProductUnitID != null)
        {
            data = _context.Products.Where(x =>
          x.Name.Contains(product.Name) &&
          x.Code.Contains(product.Code) &&
          x.Barcode.Contains(product.Barcode) &&
          x.InnerCode.Contains(product.InnerCode) &&
          (x.ProductTypeID == product.ProductTypeID &&
          x.ProductUnitID == product.ProductUnitID))

           .Include(x => x.ProductType)
           .Include(x => x.ProductUnit);
        }
        else if(product.ProductTypeID == null && product.ProductUnitID == null)
        {
            data = _context.Products.Where(x =>
        x.Name.Contains(product.Name) &&
        x.Code.Contains(product.Code) &&
        x.Barcode.Contains(product.Barcode) &&
        x.InnerCode.Contains(product.InnerCode) ||
        (x.ProductTypeID == product.ProductTypeID &&
        x.ProductUnitID == product.ProductUnitID))

         .Include(x => x.ProductType)
         .Include(x => x.ProductUnit);
        }
        else if(product.ProductTypeID != null)
        {
            data = _context.Products.Where(x =>
        x.Name.Contains(product.Name) &&
        x.Code.Contains(product.Code) &&
        x.Barcode.Contains(product.Barcode) &&
        x.InnerCode.Contains(product.InnerCode) &&
        x.ProductTypeID == product.ProductTypeID)

         .Include(x => x.ProductType)
         .Include(x => x.ProductUnit);
        }
        else
        {
            data = _context.Products.Where(x =>
        x.Name.Contains(product.Name) &&
        x.Code.Contains(product.Code) &&
        x.Barcode.Contains(product.Barcode) &&
        x.InnerCode.Contains(product.InnerCode) &&
        x.ProductUnitID == product.ProductUnitID)

         .Include(x => x.ProductType)
         .Include(x => x.ProductUnit);
        }

        return data;
    }


texts: Search for data and order by priority efficiently

texts:
I have a search-function, that searches for specific data within a huge Object.

Depending on how good a found entry matches, the finding gets "matchPoints" (or "Priority")

var findings = {};
for(var element in hugeObject){
    var points = getMatchPoints( inputToSearchFor, hugeObject[element] );
    if( points !== 0 ){    //It matched. At least a bit.
        findings[ points ] = element;
    }
}

Now I have all Elements, that somehow matched, within findings.

The function which implements this has to return an Array of all these elements. The most relevant result on the first place.

I currently use this for sorting:

var priorities = Object.keys(findings);    //Get the matchpoints of all findings
priorities.reverse(); //Sort with reverse order (highest priority / most matchpoints first)

var result = [];
for(var i=0; i<priorities.length; i++){
    result.push( findings[i] );
}
return result;

I have several issues with this code:

It is inefficient and probably very slow
The .reverse() function sorts the priorities alphabetically, not numerically
If 2 findings have the same amount of matchpoints, the findings-entry gets overwritten. So the result isn't even valid.

How can I solve this problem in an efficient and elegant way?

Edit: I should mention, that although the object where I search is very big, I only get few valid results which matchPoints > 0. In fact, most of the time I'll get only 2-3 matches at all.


texts: General feedback on Conway's Game of Life implementation

texts:
I've just written an implementation of Conway's Game of Life as an exercise and I'd love to get some feedback on how I can improve this program and hopefully my style in general.

I've tested the code in Python 2.7.3. It requires the PyPNG module to render the state of the simulation.

"""Simulate Conway's Game of Life.

The world is finite. Cells at its border always stay dead.
The frames of the simulation are saved as .png files.
"""

from numpy.random import random_integers
from png import from_array

DEAD = 1
ALIVE = 0

def saveAsImage(array, number):
    """Save the array to a .png file.

    The files are saved as 1-bit greyscale (black/white).
    """

    image = from_array(array, 'L', {'bitdepth': 1})
    image.save('image%03i.png' % number)

def simulate(world, simulationLength):
    """Simulate a certain number from steps starting from a given state.

    The frames are saved as .png images in the current working directory.

    Parameters:
        world: The initial state of the world as a two-dimensional numpy
               array in which world[y][x] describes the state of the
               cell at position x, y
        simulationLength: The number of simulated steps,
                          simulationLength + 1 images are created.
    """

    # Retrieve the dimensions of the world
    worldHeight = len(world)
    worldWidth = len(world[0])

    # Make sure there are no living cells on the border.
    world[0] = DEAD  # top
    world[worldHeight - 1] = DEAD  # bottom
    for y in xrange(1, worldHeight - 2):
        world[y][0] = DEAD  # left
        world[y][worldWidth - 1] = DEAD  # right

    saveAsImage(world, 0)

    for frame in xrange(1, simulationLength + 1):
        # Simulate simulationLength frames

        nextWorld = world.copy()

        for y in xrange(1, worldHeight - 1):
            for x in xrange(1, worldWidth - 1):
                # Iterate over all cells within the border

                neighbors = [world[y - 1][x - 1],
                             world[y - 1][x],
                             world[y - 1][x + 1],
                             world[y][x - 1],
                             world[y][x + 1],
                             world[y + 1][x - 1],
                             world[y + 1][x],
                             world[y + 1][x + 1]]
                livingNeighbors = sum(neighbor == ALIVE
                                      for neighbor in neighbors)

                if world[y][x] == ALIVE:
                    # Living cells with less than 2 or more than three
                    # living neighbors die
                    if livingNeighbors not in (2, 3):
                        nextWorld[y][x] = DEAD
                else:
                    # Dead cells with three living neighbors are reborn
                    if livingNeighbors == 3:
                        nextWorld[y][x] = ALIVE

        world = nextWorld

        saveAsImage(world, frame)

if __name__ == '__main__':
    worldWidth = 100
    worldHeight = 100

    # Populate the world with random living/dead (50% each) cells
    world = random_integers(0, 1, (worldHeight, worldWidth))

    simulate(world, 50)


texts: ToString() and AddString() method without using .Net Collections

texts:
I was asked to answer the following question before setting up a phone interview, but they said my code wasn't detailed enough.

Question:

  Without using any of the .NET Collection or Linq libraries (i.e.
  without using List), implement a ListOfStrings object that
  contains a set of strings. This object has the following methods:
  Add(string) - inserts a string to the end of the list ToString() -
  Returns the list as a comma separated string.

  Example Usage:

ListOfStrings list = new ListOfStrings(); // set is empty
list.Add("abc"); // set is "abc"
list.Add("xyz"); // set is now "abc", "xyz"
list.Add("123"); // set is now abc", "xyz", "123"
list.ToString(); // Should return "abc,xyz,123"

  Ideally, this code should be able to handle large numbers of items.

Answer:

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                ListOfStrings ls = new ListOfStrings();
                ls.Add("test1");
                ls.Add("test2");
                ls.Add("122");
                ls.Add("");
                ls.ToString();
                Console.WriteLine(ls.ToString());
            }
        }
    }

    public class ListOfStrings
    {
        private string ListOfString;

        public ListOfStrings()
        {
            ListOfString = null;
        }
        public string Add(string input)
        {
            if (input != string.Empty)
            {
                ListOfString = ListOfString == null ? input : ListOfString + "," + input;
            }
            return ListOfString;
        }

        public string ToString()
        {
            return ListOfString;
        }
    }
}

Please let me know feedback on the code.


texts: Reversing a string in-place - recursion or iteration?

texts:
I am practicing my recursion skills as I think I am really weak in this area.

I have written the following Java class whose purpose is to reverse a string but to do it 'in-place' - i.e. no additional arrays. I have two implementations - one iterative and one recursive. Why would I choose one implementation over the other?

Also, does my recursive solution use tail call optimization?

public class TestRecursion {

    public static void reverseIter(char[] in) {
        int start = 0;
        int end = in.length - 1;

        while(start < end) {
            swap(start, end, in);
            start ++;
            end--;
        }
        System.out.println("iteration result: "+in);
    }

    public static char[] reverseRecur(char[] in, int start, int end) {
        if (end < start) return in;
        else {
            swap(start, end, in);
            return reverseRecur(in, ++start, --end);
        }
    }

    private static void swap(int start, int end, char[] input) {
        char c1 = input[start];
        char c2 = input[end];

        input[start] = c2;
        input[end] = c1;
    }

    public static void main(String[] args) {
        char[] input = "testy".toCharArray();
        reverseIter(input);
        char[] input2 = "testy".toCharArray();
        char[] out = reverseRecur(input2, 0, input2.length-1);
        System.out.println("recursive result: "+out);
    }
}


texts: Replace template based on placeholder values

texts:
I have wrote a PHP template code to replace placeholders based on the value provided within the placeholder. For example the content may have placeholders like
{ITEM-100} {ITEM-110} and I want to replace them with a text made by the details fetched from db with item_id=100 or item_id=110.

The code below id working fine, and I would like to get suggestions to improve the performance of the code. Thanks in advance.

$content = 'Here is the item list {ITEM-100}  {ITEM-110}  {ITEM-200}';

if(preg_match_all('/{ITEM-.*?}/', $content, $matches))
{
    foreach($matches[0] as $v)
    {
        $value = trim($v, '{}');
        $val_chunk = explode('-', $value);
        if(isset($val_chunk[1])){
            $item_card = get_item_card($val_chunk[1]);
            $content = str_replace($v, $item_card, $content);
        }
    }
}

echo $content;


texts:
I have this code that works, but I'm sure that it can be done better, any suggestions?

    Dictionary<string, StrainGroupings> GetOperationStrainGroupings(string locale)
    {
        var result = new Dictionary<string, StrainGroupings>();

        try
        {
            Open();
            setDatabaseTables();
            result = Connection.Table<StrainGroupings>()
                .Where(sg => sg.Locale == locale)
                .Join(Connection.Table<OperationStrainGroups>(),
                    strainGrouping => strainGrouping.StrainGroupName,
                    operationStrainGroup => operationStrainGroup.StrainGroupName,
                    (strainGrouping, operationStrainGroup) => new { Name = operationStrainGroup.OperationName.Distinct(), sg = strainGrouping })
                .AsEnumerable()
                .ToDictionary(row => row.Name.ToString(), row => row.sg);
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Error retrieving operation strain groupings", ex);
        }
        finally { Close(); }
        return result;
    }

It is part of a method that returns a Dictionary(). The idea is return result, as it is dealing with a sQLite Database, it is in a try/catch/finally. That's why I'm not returning result directly, I need to close the database first and maybe dealing with exceptions.


texts:
A triangle needs a good foundation. Every row in the triangle is derived from the sum of the two values below it. However, there can be no repeated values, if a value shows up more than once the triangle crumbles. Find the base which minimises the value in the top of the triangle satisfying the condition of no duplicates.

Source

Example:

      20
    8   12
 [3]   5   7
1   2  [3]  4

Here 3 occurs twice, so the triangle is invalid

The base \$n\$ can be of any size \$n > 0\$ with

solve(1) = 1, solve(2) = [1, 2] = 3, solve(3) = [2, 1, 4] = 8

I would like suggestions on how I can improve:

The code style or best practices, so the code is easy to read.
The algorithm/constraints, I'm pretty sure that the loops can be made tighter, so not as many numbers have to be checked, but I can't figure out what the cut off is.
Is there a better way to implement the base size without hard-coding extra nested loops, as this doesn't seem very scalable?

import java.util.*;

public class spaceship {
    public static void main(String[] args) {
        long start = System.nanoTime();
        spaceship kling = new spaceship();
        kling.solveAll();
        System.out.println("Took: " + (System.nanoTime() - start) / 1000000 + "ms");
    }

    public void solveAll() {
        int len = 6;
        int bestFound = 400; //definitely big enough from previous tests
        int res = bestFound;
        int[] best = new int[len];
        int[] x = new int[len];
        int[] co = new int[] { 1, 1, 1, 1, 1, 1 };

        for (int a = 1; co[0] * a < bestFound; a++) {
            long beg = System.nanoTime();
            for (int b = 1; co[1] * b < bestFound; b++) {

                for (int c = 1; co[2] * c < bestFound; c++) {
                    for (int d = 1; co[3] * d < bestFound; d++) {
                        //for (int e = 1; co[4] * e < bestFound; e++) {
                            //for (int f = 1; co[5] * f < bestFound; f++) {

                                x = new int[] { a, b, c, d,/* e, f */};
                                res = solve(x);

                                if (res != -1 && res < bestFound) {
                                    System.out.print(Arrays.toString(x));
                                    System.out.println(":\t" + res);
                                    bestFound = res;
                                    best = x;
                                }
                            //}
                        //}
                    }
                }
            }
            System.out.println((System.nanoTime() - beg) / 1000000 + "ms");
        }

        System.out.println("The best result possible is:");
        System.out.println(bestFound);
        System.out.println(Arrays.toString(best));

    }

    public int solve(int[] in) {
        Set<Integer> data = new HashSet<>();
        // check input for duplicates
        // could be done in loops
        for (int a : in) {
            if (data.contains(a))
                return -1;
            data.add(a);
        }

        int size = in.length;
        int[][] arr = new int[size][size];
        arr[0] = in;
        // first row is the input
        // every row after is the sum of the two elements below it
        // ie pascal's triangle with outermost values ignored

        for (int i = 1; i < size; i++) {
            for (int j = 0; j < size - i; j++) {
                int a = arr[i - 1][j] + arr[i - 1][j + 1];
                if (data.contains(a))
                    return -1;
                data.add(a);
                arr[i][j] = a;
            }
        }

        // return final value, our result if no duplicates occur during the
        // process
        return arr[size - 1][0];
    }
}


texts:
I have a function that takes a four-dimensional NumPy array M and, for each value i of its second index, takes all of M without the i-th "column", evaluates the product over all other columns, and stacks the results so that the array returned has the same shape as M.

In other words, what I want to evaluate is:

$$R_{ijkl} = \prod_{j^l \ne j} M_{ij^{l}kl}$$

My main concern is performance: M's shape is usually something similar to (16,8,1000,255) and this function call takes up the great majority of my program's execution time.

import numpy as np

def sliceAndMultiply(M):
    # create masks
    masks = [ range(i) + range(i+1, M.shape[1]) for i in range(M.shape[1]) ]
    # evaluate products over masks and stack them
    return np.stack([ np.prod(M[:,m,:,:], axis=1) for m in masks ], axis=1)

M = np.random.rand(16,8,1000,255)
R = sliceAndMultiply(M)

Another variant I tried is:

def sliceAndMultiply(M):
    return np.stack([ np.prod(np.delete(M, j, axis=1), axis=1) \
                      for j in range(M.shape[1]) ], axis=1)

but the performance of these two functions is basically the same.


texts: HTML and JS to dynamically load, refresh, and execute JavaScript from external file

texts:
The following code is designed to load and refresh JavaScript code from an external file sandbox.js and allow it to be refreshed dynamically and executed without reloading the entire page. The sandbox.js file is assumed to contain a function sandbox() which may contain arbitrary JavaScript code. As the title within the code below suggests, it's a sandbox intended for rapid testing of JavaScript code, where I can just save code in the IDE and execute the updated code immediately.

The most current version of this code is available here.

<!DOCTYPE html>

        <title>Sandbox</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="/JSDev/styles.css">

Sandbox

        <button id="refreshButton" onclick="loadScript('sandbox.js')">
            Refresh script
        </button>
        <button id="runButton" onclick="sandbox()">
            Run script
        </button>

        <button id="refreshRunButton" style="font-weight:bold"
                onclick="document.getElementById('refreshButton').click();
                         sandbox();">
            Refresh and run script
        </button>


texts: D3.js interpolating line on circumference of circle

texts:
For now, I've tried to make a line rotate on the path of a circle, but used setInterval multiple times and there might be other ways of achieving the same.

I would like your thoughts before I add two more circles just like in this webpage.

var width = 300;
var height = 300;
var body = d3.select("body")
var svg = body.append("svg")
        .attr("width",width)
        .attr("height",height)
        .attr("fill","blue")

var rad = Math.PI;

var circlePath = svg.append("path")
                    .attr('d', "M70,100a30,30 0 1,0 60,0a30,30 0 1,0 -60,0")
                    .attr('fill', 'none')
                    .attr('stroke', 'steelblue' )

// var path  = <path d="M70,100a30,30 0 1,0 60,0a30,30 0 1,0 -60,0"/>

console.warn(circlePath.node());
var path1 = circlePath.node();

var myLine = svg.append('line')
                .attr('x1', 100)
                .attr('y1', 100)
                .attr('x2', function(){return path1.getPointAtLength(l).x})
                .attr('y2', function(){return path1.getPointAtLength(l).y}  )
                .attr('stroke', "red" )
                .attr('stroke-width',3)
var l = 1
setInterval(function(){
        myLine.transition()
                    .duration(20)
                    .attr('stroke', "blue")

                    .attr('x2', function(){return path1.getPointAtLength(l).x})
                .attr('y2', function(){return path1.getPointAtLength(l).y})

                .each("end", endAnimationfunc)

}, 5);
setInterval(function(){
    if(l<path1.getTotalLength()){
        l=l+1
    }
    else{
        l = 1
    }
},10)

var endAnimationfunc = function(){
    d3.select(this)
        .transition()
        .attr('x2', function(){return path1.getPointAtLength(l).x})
        .attr('y2', function(){return path1.getPointAtLength(l).y})

}

function translateAlong(path1){
    var l = path1.getTotalLength();
    // console.warn(l);
    return function(){
        // console.warn(d,i,a);

            var p = path1.getPointAtLength( l );
            console.log(p);

            return  "translate("+p.x + ","+p.y +")";

    }
}
<body></body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


texts:
I'm writing a program that has to check which are the two largest three digit numbers that are missing from a text file. I'm writing this in C++ and I'm trying to solve the mystery in a while loop. How can I "move" the search back to the beggining of the text file? More explicit: if the checking is now around the middle of the text file and I have to check at this point of time again all the numbers from the beggining of the file, how can I do this? I'm attaching only the code part which contains the while.

    while(!in.eof()&&first_number>=100&&second_number>=100)
    {   in >> number_to_compare;

        if(first_number==number_to_compare)
        {   first_number--;
            if (first_number == second_number)
                first_number--;
        }
        else if(second_number==number_to_compare)
        {   second_number--;
            if (second_number == first_number)
                second_number--;
        }
    }

I would need in bouth of the mainif operators cases a line code that makes the search to start again from the beginning of the text file. I'm just starting to learn programming, I don't know any OOP.
I tried also something similar with the logic of bubble sort algorithm (loop in loop) but I think that it's not working because the file reading will not start again from the beginning of the file for a new iteration of the main while ... so it's almost the same problem ... how can I make the program to start again to read the text file from the beginning? Here is the second attempt:

int need_to_search = 1;

    while (need_to_search)
    {   need_to_search = 0;

        while (!in.eof() && first_number >= 100 && second_number >= 100)
        {   in >> number_to_compare;

            if (first_number == number_to_compare)
            {   first_number--;
                if (first_number == second_number)
                    first_number--;

                need_to_search = 1;
            }
            else if (second_number == number_to_compare)
            {   second_number--;
                if (second_number == first_number)
                    second_number--;

                need_to_search = 1;
            }
        }
    }

Example: If the file would contain the folowing numbers:

  1292 5422 997 125 7735 1 5474 956 7557 1249 966 624 12 5499 5677 884 964 998 546 455 778 6658 957

The output should be:

  999 996

because these are the largest two numbers of three digits that are missing from the text file.

I would really appreciate a hint! Thanks!


texts:
I am learning about GraphQL so I decided to make a schema for some sort of social network. Please let me know if there are any best practices I should follow based on my schema below.

  scalar DateTime

  type Query {
      # user
      currentUser: User # use request "Authorization" header to get credentials
      getUser(uid: String!): User

      # friends
      getFriendRequest(requestId: Int!): FriendRequest
  }

  type Mutation {
      initializeNewUser: User!
      editCurrentUser(input: EditUserInput): User!

      # friends
      sendFriendRequest(toUid: String!): FriendRequest
      # from this mutation, can accept or reject friend requests.
      # server should handle adding of new friend on input.status == RequestStatus.accept
      updateFriendRequest(input: UpdateFriendRequestInput!): FriendRequest!

      # unfriend uid, and return updated list of friends
      unfriend(uid: String!): [Friend!]!
  }

  input UpdateFriendRequestInput {
      requestId: Int!
      status: RequestStatus!
  }

  input EditUserInput {
      displayName: String
      profilePic: String
  }

  type User {
      uid: String!
      profilePic: String
      displayName: String
      createdOn: DateTime!
      isOnline: Boolean
      friends: [Friend!]!
      friendRequests: [FriendRequest!]!
  }

  type Friend {
      user: User!
      friendsSince: DateTime!
      mutualFriends: [Friend!]!
  }

  type FriendRequest {
      requestId: Int!
      requestingUser: User!
      receivingUser: User!
      status: RequestStatus
      requestedAt: DateTime!
  }

  enum RequestStatus {
      pending
      accepted
      rejected
  }


texts:
I was inspired to write a query that produced a graph mapping the perceived quality of your Stack Exchange answers over time.... in other words, "Are your answers getting better, or worse?"

Because answer scores are very 'spiky', it seems natural to calculate a sliding average with a configurable window, to show trends.

The result I have is:

And this is the SEDE query.

with Rolling as (
    Select Rank() over (order by CreationDate Asc) as Answer,
           CreationDate,
           Convert(float, Score) as Score
    from Posts
    where PostTypeId = 2
      and OwnerUserId = ##UserId:int##
)
select Master.CreationDate, Master.Score as [Score], Avg(Slave.Score) as [RollingAvg]
from Rolling as Master,
     Rolling as Slave
where Slave.Answer  > Master.Answer - ##RollingAvg:int?10##
  and Slave.Answer <= Master.Answer
group by Master.CreationDate, Master.Score
order by Master.CreationDate

I am particularly interested to know whether the rolling average can be computed in a more SQL Server friendly way. There does not appear to be a performance problem, but the CTE and self join seem.... ugly.

Any other observations?


texts: Modified Z-Algorithm for string similarity with one char difference

texts:
I have modified a Z-Algorithm for string similarity in order to match strings which differ in 0 or 1 char.

However, it seems much slower than original Z-Algorithm although from my point of view there is only a minor different and it also has a O(n) time complexity.

Input is a string in which a pattern is going to be found. So the goal is to find parts in string where pattern is present. The goal is also to find parts in string where the pattern is 'almost present'. So peep, leek and peek are all 'present' in string = "blahpeekblahpeepblahleek" for pattern = "peek". The output are indices in which matches are found. So for my example the output is "4 12 20".

modified Z-Algorithm:

static String stringSimilarity(String string, String pattern ) {
String s = pattern + "$" + string;
int len = s.length();
int patternLen = pattern .length();

int[] z = new int[len];
int l, r, i;
StringBuilder result = new StringBuilder();

l = r = patternLen;
i = patternLen + 1;

while (i < len) {
    //O(1)
    if (i <= r)
        z[i] = Math.min(z[i - l], r - i + 1);

    while (i + z[i] < len && z[i] < patternLen && s.charAt(z[i]) == s.charAt(i + z[i]))
        z[i] += 1;

    // if the previous while encountered mismatch we accept the mismatch as match and seek for matches once more
    if (i + z[i] < len && z[i] < patternLen && s.charAt(z[i]) != s.charAt(i + z[i])) {
        z[i] += 1;
        while (i + z[i] < len && z[i] < patternLen && s.charAt(z[i]) == s.charAt(i + z[i]))
            z[i] += 1;
    }

    if (z[i] >= patternLen)
        result.append(i - patternLen - 1).append(" ");

    if (i + z[i] - 1 > r) {
        l = i;
        r = i + z[i] - 1;
    }

    i += 1;
}

return result.toString();
}

Z-Algorithm body (code is not entirely mine but I adopted it while mine was not that readable):

while (i < len) {       //O(n + n) = O(n)
    //O(1)
    if (i <= r)
        z[i] = Math.min(z[i - l], r - i + 1);

    //loops only n times at maximum - O(n)
    while (i + z[i] < len && s.charAt(z[i]) == s.charAt(i + z[i]))
        z[i] += 1;

    if (z[i] >= patternLen)
        result.append(i - patternLen- 1).append(" ");

    //O(1)
    if (i + z[i] - 1 > r) {
        l = i;
        r = i + z[i] - 1;
    }

    i += 1;     //O(1)
}

Can you please check the complexity of my modified Z-Algorithm?

From my point of view it is the same, however, tests on Hackerank show timeout.


texts: Python version of Clean Code book example

texts:
I started reading Robert Martin's Clean Code. I'm trying to "translate" all his examples into Python, so I can understand them better since my domain on Python is greater than on Java. Please take a look at the following:
Java original code of the book
public class GuessStatisticsMessage {
    private String number;
    private String verb;
    private String pluralModifier;

    public String make(char candidate, int count) {
        createPluralDependentMessageParts(count);
        return String.format(
            "There %s %s %s%s",
            verb, number, candidate, pluralModifier);
    }

    private void createPluralDependentMessageParts(int count) {
        if (count == 0) {
            thereAreNoLetters();
        } else if (count == 1) {
            thereIsOneLetter();
        } else {
            thereAreManyLetters(count);
        }
    }

    private void thereAreManyLetters(int count) {
        number = Integer.toString(count);
        verb = "are";
        pluralModifier = "s";
    }

    private void thereIsOneLetter() {
        number = "1";
        verb = "is";
        pluralModifier = "";
    }

    private void thereAreNoLetters() {
        number = "no";
        verb = "are";
        pluralModifier = "s";
    }
}

My Python version
class GuessStatsMessage:
    def __init__(self, candidate, count):
        self.candidate = candidate
        self.count = count
        self.__number = self.__verb = self.__plural_modifier = ''

    def make_message(self):
        self.__create_pluraldependant_message_parts()
        guess_message = (f'There {self.__verb} '
                         f'{self.__number} '
                         f'{self.candidate}{self.__plural_modifier} ')
        print(guess_message)

    def __create_pluraldependant_message_parts(self):
        if self.count == 0:
            self.__there_are_no_letters()
        elif self.count == 1:
            self.__there_is_one_letter()
        else:
            self.__there_are_many_letters()

    def __there_are_no_letters(self):
        self.__number = 'no'
        self.__verb = 'are'
        self.__plural_modifier = 's'

    def __there_is_one_letter(self):
        self.__number = '1'
        self.__verb = 'is'
        self.__plural_modifier = ''

    def __there_are_many_letters(self):
        self.__number = str(self.count)
        self.__verb = 'are'
        self.__plural_modifier = 's'

It should be used as follows:
message = GuessStatsMessage('Foo', 10)
message.make_message()
# output: There are 10 Foos


texts:
I am using ButterKnife in my project, and as we know we have to write ButterKnife.bind(this); in all the activities, so I have just created BaseActivity like this:

public class BaseActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState, int layout) {
        super.onCreate(savedInstanceState);
        setContentView(layout);
        ButterKnife.bind(this);
    }
}

and I am calling it from other activity like this

public class SplashActivity extends BaseActivity {

    @BindView(R.id.txtName)
    TextView txtName;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_splash);
    }
}

I want to know whether it is good practice to follow this approach.


texts:
I'm working on projecteuler.net problems, and I made this for problem #3:

array = []; // use this to save the prime factors
function factor(number, start){ //begin of the function
  prime=true;
  for(i = start; i < number+1; i++){ //begin of the first loop
    if(number % i == 0){ //is it a divisor of the number?
       for (x = 2; x <= Math.sqrt(i); x++) { //begin of the second lopp
          if (i % x == 0) {prime = false} //is it a prime number?
        }//end of the second loop
       if(prime){ array.push(i); factor(number/i, i); } //if it is a prime number save it and let's do the proccess again.
    }
  }  //end of the first loop
} //end of the function
array; //So you can see the result

My problem is:
I can get the prime factors of all the numbers i pass including the one they put on the example(13195), but when i try to get the prime factors of the one in the exercise(600851475143), my code do save the prime factor in the array but then i get the alert of "script not responding" in mozzila and chromes just stay there doing nothing, any way to solve this?.

Ps: i already solved the exercise but im not satisfied and can't fix it by my own.


texts: Finding connected components in the application task

texts:
I have n indexed socks, each of which has one of k colors. I also have a list that states which two socks I must wear at each of m days.

Of course I want always wear same color socks. But unfortunately I must follow the list. What I can do is to re-color some socks. The paint is expensive so I want to re-color the least possible number of socks. What is the number?

Input:

n m k
[color of sock 1] [color of sock 2] ... [color of sock n]
[pair for 1st day]
[pair for 2nd day]
...
[pair for mth day]

n, m and k are not larger than 200 000

Examples:

Input:

3 2 3
1 2 3
1 2
2 3

Output:

2

Input:

3 2 2
1 1 2
1 2
2 1

Output:

0

In my solution I find linked parts of socks. To do it I recursively look for socks which are in pair with one in any day (via dfs). All socks in a linked part must have one color. Now it's simple to determine how many socks must be re-painted in each linked part and to sum these numbers.

The problem is that my solution works rather slowly. It reaches the time limit (2000 ms) at the middle test. How do I improve my algorithm?

#include <cstdio>
#include <iostream>
#include <vector>
#include <set>
#include <stack>
using namespace std;

class Data {
    int n_socks, n_days, n_colors;
    vector<int> sock_color; // color of the sock
    vector<set<int>> sock_with; // what socks are in pair with this
public:
    Data() {
        cin >> n_socks >> n_days >> n_colors;
        sock_color.resize(n_socks);
        for (auto & c: sock_color) {
            scanf("%d", &c);
            --c;
        }
        sock_with.resize(n_socks);
        int l, r;
        for (int i = 0; i < n_days; ++i) {
            scanf("%d %d", &l, &r);
            sock_with[l - 1].insert(r - 1);
            sock_with[r - 1].insert(l - 1);
        }
    }
    int compute() {
        int sum = 0;
        vector<bool> visited(n_socks);
        int cur = 0; // first unvisited
        while (true) {
            visited[cur] = true;
            vector<int> color_number(n_colors);
            // how many socks of each color
            // are linked with cur
            ++color_number[sock_color[cur]];

            // let's find it via dfs:
            stack<int> st;
            st.push(cur);
            while (!st.empty()) {
                int u = st.top();
                st.pop();
                for (int v: sock_with[u]) {
                    if (!visited[v]) {
                        visited[v] = true;
                        ++color_number[sock_color[u]];
                        st.push(v);
                    }
                }
            }

            int max = 0, all = 0; // linked
            for (int i: color_number) {
                all += i;
                if (i > max)
                    max = i;
            }

            // we should paint all except max
            sum += all - max;

            // finding next cur:
            for (; cur < n_socks; ++cur)
                if (!visited[cur])
                    break;
            if (cur == n_socks)
                break;
        }
        return sum;
    }
};

int main() {
    Data d;
    cout << d.compute() << endl;
    return 0;
}


texts:
The desired behavior would be:

    [TestMethod]
    public void Compare_Value_Identity()
    {
        var source = new[] { 1, 2 };
        var modified = new[] { 2, 3 };

        var (inserted, deleted) = source.Compare(modified);

        CollectionAssert.AreEqual(new[] { 3 }, inserted.ToArray());
        CollectionAssert.AreEqual(new[] { 1 }, deleted.ToArray());
    }

And:

    [TestMethod]
    public void Compare_Id_Identity()
    {
        var source = new[] { (1, "A"), (2, "B"), (3, "C") };
        var modified = new[] { (2, "B"), (3, "D"), (4, "E") };

        var (inserted, updated, deleted) = source.Compare(modified, x => x.Item1);

        CollectionAssert.AreEqual(new[] { (4, "E") }, inserted.ToArray());
        CollectionAssert.AreEqual(new[] { (3, "D") }, updated.ToArray());
        CollectionAssert.AreEqual(new[] { (1, "A") }, deleted.ToArray());
    }

Library code is:

public static class SequenceChange
{
    public static (IEnumerable<T> Inserted, IEnumerable<T> Deleted) Compare<T>(
        this IEnumerable<T> source, IEnumerable<T> modified) =>
        source.Compare(modified, EqualityComparer<T>.Default);

    public static (IEnumerable<T> Inserted, IEnumerable<T> Deleted) Compare<T>(
        this IEnumerable<T> source, IEnumerable<T> modified, IEqualityComparer<T> comparer) =>
        (modified.Except(source, comparer), source.Except(modified, comparer));

    public static (IEnumerable<T> Inserted, IEnumerable<T> Updated, IEnumerable<T> Deleted) Compare<T, TKey>(
        this IEnumerable<T> source, IEnumerable<T> modified, Func<T, TKey> keySelector) =>
        source.Compare(modified, keySelector, EqualityComparer<T>.Default);

    public static (IEnumerable<T> Inserted, IEnumerable<T> Updated, IEnumerable<T> Deleted) Compare<T, TKey>(
        this IEnumerable<T> source, IEnumerable<T> modified, Func<T, TKey> keySelector, IEqualityComparer<T> comparer) =>
        (modified.ExceptBy(source, keySelector),
        from s in source
        join m in modified on keySelector(s) equals keySelector(m)
        where !comparer.Equals(s, m)
        select m,
        source.ExceptBy(modified, keySelector));
}


texts:
I have tried Implementing Stacks Using Linked Lists, and would like some tips and tricks regarding optimizations or ways to simplify/compact processes.

It has 3 functions, Push, Pop, and Peek (For checking the top item in stacks)

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

class Stack:
    def __init__(self):
        self.bottom = None
        self.top = None
        self.length = 0

    def peek(self):
        return self.top.data if self.top != None else None

    def push(self, data):
        NewNode = Node(data)
        if self.length == 0:
            self.bottom = self.top = NewNode
        else:
            top = self.top
            self.top = NewNode
            self.top.next = top
        self.length += 1
        return self

    def pop(self):
        length = self.length
        top = self.top
        if length == 0:
            raise IndexError('No items in stack')
        elif self.bottom == top:
            self.bottom = None
        else:
            NextTop = self.top.next
            self.top = NextTop
        self.length -= 1
        return top.data

Output:

stack = Stack()

stack.push(0)
stack.push(1)
stack.push(2)
stack.push(3)

print(stack.peek())

print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.pop())

stack.push(5)
stack.push(2)
print(stack.pop())
print(stack.pop())

-----------------------
3
3
2
1
0
2
5
-----------------------


texts: Finding the longest common suffix recursively

texts:
I'm getting the correct results, but my method isn't the prettiest. Is there any way to do this with less code?

var longestSuffix = function(A, B) {
    return rec(A, B, 0);

    function rec(A, B, count) {
        if (!A.length || !B.length) return '';
        if (A[A.length - count - 1] === B[B.length - count - 1]) {
            console.log(A[A.length-count-1]);
            return rec(A, B, ++count) + A[A.length - count - 2];
        }
        return rec('','');
    }
};

console.log(longestSuffix('cababa', 'cabjklaba'));


texts: Detecting arithmetic overflow in C with NASM

texts:
This snippet is about detecting whether the carry flag is set or cleared. I work on Mac OSX, so my snippet supports Mac only.

First, we need a routine that does the job:

func.s:

global _read_carry_flag

_read_carry_flag:
    mov al, 0
    jnc end
    mov al, 1
end:
    ret

(Try nasm2 -f macho64 func.s for compiling into an object file.)

main.c:

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#define A (2 * 1000 * 1000 * 1000)
#define B (1 * 1000 * 1000 * 1000)

extern bool read_carry_flag();

int main(int argc, char* argv[])
{
    int32_t a = A;
    int32_t b = B;
    int32_t ret = a + a + b;

    printf("%d\n", read_carry_flag());

    a = A;
    b = 1;
    ret = a + b;

    printf("%d\n", read_carry_flag());
    return 0;
}

(Try gcc -o prog main.c func.o for obtaining a process image.)

I would like to hear about possible improvements/extensions to the idea.


texts: Trying to simplify a setTimeout sequence

texts:
Here is the script:

function opening(){
    setTimeout(function () {
        var opening = $('#stage');
        opening.find('h1').fadeIn('slow', function(){
            setTimeout(function () {
                opening.find('.logo').fadeIn('slow', function(){
                    setTimeout(function () {
                        opening.find('p').fadeIn('slow');
                        opening.find('#btn').fadeIn('slow');
                    }, 400);
                });
            }, 800);
        });
    }, 400);
}

It's work fine. But I would like to try to simplify it. Is possible?


texts: Generic Makefile handling unit testing and folder structure

texts:
I'm going back to C++ and, even though I'm not a beginner in programming and OOP, I'm quite new in the C++ world and I've not mastered the art of Makefiles.

I'd like to know what you think about my third Makefile and the folder structure that I use. Don't hesitate to make any comments you think necessary.

Here is the folder structure of the "project":

out/   ---   *.exe and *.zip
tmp/   ---   *.o
lib/
|   catch/   ---   Unit testing framework
|   |   inc/
|   |   |   catch.hpp
inc/   ---   Headers
|   Factorial.hpp
src/   ---   Source files
|   Factorial.cpp
|   main.cpp
tst/   ---   Tests specific source files
|   FactorialTest.cpp
|   MathTest.cpp
|   mainTest.cpp
Makefile

It is designed to support unit testing (here using Catch) with the tst folder.

I didn't know how to use external libraries with C++, so I created a lib folder to put Catch in. I thought libraries could be downloaded from the configure.sh script in the future. Does it sound like a "professional" solution for larger projects?

The Makefile :

CXX           := g++
LD            := g++

EXEC          := factorial
FLAGS         := -Wall
CXXFLAGS      := $(FLAGS)
LDFLAGS       := $(FLAGS)
INC           := -I inc
SRC           := $(wildcard src/*.cpp)
OBJ           := $(SRC:src/%.cpp=tmp/%.o)

EXEC_TEST     := test
FLAGS_TEST    := $(FLAGS)
CXXFLAGS_TEST := $(CXXFLAGS)
LDFLAGS_TEST  := $(LDFLAGS)
INC_TEST      := $(INC) -I lib/catch/inc
SRC_TEST      := $(wildcard tst/*.cpp)
OBJ_TEST      := $(filter-out tmp/main.o, $(OBJ)) $(SRC_TEST:tst/%.cpp=tmp/%.o)

.SUFFIXES:

# --------------------------------------------------------------

.PHONY: all
all: out/$(EXEC)

out/$(EXEC): $(OBJ)
    @$(LD) $(LDFLAGS) $^ -o $@ && echo "[OK]  $@"

# --------------------------------------------------------------

.PHONY: test
test: out/$(EXEC_TEST)

out/$(EXEC_TEST): $(OBJ_TEST)
    @$(LD) $(LDFLAGS_TEST) $^ -o $@ && echo "[OK]  $@"

# --------------------------------------------------------------

tmp/%.o: src/%.cpp
    @$(CXX) $(CXXFLAGS) -c $< $(INC) -o $@ && echo "[OK]  $@"

tmp/%.o: tst/%.cpp
    @$(CXX) $(CXXFLAGS_TEST) -c $< $(INC_TEST) -o $@ && echo "[OK]  $@"

# --------------------------------------------------------------

.PHONY: clean, clear
clean clear:
    @rm -f out/* && echo "[CL]  out/"
    @rm -f tmp/* && echo "[CL]  tmp/"

.PHONY: archive, zip
archive zip:
    @zip -x out/* tmp/* lib/* -q -r out/$(EXEC)-$(shell date '+%F').zip . && echo "[OK]  out/$(EXEC)-$(shell date '+%F').zip"

The Makefile is to be used via all and test targets, which build the final executable and the unit testing executable respectively.

I tried to avoid duplicating tmp/%.o: src/%.cpp and tmp/%.o: tst/%.cpp recipes with test target-specific variables buy it didn't work because there are variables in targets' and dependencies' names.

PS: It's also my third post on the Stack Exchange Network, so please feel free to make remarks about anything that is not "StackExchange-compliant".


texts:
So I wrote this class to handle my ajax calls simply:

ajaxCon.php:

class ajaxCon{
    private $init = false;
    private $functionArray = array();
    private $Message = false;
    private $function = null;
    private $arguments = null;
    private $post = null;

    public function __construct(){
        if(!isset($_POST['ajaxRequest'], $_POST['ajaxFunction'])) return;
        $this->init = true;
        ob_start();
        $this->post = $this->sanitizeArr($_POST);
        $this->arguments = $this->sanitizeArr($_POST['arguments']);
        $this->function = $_POST['ajaxFunction'];
    }

    public function addFunction($functionName, $functionCode){
        if(!$this->init || !isset($functionName, $functionCode) || $functionName != $this->function) return $this;
        $this->Message = call_user_func_array($functionCode, $this->arguments) ? 'success' : 'fail' ;
        unset($this->init, $this->functionArray, $this->post);
        $returnVars = get_object_vars($this);
        ob_clean();
        echo json_encode($returnVars);
        ob_flush();
        exit();
    }

    private function sanitizeArr($returnArr, $sanitizer = 'sanitize_sql_string') {
        array_walk_recursive($returnArr, function (&$value) use ($sanitizer) {
            $value = $sanitizer($value);
        });

        return $returnArr;
    }
}

ajaxCon.js:

function ajax() {

    this.callback = false;

    this.ajaxFailure = function (returnData) {};

    this.ajaxSuccess = function (returnData) {};

    this.call = function(functionName, argumentArray, callback){
        $.ajax( $.extend(true, {}, this.ajaxSettings, {data:{'ajaxFunction':functionName, 'arguments':argumentArray}} ) );
        this.callback = callback;
    };

    this.ajaxReturn = function (returnData){
        returnData = returnData.substring(returnData.indexOf("{") - 1);
        returnData = returnData.substring(0, returnData.lastIndexOf("}") + 1);
        var responseArray = $.parseJSON(returnData);

        if (responseArray.Message.toLowerCase() != "success"){
            this.ajaxFailure(responseArray);
            return;
        }

        this.ajaxSuccess(responseArray);
        if(this.callback != false) this.callback(responseArray);
    };

    window.ajaxCon = this;
    this.ajaxSettings = { url: window.location.href, type: 'POST', cache: false, data: {ajaxRequest: true}, success: function (returnData) {
        ajaxCon.ajaxReturn(returnData)
    }};
}

and you call it like so:

<?php
    $ajaxCon = new ajaxCon;

    $ajaxCon->addFunction('checkEmail', function($Email){
        global $ajaxCon;
        if(emailIsInDB($Email)) $ajaxCon->hasAccount = true;
        return true;
    });
?>
<script type="text/javascript">
    var ajaxCon = new ajaxCon();

    function checkEmail() {
        ajaxCon.call('checkEmail', {'Email':$('#Email').val()}, function(result){
            if(!result.hasAccount) $('#SignUp').submit();
        });
    }
</script>

The drawbacks I know of are lot's of preprocessing (The entire page has to be preprocesed) and the page then executes as normal until the php function I need is defined and called.

Any ideas on how I can optimize the code and make it run more efficiently while preserving/improving readability?


texts: Using something other than form field's value in Vue

texts:
I have a form, I need to send untraslated values, but as well, I need to get translated ones from Vue to write them down in page.

For now, I ended up creating a 'shadow' property and changing it via the watch function. Note that I'm referencing the SELECT via the custom ref prop and Vue.$refs. So:

<select name="screw[type]" ref="screw_type_select" v-model="form.screw.type">
   <option value="My value" data-value="<?php _e('My value', 'context'); ?>"><?php _e('My value', 'context'); ?></option>
   //[...]

Then in Vue:

var vueapp = new Vue({
  el: '#form'
  ,data:{
    form:{
      ,screw:{
        type: "Svasata Piana"
        ,type_t: "Svasata Piana"
      }
    }
  }// data
  ,watch:{
    'form.screw.type':function(){
      var select = this.$refs.screw_type_select;
      this.form.screw.type_t = select.options[select.selectedIndex].getAttribute('data-value')
    }
  }
});

Then again in html:

{{ form.screw.type_t }} // instead of {{ form.screw.type }}

So the form will send value, but the user will see data-value intead (which is translated).

What do you think of this way?


texts: Pure JS countdown clock not converting millisecond time correctly

texts:
I have a semisimple pure js countdown clock that I am having trouble converting the millisecond time correctly.

Here is a working Plunker (besides the date counter)

It Should only be 38 days instead of 184.

//// Should Countdown till feb, 4th 2019 /////

let cd = new Countdown({
  cont: document.querySelector(".container"),
  endDate: 1549263600000,
  outputTranslation: {
    year: "Years",
    week: "Weeks",
    day: "Days",
    hour: "Hours",
    minute: "Minutes",
    second: "Seconds"
  },
  endCallback: null,
  outputFormat: "day|hour|minute|second"
});

Thank's I appreciate the help!


texts:
This problem is from HackerEarth:

  The Monk learned about priority queues recently and asked his teacher for an interesting problem. So his teacher came up with a simple problem. He now has an integer array A. For each index i, he wants to find the product of the largest, second largest and the third largest integer in the range [1,i].

  Note: Two numbers can be the same value-wise but they should be distinct index-wise.

  Input:

  The first line contains an integer N, denoting the number of elements in the array A.
  The next line contains N space separated integers, each denoting the ith integer of the array A.

  Output:

  Print the answer for each index in each line. If there is no second largest or third largest number in the array A upto that index, then print "-1", without the quotes.

  Constraints:

  1 <= N <= 100000
  0 <= A[i] <= 1000000

  Sample Input

5
1 2 3 4 5

  Sample Output

-1
-1
6
24
60

  Explanation

  There are 5 integers 1,2,3,4 and 5.

  For the first two indexes, since the number of elements is less than 3, so -1 is printed.
  For the third index, the top 3 numbers are 3,2 and 1 whose product is 6.
  For the fourth index, the top 3 numbers are 4,3, and 2 whose product is 24.
  For the fifth index, the top 3 numbers are 5,4 and 3 whose product is 60.

  Time Limit: 1.0 sec(s) for each input file.

  Memory Limit: 256 MB

  Source Limit: 1024 KB

  Marking Scheme: Marks are awarded if any testcase passes.

  Allowed Languages: C, CPP, CLOJURE, CSHARP, GO, HASKELL, JAVA, JAVASCRIPT, JAVASCRIPT_NODE, LISP, OBJECTIVEC, PASCAL, PERL, PHP, PYTHON, RUBY, R, RUST, SCALA

Here is my solution:

#include <iostream>
#include <limits>

#define lld long long
int n, N = 0;
using namespace std;
void max_heapify(int arr[], int n, int i){
    int largest = i;
    int left = 2 * i;
    int right = 2*i + 1;
    if(left <= n && arr[left] > arr[largest]){
        largest = left;
    }
    if(right <= n && arr[right] > arr[largest]){
        largest = right;
    }
    if(largest != i){
        swap(arr[i], arr[largest]);
        max_heapify(arr, n, largest);
    }
}
void build_max_heap(int arr[], int n){
    for(int i = n/2; i >=1; i--){
        max_heapify(arr,n,i);
    }
}

int extract_max(int arr[], int in){

    if(in < 1){
        throw "underflow";
    }

    int max = arr[1];
    arr[1] = arr[in--];
    max_heapify(arr, in, 1);
    return max;
}

int main(){
    cin >> n;
    int in;
    int *arr = new int[n+100];
    int _1st,_2nd,_3rd;
    for (int i = 1; i <= n; ++i) {
        cin >> arr[i];
        build_max_heap(arr, i);

        lld ans;

        if (i <= 2) {
            cout << "-1" << endl;
        }
        else {
            _1st = extract_max(arr, n);
            _2nd = extract_max(arr, n);
            _3rd = extract_max(arr, n);

            ans = _1st * _2nd * _3rd;
            printf("%lld\n", ans);
            int p = i;
            arr[p] = _1st; p--;
            arr[p] = _2nd; p--;
            arr[p] = _3rd;

        }
    }

    return 0;
}

Here I'm calling the build_max_heap for every input, because the problem demand to produce an output after each input so, I think that's causing the problem, but as far as I know, Heapify takes O(log n) time and build_max_heap takes linear time, so it shouldn't exceed more that one second for the 4th input which is here around 1000000 input.


texts:
I'm trying to compare several files using md5 hash with powershell 2.0. The code works, the problem is that it's to slow. It takes longer in step 3. It's about 500 files to compare. Can you see a way to get it faster, like, don't do the step 3 every time?

write-host "1"
    $COMP_ORI=$LOCAL_HOME+"\"+$PROG+"\"+$COMPARE
    $file_ori = Get-ChildItem -Path $COMP_ORI -name
write-host "2"
    $COMP_DEST="\\"+$HOSTIP[$i]+"\"+$PROG_PATH
    $file_dest = Get-ChildItem -PATH $COMP_DEST -name
write-host "3"
    for ($i=0; $i -lt $file_ori.Count; $i++) {
write-host "compare md5" $i
    if ( Get-ChildItem -PATH $COMP_DEST -name -Include $file_ori[$i] ) {
        $md5 = New-Object -TypeName system.Security.Cryptography.MD5CryptoServiceProvider
write-host "4"
        $hash_ori = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($COMP_ORI+"\"+$file_ori[$i])))
write-host "5"
        $hash_dest = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($COMP_DEST+"\"+$file_ori[$i])))
write-host "6"
    if ($hash_ori -ne $hash_dest) {
        $out=$file_ori[$i]
        $out=$out+" IS DIFFERENT"
        output message_solo $out
    }
}

}


texts:
I am writing a function that does a constant time compare of two byte arrays. I want it to be constant time to insure there is no side channel attacks possible.

Does the code protect against timing attacks or other side channel attacks (of which I could fix)
Any other suggestions for improvements

Note: This code is called infrequently so performance is not a big deal

/// <summary>
/// Performs a comparison of two identical sized byte arrays.
/// Performs in constant time to prevent timing/side channel attacks
/// </summary>
public int CompareConstantTime(byte[] bytesA, byte[] bytesB)
{
    if (bytesA == null)
        throw new ArgumentNullException(nameof(bytesA));
    if (bytesB == null)
        throw new ArgumentNullException(nameof(bytesB));
    if (bytesA.Length != bytesB.Length)
        throw new ArgumentOutOfRangeException("byte length must be equal");

    //only the lest significant bit is used
    int aIsLarger = 0;
    int bIsLarger = 0;

    unchecked
    {
        for (int i = 0; i < bytesA.Length; i++)
        {
            int byteA = bytesA[i];
            int byteB = bytesB[i];

            int byteAIsLarger = ((byteB - byteA) >> 8) & 1;
            int byteBIsLarger = ((byteA - byteB) >> 8) & 1;

            aIsLarger = aIsLarger | (byteAIsLarger & ~bIsLarger);
            bIsLarger = bIsLarger | (byteBIsLarger & ~aIsLarger);
        }

        //fixes to standard compaire results (0 if A = B, 1 if A > B, -1: B > A)
        int result = aIsLarger - bIsLarger;
        return result;
    }
}


texts:
Help me refactor this class that helps to represent an object state as String:

public class ConvertorToString {
    private static final String SEPARATOR_BETWEEN_FIELD_NAME_AND_VALUE = "=";
    private static final String SEPARATOR_BETWEEN_FIELDS = ", ";
    private static final String OPEN_FIELDS = "( ";
    private static final String CLOSE_FIELDS = " )";

    private final String className;
    private String[] fieldNames;
    private Object[] fieldValues;

    public static ConvertorToString buildFor(Object someObject) {
        return new ConvertorToString(someObject.getClass().getName());
    }

    private ConvertorToString(String className) {
        this.className = className;
    }

    public ConvertorToString withFieldNames(String... fieldNames) {
        this.fieldNames = fieldNames;
        return this;
    }

    public ConvertorToString withFieldValues(Object... fields) {
        this.fieldValues = fields;
        return this;
    }

    private class Field {
        private final int index;

        public Field(int index) {
            this.index = index;
        }

        public String toString() {
            checkIndex(index);
            return fieldNames[index] + SEPARATOR_BETWEEN_FIELD_NAME_AND_VALUE + fieldValues[index];
        }

        private void checkIndex(int index) {
            if (index < 0 || index >= countOfFields()) {
                throw new IllegalArgumentException("Index should be inside a range: " +
                        "[0," + countOfFields() + "];  " + "but index was: " + index);
            }
        }
    }

    public String toString() {
        checkState();
        return className
               + OPEN_FIELDS +
                StringsCombiner.combine(getFields(), SEPARATOR_BETWEEN_FIELDS)
               + CLOSE_FIELDS;
    }

    private void checkState() {
        if (fieldNames == null || fieldValues == null || fieldNames.length != fieldValues.length) {
            throw new IllegalStateException("count of fieldNames should be equal to count of fieldValues");
        }
    }

    private List<Field> getFields() {
        List<Field> fields = new ArrayList<Field>(countOfFields());
        int countOfFields = countOfFields();
        for (int i = 0; i < countOfFields; ++i) {
            fields.add(new Field(i));
        }
        return fields;
    }

    private int countOfFields() {
        return fieldNames.length;
    }
}

Using:

class SomeClass {
    int id;
    String title;

    @Override
    public String toString() {
        return ConvertorToString.buildFor(this)
            .withFieldNames("id", "title")
            .withFieldValues(id, title)
            .toString();
    }
}


texts: PHP subset of 2 arrays containing objects - compared only by 1 attribute

texts:
I'm looking for a fast way to get the subset of 2 arrays containing the same kind of objects using PHP functions.

I'm looking for the red part:

class Order
{
 private $_orderId;
 private $_someOtherAttributes;
}

I'm currently using array_uintersect() to get the intersection and array_udiff() to get rid of the intersection.

$array_1 = array($o1, $o2, $o3 ... $on);
$array_2 = array($o1, $o2, $o3 ... $on);

function order_hash($object)
{
    return sprintf('%d', $object->getOrderId());
}

 function compare_objects($a, $b)
 {
      return strcmp(order_hash($a), order_hash($b));
 }

$intersection = array_uintersect($array_1, $array_2, 'compare_objects');
$subset = array_udiff($array_2, $intersection, 'compare_objects');

Is there a faster / more efficient way? I need to work with a lot of objects > 400 each array and very often as well.

I'm currently using PHP Version 7.1.4.

My changes:

I changed the Order-Class to:

class Order
{
     public $_orderId;
     private $_someOtherAttributes;
}

and compare_objects() to:

function compare_objects($a, $b)
{
       if($a->_orderId> $b->_orderId)
       {
           return 1;
       }
       else if($a->_orderId< $b->_orderId)
       {
            return -1;
       }
       return 0;
}

and using array_udiff($array_1, $array_2, 'compare_objects') instead off array_udiff($array_2, array_udiff($array_1, $array_2, 'compare_objects'), 'compare_objects')

I'm aware that public attributes aren't the best practice, but changing it this way I gained 300% more speed.


texts: Checking whether a user is on the donors list

texts:
I was wondering if I could please get some justification if the PHP code I wrote using Mysqli prepared statements would be able to withstand SQL injection attacks.

I have one field that gets a value from a form. Code works 100% fine, just want to make sure it is secure against SQL injection.

$steaminput = filter_input(INPUT_POST, 'steamid_user', FILTER_SANITIZE_STRING);
$conn = mysqli_connect(host, user, pass, table);
$sql = "SELECT username, activated, expiration_date FROM donors WHERE steam_id=?";

$stmt = mysqli_prepare($conn, $sql);

mysqli_stmt_bind_param($stmt, "s", $steaminput);

mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result($stmt, $username_res, $activated_res, $expiration_res);

  while(mysqli_stmt_fetch($stmt)){
    $data = array('username'=>$username_res, 'activated'=>$activated_res, 'expiration_date'=>$expiration_res);
  }

mysqli_stmt_close($stmt);
mysqli_close($conn);
//I use array information from retreival here


texts: Handling exceptions for providing log information while debugging

texts:
I am catching exceptions to provide better information for the logs to make debugging easier in production. Does this code follow best practices, since I'm not really handling the error but just logging extra information? I was also considering creating a custom RazorException, and throwing that instead. What do you think?

public string ParseFile(string templatePath, object model = null)
{
    //some code removed for clarity

    try
    {
        ITemplate template = _templateService.Resolve(templatePath, model);
        ExecuteContext context = new ExecuteContext();
        content = template.Run(context);
    }
    catch (TemplateCompilationException tcex) {
        _logger.Fatal("Razor parse failed: check for syntax error", tcex);
        throw;
    }
    catch (InvalidOperationException ex) {
        _logger.Fatal("Razor parse failed: trying to compile layout on its own", ex);
        throw;
    }
    catch (Exception ex) {
        _logger.Fatal("Razor parse failed", ex);
        throw;
    }
    return content;
}


texts:
I thought I would give this months community challenge a try. This is my first time using Python.
It does take quite a while to run and it's not very colourful but it works.

from PIL import Image, ImageDraw

img = Image.new("RGB", (2400, 2400), "white")
draw = ImageDraw.Draw(img)

max_count = 200
width = img.size[0]
height = img.size[1]

for row in range(height):
    for col in range(width):
        str_output = ""
        c = complex(
            (col - float(width)/2.0)*5.0/float(width),
            (row - float(height)/2.0)*5.0/float(height)
        )
        iteration = 0
        z = 0
        while abs(z) < 2 and iteration < max_count:
            z = z**2 + c
            iteration += 1
        if abs(z) < 2:
            draw.point((col, row), fill="black")
        else:
            draw.point((col, row), fill=(255 - iteration,255 - iteration,255 - iteration))

img.save('mandelbrot.png')