texts: Complexity for two approaches of finding next biggest palindrome of a number

texts:
I have come up with a problem online about the next biggest palindrome of a number and i have solved the problem by two different approaches in python. The first one is,

t = long(raw_input())

for i in range(t):
    a = (raw_input())
    a = str(int(a) + 1)
    palin = ""
    oddOrEven = len(a) % 2

    if oddOrEven:
        size = len(a) / 2
        center = a[size]
    else:
        size = 0
        center = ''

    firsthalf = a[0 : len(a)/2]
    secondhalf = firsthalf[::-1]
    palin = firsthalf + center + secondhalf

    if (int(palin) < int(a)):
        if(size == 0):
            firsthalf = str(int(firsthalf) + 1)
            secondhalf = firsthalf[::-1]
            palin = firsthalf + secondhalf

        elif(size > 0):
            lastvalue = int(center) + 1

            if (lastvalue == 10):
                firsthalf = str(int(firsthalf) + 1)
                secondhalf = firsthalf[::-1]
                palin = firsthalf + "0" + secondhalf

            else:
                palin = firsthalf + str(lastvalue) + secondhalf
    print palin

and the another one is,

def inc(left):
    leftlist=list(left)
    last = len(left)-1
    while leftlist[last]=='9':
        leftlist[last]='0'
        last-=1

    leftlist[last] = str(int(leftlist[last])+1)
    return "".join(leftlist)

def palin(number):
    size=len(number)
    odd=size%2
    if odd:
        center=number[size/2]
    else:
        center=''
    print center
    left=number[:size/2]
    right = left[::-1]
    pdrome = left + center + right
    if pdrome > number:
        print pdrome
    else:
        if center:
            if center<'9':
                center = str(int(center)+1)
                print left + center + right
                return
            else:
                center = '0'
        if left == len(left)*'9':
            print '1' + (len(number)-1)*'0' + '1'
        else:
            left = inc(left)
            print left + center + left[::-1]

if __name__=='__main__':
    t = long (raw_input())
    while t:
        palin(raw_input())
        t-=1

As a computer science perspective, what is the complexity of both of this algorithms? which one is more efficient to use?


texts:
I need to calculate some dates like yesterday, this week/month, last three/ten days etc.

To make it a little bit easier and don't think about the Date weirdness all the time I created this helper:

var HumanDate = function() {

  var date = new Date();

  this.day = function(numOfDays) {
    if (numOfDays === undefined) {
        return date.getDate();
    }
    else {
        date.setDate(date.getDate() + numOfDays);
        return this;
    }
  };

  this.month = function(month) {
    if (month === undefined) {
      return date.getMonth() + 1;
    }
    else {
      date.setMonth(date.getMonth() + month);
      return this;
    }
  };

  this.year = function() {
    return date.getFullYear();
  };

  this.dayOfWeek = function() {
        var dayOfWeek = date.getDay();
    return dayOfWeek === 0 ? dayOfWeek + 1 : dayOfWeek;
    };

  this.beginningOfTheWeek = function() {
    return this.day(-this.dayOfWeek() + 1);
  }

  this.endOfTheWeek = function() {
    return this.day(7 - this.dayOfWeek());
  }

  this.beginningOfTheMonth = function() {
    return this.day(-this.day() + 1);
  }

  this.endOfTheMonth = function() {
    return this.day(7 - this.dayOfWeek());
  }

  this.toJSDate = function(format) {
    return date;
  }

};

Examples:

console.log('day: ' + new HumanDate().day());
console.log('month: ' + new HumanDate().month());
console.log('year: ' + new HumanDate().year());
console.log('day of week: ' + new HumanDate().dayOfWeek());

console.log('yesterday: ' + new HumanDate().day(-1).day());
console.log('next month: ' + new HumanDate().month(1).toJSDate());
console.log('last month: ' + new HumanDate().month(-1).toJSDate());
console.log('beginning of the week: ' + new HumanDate().beginningOfTheWeek().toJSDate());
console.log('end of the week: ' + new HumanDate().endOfTheWeek().toJSDate());
console.log('beginning of the month: ' + new HumanDate().beginningOfTheMonth().toJSDate());
console.log('end of the week: ' + new HumanDate().endOfTheWeek().toJSDate());

Output:

day: 7
month: 9
year: 2016
day of week: 3
yesterday: 6
next month: Fri Oct 07 2016 20:04:50 GMT+0200 (W. Europe Summer Time)
last month: Sun Aug 07 2016 20:04:50 GMT+0200 (W. Europe Summer Time)
beginning of the week: Mon Sep 05 2016 20:04:50 GMT+0200 (W. Europe Summer Time)
end of the week: Sun Sep 11 2016 20:04:50 GMT+0200 (W. Europe Summer Time)
beginning of the month: Thu Sep 01 2016 20:04:50 GMT+0200 (W. Europe Summer Time)
end of the week: Sun Sep 11 2016 20:04:50 GMT+0200 (W. Europe Summer Time)

I need it for Google Sheets scripting & calculations so I'd rather not use an external library - (at least for now)


texts: MySQL/CUPS PDF printer for STAR TSP100 ECO

texts:
This is my very first attempt at Python and whilst the script works perfectly, I'd like to see if I'm missing anything obvious or doing anything particularly stupid. I think this runs on Python 2.7, but I'm not 100% sure.

Goal:
The goal here is to grab a task and its elements (records contain BLOB PDF data) and write them all to CUPS as a single print job for a receipt printer, starting with a plaintext header, followed by a list of PDF files and followed by a plaintext header.

Finally, the code should mark the task as printed in the database and remove all blob-data associated with the task as to prevent my database from turning into a massive waste of space. It should likewise delete the folder containing the 'downloaded' PDFs and header/footer files.

import os
import shutil
import MySQLdb
import cups

printername = "STARTTSP100"
dbAddress =  "nope"
dbUser = "nope"
dbPasswd = "nope"
dbDatabase = "printer"

# Connect to the Printer DB
db = MySQLdb.connect(
    host=dbAddress,
    user=dbUser,
    passwd=dbPasswd,
    db=dbDatabase
 )

curOne = db.cursor()
curOne.execute("SELECT task.id, task.header, task.footer FROM task WHERE task.printDate IS NULL ORDER BY task.regDate ASC LIMIT 5")
for row in curOne:

    printList = []

    if not os.path.exists(row[0]):
        os.makedirs(row[0])

    header = open(row[0]+"/"+row[0]+"_header.txt","w")
    header.write(row[1])
    header.close()
    printList.append(row[0]+"/"+row[0]+"_header.txt")

    curTwo = db.cursor()
    curTwo.execute("SELECT elements.id, elements.count, elements.data FROM elements WHERE task = '"+row[0]+"' ORDER BY count ASC")

    for subrow in curTwo:
        tempPdf = open(row[0]+"/"+subrow[0]+".pdf","wb")
        tempPdf.write(subrow[2])
        tempPdf.close()
        for x in range(0,subrow[1]):
            printList.append(row[0]+"/"+subrow[0]+".pdf")

    footer = open(row[0]+"/"+row[0]+"_footer.txt","w")
    footer.write(row[2])
    footer.close()
    printList.append(row[0]+"/"+row[0]+"_footer.txt")

    cups.Connection().printFiles(printername, printList, "expedition-"+row[0],{})

    curThree = db.cursor()
    curThree.execute( "UPDATE task SET printDate = NOW() WHERE id = '"+row[0]+"'" )
    curThree.close()

    curFour = db.cursor()
    curFour.execute( "UPDATE elements SET data = null WHERE task = '"+row[0]+"'" )
    curFour.close()

    shutil.rmtree(row[0])

db.commit()
db.close()

print("done")


texts: Scraping webpage elements with VBA script

texts:
With some help I've put together a macro to scrape webpage elements by tag ID from URLs (indicated in column A of an Excel sheet) and insert the text into columns B, C and D. The code loops from 1st row until 1000th. So far so good.

The problem is that it seems to be taking SOOOO much time. Is there any way to speed up the process? I feel like my use of IE pages isn't optimal.

(Please note that I'm aware that On Error the code is copying previous data as new but I have a manual easy work around to clean the data, which works fine until I get around to fixing that issue.)

Sub getCountry()
'
' GetCountry Macro
'
' Keyboard Shortcut: Ctrl+k
'
  Dim IE      As Object: Set IE = CreateObject("InternetExplorer.Application")
  Dim ws      As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
  Dim Country As String
  Dim Category As String
  Dim Network As String
  Dim n As Integer
  n = 729
  For n = 729 To 1000
    With IE
    Visible = False
    .navigate ws.Range("A" & n).Value
    Do
      DoEvents
        Loop Until .readyState = 4
      End With
      On Error Resume Next
      Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
      On Error Resume Next
      Category = Trim$(IE.document.getElementByID("youtube-user-page-channeltype").innerText)
      On Error Resume Next
      Network = Trim$(IE.document.getElementByID("youtube-user-page-network").innerText)
      ws.Range("B" & n).Value2 = Country
      ws.Range("C" & n).Value2 = Category
      ws.Range("D" & n).Value2 = Network
    Next n
  IE.Quit
  End Sub


texts: A JavaScript isEven() function, defined recursively

texts:
Can someone please take a look at these recursive functions, offer some advice on the code, or just critique my attempt into thinking recursively?

Problem:

  We’ve seen that % (the remainder operator) can be used to test whether a number is even or odd by using % 2 to see whether it’s divisible by two. Here’s another way to define whether a positive whole number is even or odd:

  Zero is even.
  One is odd.
  For any other number \$N\$, its evenness is the same as \$N - 2\$.

  Define a recursive function isEven corresponding to this description. The function should accept a single parameter (a positive, whole number) and return a Boolean. - eloquentJavascript, chapter 3

My attempt:

function isEven(x) {
  if (x < 0 ) {
        return false
  }
   else if (x % 2 == 0) {
        return true
  } else {
        return isEven(x-2)
  }
}

Offical Solution:

function isEven(n) {
  if (n == 0)
    return true;
  else if (n == 1)
    return false;
  else if (n < 0)
    return isEven(-n);
  else
    return isEven(n - 2);
}

I know there are many ways to write the same piece of functionality but I want to know if the following code holds up to scrutiny. The official solution I checked my code against is obviously different but I'm getting the correct solutions.

console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false

What events does

else if (n < 0)
    return isEven(-n);

handle that,

 else
    return isEven(n - 2);

doesn't?

I started reading 'the little Schemer' on the advice of Douglas Crockford in an attempt to learn how to think recursively but the examples are in Scheme which just looks like ((( n ) * atom)) to me...so not very useful until I can read the syntax.


texts: Compute count of unique words using ES6 sets

texts:
I have written a function which counts how many unique words are included in a given text.

The source-code:

const computeCountUniqueWords = (strToExamine) => {
  let parts = strToExamine.split(" ");

  let validWords = parts.filter((word) => {
    return /^\w/.test(word);
  });

  let uniqueWords = new Set(validWords);

  return uniqueWords.size;
}

let text1 = "Lorem ipsum dolor sit amet consectetuer adipiscing elit aenean commodo ligula eget dolor.";
let text2 = "Etiam ultricies nisi vel augue. Curabitur ullamcorper";

console.log(`Text 1 has ${computeCountUniqueWords(text1)} words`);
console.log(`Text 2 has ${computeCountUniqueWords(text2)} words.`);

I think it has become quite neat and short.

Nevertheless: Is there a better way to solve the described task?

Moveover: Is my checking with the regular expression sufficient? Or should it be enhanced?

Looking forward to reading your answers.


texts: Plotting Frequency of Vowels in a Paragraph

texts:
I wanted to play around with the following idea:

  Give a paragraph, I wanted to find out the relative frequency of usage
  of each of the five vowels. I wanted to plot a pie chart depicting
  this.

Here is my code:

from sys import stdin
from re import sub
import pylab
DataToRead = stdin.read()
VowelData = sub(r"[^aeiou]","",DataToRead) #Take Out Everything which is NOT a vowel
VowelList = ['a','e','i','o','u']
VowelCount = [sum(map(lambda x: x==Vowel,VowelData)) for Vowel in VowelList] # Number of times each vowel appears
print VowelCount
VowelPerc = [x*100.0/sum(VowelCount) for x in VowelCount] #Find the percentage of each
pylab.pie(VowelPerc,None,VowelList,autopct='%1.1f%%')
pylab.show()

It does what it needs to (I think) but I feel there is a better way of doing this (algorithmically speaking). I like Functional Programming so I threw in the Mapper but there is no other reason for that.


texts: Saving array values for a secondary foreach loop

texts:
Although used within the WordPress platform, this is PHP focussed question.

I have an array of child posts, some have content, some don't. My client wishes to display the posts in alphabetical order, but posts without content are to be positioned at the end (still in A-Z order).

My solution is to assign posts that lack content to an array, use continue to move the main array counter forward and then foreach over the the new array at the end:

<?php

    $child_pages = pp_get_child_pages();

    if ( count( $child_pages ) != 0 ) :

        $empty_child_pages = array();

        echo '
';

        foreach ( $child_pages as $post ) :

            setup_postdata( $post );

            if ( $post->post_content == "" ) {
                $empty_child_pages[] = $post;
                continue;
            }

            pp_get_template_part( 'content', 'child-page' );

        endforeach;

        foreach ( $empty_child_pages as $post ) :

            setup_postdata( $post );

            pp_get_template_part( 'content', 'child-page' );

        endforeach;

        echo '
';

    endif;

    wp_reset_postdata();

?>

Is there a more efficient way to write this?

Would you modify the array during the initial loop?


texts: Minimum steps to reach target by a Knight In Scala

texts:
Given a chessboard of N size (square matrix), the position of Knight and position of a target, find out minimum steps (both count and exact steps) from start to target for a Knight.

If it is not possible to reach to the given position, return -1 as step count.

Here is my implementation in Scala (assuming N = 4 or 4X4 chess board):

import scala.collection.mutable._

object KnightMoves extends App {
  case class Pos(row: Int, col: Int)
  val Size = 4

  def calculateMoves(from: Pos, target: Pos ): (Int, Seq[Pos])= {
    val pendingPos = collection.mutable.Queue[Pos](from)
    val positionVisited = collection.mutable.HashMap[Pos, (Int, Seq[Pos])](from -> (0, Seq()))
    var targetReached = false

    while(pendingPos.nonEmpty && !targetReached) {
      val p = pendingPos.dequeue()
      possibleMoves(p) foreach { position =>
        if ( position == target) {
          targetReached = true
        } else if (!(positionVisited contains position)) {
          pendingPos enqueue position
        }
        positionVisited += position -> ((positionVisited(p)._1 + 1,(positionVisited(p)._2 ++ Seq(p))))
      }
    }
    if (targetReached) positionVisited(target) else (-1, Seq())
  }

  def isValidPos(position: Pos): Boolean =
    ((0 until Size) contains position.row) && ((0 until Size) contains position.col)

  def possibleMoves(position: Pos): List[Pos] =
    List(Pos(position.row - 2, position.col + 1),
        Pos(position.row - 2, position.col - 1),
        Pos(position.row + 2, position.col + 1),
        Pos(position.row + 2, position.col - 1),
        Pos(position.row - 1  , position.col + 2),
        Pos(position.row - 1  , position.col - 2),
        Pos(position.row + 1  , position.col + 2),
        Pos(position.row + 1  , position.col - 2)
    ) filter( pos => isValidPos(pos))

  println(calculateMoves(Pos(0,1),Pos(0,0)))
  println(calculateMoves(Pos(0,1),Pos(0,2)))
}

This program generates the following output for two test statements at bottom.

(3,ArrayBuffer(Pos(0,1), Pos(2,0), Pos(1,2)))
(3,ArrayBuffer(Pos(0,1), Pos(2,2), Pos(1,0)))


texts: Checking if a string has all unique characters

texts:
I'm wondering if this code can be optimized in terms of time complexity. The problem is checking to see if a string has all unique characters.

#include <iostream>
#include <string>
using namespace std;

//Assuming ASCII

bool checkString (string user) {
    if (user.length() > 256)
    {
        return false;
    }

    //creating a boolean array of size 256
    //setting all values to false (0)
    bool check[256] = {false};

    for (int i = 0; i < user.length(); i++)
        {
        int value = user.at(i);
            if (check[value] == true)
            {
                return false;
            }

            else
            {
                check[value] = true;
            }
        }
    return true;
}

int main() {

    string user;
    cout << "Please enter in a string: ";
    cin  >> user;

    cout << checkString(user) << endl;

    return 0;
}

I'm not very good with determining the time complexity. Right now, would it be \$O(n^2)\$ (because of the for loop)?


texts: Is this an appropriate approach to "tweak" a color to a similar lighter/darker color?

texts:
I have written this function for the sole purpose to get a similar color either brighter or darker than any given color, depending on an average lightness/darkness. Essentially, I add up the R/G/B values and divide by 3, thus giving the average intensity of each color channel. Then, depending on that result, if it's less than half (darker) I lighten the color, and if it's more than half (lighter), I darken the color. The amount to lighten/darken depends on a given "difference" parameter (Diff).

The purpose and use of this function is in custom drawing controls to color themes, and shading colors based on other colors. If the color is dark, the tweaked color is a little bit lighter. If the color is light, the tweaked color is a little bit darker.

Do you see any shortcomings with my approach? Could I make this any better?

function IntRange(const Value, Min, Max: Integer): Integer;
begin
  Result:= Value;
  if Result < Min then Result:= Min;
  if Result > Max then Result:= Max;
end;

function TweakColor(const AColor: TColor; const ADiff: Integer): TColor;
var
  R, G, B: Byte;
  D: Integer;
  Dir: Integer;
begin
  R:= GetRValue(AColor);
  G:= GetGValue(AColor);
  B:= GetBValue(AColor);
  D:= (R + G + B) div 3; //D = average difference of all 3 color channels
  if D >= (256 div 2) then begin   //If average is a lighter color...
    Dir:= -ADiff;                  //Make the color darker
  end else begin                   //If average is a darker color...
    Dir:= ADiff;                   //Make the color lighter
  end;
  R:= IntRange(R + Dir, 0, 255);
  G:= IntRange(G + Dir, 0, 255);
  B:= IntRange(B + Dir, 0, 255);
  Result:= RGB(R, G, B);
end;

Example Usage:

Canvas.Font.Color:= TweakColor(Canvas.Font.Color, 50);


texts: Check where the integers are Tprime or not

texts:
The objective of the code is to check the given inputs are tprime or not.

Example:

3 //no of integers(1 ≤ n ≤ 10^5)
4 5 6 //space-separated integers xi (1 ≤ xi ≤ 10^12)

Output:

YES
NO
NO

The code works fine but always exceeds time limit 2000ms. How to reduce it?

import java.util.Scanner;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TprimePractise {

public static void main(String[] args) throws Exception {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int input = Integer.valueOf(line);
line = br.readLine();
long sqrt, x;
for (String num : line.split("\\s")) {
    x = Long.valueOf(num);

    if (x == 1) {
        System.out.println("NO");
        continue;
    }
    sqrt = (long) Math.sqrt(x);
    if (sqrt * sqrt == x && isPrime(sqrt)) {
        System.out.println("YES");
    } else {
        System.out.println("NO");
    }

  }
}

public static boolean isPrime(long num) {

for (int j = (int) num / 2; j >= 2; j--) {
    if (num % j == 0) {
        return false;
    }
}
return true;
 }

}


texts: Flow control with try catch to reduce redundancy

texts:
I've seen a similar question to this but mine's a little more specific. I have the below

File f = new File("./data.txt");
if(f.isFile())
{
    try
    {
        FileChannel fc = new RandomAccessFile(f,"r").getChannel();
        //Get information and return it
    }
    catch(FileNotFoundException e)
    {
        System.out.println("FileNoFoundException: "+e.getMessage());
    }
}
else
{
    //If the file wasn't found, return default values
}

I was wondering, should I just put the default returning of the information in the catch block? I assumed that'd be a no because you're not really supposed to use it to control flow. But having the both the if and the try catch just looks too redundant to me.


texts: Bash script to monitor Webserver php script

texts:
Below is a script I wrote today to use CURL to monitor the length of various HTTP server outputs and output a response if this is different than 103 characters.
This is my first bash script, so I had some reading/experimenting to do and it is quite rough.
The idea is that if there are no errors, my php script will ouput exactly 103 characters. If there are errors, this will be increased.

IDScript

#!/bin/bash
# Check for missing IDs - greater output than 103 characters
cd "/media/SMALL/scripts"

if [[ -z "$1" ]] # check if script arguement exists
then
        a=$(./IDscript "server");
        a=$(./IDscript "server2")$a;  #concatenate with previous output
        a=$(./IDscript "server3")$a;

        lenA=$(expr length "$a");

        if [ $lenA -eq 0 ] #check length of A is empty
        then
                echo "No errors";
        else
                mail -s "TID error" myEmail@company.org <<< "There are errors:"$a; # send the e-mail
        fi
        exit;
fi

#create random number from 50 to 99
r=$(( $RANDOM % 50 + 50 ));
#bypass HTTP proxy with random number
testURL=$1"/checkError?which=IDError&rand="$r;

curlOut=$(curl -s "$testURL");
curlLength=$(expr length "$curlOut");

if [ $curlLength -ne 103 ] #103 char is response length when no missing IDs exist
then
echo "length is not 103:"$testURL;
echo -e "\n";
fi

Comments and suggestions are welcome!


texts:
Could it be written better?

package main

import (
    "code.google.com/p/go-tour/wc"
    "fmt"
)

func WordCount(s string) map[string]int {
    dict := make(map[string]int)

    splited := Split(s)
    for _, string := range splited {
        _, present := dict[string]
        if present {
            dict[string]++
        } else {
            dict[string] = 1
        }
    }
    return dict
}

func Split(s string) []string{
    arraySize := 1
    for i := 0; i < len(s); i++ {
        if s[i] == ' ' {
            arraySize++
        }
    }
    array := make([]string, arraySize)

    currentStrInd := 0
    currentStr := ""
    for i := 0; i < len(s); i++ {
        if s[i] == ' ' {
            array[currentStrInd] = currentStr
            currentStrInd++
            currentStr = ""
        } else {
            currentStr += string(s[i])
        }
    }
    array[arraySize - 1] = currentStr
    return array;
}

func main() {
    fmt.Println(Split("I am learning Go!"))
    wc.Test(WordCount)
}


texts:
I am making a class method in ruby to convert from roman number to Arabic and vice versa. However the loop is run to match each character and again to match with roman mapper. Can I optimize the same?

class String
      private

      def roman_mapping
        {
          1000 => "M",
          900 => "CM",
          500 => "D",
          400 => "CD",
          100 => "C",
          90 => "XC",
          50 => "L",
          40 => "XL",
          10 => "X",
          9 => "IX",
          5 => "V",
          4 => "IV",
          1 => "I"
        }
      end
    end

def to_arabic(str = self, result = 0)
  return result if str.empty?
  roman_mapping.values.each do |roman|
    if str.start_with?(roman)
      result += roman_mapping.invert[roman]
      str = str.slice(roman.length, str.length)
      return to_arabic(str, result)
    end
  end
end


texts:
I use named scopes all over the place.

When I have a named scope that deals with two different tables, I tend to query the second table in a sub-query. That way, if I mix and match with other tables I don't need to worry about reusing a table alias or having ambiguous column names that only appear in bizarre scenarios.

For example, suppose I have a posts table that is one-to-many related to a tags table. I might add a with_tags scope on my Post model like this:

named_scope :with_tags, lambda { |tags|
  tags = [tags] if tags.kind_of? String
  {:conditions => ["id IN (SELECT post_id FROM tags WHERE name IN (?))", tags]}
}

However, that doesn't seem ideal. Many databases can use a join more efficiently than they can use a sub-query. A query that looks like this might perform better:

SELECT DISTINCT posts.* FROM posts JOIN tags ON posts.id = tags.post_id WHERE tags.name IN (?)

How do other people do this? Do you use the :include/:join parameters cleverly to know what the aliases ActiveRecord will use?


texts: Given some integers, find triplets where the product of two numbers equals the third number

texts:
I am trying to solve a coding challenge:

  Given N integers A1, A2, …, AN, count the number of triplets (x, y, z) (with 1 ≤ x < y < z ≤ N) such that at least one of the following is true:

  Ax = Ay × Az, and/or
  Ay = Ax × Az, and/or
  Az = Ax × Ay

  Sample case 1

  5 2 4 6 3 1

  In Sample Case #1, the only triplet satisfying the condition given in the problem statement is (2, 4, 5). The triplet is valid since the second, fourth, and fifth integers are 2, 6, and 3, and 2 × 3 = 6. thus the answer here is 1.

  Sample case 2

  2 4 8 16 32 64

  The six triplets satisfying the condition given in the problem statement are: (1, 2, 3), (1, 3, 4), (1, 4, 5), (1, 5, 6), (2, 3, 5), (2, 4, 6). so the answer here is 6.

My Code in python:

import itertools
count=0
for t in itertools.combinations(l,3):
    if t[0]*t[1]==t[2] or t[1]*t[2]==t[0] or t[0]*t[2]==t[1]:
        count+=1
print(count)

This is the naive way of generating all possible 3 length combinations and checking for the condition. This works fine for smaller input but when the inout size increase time complexity increases. I am assuming for an example that has 1,2,3,6,8 the combinations generated are (2,3,6),(2,3,8) 2,3,6 satisfy the condition so the checking for 2,3,8 is unnecessary and can be avoided. How can I modify my code to take advantage of this observation ?


texts: Split excel file with multiple sheets, manipulate the data and create final out file

texts:
I have an excel file with 20+ separate sheets containing tables of data. My script iterates through each sheet, manipulates the data into the format I want it and then saves it to a final output file. I think it can be improved, and I've flagged sections in the code with "review this" which I think I've done more work than I've needed to. Any feedback or criticism would be awesome!

import openpyxl
import pandas as pd

path = 'C:/Desktop/Python/Excel Manipulation/'

wb = openpyxl.load_workbook(path + 'inputfile.xlsx')
sheets = wb.get_sheet_names()

CSVList = []

for sheet in sheets:

    #get the current active sheet
    active_sheet = wb.get_sheet_by_name(sheet)

    #count numbers of rows
    row_count = active_sheet.get_highest_row() - 1
    #count number of columns
    column_count = active_sheet.get_highest_column()

    count = 0
    values = []

    #write each row to a list, stop when reached max rows (REVIEW THIS - would have thought there was a better way than using a counter)
    while count <= row_count:
        for i in active_sheet.rows[count]:
            values.append(i.value)
        count = count + 1

    #split values list into tuples based on number of columns
    split_rows = zip(*[iter(values)]*column_count)

    #convert list of tuples to list of lists  (REVIEW THIS - creating a tuple and then converting to list seems like extra work?!?)
    rows = [list(elem) for elem in split_rows]

    #get elements of file and store (REVIEW THIS - looks messy?)
    title = rows.pop(0)[0]
    headers = rows.pop(0)
    headers[1] = 'Last Year'
    rows.pop(0)

    #create pandas dataframe
    df = pd.DataFrame(rows, columns=headers)

    #take header_id and remove to normalise the data
    header_id = headers.pop(2)

    normalise_data = pd.melt(df, id_vars=header_id, value_vars=headers, var_name='Measure', value_name='Value')
    normalise_data.insert(0, 'Subject', title)
    CSVList.append(normalise_data)

frame = pd.concat(CSVList)
frame.to_csv(path + 'CSV Outputs/' + 'final.csv', sep=',', index=False)


texts: Algorithm to identify a shift and its type based on on and off times

texts:
Following code is supposed to identify a shift and then it should identify whether the shift is a night or a day shift. The method will take 'in time' and 'out time' as two parameters.

These are the rules:

Day shift - From 7AM to 7PM
Night shift - From 7PM to 7AM (on the next day)
The employee should report before 8AM for a day shift, otherwise the shift will not be taken into account.
The employee should report before 8PM for a night shift, otherwise the shift will not be taken into account.
If an employee leaves before the regular off time of a shift, that shift will not be taken into account.

This code gives the intended result. Please let me know is the way I've done this acceptable? Do you have any better idea to achieve the same?

public string IdentifyShift(DateTime inTime, DateTime OutTime)
{

    var compareInTimeToOutTIme = inTime.CompareTo(OutTime);

    //Two random dates used to assign value '1 day' to timespan "aDay"
    DateTime from= Convert.ToDateTime("05/01/2014 12:00:00");
    DateTime to=Convert.ToDateTime("05/02/2014 12:00:00");

    TimeSpan aDay = (to - from).Duration();

    //If OutTime is less than the InTime that means the OutTime is on the next day
    if (compareInTimeToOutTIme > 0)
    {
        OutTime = OutTime.Add(aDay);
    }

    TimeSpan shift = (OutTime - inTime).Duration();

    var compareInTimeTo8AM =inTime.CompareTo(Convert.ToDateTime( inTime .ToShortDateString() +" 08:00:00")); //InTime of a day shift should be before 08AM
    var compareOutTimeTo7PM = OutTime.CompareTo(Convert.ToDateTime(inTime .ToShortDateString ()+" 19:00:00")); //OutTime of a day shift should be after or equal to 07PM

    var compareInTimeTo8PM =inTime.CompareTo(Convert.ToDateTime(inTime.ToShortDateString ()+" 20:00:00")); //InTime of a night shift should be before 08AM

    string DayOfnightShiftOutTime= inTime.Add(aDay).ToShortDateString();
    var compareOutTimeTo7AM =OutTime.CompareTo(Convert.ToDateTime(DayOfnightShiftOutTime+" 07:00:00")); //OutTime of a night shift should be after or equal to 07AM on the next day

    if (shift.TotalHours >= 11)
    {
        if ((compareInTimeTo8AM < 0) & (compareOutTimeTo7PM >= 0))
        {
            return "Day Shift";
        }
        else if ((compareInTimeTo8PM < 0) & (compareOutTimeTo7AM >= 0))
        {
            return "Night Shift";
        }
        else
        {
            return "Not a Shift";
        }
    }
    else
    {
        return "Not a Shift";
    }
}


texts:
class text_generator
 {
   public int getWordIndex(List<string> source, Random value)
    {
      return value.Next(0, source.Count - 1);
    }
      public bool checkListLength(List<string> source)
    {
      return source.Count == 0;
    }
   public string getText(List<string> source, List<string> backup_source, Random value)
    {
      if (checkListLength(source))
      {
        source.AddRange(backup_source);
      }
      ;
      int index = getWordIndex(source, value);
      string result = source[index];
      source.RemoveAt(index);
      return result;
  }
}

Then I open a main list and an empty list.

text_generator textix = new text_generator();
List<string> hi = new List<string> { "Hi", "Howdy", "Hey", "etc" };
List<string> work_hi = new List<string>();

And... Generate. They will always be different until all elements will be used.

Random rand = new Random();
Console.WriteLine(textix.getText(work_hi, hi, rand));

My question is: While this code works fine, it seems a bit long. Is it possible to make the same with just one method? Is it possible NOT to open one more list? How can I do it?


texts:
Today I had an interview, where I was asked to solve this problem:

  Generate nth prime number. Given a signature below, write python logic
  to generate the nth prime number:

def nth_prime_number(n):
  # n = 1 => return 2
  # n = 4 => return 7
  # n = 10 => return 29

I wrote this code, but couldn't get through:

def nth_prime_number(n):
    if n==1:
        return 2
    count = 1
    num = 3
    while(count <= n):
        if is_prime(num):
            count +=1
            if count == n:
               return num
        num +=2 #optimization

def is_prime(num):
    factor = 2
    while (factor < num):
        if num%factor == 0:
             return False
        factor +=1
    return True

The overall feedback was that the code quality could be improved a lot, and that I should be more optimal in my approach. How can I improve this code?


texts:
I am using a public validating sub to help validate the other subs. Is this the most efficient way to do this?

Public Sub Validator(sender As Object, e As EventArgs) Handles GrossRevenueButton.Click, CPTCodesButton.Click, EstablishedVisitsButton.Click
    Dim validater As Integer = 0 'this is the variable that gets sent out from this sub
    If MonthSelectBox.Text = "" Then
        Label1.Text = "You didn't select a month!"
        validater = 1
    Else
        Label1.Text = ""
    End If
    If YearSelectBox.Text = "" Then
        Label2.Text = "You didn't select a year!"
        validater = 2
    Else
        Label2.Text = ""
    End If
    If FilepathTextBox.Text = "" Then
        Label3.Text = "You didn't select a file!"
        validater = 3
    Else
        Label3.Text = ""
    End If

    If MonthSelectBox.Text.Length > 1 And YearSelectBox.Text.Length > 1 And FilepathTextBox.Text.Length > 1 Then
        validater = 0
    End If
End Sub

'GROSS REVENUE
Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles GrossRevenueButton.Click
    Dim validater As Integer 'validater comes from the validate sub
    If validater > 0 Then
        Call Gross_Revenue()
    Else
        Label4.Text = "Something went wrong!"
    End If
End Sub

'CPT CODES
Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles CPTCodesButton.Click
    Dim validater As Integer 'validater comes from the validate sub
    If validater > 0 Then
        Call CPT_Totals()
    Else
        Label4.Text = "Something went wrong!"
    End If
End Sub

'ESTABLISHED VISTS
Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles EstablishedVisitsButton.Click
    Dim validater As Integer 'validater comes from the validate sub
    If validater > 0 Then
        Call Established_Visits()
    Else
        Label4.Text = "Something went wrong!"
    End If
End Sub


texts:
I have several huge 100MB text files that I need to scan through to pick out certain frame numbers which relate to a specific log packet of interest.  My plan was to scan for these frame numbers and drop them into a list (often 6000+ frames per text file!).  Ok so far, but there is second packet of interest which should accompany the first packet, these pairs of packets can only be matched by a frame number in my newly created list, so to avoid grabbing useless/blank data from non-matching frames.  So I would then re-scan the text file to get the frame related packet data.  It was suggested on Stack Overflow that I go down the regex route, and whilst this method worked it was extremely slow, taking up to 3 minutes to process a single text file.

I was wondering if there is a suitable optimization to my code, or even a completely different approach to grabbing this data?

for root, subFolders, files in os.walk(path):
  for filename in files:
    if filename.endswith('.txt'):
        with open(os.path.join(root, filename), 'r') as f:
            print '\tProcessing file: '+filename

            for line in f:
               #first find first key packet and grab frame number
               if 'KEY_FRAME details' in line:
                    chunk = [next(f) for x in xrange(5)]
                    FRAME = chunk[5].split()
                    FRAME = FRAME[2]

                    #drop frame number into a list
                    framelist.append(str(FRAME))

            #return to the start of the file, and search for next packet
            f.seek(0)

            framed = re.compile('|'.join(framelist))
            framed = framed.pattern

            #Look for any frame number in list based on 'FrameNumber = '+f and 'FN = '+f match
            sentences = f
            for s in sentences:
                if any(('FrameNumber = '+f) in s for f in framelist):
                    print 'first found'
                    #do stuff

                if any(('FN = '+f) in s for f in framelist):
                    print 'second found'
                    #do stuff

The data I scan through is multiple repetitions of various packets, some packets are blank of info, some have paired info related to the particular frame.

17:29:50.040  AFP  276  Second_Packet details
  FN = 54332
  Tp = TDSAA
  Te = True
  St = Test

17:29:50.040  TWR  765  KEY_FRAME details
TAPP            = 1
FrameNumber   = 54332
Cap             = 2
Tee             = NA

17:29:50.040  AKK  347 Second_Packet details
  FN = 50000
  Tp = KLA
  Te = True
  St = NA

17:29:50.040  AFP  276  Second_Packet details
  FN = 54367
  Tp = Ax56
  Te = True
  St = Test

17:29:50.040  YYY  765  KEY_FRAME details
TAPP            = 1
FrameNumber   = 54367
Cap             = 2
Tee             = NA

17:29:50.040  YYY  765  KEY_FRAME details
TAPP            = 1
etc......

Just to make it tougher the second packet often comes before the first key packet in the text files.

Finally, I am looking to present the data in packet groups like below, for each key frame number:

FrameNumber   = 54367
TAPP            = 1
Cap             = 2
Tee             = NA
Tp              = Ax56
Te              = True
St              = Test


texts: Optimizing nested loop in run length encoding function

texts:
I'm currently working on a tool that needs to decode, modify data, then re-encode that data using the Yaz0 format. Everything has been in a working state, but after running some code analysis on my program it turns out it is spending an obscene amount of time on the encoding portion (Over 95%). However, I cannot think of a way to make the loop in this function any more efficient than it already is.

So far I have compacted the inside for loop which used to have a break and two ifs inside it. I also tried using OpenMP, but since I am running async operations on all cores it just hindered performance. I haven't touched anything outside the loop because it is negligible as far as the analysis shows.

Here is a screenshot of the code analysis as well as the function in question. The code is compiled using Microsoft Visual Studio 2013 in debug mode and ran on Windows 8.1.

uint32_t simpleEnc(uint8_t *src, uint32_t size, uint32_t pos, uint32_t *pMatchPos)
{
  int32_t startPos = pos - 0x1000;
  uint32_t numBytes = 1;
  uint32_t matchPos = 0;
  int32_t diff = size - pos;

  if (startPos < 0)
  {
    startPos = 0;
  }

  for (int i = startPos; i < pos; i++)
  {
    for (int j = 0; j < diff && src[i + j] == src[j + pos]; j++)
    {
      if (j > numBytes)
      {
        numBytes = j;
        matchPos = i;
      }
    }
  }

  *pMatchPos = matchPos;

  if (numBytes == 2)
  {
    numBytes = 1;
  }

  return numBytes;
}

Are there any performance optimizations I've missed? I know there is some barrier where this will just take a fair amount of time, but since this is the biggest bottleneck in the program I want it to be as fast as possible.


texts: Find all root to leaf paths in binary tree

texts:
Description:

Given a binary tree, return all root-to-leaf paths.

Leetcode

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

Code:

class Solution {

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<>();
        traverse(root, new ArrayList<>(), paths);
        return paths;
    }

    private void traverse(TreeNode root, List<String> path, List<String> paths) {
        if (root == null) return;

        path.add(""+root.val);
        if (root.left == null && root.right == null) {
            paths.add(String.join("->", path));
        }

        traverse(root.left,  path, paths);
        traverse(root.right, path, paths);

        path.remove(path.size() - 1);
    }
}


texts:
This is my first attempt at Clojure! Apart from all game related issues, how is my code? Is there anything I can do to make it more idiomatic?

(ns hangman.core
  (:import (java.net ServerSocket Socket SocketException)
           (java.io PrintWriter InputStreamReader BufferedReader))
  (:gen-class))

(defn guess [guess word]
  (apply str (map #(let [x (str %)] (if (.contains guess x) x "*")) word)))

(defn listen [port]
  (new ServerSocket port))

(def word "clojure")

(defn conn-handler [conn]
  (let [in (:in @conn)
        out (:out @conn)]
    (.println out "Welcome to this simple hangman game.")
    (def the-guess (atom ""))
    (loop [conn conn]
      (.println out (str "Guess the word: " (guess @the-guess word)))
      (.flush out)
      (let [g (str @the-guess (.readLine in))
            res (guess g word)]
        (if (= word res)
          (do
            (.println out res)
            (.println out "Correct!")
            (.flush out))
          (do
            (reset! the-guess g)
            (recur conn)))))))

(defn -main [& args]
  (println "Server running…")
  (with-open [server (listen 3456)]
    (loop []
      (let [client (.accept server)
          in (BufferedReader.(InputStreamReader.(.getInputStream client)))
          out (PrintWriter. (.getOutputStream client))
          conn (ref {:in in :out out})]
        (println "Client connected")
        (doto (Thread. #(conn-handler conn)) (.start))
        (recur)))))


texts: Simple shared pointer implementation in a single threaded environment (revised)

texts:
std::shared_ptr does not stop you from having the same resource managed by multiple control-blocks (and thus independent sets of shared-pointers), even though it is illegal and leads to double-deletes. Additionally, atomic reference-counts don't have any advantage in single-threaded environments but are still more expensive. Thus I wrote the following version to avoid these problems.

(This is a follow-up to: simple shared pointer implementation in single threaded environment)

template <typename T>
struct ThreadUnsafeSharedPtr {
private:
    struct Pair {
        T data;
        size_t cnt;
        template <typename ... Args>
        Pair(Args && ... args): data(std::forward<Args>(args)...), cnt(1) {}
    };
    Pair *ptr;

public:
    template <typename ... Args>
    static ThreadUnsafeSharedPtr make(Args && ... args) {
        ThreadUnsafeSharedPtr p;
        p.ptr = new Pair(std::forward<Args>(args)...);
        return p;
    }

    ThreadUnsafeSharedPtr() : ptr(nullptr) {}

    ThreadUnsafeSharedPtr(const ThreadUnsafeSharedPtr & other) : ptr(other.ptr) {
        if (ptr && &other != this) {
            ++(ptr->cnt);
        }
    }
    ThreadUnsafeSharedPtr & operator=(const ThreadUnsafeSharedPtr & other) {
        if (ptr && &other != this) {
            ptr = other.ptr;
            ++(ptr->cnt);
        }
        return *this;
    }
    ThreadUnsafeSharedPtr(ThreadUnsafeSharedPtr && other) : ptr(other.ptr) {
        if (&other != this) {
            other.ptr = nullptr;
        }
    }
    ThreadUnsafeSharedPtr & operator=(ThreadUnsafeSharedPtr && other) {
        if (&other != this) {
            ptr = other.ptr;
            other.ptr = nullptr;
        }
        return *this;
    }

    ~ThreadUnsafeSharedPtr() {
        if (ptr) {
            if(--ptr->cnt == 0) {
                delete ptr;
            }
        }
    }
    T & operator* () {
        return ptr->data;
    }

    T * operator-> () {
        return &(ptr->data);
    }
};


texts: setup.py with data_files and __author__ parsing

texts:
All my projects have a fairly similar package layout:

package_name/
package_name/setup.py
package_name/package_name/__init__.py
package_name/package_name/data/foo.txt

package_name/package_name/__init__.py contains:

__version__ = '0.0.1'
__author__ = 'Alec Taylor <alec.taylor6@gmail.com>'

With a setup.py like:

from setuptools import setup, find_packages
from os import path, listdir
from functools import partial
from itertools import imap, ifilter
from ast import parse
from pip import __file__ as pip_loc

if __name__ == '__main__':
    package_name = 'foooooo'

    f_for = partial(path.join, path.dirname(__file__), package_name)
    d_for = partial(path.join,path.dirname(path.dirname(pip_loc)), package_name)
    to_funcs = lambda name: (partial(path.join, f_for(name)),
                             partial(path.join, d_for(name)))

    _data_join, _data_install_dir = to_funcs('data')

    get_vals = lambda var0, var1: imap(
                   lambda buf: next(imap(lambda e: e.value.s, parse(buf).body)),
                       ifilter(lambda line: line.startswith(var0) or
                                            line.startswith(var1), f))

    with open(path.join(package_name, '__init__.py')) as f:
        __author__, __version__ = get_vals('__version__', '__author__')

    setup(name=package_name,
        author=__author__,
        version=__version__,
        test_suite=package_name + '.tests',
        packages=find_packages(),
        package_dir={package_name: package_name},
        data_files=[
            (_data_install_dir(), map(_data_join, listdir(_data_join())))
        ]
    )

This setup.py has been tested on Windows and Linux with Python 2.7.

PS: I'm planning to upgrade all my packages to work with 2.7 and 3+.


texts: react, react native refactor component for style

texts:
I have a button component on react native, depending on the "theme" prop I need to render a different style for the button
const OvalButton = ({ title, onPress, theme, style }) => {

    switch(theme){
        case GRAY_BUTTON:
            return (
                <TouchableOpacity style={[styles.graybutton, style]} onPress={onPress}>
                    <Text style={styles.buttonText}>{title}</Text>
                </TouchableOpacity>
            )
        case BORDERED_BLUE_BUTTON:
        return (
            <TouchableOpacity style={[styles.bordered_button, style]} onPress={onPress}>
                <Text style={styles.buttonText}>{title}</Text>
            </TouchableOpacity>
        )
        default:
            return (
                <TouchableOpacity style={[styles.button, style]} onPress={onPress}>
                    <Text style={styles.buttonText}>{title}</Text>
                </TouchableOpacity>
            )
    }
}

export default OvalButton;

const styles = StyleSheet.create({
    button: {
        height: 44,
        backgroundColor: PRIMARY,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 22
    },
    graybutton: {
        height: 44,
        backgroundColor: BACKGROUND_LIGHT,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 22
    },
    bordered_button: {
        height: 44,
        backgroundColor: PRIMARY,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 22,
        borderWidth: 5,
        borderColor: 'white'
    },
    buttonText: {
        fontSize: 14,
        color: 'white',
        fontWeight: 'bold'
    }
})

so when I instantiate the button:
<OvalButton
            title="CONTINUE"
            style={[styles.continueButton]}
            onPress= { () => navigation.dispatch(navigateToOnboarding()) }
            theme={BORDERED_BLUE_BUTTON}
        />

it renders different, but I have lots of duplicated code, how to polish this?


texts:
Please give me some feedback on how I could make it better or simpler.

public class BinarySearchTree {

    private static TreeNode root;

    public static void main(String args[]) {
        BinarySearchTree bst = new BinarySearchTree();
        root = bst.addItem(root, 10);
        bst.addItem(root, 2);
        bst.addItem(root, 6);
        bst.addItem(root, 3);
        bst.addItem(root, 1);
        bst.addItem(root, 15);
        bst.addItem(root, 12);
        bst.addItem(root, 16);

        System.out.println("** Print BST PRE ORDER **");

        bst.printPreOrderTree(root);

        System.out.println("** Print BST IN ORDER **");

        bst.printInOrderTree(root);

        System.out.println("** Print BST POST ORDER **");

        bst.printPostOrderTree(root);
    }

    private TreeNode addItem(TreeNode root, int item) {
        if (root == null) {
            root = new TreeNode(null, item, null);
            return root;
        } else {
            if (item < root.element) {
                if (root.left == null) {
                    TreeNode node = addItem(root.left, item);
                    root.left = node;
                } else {
                    addItem(root.left, item);
                }
            } else if (item > root.element) {
                if (root.right == null) {
                    TreeNode node = addItem(root.right, item);
                    root.right = node;
                } else {
                    addItem(root.right, item);
                }
            } else {
                System.out.println("Duplicate Item");
            }
        }
        return root;
    }

    private void printPreOrderTree(TreeNode root) {
        if (root != null) {
            System.out.println(root.element);
            printPreOrderTree(root.left);
            printPreOrderTree(root.right);
        }
    }

    private void printInOrderTree(TreeNode root) {
        if (root != null) {
            printInOrderTree(root.left);
            System.out.println(root.element);
            printInOrderTree(root.right);
        }
    }

    private void printPostOrderTree(TreeNode root) {
        if (root != null) {
            printPostOrderTree(root.left);
            printPostOrderTree(root.right);
            System.out.println(root.element);
        }
    }

    private static class TreeNode {
        TreeNode left;
        int element;
        TreeNode right;

        protected TreeNode(TreeNode left, int element, TreeNode right) {
            this.left = left;
            this.element = element;
            this.right = right;
        }
    }
}


texts: Arduino controller to control the backlighting of a gear selector

texts:
Background

The gear selector on a car allows the driver to select which state the transmission should be in.

In the example picture, one of the five letters (P, R, N, D & S) lights up to indicate which state the transmission is presently in.

The position of the rotary dial is sufficient to determine which state the gear selector should be in (and subsequently which letter should light up). With this analog input (coming from a pair of Hall sensors), an Arduino board should be able to figure out which LED should be lit.

Code at present

This is my first attempt at writing C code, so pardon any Perl dialect.

"U" represents an undefined state

#define NOFIELD 505L       // Calibration constant
#define TOMILLIGAUSS 1953L // Unit conversion factor

#define P_led 13
#define R_led 12
#define N_led 11
#define D_led 10
#define S_led 9
#define U_led 8

#define numLED 5

struct interval
{
    int lower;
    int upper;
};

struct state
{
    char name;
    int led;
    interval gauss1;
    interval gauss2;
} ;

state shift_condition[] = {
  { 'P', P_led, {  74,  95 }, { -86, -40 } },
  { 'R', R_led, {  61,  92 }, { -20,  10 } },
  { 'N', N_led, { -30,   6 }, {  36,  90 } },
  { 'D', D_led, { -80, -53 }, {   2,  50 } },
  { 'S', S_led, { -25,  15 }, { -80, -25 } },
};

state prev_state;
long prev_gauss1;
long prev_gauss2;
bool gear_defined;

bool inRange( long value, struct interval range )
{
  return range.lower <= value && value <= range.upper;
}

void selectGear(int raw1, int raw2)
{

    long gauss1 = ( raw1 - NOFIELD ) * TOMILLIGAUSS / 1000;
    long gauss2 = ( raw2 - NOFIELD ) * TOMILLIGAUSS / 1000;

    // if no signal, no need to switch gear, bail out
    if ( prev_gauss1 == gauss1 && prev_gauss2 == gauss2 ) {
      return;
    }

    // update values for next evaluation

    prev_gauss1 = gauss1;
    prev_gauss2 = gauss2;

    // if new readings in existing state range,
    // no need to switch gear, bail out
    if ( gear_defined && inRange(gauss1, prev_state.gauss1) && inRange(gauss2,prev_state.gauss2) ) {
      return;
    }

    for( int i=0; i<numLED; i++) { // determine new state

        state curr_state = shift_condition[i];

        if ( inRange(gauss1, curr_state.gauss1) && inRange(gauss2, curr_state.gauss2) ) {

            Serial.print("Switching from ");
            Serial.print(prev_state.name);
            Serial.print(" to ");
            Serial.println(curr_state.name);

            digitalWrite(prev_state.led, LOW);
            digitalWrite(curr_state.led, HIGH);

            prev_state = curr_state;
            gear_defined = true;
            return;
        }
    }

    // no states matched, default to "undefined" state

    gear_defined = false;
    digitalWrite(prev_state.led, LOW);
    digitalWrite(U_led, HIGH);
}

void setup()
{
    Serial.begin(9600);
    pinMode(P_led, OUTPUT);
    pinMode(R_led, OUTPUT);
    pinMode(N_led, OUTPUT);
    pinMode(D_led, OUTPUT);
    pinMode(S_led, OUTPUT);
    pinMode(U_led, OUTPUT);
}

void loop()
{
    selectGear(analogRead(1),analogRead(2));
}

Questions/Concerns

As this is my first attempt at writing C code, what constructs/conventions could I leverage to write more robust code? The "undefined" state in particular bothers me, as does the fact that there doesn't seem to be a built-in way to count the length of an array.
Are there any gotchas pertaining to Arduino and typedefs? I tried to set a typedef on a struct and the code didn't compile.
I used char name to act as a pseudo-hash key. Is there a smarter way to go about defining dictionaries or hashes with (or without?) structs in C?
In the context of Arduino programming, how good is this implementation of a finite state machine? Are there any issues that may not be obvious in the course of this limited testing?
How would the use of pointers benefit memory usage here?

The main purpose of posting this question is to learn better C (& Arduino) by doing.


texts:
I'm new to JavaScript, and I've been learning off Khanacademy. I wrote the following basic terrain generator and I'm wondering if it could use any improvements. Here's the code:

var res = 7;

var area = [];

var camP = [random(500,1000), random(500,1000)];

var setArea = function()
{
    area = [];
    for (var y = -200; y < 200; y+=res)
    {
        var row = [];
        for (var x = -200; x < 200; x+=res)
        {
            row.push(noise((x+camP[0])/200, (y+camP[1])/200));
        }
        area.push(row);
        row = [];
    }
};

var drawPix = function(v, x, y){
    if (v < 0.49)
    {
        fill(random(30,40), random(100,128), random(20,30));
    }
    else
    {
        fill(random(0,10), random(40,50), random(245,255));
    }
    rect(x*res,y*res,res,res);
};

var drawArea = function()
{
    background(255, 255, 255);
    noStroke();
    for (var y in area)
    {
        for (var x in area[y])
        {
            drawPix(area[y][x],x,y);
        }
    }
};

setArea();
drawArea();

Here's an example of output:


texts:
I'm trying to figure out what the best way to do this is.

I have a part on my website where people can search for a particular card based on multiple different factors. Like the name of the card, color, cost, etc. When the user types in the criteria, I send the information via ajax GET. So the url looks something like this:

http://sitename.dev/search?query=asdf&color=red&etc=

The good thing is, the above provides a url so the user can easily copy paste and share the results with friends. The not so good part is, it's not so good for search engine optimization.

First question: How do I make these type of links good for SEO and is this secure? It seems like it would be easy to inject code?

Second question:

After getting the corresponding input from the user, I have the following in my SearchController to deal with the input:

public function postSearchResults() {
        $searchStr = Input::get('query');
        $color = Input::get('color');
        $etc = Input::get('etc');

        $query = DB::connection('mysql')->table('cards')
            ->where('name', 'LIKE', '%'.$searchStr.'%')
            ->where('color', 'LIKE', '%'.$color.'%')
            ->where('etc', 'LIKE', '%'.$etc.'%')
            ->get();

        return parent::ajaxView('results', compact('query'));
}

Is the above secure or is there something I should do in addition to make it secure?


texts: Implementing key map with expire and size limit

texts:
Recently I have been asked to implement a key map with expire time for each key and possibility to limit the number of keys, in Python. I've used a dictionary + heap to store the entries, e.g.:

from datetime import datetime, timedelta
from heapq import heapify, heappop, heappush

class KeyMap:
    def __init__(self, maxsize=None):
        self.maxsize = maxsize
        self.entries = {}
        self.entries_heap = []

    def set(self, key, value, expiration_time: timedelta):
        expires_at = datetime.now() + expiration_time
        entry = {'key': key, 'value': value, 'expires_at': expires_at}
        self.entries[key] = entry
        heappush(self.entries_heap, (expires_at, entry))

        if len(self.entries) > self.maxsize:
            _, oldest = heappop(self.entries_heap)
            del self.entries[oldest['key']]

    def get(self, key):
        entry = self.entries[key]
        if entry['expires_at'] < datetime.now():
            del self.entries[key]
            raise KeyError(key)
        return entry[value]

    def delete(self, key):
        del self.entries[key]
        for i in range(len(self.entries)):
            if self.entries_heap[i][1]['key'] == key:
                self.entries_heap[i] = self.entries_heap[-1]
                self.entries_heap.pop()
        heapify(self.entries_heap)

AFAIC, this should give O(log n) time for set(), O(1) for get() and O(n) for delete(). Are there any ways to improve the performance of set() and delete() methods?


texts:
I've started a little challenge on a website, and the first one was about counting different DNA letters. I've done it, but I found my method very brutal. I have a little experience, and I know that hard-coded information is not good. Any way to improve this code?

chaine = "AAAACCCGGT"

nA = 0
nT = 0
nG = 0
nC = 0

for i in range(len(chaine)):
   if chaine[i] == "A":
       nA = nA + 1
   if chaine[i] == "C":
       nC = nC + 1
print nA, nC


texts: Python custom generator of object not efficient

texts:
Let's consider the following class Signal which defines a multiphasic signal:

class Signal:
    def __init__(self, fq, phases):
        self.fq = fq
        self.phases = phases

I created a function that generates Signal to test in another function.

# -*- coding: utf-8 -*-

import itertools

def duo_SBs_to_test(SB1, SB2, frequency_step = 1, shift_step = 50, max_shift = 20000, permutations = True):

    upper_frequency = frequency_step + 1/(2*max(sum(SB1.phases), sum(SB2.phases)))*1000000

    if SB1.fq <= 100 and SB2.fq <= 100:
        r1 = 0.1
        r2 = 0.1
        upper1 = SB1.fq + r1*SB1.fq + frequency_step
        upper2 = SB2.fq + r2*SB2.fq + frequency_step
    elif SB1.fq <= 100 and SB2.fq > 100:
        r1 = 0.1
        r2 = 0.2
        upper1 = SB1.fq + r1*SB1.fq + frequency_step
        upper2 = SB2.fq + r2*SB2.fq + frequency_step
        if upper2 > upper_frequency:
            upper2 = upper_frequency
    elif SB1.fq > 100 and SB2.fq <= 100:
        r1 = 0.2
        r2 = 0.1
        upper1 = SB1.fq + r1*SB1.fq + frequency_step
        upper2 = SB2.fq + r2*SB2.fq + frequency_step
        if upper1 > upper_frequency:
            upper1 = upper_frequency
    else:
        r1 = 0.2
        r2 = 0.2
        upper1 = SB1.fq + r1*SB1.fq + frequency_step
        upper2 = SB2.fq + r2*SB2.fq + frequency_step
        if upper1 > upper_frequency:
            upper1 = upper_frequency
        if upper2 > upper_frequency:
            upper2 = upper_frequency

    for s, f1, f2 in itertools.product(range(0, max_shift+shift_step, shift_step),
                                       range(int(SB1.fq - r1*SB1.fq), int(upper1), frequency_step),
                                       range(int(SB2.fq - r2*SB2.fq), int(upper2), frequency_step)):

        yield (Signal(f1, SB1.phases), Signal(f2, SB2.phases), s)
        if permutations:
            yield (Signal(f2, SB2.phases), Signal(f1, SB1.phases), s)

Surprisingly, the performance isn't great. It's my first time creating a generator, and I guess I missed something.

%timeit res = [elt for elt in duo_SBs_to_test(SB1, SB3, frequency_step = 1,
shift_step = 50, max_shift = 20000, permutations = True)]
829 ms ± 11.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit res = [elt for elt in duo_SBs_to_test(SB1, SB3, frequency_step = 1,
shift_step = 50, max_shift = 20000, permutations = True)]
842 ms ± 13.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit for elt in duo_SBs_to_test(SB1, SB3, frequency_step = 1,
shift_step = 50, max_shift = 20000, permutations = True): continue
765 ms ± 5.81 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit for elt in duo_SBs_to_test(SB1, SB3, frequency_step = 1,
shift_step = 50, max_shift = 20000, permutations = True): continue
768 ms ± 5.66 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

The former function I was using was storing frequency_to_test in a list, shifts in a numpy array before running the itertools.product() and storing in a list the Signals_to_test. Yet, it was just as fast...

EDIT:

SB1 = Signal(50, [300, 50, 900])
SB3 = Signal(80, [300, 50, 900])

Thanks for the tips :)

EDIT2: Next step:

def compute(SB1, SB2, frequency_step = 1, shift_step = 50, max_shift = 20000, permutations = True):

    result = list()
    for duo_generated in duo_SBs_to_test(SB1, SB2, frequency_step, shift_step, max_shift, permutations):
        if not condition(duo_generated):
            continue
        else:
            result.append(duo_generated)

    return result

condition() is a function returning a boolean.


texts:
A binary tree is balanced if both its children are balanced and the difference between the heights of its children is at most 1.

/**
 * Definition for a binary tree node.
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode parent;

    TreeNode(int x) {
        val = x;
    }
}

public class isBalanced {
    // first we will get the left height and right height of the node
    // and compute the height difference.if it is > 1 we will return false
    // hashtable to maintain height of each node to reduce the no of redundant
    // height computations
    static Hashtable<TreeNode, Integer> haTab = new Hashtable<>();

    static int height(TreeNode root) {
        // if the node is null then it returns the height as -1
        int heightOfNode;
        if (root == null) {
            return -1;
        }
        if (haTab.containsKey(root)) {
            return haTab.get(root);
        }
        int leftHeight, rightHeight;
        leftHeight = height(root.left);
        rightHeight = height(root.right);
        // finds the height of left subtree and right subtree and returns
        // the max of both + 1
        heightOfNode = Math.max(leftHeight, rightHeight) + 1;
        haTab.put(root, heightOfNode);
        return heightOfNode;
    }

    public static boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftHeight, rightHeight;
        leftHeight = height(root.left);
        rightHeight = height(root.right);
        // if left child and right child are balanced and the difference in
        // their heights is < 2
        // then it is balanced
        if (isBalanced(root.left) && isBalanced(root.right)
                && Math.abs(leftHeight - rightHeight) < 2) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(-2);
        root.right = new TreeNode(-3);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right.right = new TreeNode(-1);
        System.out.println(isBalanced(root));
    }
}


texts:
I have a simple python script that's repeating a HTTP response/request. I would like to know how I could have constructed this better, particularly if there's a way I could have incorporated the slice operator to cut down on my variable usage.

For context - the response contained a JSON string in between the <ExecuteResult> flags that I'm removing currently with split()

import requests
import json
from pprint import pprint

url = "<redacted>"
cookies = {<redacted>}
headers = {<redacted>}
data="<redacted>"

submissions = input("How many submissions to create:")

while submissions > 0:
    response = requests.post(url, headers=headers, cookies=cookies, data=data)
    xml_string = response.content
    json_file = xml_string.split('<ExecuteResult>')[1]
    json_file = (json_file.split('</ExecuteResult>')[0]).replace("\\", "")
    json_response = json.loads(json_file)
    print "Created Id: " + json_response['_entity']['Id']
    submissions -= 1


texts:
Does my PHP look secure enough for a sign up form?

<?php
$con=mysqli_connect("host","user","password","db_name");
$sql="INSERT INTO users values (?, ?, ?)";
if ($stmt = mysqli_prepare($con,$sql)) {
  mysqli_stmt_bind_param($stmt, "sss",
    $_POST["username"], $_POST["pwd"], $_POST["email"]);
  if (mysqli_stmt_execute($stmt)) {
    echo "User added!";
  }
}


texts:
So, here's my code:

public class NList : SExp, IEnumerable<Object>
{
    private Object _car;
    private NList _cdr;

    IEnumerator<Object> IEnumerable<Object>.GetEnumerator()
    {
        return new NListEnumerator(this);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return new NListEnumerator(this);
    }

    public object car ()
    {
        return _car;
    }

    public NList cdr ()
    {
        return _cdr;
    }

    public NList cons (object o)
    {
        return new NList(o, this);
    }

    public NList() // empty list
    {

    }

    public NList(List<Object> lst)
    {
        if (lst.Count == 1)
        {
            this._car = lst[0];
            this._cdr = null;
        }
        else
        {
            this._car = lst[0];
            this._cdr = new NList(lst.GetRange(1, lst.Count - 1));
        }
    }

    public NList (Object fst)
    {
        this._car = fst;
        this._cdr = null;
    }

    public NList (Object fst, NList rst)
    {
        this._car = fst;
        this._cdr = rst;
    }

    public object Last()
    {
        NList list = this;
        while(list.cdr() != null)
        {
            list = list.cdr();
        }
        return list.car();
    }

    public int Count { get { return this.length(); } }

    public int length()
    {
        if (this._car == null && this._cdr == null) return 0;
        NList list = this;
        int len = 1;
        while(list.cdr() != null)
        {
            list = list.cdr();
            len++;
        }
        return len;
    }

    public NList cddr()
    {
        return this.cdr().cdr();
    }

    public object cadr()
    {
        return this.cdr().car();
    }

    public object elm(int k)
    {
        if(k == 0) return car();
        NList list = cdr();
        for(int i = 1; i < k; i++, list = list.cdr()) ;
        return list.car();
    }

    public NList append(NList lst)
    {
        NList lst1 = this;
        NList lst2 = lst;
        if (this._car == null && this._cdr == null)
            return lst2;
        foreach(var e in Reverse(lst1))
        {
            lst2 = lst2.cons(e);
        }
        return lst2;
        //return lst1.Aggregate(lst2, (NList acc, object b) => acc);
    }

    public static NList Reverse(NList lst)
    {
        NList l = lst;
        NList res = null;
        while(l != null)
        {
            res = new NList(l.car(), res);
            l = l.cdr();
        }
        return res;
    }

    public override string ToString ()
    {
        if (this._car == null && this._cdr == null) return "()";
        string s = "(";
        for(int i = 0; i<this.Count-1; i++)
        {
            s+=this.elm(i).ToString() + " ";
        }
        s+=this.Last().ToString() + ")";
        return s;
    }
    public NObj[] ToNObjArray()
    {
        NObj[] a = new NObj[this.Count];
        int k = 0;
        foreach (var e in this)
        {
            a[k] = (e as NObj);
            k++;
        }
        return a;
    }
    public object[] ToArray()
    {
        object[] a = new object[this.Count];
        int k = 0;
        foreach(var e in this)
        {
            a[k] = e;
            k++;
        }
        return a;
    }
}

public class NListEnumerator : IEnumerator<Object>, IEnumerator
{
    NList list;
    NList tmp;
    public void Dispose()
    {
    }
    public NListEnumerator(NList list)
    {
        this.list = list;
        this.tmp = list.cons(null);
    }

    public object Current
    {
        get { return tmp.car(); }
    }

    public bool MoveNext()
    {
        tmp = tmp.cdr();
        return (tmp != null);
    }

    public void Reset()
    {
        tmp = list.cons(null);
    }
}

I am kinda worried that I have no separate class for simple pairs (eg: non-properly terminated lists like (1 . 2), (a . b)). Should I create a separate class (and an interface for both classes), or should I try to expand this one?

TIA.


texts:
I implemented search module, but I'm a novice in programming and I'm not sure about public and private functions that I coded. Did I do it right?

var data = require('./data');

function My_module(string) {
    var data_size_ = data.length;

    /**
     * @param {Array.<Object>} data.
     * @return {Array.<Object>} result.
     */

    var reformat_ = function() {
        var result = new Array(data_size_);

        var first_name;
        var last_name;
        var domain;

        for (var i = 0; i < data_size_; ++i) {
            first_name = data[i].first_name.toLowerCase();
            last_name = data[i].last_name.toLowerCase();
            domain = data[i].domain.toLowerCase();

            result[i] = {
                'first_name': first_name,
                'last_name': last_name,
                'domain': domain,
            };
        }

        return result;
    };

    var formatted_data_ = reformat_();

    /**
     * A search function.
     * @return {Array.<Object>} Result
     */

    this.search = function(string) {
        var result = [];
        var len = string.length;

        for (var i = 0; i < data_size_; ++i) {
            if (formatted_data_[i].first_name.slice(0, len) === string ||
                formatted_data_[i].last_name.slice(0, len) === string ||
                formatted_data_[i].domain.slice(0, len) === string) {
                result.push(formatted_data_[i]);
            }
        }

        if (result) {
            return result;
        }
    }

}

module.exports = My_module;


texts: Representation of the formula P(n) = (n!)(6^n) in C

texts:
I'm trying to represent the following mathematical expression in C:

$$P(n)=(n!)(6^n)$$

The first program should compute the answer to expression when n = 20. I have attempted to create the program in C and it produces the correct answer (when compared with wolfram alpha's answer). The answer is approximately \$10^{34}\$.

Is there any way that I could improve the code?:

#include <math.h>
typedef unsigned int uint;

void main()
{
    uint n=20;
    double F=1,pwr,P;

    pwr=pow(6,n);

    while(n>0){
        F=F*n;
        n=n-1;
    }
    P=F*pwr;
}


texts: LeetCode "Jewels and Stones": counting certain characters in a string

texts:
LeetCode "Jewels and Stones"

  You're given strings J representing the types of stones that are
  jewels, and S representing the stones you have.  Each character in
  S is a type of stone you have.  You want to know how many of the stones you have are also jewels.

  The letters in J are guaranteed distinct, and all characters in J
  and S are letters. Letters are case sensitive, so "a" is considered
  a different type of stone from "A".

  Example 1:

  Input: J = "aA", S = "aAAbbbb"
  Output: 3

  Example 2:

  Input: J = "z", S = "ZZ"
  Output: 0

  Note:

  S and J will consist of letters and have length at most 50. The
  characters in J are distinct.

My approach:

class Solution {
    public int numJewelsInStones(String J, String S) {

        int count = 0;
        for( int i = 0; i < J.length(); i++ )
        {
            for( int j = 0; j < S.length(); j++ )
            {
                if( J.charAt(i) == S.charAt(j) )
                    count++;
            }
        }
        return count;
    }
}

Time complexity: O(n^2)

Space complexity: O(1)

Another approach:

class Solution {
    public int numJewelsInStones(String J, String S) {
        Set<Character> jSet = new HashSet<>();
        for(Character ch : J.toCharArray()) {
            jSet.add(ch);
        }
        int count = 0;
        for(Character ch: S.toCharArray()) {
            if(jSet.contains(ch)) {
                count++;
            }
        }
        return count;
    }
}

Time complexity: O(n)
Space complexity: O(n)

I have the following questions regarding the above code snippets:

Which approach is better according to you?
Will the interviewer be more impressed by the 2nd method as it has used Set?
How can I further improve my code (sort the string and perform a binary search)-> O(n*log(n))?


texts:
here is my implementation to find the lowest common ancestor in a binary tree. It works but i would like to know if i could have done anything better or if i have missed an specific case. would really appreciate ur feedback:

//The function findOrQueue is to enqueue all elements upto target node to a queue
public void findOrQueue(Node target, Node top, LLQueue q) {
    int cmp = target.getData().compareTo(top.getData());
    if(cmp == 0) {
        q.enqueue(top);
        return ;
    }
    else if (cmp < 0) {
        q.enqueue(top);
        findOrQueue(target, top.getLeftChild(),q);
    }
    else {
        q.enqueue(top);
        findOrQueue(target, top.getRightChild(),q);
    }
}

public Node LCA(Node n1, Node n2) throws QueueEmptyException {
    LLQueue q1 = new LLQueue();
    LLQueue q2 = new LLQueue();
    findOrQueue(n1,getRoot(),q1);
    findOrQueue(n2,getRoot(),q2);
    Node t = null;
    while (!q1.isEmpty() && !q2.isEmpty()) {
        Node t1 = (Node)q1.dequeue();
        Node t2 = (Node)q2.dequeue();
        if(t1.getData() != t2.getData()) {
            return t;
        }
        else t = t1;
    }
    if(q1.isEmpty() && q2.isEmpty())
        return null;
    else
        return t;
}


texts:
I haven't been learning Python for too long and I was just wondering how this Pokémon style battle looks? It's based off of this:
Turn Based Pokémon Style Game. It's my first proper time using classes so I'd love advice or critique on the usage. Also, where I make the CPU more likely to use heal when under 35 health, there must surely be a better way to do that.

# Simple battle simulator in the style of Pokemon.
# author: Prendy

import random

moves = {"tackle": range(18, 26),
         "thundershock": range(10, 36),
         "heal": range(10, 20)}

class Character:
    """ Define our general Character which we base our player and enemy off """
    def __init__(self, health):
        self.health = health

    def attack(self, other):
        raise NotImplementedError

class Player(Character):
    """ The player, they start with 100 health and have the choice of three moves """
    def __init__(self, health=100):
        super().__init__(health)

    def attack(self, other):
        while True:
            choice = str.lower(input("\nWhat move would you like to make? (Tackle, Thundershock, or Heal)"))

            if choice == "heal":
                self.health += int(random.choice(moves[choice]))
                print("\nYour health is now {0.health}.".format(self))
                break
            if choice == "tackle" or choice == "thundershock":
                damage = int(random.choice(moves[choice]))
                other.health -= damage
                print("\nYou attack with {0}, dealing {1} damage.".format(choice, damage))
                break
            else:
                print("Not a valid move, try again!")

class Enemy(Character):
    """ The enemy, also starts with 100 health and chooses moves at random """
    def __init__(self, health=100):
        super().__init__(health)

    def attack(self, other):
        if self.health <= 35:
            # increasing probability of heal when under 35 health, bit janky
            moves_1 = ["tackle", "thundershock", "heal", "heal", "heal", "heal", "heal"]
            cpu_choice = random.choice(moves_1)
        else:
            cpu_choice = random.choice(list(moves))
        if cpu_choice == "tackle" or cpu_choice == "thundershock":
            damage = int(random.choice(moves[cpu_choice]))
            other.health -= damage
            print("\nThe CPU attacks with {0}, dealing {1} damage.".format(cpu_choice, damage))
        if cpu_choice == "heal":
            self.health += int(random.choice(moves[cpu_choice]))
            print("\nThe CPU uses heal and its health is now {0.health}.".format(self))

def battle(player, enemy):
    print("An enemy CPU enters...")
    while player.health > 0 and enemy.health > 0:
        player.attack(enemy)
        if enemy.health <= 0:
            break
        print("\nThe health of the CPU is now {0.health}.".format(enemy))
        enemy.attack(player)
        if player.health <= 0:
            break
        print("\nYour health is now {0.health}.".format(player))
    # outcome
    if player.health > 0:
        print("You defeated the CPU!")
    if enemy.health > 0:
        print("You were defeated by the CPU!")

if __name__ == '__main__':
    battle(Player(), Enemy())


texts: JavaScript bottom-up tree transformer aimed for performance

texts:
function transform(tree,fn){
    var root = tree,
        node = tree,
        child,
        parent,
        is_node,
        dir;
    root.dir = 0;
    while(true) {
        is_node = typeof(node)==="object";
        dir = is_node ? node.dir : 2;
        if (dir < 2)
            child = node[dir],
            node.dir++,
            child.parent = parent = node,
            child.dir = 0,
            node = child;
        else if ((changed = fn(node))!==undefined)
            changed.parent = parent,
            changed.dir = 0,
            node = changed;
        else
            if (!parent)
                return node;
            else
                parent[parent.dir-1] = node,
                node = parent,
                parent = node.parent;
    };
};

// TEST
var tree = [[1,2],[[3,4],[5,6]]];
console.log(
    JSON.stringify(transform(tree,function(a){
        if (a[0]===1) return [3,[5,5]];
        if (a[0]===5) return 77;
    })) === "[[3,77],[[3,4],77]]");

I need to make this function as fast as possible, no matter what. I'm aware this is far from the optimal implementation. How could I improve it? Asm.js, maybe?


texts: Sorting an array of bands by omitting articles

texts:
I've written a simple script that takes an array, sorts it (by omitting the articles) and displays it on a list. But I feel like this code is really huge, bulky and messy and could be simplified!

What I'm asking for:

What would be a more efficient way to do what I'm trying to do?
How would I make this code more neat (or compact in other words).
Could any new JS features ease up my work?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Sort Without Articles</title>


texts: updatePositions() Laravel controller method

texts:
I have been trying to implement good 'OOP' and coding standards, but I always end up with bloated controllers. How could I clean this controller method?

public function updatePositions(Request $request)
{
    MenuItem::setNewOrder($request->positions);
    $item = MenuItem::findOrFail($request->itemId);

    if (!is_array($request->path)) {
        return response()->json('Invalid data', 400);
    }

    if (count($request->path) === 1) {
        if ($item->parent()->exists()) {
            $item->parent()->dissociate();
            $item->save();
        }
    } else {
        $potentialParent = $item->sort_order - last($request->path) - 1;
        $previousRecord = MenuItem::where('sort_order', $potentialParent)->first();
        $item->parent()->associate($previousRecord);
        $item->save();
    }
}

it sets a completely new order for the MenuItem at hand, which I think in itself my be a method?
it checks if the $request->path is an array and returns a formatted json response, should this throw an exception?
It then checks the length of $request->path and disassociates a relation model or if the length is greater then 1, it associates a relationship object after finding that.

Any advice in the good direction is welcome here.


texts: Method that checks whether to disable or enable the buttons depending on whether data is null or not

texts:
I have this bit of code that needs refactoring/simplification. The below grabs the planning data for view A and B. Then it joins the planning and matching image for view details. So then it determines if it should set the buttons to be disabled or not based on whether or not, if the data is empty/null or not.

I think the major refactoring might be needed for adding the elements to the dictionaries for each view.

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult CheckButtons()
{
    int planId = (int)UserSession.GetValue(StateNameEnum.ID, "PlanID");

    planning resultSetA = db.planning.Where(t => t.PlanId == planId).Join(db.matching_image, p => p.MatchingImageId, i => i.Id,
      (p, i) => new
      {
          planning = p,
          i.View
      }).Where(j => j.View == "A").Select(j => j.planning).FirstOrDefault();

    structure sA = db.structure.FirstOrDefault(s => s.PlanId == planId && s.Type == "A");

    planning resultSetB = db.planning.Where(t => t.PlanId == planId).Join(db.matching_image, p => p.MatchingImageId, i => i.Id,
      (p, i) => new
      {
          planning = p,
          i.View
      }).Where(j => j.View == "B).Select(j => j.planning).FirstOrDefault();

    structure sB = db.structure.FirstOrDefault(s => s.PlanId == planId && s.Type == "B");

    Dictionary<string, string> buttonADictionary = new Dictionary<string, string>();
    Dictionary<string, string> buttonBDictionary = new Dictionary<string, string>();
    buttonADictionary.Add("C", resultSetA.CorrespondingId != null ? "disabled" : "enabled");
    buttonADictionary.Add("R", resultSetA.ResponseId != null ? "disabled" : "enabled");
    buttonADictionary.Add("S", (sA != null && sA.Point_x != null) ? "disabled" : "enabled");
    buttonADictionary.Add("D", resultSetA.DistalId != null ? "disabled" : "enabled");
    buttonADictionary.Add("P", resultSetA.ProximalId != null ? "disabled" : "enabled");
    buttonBDictionary.Add("C", resultSetB.CorrespondingId != null ? "disabled" : "enabled");
    buttonBDictionary.Add("R", resultSetB.ResponseId != null ? "disabled" : "enabled");
    buttonBDictionary.Add("S", (sB != null && sB.Point_x != null) ? "disabled" : "enabled");
    buttonBDictionary.Add("D", resultSetB.DistalId != null ? "disabled" : "enabled");
    buttonBDictionary.Add("P", resultSetB.ProximalId != null ? "disabled" : "enabled");
    bool aHasData = buttonADictionary.ContainsValue("disabled");
    bool bHasData = buttonBDictionary.ContainsValue("disabled");

    return Json(new { buttonADictionary, buttonBDictionary, aHasData, bHasData }, JsonRequestBehavior.AllowGet);
}


texts:
This is an implementation of a 2D peak finder from MIT's Intro to Algos.
I'm a C beginner and I would really like some feedback on coding style, documentation and any other general C bad practices.
Additionally have I correctly freed the memory of the recursive calls?
#include <stdio.h>
#include <stdlib.h>

typedef struct max_vector {
    unsigned int col_index;
    unsigned int row_index;
    int index_value;
} max_vector;

max_vector * find_col_peak(int *arr, int rows, int col){
    /* Find the peak of a column.

    This function treats a 2D array like a 1D array and
    traverses using some basic pointer arithmetic.

    next item = *((i * row + arr) + j)
    where:
        - i == current row number (the y axis in matrix i.e. up and down)
        - j == column number in column space (the x axis i.e left to right)
        - row == the number of items in each row
        - *arr == the first item in the array
    */

    // we want a vector to save the max number and its index
    max_vector *vector = malloc(sizeof(max_vector));

    if (vector) {
        // set max to the first item of the column
        vector->col_index = 0;
        vector->index_value = *(col + arr);

        // loop through the rest of the column
        for (int i=1; i < rows; i++){
            int next_number = *((i * rows + arr) + col);
            if (next_number > vector->index_value){
                vector->col_index = i;
                vector->index_value = next_number;
            }
        }
        printf("the max value is %d and it is at index %d\n",
            vector->index_value, vector->col_index);
        return vector;
    }
    return NULL;
}

max_vector * peak_finder(int *matrix, int rows, int first, int last){
    /* Find a local 2D peak.

    NOTE: Expects a matrix of size row x col

    A peak is defined as:
    (i, j) >= (i, j + 1), (i, j - 1), (i + 1, j) (i - 1, j)
    */

    max_vector *vector;

    int middle = last / 2;
    vector = find_col_peak(matrix, rows, middle);

    if (vector){
        if (middle == first || middle == last){
            vector->row_index = middle;
            return vector;
        }

        if (last > first) {
            int current = *((vector->col_index * rows) + matrix + middle);
            int one_less = *((vector->col_index * rows) + matrix + middle - 1);
            int one_more = *((vector->col_index * rows) + matrix + middle + 1);

            if (one_less <= current >= one_more) {
                vector->row_index = middle;
                return vector;
            }

            // if current is not a peak we can free the vector
            if (one_less > current){
                free(vector);
                return peak_finder(matrix, rows, first, middle - 1);
            } else {
                free(vector);
                return peak_finder(matrix, rows, middle + 1, last);
            }
        }
        vector->row_index = middle;
        return vector;
    }
    return NULL;
}

int main(void) {
  int arr [5][5] = {
    {10, 8, 11, 10, 16},
    {14, 13, 12, 11, 24},
    {15, 9, 11, 21, 6},
    {16, 21, 19, 20, 12},
    {100, 6, 13, 19, 9},
  };

  max_vector *ptr = peak_finder(*arr, 5, 0, 5);
  printf("the local peak is at %d, %d", ptr->row_index, ptr->col_index);
  free(ptr);
  return 0;
}


texts: R-Python sieve, 36 times slower than World Record

texts:
I decided to write a sieving prime-finding programme and make it fast. It works correctly but counting the primes below 10**9 takes 36 times as primesieve downloaded from http://primesieve.org/.

Now I understand that they have a World Record so they better be fast, but we all know that a compiler is much better than a human at making optimization, so I fear I missed a massive optimization in my implementation.

Some timings:

time ./sieve-c 100000000
Up to 100000000 there are 5761455 primes.

real  0m1.914s
user  0m1.876s
sys   0m0.032s

time ./primesieve 100000000
Sieve size = 32 kilobytes
Threads    = 4
100%
Prime numbers : 5761455
Time elapsed  : 0.0568619 sec

real  0m0.206s
user  0m0.192s
sys   0m0.004s

time ./sieve-c 1000000000
Up to 1000000000 there are 50847534 primes.

real  0m21.408s
user  0m21.128s
sys   0m0.252s

time ./primesieve 1000000000
Sieve size = 32 kilobytes
Threads    = 4
100%
Prime numbers : 50847534
Time elapsed  : 0.582213 sec

real  0m0.607s
user  0m2.220s
sys   0m0.000s

Where should I go next for better performance (wheel factorization, memoization, segmentation, parallelism)?

Also, my code is not able to calculate 10**10 or more because that would take up too much space and my computer crashes. Maybe I should try segmentation?

Please note that R-Python is a subset of Python, so you can run my programme with a regular Python too (but it will be much slower).

import doctest
import math
import sys
import doctest

def sieve(limit):
    """
    Returns the primes below the `limit`

    >>> sieve(9)
    [False, False, True, True, False, True, False, True, False]
    >>> sieve(100000).count(True)
    9592
    """
    sieve = [True]*limit
    sieve[0],sieve[1] = False, False
    sqrt_limit = math.sqrt(limit)
    for number, prime in enumerate(sieve):
        if prime:
            for multiple in xrange(number*2, limit, number):
                sieve[multiple] = False
        if number > sqrt_limit:
            break
    return sieve

doctest.testmod()

def _sum(lst):
    s = 0
    for i in lst:
        s += i
    return s

def main(argv):
    print("Up to " + argv[1] +" there are " +str(_sum(sieve(int(argv[1])+1))) + " primes.")
    return 0

def target(*args):
    return main, None

if __name__ == '__main__':
    import sys
    main(sys.argv)


texts: One producer and multiple consumers wherein the producer has to wait until all consumers finish before adding more data

texts:
I am trying to solve the scenario involving 1 producer and 5 consumers. The producer puts data to queue and waits till all consumers have finished before adding more data.

Please review and let me know if there is room for improvement.

import java.util.LinkedList;
import java.util.Queue;

public class ReadUpdate {

   static int cntr;
   static volatile int writeLck = 1;
   static int numSupplied;
   Queue queue = new LinkedList<Node>();

    public static void main(String arg[]) {
        ReadUpdate rU = new ReadUpdate();
        Producer p = new Producer(rU.queue);
        p.start();
        Consumer c1 = new Consumer(rU.queue, 1);
        c1.setName("1");
        c1.start();
        Consumer c2 = new Consumer(rU.queue, 2);
        c2.setName("2");
        c2.start();
        Consumer c3 = new Consumer(rU.queue, 3);
        c3.setName("3");
        c3.start();
        Consumer c4 = new Consumer(rU.queue, 4);
        c4.setName("4");
        c4.start();
        Consumer c5 = new Consumer(rU.queue, 0);
        c5.setName("5");
        c5.start();
    }
 }

class Consumer extends Thread {
    Queue queue;
    int turn;

    Consumer(Queue queue, int turn) {
        this.queue = queue;
        this.turn = turn;
    }

    public void run() {
        while (ReadUpdate.numSupplied <= 100) {
            synchronized (ReadUpdate.class) {
                while (queue.isEmpty() || ReadUpdate.cntr % 5 != this.turn) {
                    try {
                        ReadUpdate.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("THREAD " + Thread.currentThread().getName()
                        + " GOT " + queue.poll());
                if (ReadUpdate.cntr % 5 == 0) {
                    ReadUpdate.writeLck = 1;
                } else {
                    ReadUpdate.cntr++;
                }
                ReadUpdate.class.notifyAll();
            }
        }
    }
}

class Producer extends Thread {
    Queue queue;

    Producer(Queue queue) {
        this.queue = queue;
        ReadUpdate.numSupplied++;
    }

    public void run() {
        while (ReadUpdate.numSupplied < 100) {
            synchronized (ReadUpdate.class) {
                while (ReadUpdate.writeLck == 0) {
                    try {
                        ReadUpdate.class.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < 5; i++) {
                    queue.offer(ReadUpdate.numSupplied++);
                }
                ReadUpdate.writeLck = 0;
                ReadUpdate.cntr++;
                ReadUpdate.class.notifyAll();
            }
        }
    }
}


texts:
I wrote some code to validate a form, I'm using live validation, as the user types, here is the snippet that I wrote just for the live validation, but I think I'm repeating too much and I'm looking for some advices:

  $('form input').focus(function(){
      var inp = $(this).attr('name');
      switch(inp)
      {
        case 'password2':
          var theIn = $(this).parent().prev().find('input');
          if(!theIn.val() != '')
          {
            theIn.addClass('error');
          }else{
            theIn.removeClass('error');
          }

        var theInp = $(this).parent().prevAll().find('input,select');
        theInp.each(function(){
        if((!$(this).val()) || ($(this).val() == '-1'))
        {
          $(this).addClass('error');
        }else{
          $(this).removeClass('error');
        }
        });

        break;
        default:
        //Find all previous inputs and see if they are OK
        var theInp = $(this).parent().prevAll().find('input,select');
        theInp.each(function(){
        if((!$(this).val()) || ($(this).val() == '-1'))
        {
          $(this).addClass('error');
        }else{
          $(this).removeClass('error');
        }
        });
      }
    });

/*
* Register front on keypress
 */
  $('form input,form select').each(function(){

    //Select <select>
    $(this).change(function(){
      if($(this).val() == '-1')
      {
        $(this).addClass('error');
      }else{
        $(this).removeClass('error');
      }
    });
    $(this).keyup(function(e){
      var type = $(this).attr('name');
      $(this).parent().find('span.preloader').css('visibility','hidden');
      switch(type)
      {
        case 'email':
          var pattern = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;
          if(!$(this).val().match(pattern))
          {
            $(this).addClass('error');
          }else{
            $(this).removeClass('error');
          }
        break;
        case 'password2':

          if($(this).val() != $(this).parent().prev().find('input').val())
          {
            $(this).addClass('error');
            $(this).parent().prev().find('input').addClass('error');
          }else{
            $(this).removeClass('error');
            $(this).parent().prev().find('input').removeClass('error');
          }
        break;
        case 'password':
          if($(this).val() == $(this).parent().next().find('input').val())
          {
            $(this).parent().next().find('input').removeClass('error');
            $(this).removeClass('error');
          }else{
            $(this).addClass('error');
          }
          return true;
        break;
        default:
          if((!$(this).val()) || ($(this).val() == '-1'))
          {
            $(this).addClass('error');
          }else{
            $(this).removeClass('error');
          }
      }
  });
});