texts:
This method is written for much larger Web application, but I just extracted it and added class and main method around it so that it can be debugged locally.

Browser detection is done in another method, then this one is called to precisely determine IE version, i.e. if it is in compatibility mode or not. All other checks are done previously.

String headerUserAgent = "headerUserAgent mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko"; is "REAL" IE 11 so the output will be 11.0

String headerUserAgent = "mozilla/4.0 (compatible; msie 7.0; windows nt 6.1; wow64; trident/7.0; slcc2; .net clr 2.0.50727; .net clr 3.5.30729; .net clr 3.0.30729; media center pc 6.0; .net4.0c; .net4.0e; infopath.3; gwx:reserved)"; is one of compatibility modes so output will be as expected: 00

Code works according to my tests.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnsupportedBrowserMode
{
    public static void main(String[] args)
    {
        String headerUserAgent = "mozilla/4.0 (compatible; msie 7.0; windows nt 6.1; wow64; trident/7.0; slcc2; .net clr 2.0.50727; .net clr 3.5.30729; .net clr 3.0.30729; media center pc 6.0; .net4.0c; .net4.0e; infopath.3; gwx:reserved)";
        //String headerUserAgent = "headerUserAgent mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko";
        String version = getInternerExplorerVersion(headerUserAgent);
        System.out.println(version);
    }

    public static String getInternerExplorerVersion(String headerUserAgent)
    {
        String version = null;
        String TrueVersion = null;
        String ActingVersion = null;

        if (headerUserAgent != null)
        {
            headerUserAgent = headerUserAgent.toLowerCase();

            // Try to find the Trident version number
            Matcher trident = Pattern.compile("trident\\/(\\d+)").matcher(headerUserAgent);

            if (trident.find() && trident.groupCount() > 0)
            {
                // Convert from the Trident version number to the IE version number
                TrueVersion = trident.group(1);

                // If it is IE 11 TrueVersion will be overwritten with revision number
                int x = headerUserAgent.indexOf("rv:");
                if (x > 0)
                {
                  int y = headerUserAgent.indexOf(")", x);
                  if (y > x)
                  {
                      TrueVersion = headerUserAgent.substring(x + 3, y);
                  }
                }
            }

            // Try to find the MSIE number
            Matcher msie = Pattern.compile("msie[ \\(]+([^ ;\\)]+)").matcher(headerUserAgent);
            if (msie.find() && msie.groupCount() > 0)
            {
                // Find the IE version number from the user agent string
                ActingVersion = msie.group(1);
            } else
            {
                // Must be IE 11 in "edge" mode
                ActingVersion = TrueVersion;
            }

            // If we have both a Trident and MSIE version number, see if they're different
            if (Float.parseFloat(TrueVersion) > 0 && Float.parseFloat(ActingVersion) > 0)
            {
                // In compatibility mode if the trident number doesn't match up with the MSIE number
                if (TrueVersion != ActingVersion)
                {
                    version = "00";
                } else {
                    version = TrueVersion;
                };
            }
        }

        return version;
    }
}


texts:
I decided to run a few test on js functions on jspref to see which method of using function is better suited for this small particular example, to get a better understanding.

Page with tested functions

Problem:

Getting different results each time, Cold Start, Re-test, Re-Re Test are all coming with different results

First function - is just embedded in normally

$(function() {
  var up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25,
      triga = $('.trigger');
  triga.css("display", "none");
  $(window).scroll(function() {
    var down = $(this).scrollTop();
    (down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
  });
});

Second function - calling a global function

$(function() {
  triga.css("display", "none");
  $(window).scroll(function() {
    scrollMenu($(this).scrollTop())
  });
});

function scrollMenu(down) {
  var up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25,
      triga = $('.trigger');
  (down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
}

Third function - registering/calling variable function (to test/learn: I have no idea what I'm doing)

$(function() {
  $(window).scroll(function() {
    scrollMenu($(this).scrollTop())
  });
  var scrollMenu = function(down) {
      var triga = $('.trigger'),
          up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;
      (down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
      }
});

Fourth Func - Same as Third except Up is called before hand, and registered as a global func. Which i'm guessing is not a good idea if the project gets bigger over time.

// Variable Up Takes up The Global Namespace. Is it better to pre-define it OR have it         inside the scroll Menu anonymous func and get calculated each time the function is run?
$(function() {
  var up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;
  $(window).scroll(function() {
    scrollMenu(up, $(this).scrollTop())
  });
  var scrollMenu = function(up, down) {
      var triga = $('.trigger');
      (down > up) ? triga.fadeIn('fast') : triga.fadeOut('fast')
      }
});


texts:
I have my own type of object, which implements Serializable. Here I have one called "extendedFormat" (not a terribly helpful name, yes, I know). I'm writing it out to a file like so:

try {
    // is this the best way to do this????????
    // this seems like too many streams perhaps.
    // like maybe this is now a river
    File file = new File("C:/temp/tempExport.bef");
    file.createNewFile();
    FileOutputStream fileStream = new FileOutputStream(file);
    BufferedOutputStream bufferStream = new BufferedOutputStream(fileStream);
    ZipOutputStream zipStream = new ZipOutputStream(bufferStream);
    zipStream.putNextEntry(new ZipEntry("bef"));
    ObjectOutputStream objectStream = new ObjectOutputStream(zipStream);
    objectStream.writeObject(extendedFormat);
    zipStream.closeEntry();
    objectStream.close();
    zipStream.close();
    bufferStream.close();
    fileStream.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Is this the best way to do this? It seems a little over complicated but I want to save as much time writing it out and also space in terms of how big the file is that I write out.

I know this may seem like a lot for one object, but it can hold an entire table with possibly hundreds of columns and thousands of rows, so efficiency is important.


texts:
I just wrote a little Python 3 program to spit out every possible combination of a set of 99 characters.
It gets the job done, but I would be very interested in what you think of it.
I am just a few days into Python, so I would be grateful for even seemingly obvious advice.

import sys

# List of 99 characters and a blank string:

lib=["","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","°","!","\"","§","$","%","&","/","(",")","=","ß","´","`","+","#","-",".",",",">","<","@","€","|","^","~","–","{","[","]","}","Ä","Ö","Ü","ä","ö","ü"]

# 10 counters for up to 10-digit-combinations:

counter0=-1
counter1=0
counter2=0
counter3=0
counter4=0
counter5=0
counter6=0
counter7=0
counter8=0
counter9=0

# Repetitive if-statements adding to the counters:

for i in range(sys.maxsize**99999):
    counter0+=1

    if counter0>99:
        counter0=counter0*0
        counter1+=1

    elif counter1>99:
        counter1=counter1*0
        counter2+=1

    elif counter2>99:
        counter2=counter2*0
        counter3+=1

    elif counter3>99:
        counter3=counter3*0
        counter4+=1

    elif counter4>99:
        counter4=counter4*0
        counter5+=1

    elif counter5>99:
        counter5=counter5*0
        counter6+=1

    elif counter6>99:
        counter6=counter6*0
        counter7+=1

    elif counter7>99:
        counter7=counter7*0
        counter8+=1

    elif counter8>99:
        counter8=counter8*0
        counter9+=1

    elif counter9>99:
        print("DONE.")

# Printing the translation from counters to character - and deleting the former output so it stays in one line:

    else:
        print(lib[counter0]+lib[counter1]+lib[counter2]+lib[counter3]+lib[counter4]+lib[counter5]+lib[counter6]+lib[counter7]+lib[counter8]+lib[counter9], end="\r")
        sys.stdout.write("\b"*10+" "*10+"\b"*10)


texts:
I have the ubiquitous "validate and save" scenario, wherein the Save() method performs various validity checks and proceeds to save the data. The solution works just fine, but I am interested to know how elegantly and correctly this code can be refactored.

First, the domain:

public class Car
{
    public int Id { get; set; }
    public decimal Length { get; set; }
    public int Years { get; set; }

    private List<IValidationRule<Car>> _validationList;

    public Car()
    {
        this._validationList = new List<IValidationRule<Car>>();
        this._validationList.Add(new ValidateCarId());
        this._validationList.Add(new ValidateCarLength());
    }

    public void Save()
    {
        // This commented code will also work!
        //_validationList.TrueForAll(x => x.Validate(this));

        foreach (var item in _validationList)
        {
            item.Validate(this);
        }

        // Proceed to Save the data
        Console.WriteLine("Done!");
    }
}

Validation interface and validation provider classes:

interface IValidationRule<T>
{
    bool Validate(T t);
}

public class ValidateCarId : IValidationRule<Car>
{
    public bool Validate(Car t)
    {
        if (t.Id <= 0)
        {
            throw new IdNotFoundException("This Id is not available!");
        }
        else
        {
            return true;
        }
    }
}

public class ValidateCarLength : IValidationRule<Car>
{
    public bool Validate(Car t)
    {
        if (t.Length <= 1000m)
        {
            throw new LengthInvalidException("Length must be more than 1000");
        }
        else
        {
            return true;
        }
    }
}

public class ValidateCarYear : IValidationRule<Car>
{
    public bool Validate(Car t)
    {
        if (t.Years <= 0 || t.Years >= 2)
        {
            throw new YearInvalidException("Year invalid!");
        }
        else
        {
            return true;
        }
    }
}

Custom exceptions:

public class IdNotFoundException : Exception
{
    public IdNotFoundException() { }
    public IdNotFoundException(string message) : base(message) { }
    public IdNotFoundException(string message, Exception inner) : base(message, inner) { }
    protected IdNotFoundException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
}

[Serializable]
public class LengthInvalidException : Exception
{
    public LengthInvalidException() { }
    public LengthInvalidException(string message) : base(message) { }
    public LengthInvalidException(string message, Exception inner) : base(message, inner) { }
    protected LengthInvalidException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
}

[Serializable]
public class YearInvalidException : Exception
{
    public YearInvalidException() { }
    public YearInvalidException(string message) : base(message) { }
    public YearInvalidException(string message, Exception inner) : base(message, inner) { }
    protected YearInvalidException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }
}

And finally, the client:

class Program
{
    static void Main(string[] args)
    {
        Car vw = new Car { Id = -2, Length = 102, Years = 25 };

        try
        {
            vw.Save();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.WriteLine("Passed!");
    }
}

PS: I had to provide an else block in Validate(Cat t) for _validationList.TrueForAll(x => x.Validate(this)); to work. I felt this can be superfluous. How does it compare with foreach (var item in _validationList)?


texts: Overloading operator ->* for smart pointers

texts:
I am implementing a smart pointer class template and I want to overload operator ->* (even if it’s rarely done). I came across Scott Meyer’s article Implementing operator ->* for Smart Pointers. The article is from 1999 so I decided to try to adapt the code for C++ 14 (using parameter packs and perfect forwarding) and to improve it by adding support for pointer to data member—Meyer’s implementation only supports pointer to member functions—(which is the first of the two remaining problems of Meyer’s implementation that are listed at the section “Loose Ends” of his article and that he gives the reader as exercises to solve).

I ended up with the following code that seems to work quite fine. Now I have two questions:

Is there anything that could be improved in my code?
How to solve the second remaining problem listed at the section “Loose Ends” of Meyer’s article? (“You can’t use user-defined pointers-to-members. If someone has overloaded operator ->* to take objects that act like member pointers, you may want to support such ‘smart pointers to members’ in your smart pointer class. Unfortunately, you need traits classes to get the result type of such overloaded operator ->*.”)

Here is the code:

#include<iostream>

template<typename T>
struct Member_function_type_traits { };

template<typename O, typename... A, typename R>
struct Member_function_type_traits<R (O::*)(A...)> {
  typedef O Object_T;
  typedef R Return_T;
};

template<typename O, typename... A, typename R>
struct Member_function_type_traits<R (O::*)(A...) const> {
  typedef O Object_T;
  typedef R Return_T;
};

template<typename O, typename... A, typename R>
struct Member_function_type_traits<R (O::*)(A...) volatile> {
  typedef O Object_T;
  typedef R Return_T;
};

template<typename O, typename... A, typename R>
struct Member_function_type_traits<R (O::*)(A...) const volatile> {
  typedef O Object_T;
  typedef R Return_T;
};

template<typename T>
class Pending_member_function_call {
  typedef typename Member_function_type_traits<T>::Object_T Object_T;
  typedef typename Member_function_type_traits<T>::Return_T Return_T;
  std::pair<Object_T*, T> operands;
  public:
    Pending_member_function_call(std::pair<Object_T*, T> opr): operands{opr} { }
    template<typename... U>
    Return_T operator ()(U&&... args) {
      return (operands.first->*operands.second)(std::forward<U>(args)...);
  }
};

template<typename T>
class Smart_pointer {
  T* ptr;
  public:
    Smart_pointer(T* ptr): ptr{ptr} { }
    ~Smart_pointer() { delete ptr; }
    // …
    // operator ->* overload for pointers to data member
    template<typename U, typename V>
    V operator ->*(V U::* pdm) const {
      return ptr->*pdm;
    }
    // operator ->* overload for pointers to member function
    template<typename U>
    Pending_member_function_call<U> operator ->*(U pmf) const {
      return std::make_pair(ptr, pmf);
    }
};

struct A {
  int dm{5};
  int mf(int x) { return 2 * x; }
};

int main() {
  Smart_pointer<A> p{new A};
  auto pdm = &A::dm;
  auto pmf = &A::mf;
  std::cout << "A::dm called: " << p->*pdm << '\n';
  std::cout << "A::mf called: " << (p->*pmf)(8) << '\n';
  return 0;
}


texts:
I've been revamping on my coding puzzles practices. What is the complexity (both time and space) for this method?

public static String reverse(String word) {

    if (word == null || "".equals(word) || word.length() == 1) {
        throw new IllegalArgumentException("Invalid Entry");
    }

    StringBuilder result = new StringBuilder();

    for (int i=word.length() - 1; i >= 0; i--) {
        result.append(word.charAt(i));
    }

    return result.toString();
 }

Is this a more optimized solution (what is the time and space complexity of this one as well):

public static String reverse ( String s ) {
    int length = s.length(), last = length - 1;
    char[] chars = s.toCharArray();
    for ( int i = 0; i < length/2; i++ ) {
        char c = chars[i];
        chars[i] = chars[last - i];
        chars[last - i] = c;
    }
    return new String(chars);
}

I know that there might be duplicate questions similar to this but am not asking for a solution. I'm only seeking how to figure out the two different types of complexities.


texts:
I have a implementation of following code block,

public class FileFormatConversion {

public static enum File_TYPES {

  PDF, PNG, OTHERS, ALL
}

public static void processOtherFileType(String arg1) {
    System.out.println("Other file output -- " + arg1 + " file");
}

public static void processPNGPDFALL(String arg1, String arg2) {
    System.out
            .println("General block for processing PDF/PNG or ALL other file format -- "
                    + arg2
                    + "\\"
                    + arg1
                    + " parameter validation/check file availability");
}

public static void processPDF(String arg1, String arg2) {
    System.out.println("Block for processing PDF file -- " + arg2 + "\\"
            + arg1 + ".pdf");
}

public static void processALL(String arg1, String arg2) {
    System.out.println("Block for processing ALL file types -- " + arg2
            + "\\" + arg1 + ".all");
}

public static void processPNGALL(String arg1, String arg2) {
    System.out
            .println("Common block for manipulating file formats such as PNG or ALL files");
}

/**
 * @param args
 */
public static void main(String[] args) {

    args = new String[3];

    args[0] = "ALL";
    args[1] = "fileName";
    args[2] = "C:\\filePath";

    File_TYPES fileFormatInput = File_TYPES.valueOf(args[0]);

    if (File_TYPES.OTHERS == fileFormatInput) {
        processOtherFileType(args[1]);
    } else {
        processPNGPDFALL(args[1], args[2]);
        if (File_TYPES.ALL == fileFormatInput
                || File_TYPES.PNG == fileFormatInput)
            processPNGALL(args[1], args[2]);
        if (File_TYPES.ALL == fileFormatInput)
            processALL(args[1], args[2]);
        if (File_TYPES.PDF == fileFormatInput)
            processPDF(args[1], args[2]);
    }

    System.out.println("Completed");
}

I might need to add more options in ENUM in future. so using if-else will make it complex while debugging/adding. Is there any better alternative way to improve this block - improve understandability/maintenance.


texts:
I wrote a program where the computer guesses a random number.

To do this, I implemented a form of binary search. This correctly handles any edge-cases that I know of, including 0 and std::numeric_limits<int>::max(). This doesn't handle negative numbers (since rand will never return one) but that could easily be fixed.

The average amount of tries it takes to guess the number is around 29 or 30.

Here it is:

#include <functional>
#include <iostream>
#include <cstdlib>
#include <limits>
#include <ctime>

static int random_number;

int compare(int guess)
{
    if(guess > random_number)
        return 1;
    if(guess < random_number)
        return -1;
    return 0;
}

struct guess_stats
{
    int guesses = 0;
    int number = 0;
};

guess_stats finder(std::function<int(int)> &&cmp)
{
    int max = std::numeric_limits<int>::max();
    int min = 0;
    int guess = (min + max) / 2;
    int cmp_result;
    guess_stats results;

    do
    {
        cmp_result = cmp(guess);

        if(cmp_result < 0)
        {
            std::cout << "Greater than " << guess;
            min = guess;
            const int diff = max - guess;
            guess += diff - (diff / 2);
        }
        else if(cmp_result > 0)
        {
            std::cout << "Less than " << guess;
            max = guess;
            const int diff = guess - min;
            guess -= diff - (diff / 2);
        }

        std::cout << '\n';

        results.guesses++;
    } while(cmp_result);

    results.number = guess;

    return results;
}

int main(void)
{
    std::srand(std::time(0));
    random_number = std::rand();
    guess_stats stats = finder(compare);

    std::cout << "Number: " << stats.number << '\n'
              << "Guesses: " << stats.guesses << '\n';

    return 0;
}

What I'm looking for:

Although I don't expect there will be, are there any edge-cases I may not have seen?
Are there any algorithmic changes that I could make to have less time-complexity? I don't think so (because this is only O(log n) as it is), but I may be surprised to find out.
Are there any better ways to generate random numbers? I used srand, time, and rand in this program, but those are old solutions. I imagine C++ has something much more up-to-date for generation of random numbers.
Any other general advice on what to improve would be appreciated.


texts:
Given a string, I've done the below to search a CSV for a keyword and display the row if it's found

<?php
$ch = fopen("test.csv", "r");
$header_row = fgetcsv($ch);

/* This will loop through all the rows until it reaches the end */
while(($row = fgetcsv($ch)) !== FALSE) {
    $cols = array($row[0], $row[1], $row[2], $row[3]);
    if (in_array("text", $cols)) {
        echo '<div>'.$row[0].' | '.$row[1].' | '.$row[2].' | '.$row[3].' </div>';
    }
?>

I'm worried it's not best optimised for my needs, especially as the search is not regex'd and its assuming a X number of columns


texts:
This is a simple web form handler in PHP that sends a completely filled web form to a email.

I see lots of repeating code. What is the best way to reduce repetition?
Is my way of checking for fields being empty good? The "empty()" method seems to also treat "0", "0.0" and similar values as empty.
Am I doing something that is unneccesary?

Any other criticism is appreciated.

<?php

if ( $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
        die( 'Please use a form to send a message!' );
}

if ( !isset( $_POST['name'] ) || trim( $_POST['name'] ) === '' ) {
        die( 'Please enter your name!' );
}

if ( !isset( $_POST['phone'] ) || trim( $_POST['phone'] ) === '' ) {
        die( 'Please enter your phone number!' );
}

if ( !isset( $_POST['city'] ) || trim( $_POST['city'] ) === '' ) {
        die( 'Please enter your city!' );
}

$name = trim( $_POST['name'] );
$phone = trim( $_POST['phone'] );
$city = trim( $_POST['city'] );

$contents = '';

$contents .= "New order!\r\n";
$contents .= "\r\n";
$contents .= "Name: {$name}\r\n";
$contents .= "Phone number: {$phone}\r\n";
$contents .= "City: {$city}\r\n";

if ( mail( '<email removed>', 'New order!', htmlspecialchars($contents), 'From: <email removed>' ) ) {
    die( 'Thanks! We will contact you very soon!' );
} else {
    die( 'Unfortunately an error occurred. Please try again later.' );
}


texts: Replacing spaces with tabs. Exercise 1-21 in "The C Programming Language"

texts:
I'm looking for feedback on the code I came up with for exercise 1-21 in "The C Programming Language" by K&R.

  Write a program entab that replaces strings of blanks with the minimum number of tabs and blanks to achieve the same spacing. Use the same stops as for detab . When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?

The feedback I would mainly like is on readability, conventions and general good (or bad) practices.

This was a fun problem to solve and I think I came up with a efficient solution.

#include <stdio.h>

#define TABSIZE 8
#define MAXLENGTH 80

void entab(char s[]);
int _getline(char s[], int lim);

int main()
{
    int len;
    char line[MAXLENGTH];

    while ((len = _getline(line, MAXLENGTH)) > 0)
        entab(line);
}

void entab(char s[])
{
    int i, c, nb;

    nb = 0;

    for (i = 0; (c = s[i]) != '\0'; ++i)
    {
        if (c == ' ')
        {
            if (++nb > 1)
            {
                if (i + 1 % TABSIZE == 0)
                {
                    putchar('\t');
                    nb = 0;
                }
            }
        }

        else
        {
            if (nb > 0)
            {
                for (; nb > 0; --nb)
                    putchar('x');
            }

            putchar(c);
        }
    }
}

int _getline(char s[], int lim)
{
    int c, i;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
        s[i] = c;
    if (c == '\n')
    {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';

    return i;
}

The function _getline() was given by the book.
Only practices encountered in the book up until this assignment are used, I have not yet read about things like pointers and other more advanced features

My own thoughts

Use (more) comments when coding
Use more "self-explaining" variable names
Input longer than 80 characters isn't handled correctly


texts: Find largest substring in alphabetical order in a given string

texts:
#include<iostream>
#include<string>

using namespace std;

int main()
{
    string s, sub;
    cin >> s;
    int check = 1, count = 0, pos = 0; // keeping count of number of alphabetical ordered substring characters
    int i = 1; // loop variable
    int prev = 0; //to hold previous value of loop variable

    while (i< s.size())
    {
        check = 1;
        while ((int)s[i] >= (int)s[i - 1])
        {
            ++check;
            ++i;
        }
        if (check > count)
        {
            count = check;
            pos = i - check;
        }

        if (i == prev)
            ++i;
        prev = i; //if the inner while loop isn't executed, then i will be incremented here
    }
    cout << "Longest substring in alphabetical order is :" << s.substr(pos, count) << endl;
}

This was a part of my assignment. I could solve this in 10 minutes but I am not sure if this is a very efficient code. Though a (if any) more efficient algorithm exists for this, it may not make much of a different but I am keen on making all my programs as efficient as possible right from beginning.


texts:
This is a continued discussion (from here => Group duplicate files (part 2)) with new code and new thoughts/questions (see special question part for details for new questions), and I decide to make a new post.

Here is my source code which group duplicate files together, written in Python 2.7. Any advice on smarter ideas to group duplicate files together more efficient, it will be great. Any general advice on code bugs and code style are also appreciated.

Problem statement:

I am given a list of files e.g. ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt", "6.txt"]. I want to group all files which have the exact same content. Suppose in this example, file "1.txt", "2.txt", "3.txt" are the same, file "4.txt", "5.txt", "6.txt" have common header, but "4.txt", "6.txt" are exactly the same whole content. Then, the output should be two groups "1.txt", "2.txt", "3.txt" and "4.txt", "6.txt".

My major idea:

To avoid reading full content for each file, I generate a hash code for a piece of a file (in my example, I define the piece of file to be the 10 bytes of a file)
Each time after reading the next 10 bytes, I will hash the content of the next 10 bytes, and combine the hash value (of the next 10 bytes) with existing hash value of a file
Each time I see there is no common hash value for a file, I will stop reading this file from next piece (del file_handle_map[f])
The whole algorithm complete when all files are read

Special question

In method hash_next_n_bytes, I will return -1 if file already reached end (EOF), but sure if there is any better way to represent it, since I think -1 may conflict with some valid hash value -1?

Source code in Python 2.7

from collections import defaultdict
def group_duplicate_files(files):
    # open all filee
    file_handle_map = defaultdict(file)
    file_hash_map = defaultdict(int)
    for f in files:
        file_handle_map[f] = open(f, "r")
    while True:
        terminate = True
        group_map = defaultdict(list)
        for file_name, file_handle in file_handle_map.items():
            h = hash_next_n_bytes(file_handle, 10)
            if h != -1:
                terminate = False
                file_hash_map[file_name] = hash(file_hash_map[file_name]+h)
            group_map[file_hash_map[file_name]].append(file_name)
        remove_list = []
        for h, file_list in group_map.items():
            if len(file_list) == 1:
                remove_list.append(file_list[0])
        for f in remove_list:
            del file_handle_map[f]
        if terminate:
            break
    for h in file_handle_map.values():
        h.close()
    return group_map

def hash_next_n_bytes(f,n):
    x = f.read(n)
    if x:
        return hash(x)
    else:
        return -1

if __name__ == "__main__":
    files = ["1.txt", "2.txt", "3.txt", "4.txt", "5.txt", "6.txt"]
    print group_duplicate_files(files)


texts: Optimal algorithm to move a a rope from one position to another

texts:
I'm an engineer working with a deformable membrane that is attached to actuators.  The goal is to move the membrane from one shape to another, without ripping the membrane.  This imposes "neighbor rules" which state the maximum deviation between neighboring actuators cannot exceed some value, or the membrane will rip.

For the purposes of the problem, let's consider a 1-d membrane or "rope" that is attached to actuators:

The goal is to move the rope from one set of actuator positions to another in the minimum number of moves.

The rules are

Only one actuator may be moved at a time
An actuator may be moved any distance, but
An actuator must respect the neighbor rule, so the distance between it and subsequent actuators cannot exceed a fixed distance

The code below presents two algorithms, neither of which is optimal.  The first algorithm, get_max_deviation_index picks the actuator which is furthest from its final position, then moves it the maximum distance possible.  This algorithm gets stuck on a simple test of moving from position [2, 4, 6, 3] to [-2, -4, -6, -3].  The next algorithm, get_next_index, starts at the first actuator, moves it the maximum distance possible, and then moves to the subsequent actuator and does the same, until it is converged.  This algorithm works, but I do not believe it is optimal.

The code below implements both algorithms; please comment in/out the line beginning with ind = to switch between them.  My question is:

What is the optimal algorithm to move between one position and another?

import numpy as np

def check_legal(y, max_dist=None):
    #checks if a position is legal
    return np.all(np.diff(y)<=max_dist)

def get_neighbors(index, array):
    #gets neighbors of an element in a  list,
    #respecting end nodes
    max_index = len(array)-1
    if index == 0:
        neighbors = [array[index+ 1]]
    elif index == max_index:
        neighbors = [array[index- 1]]
    else:
        neighbors = list(array[[index-1, index + 1]])
    return neighbors

def get_max_deviation_index(current_pos, final):
    diff = np.abs(final-current_pos)
    max_ind = np.where(diff == np.max(diff))[0][0]
    #find move amt necessary to get to final position
    return max_ind

def get_next_index(current_pos, current_ind):
    if current_ind == len(current_pos)-1:
        next_ind = 0
    else:
        next_ind = current_ind+1
    return next_ind

def solve(init, final, max_dist=None):
    assert check_legal(init, max_dist=max_dist)
    assert check_legal(final, max_dist=max_dist)
    assert len(init) == len(final)
    print init
    current_pos = init
    idx = 0
    ind = 0
    while not np.allclose(current_pos, final):
        #find index that has maximum offset from where it should be
        #ind = get_max_deviation_index(current_pos, final)
        ind = get_next_index(current_pos, ind)
        delta = final[ind]-current_pos[ind]
        if delta == 0:
            continue
        sign = np.sign(delta)
        #find neighbors of that point
        neighbors = get_neighbors(ind, current_pos)
        #find the maximum allowable move
        pos_options = [final[ind]]\
                      +[n+sign*max_dist for n in neighbors]
        if sign<0:
            move = max(pos_options)
        else:
            move = min(pos_options)
        current_pos[ind] = move
        print current_pos
        idx+=1
    return idx

if __name__ == "__main__":
    initial_state = np.array([2,4,6, 3])
    final_state = -initial_state
    max_dist = 3 #max distance between neighboring actuators
    ans = solve(initial_state, final_state, max_dist=max_dist)
    print "Completed in ", ans, " moves"


texts: Simple wrapper for member function pointers with known signature

texts:
I always wanted to know how to pass member functions as arguments, and then I stumbled across templates that could automatically deduce types, and so I rejoiced! This is used in a Publisher-Subscriber system for a game server. I wanted the subscribing to individual packet 'types' (i.e. by enum) to be simple at the calling site.

/**
* Wrapper struct for callbacks fired when RakNet::Packet*s arrive.
* TargetObj is used to identify this callback by which object it is bound to.
*/
struct PacketCallback
{
    template <typename Obj>
    PacketCallback(void(Obj::*mf)(const RakNet::Packet*), Obj* obj)
        : TargetObj(obj)
    {
        Func = std::bind(mf, obj, std::placeholders::_1);
    }

    std::function<void(const RakNet::Packet*)> Func;
    void* TargetObj = nullptr;
};

Used thus:

class ClientManagementTest : public INetworkSubscriber
{
public:

    virtual void Subscribe(NetworkPublisher* a_networkPublisher) override
    {
        a_networkPublisher->Register(ID_NEW_INCOMING_CONNECTION,
            PacketCallback(&ClientManagement::OnClientConnected, this));

        a_networkPublisher->Register(ID_CONNECTION_LOST,
            PacketCallback(&ClientManagement::OnClientDisconnected, this));

        a_networkPublisher->Register(ID_DISCONNECTION_NOTIFICATION,
            PacketCallback(&ClientManagement::OnClientDisconnected, this));
    }

    virtual void Unsubscribe(NetworkPublisher* a_networkPublisher) override
    {
        a_networkPublisher->UnregisterAll(this);
    }

    void OnClientConnected(const RakNet::Packet* a_packet)
    {
        printf("Someone connected\n");
    }

    void OnClientDisconnected(const RakNet::Packet* a_packet)
    {
        printf("Someone disconnected\n");
    }

};

Are there any glaring flaws or possible improvements, here? Perhaps something that's incredibly unsafe?

For context, the function pointer is invoked thus, where the publisher stores the callbacks in the form std::map<int, std::vector<PacketCallback>> m_subscribers;:

void NetworkPublisher::NotifySubscribers(int a_packetType, RakNet::Packet* a_packet)
{
    auto it = m_subscribers.find(a_packetType);
    if (it != m_subscribers.end())
    {
        for (int i = 0; i < it->second.size(); ++i)
        {
            it->second[i].Func(a_packet);
        }
    }
}

I'm really happy with it, but would appreciate criticism.

Thanks!


texts: Validate input of month/year, otherwise set it to current month/year

texts:
Is there a cleaner way of doing this? I'm using filter_input to first check for valid input, then using it again to assign the variable. Also, my condition in if/else seems quite long.

$optionsMonth = array('options'=>array('min_range'=>1, 'max_range'=>12));
$optionsYear = array('options'=>array('min_range'=>1900, 'max_range'=>9999));

if ((filter_input(INPUT_GET, 'month', FILTER_VALIDATE_INT, $optionsMonth))&&(filter_input(INPUT_GET, 'year', FILTER_VALIDATE_INT, $optionsYear))){
    $month = filter_input(INPUT_GET, 'month', FILTER_VALIDATE_INT, $optionsMonth );
    $year = filter_input(INPUT_GET, 'year', FILTER_VALIDATE_INT, $optionsYear);
} else {
    $datetime = new Datetime('NOW');
    $month = $datetime->format('m');
    $year = $datetime->format('Y');
}


texts:
Out of fun, I solved "Nice Angles" challenge on CodeEval in C# 4.0:

  CHALLENGE DESCRIPTION:

  Write a program that outputs the value of angle, reducing its
  fractional part to minutes and seconds.

  INPUT SAMPLE:

  The first argument is a path to a file that contains the values of
  angles with their decimal fractions:

330.39991833
0.001
14.64530319
0.25
254.16991217

  OUTPUT SAMPLE:

  Print to stdout values of angles with their fractional parts reduced
  to minutes and seconds.

  The whole and fractional parts are separated by period, minutes are
  separated by apostrophe, seconds by double quotes. The values of
  minutes and seconds are shown as two numbers (with leading zeros if
  needed).

 330.23'59"
 0.00'03"
 14.38'43"
 0.15'00"
 254.10'11"

This is the code I used to solve the problem:

public static void ConvertToMinSec(string path)
        {
            using (StreamReader reader = File.OpenText(path))
            {

                while (!reader.EndOfStream)
                {
                    var degreeValues = reader.ReadLine();
                    if (!string.IsNullOrWhiteSpace(degreeValues))
                    {
                        var totalVal = degreeValues.Split('.');
                        if (totalVal.Length == 1)
                        {
                            var temp = totalVal[0] + ".0";
                            totalVal = temp.Split('.');
                        }
                        var intPart = totalVal[0];
                        var decimalPart =  "0." + totalVal[1];
                        decimal minutes;
                        decimal.TryParse(decimalPart, out minutes);

                        minutes = decimal.Multiply(minutes, 60);
                        var minutePart = (int)minutes;
                        var remainingDecimal = minutes.ToString().Split('.');
                        if (remainingDecimal.Length == 1)
                        {
                            var tempDecimal = remainingDecimal[0] + ".0";
                            remainingDecimal = tempDecimal.Split('.');
                        }

                        decimal seconds;
                        decimal.TryParse("0." + remainingDecimal[1], out seconds);
                        seconds = seconds*60;
                        var secondsPart = (int) seconds;
                        var report = string.Format("{0}"+"."+"{1:00}"+"'"+"{2:00}"+'"', intPart,
                            minutePart, secondsPart);

                        Console.WriteLine(report);
                    }
                }
            }


texts: A simple Decryption Program using Python

texts:
This is a program that can decrypt the codes that have been encrypted using the algorithm that my previously posted encryption program follows, you just need to enter the encrypted text from that program.

I got a lot of suggestions from people on the encryption post, I have tried to make this program as short as possible (in my efforts), I did not use the method they suggested to shorten functions because I don't want to use it without understanding how it works, I will implement it in my further programs as soon as I understand it...

Thank You for the suggestions on the previous program, it helped me reduce the length of this program by 16 lines.

Please let me know what you think about this program

Python Code :

alphabets = 'abcdefghijklmnopqrstuvwxyz'

def position_in_alphabets(tofind):
    for i in range(0,26):
        if tofind == alphabets[i]:
            position = i+1
            break
    return position

def decrypt(a):
    output = ''
    for i in range(0,len(a)):
        character = a[i]
        z = i+1
        y = position_in_alphabets(character)
        x = z+y-26
        if x>len(alphabets):
            x = x % len(alphabets)
        alpha = alphabets[x-1]
        output += alpha
    return output

print ()
print ("NOTE : Please enter just lowercase characters (no special characters) and no spaces")
print ()
given = input("Please enter the word to be decrypted : ")
output = decrypt(given)
print ()
print ("The word which is coded as ",given," is : ",output)

Thank You :)


texts:
I'm making the very common example of Factory design pattern which creates a factory of shapes and return an instance of the type Shape. I wonder which is the best way to replace that bunch of nested if-else statements so that my code is more readable and maintainable.

I think there should exist a suitable design pattern to solve this issue but since I'm a beginner using design patterns I don't know where to start.

This is the code snippet for the getShape() method:

public Shape getShape(String type, String scope) {

    if (type == null) {
        return null;
    }
    if (type.equalsIgnoreCase("circle")) {
        if (scope.equalsIgnoreCase("singleton")) {
            return SingletonCircle.getInstance();
        }
        return new PrototypeCircle();
    } else if (type.equalsIgnoreCase("rectangle")) {
        if (scope.equalsIgnoreCase("singleton")) {
            return SingletonRectangle.getInstance();
        }
        return new PrototypeRectangle();
    } else if (type.equalsIgnoreCase("square")) {
        if (scope.equalsIgnoreCase("singleton")) {
            return SingletonSquare.getInstance();
        }
        return new PrototypeSquare();
    }
    return null;
}


texts:
Overview

The string 0123456789 is written in a zigzag pattern (following the path going all the way down, then diagonally moving towards the top right) using a given number of rows. Like this example in the case of 3 rows.

0   4   8
1 3 5 7 9
2   6

This string is then read line by line and converted into a new string. In this case this new string from the zigzag will be 0481357926.

I'd like to understand any optimizations I can make using C++17 features, edge cases I may gave missed, possible overflows errors, etc.

#include <cmath>
#include <iostream>
#include <string>

class Solution {
    public:
        std::string convert(const std::string& s, const int numRows) {
            if (numRows == 1) { return s; }
            const int size = s.size();
            std::string converted = "";
            const int num  = numRows + (numRows - 2);
            int row = 0;
            int i   = 0;
            int sub = 0;
            bool useDiff = true;
            while (row < numRows) {
                converted += s[row];
                if (row == 0 || row == numRows - 1) {
                    i = row + num;
                    while (i < size) {
                        std::string str(1, s[i]);
                        converted.append(str);
                        i += num;
                    }
                } else {
                    int diff = std::abs(num - sub);
                    i = diff;
                    while (i < size && row + i < size) {
                        if (useDiff) {
                            std::string str(1, s[row + i]);
                            converted.append(str);
                            useDiff = false;
                            i += sub;
                        } else {
                            std::string str(1, s[row + i]);
                            converted.append(str);
                            useDiff = true;
                            i += diff;
                        }
                    }
                }
                useDiff = true;
                sub += 2;
                row++;
            }

            return converted;
        }
};

int main()
{
    Solution solution;
    std::string s = "0123456789";
    int numRows = 3;
    std::cout << s << '\n';
    s = solution.convert(s, numRows);
    std::cout << s << '\n';
}


texts: Singleton class extending a parent class to utilise shared functionality

texts:
I have a singleton class which extends from an abstract java class. Two singleton classes extend from ItemImageThreadManager, the reason for this is to use shared scheduling functionality. A thread is created and passed into the runThread method of ItemImageThreadManager.

Is this good design?

Abstract Parent Class

public abstract class ItemImageThreadManager {

    private Timer timer = new Timer();

    public void runThread(final Thread runThread){

        try {
            scheduleTimer(runThread);
        }
        catch(IllegalStateException ise){
            /**
             * When the timer is cancelled (when screen closed) and the images are
             * removed from memory(in-app resync) and this screen is opened again,
             * an IllegalStateException will be thrown since the images will need
             * to be re-downloaded
             *
             * Solution - create a new timer.
             */
            timer = new Timer();
            scheduleTimer(runThread);
        }
    }

    /**
     * Starts a new thread. This thread is run in the order is has been added.
     * Since timer runs in it's own thread, this gaurantees that just one thread
     * will be started at one time....
     * @param thread
     */
    private void scheduleTimer(final Thread thread){

        timer.schedule(new TimerTask() {

            public void run() {
                thread.start();
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, 0);
    }

    public void cancelTimer(){
        timer.cancel();
    }

}

First Extended class

public class ContestantImageThreadManager extends ItemImageThreadManager{

    private static ContestantImageThreadManager ref;

    private ContestantImageThreadManager(){
        super();
    }

    public static ContestantImageThreadManager getSingletonObject()
    {
      if (ref == null){
          ref = new ContestantImageThreadManager();
      }
      return ref;
    }

}

Second Extended class

public class JudgeItemImageThreadManager extends ItemImageThreadManager{

    private static JudgeItemImageThreadManager ref;

    private JudgeItemImageThreadManager(){

    }
    public static JudgeItemImageThreadManager getSingletonObject()
    {
      if (ref == null){
          ref = new JudgeItemImageThreadManager();
      }
      return ref;
    }

}


texts: method isInteger(BigDecimal number) isn't compliant with sonar rules

texts:
public boolean isInteger(BigDecimal number) {
    boolean ret;
    try {
        number.toBigIntegerExact();
        ret = true;
    } catch (ArithmeticException ex) {
        ret = false;
    }
    return ret;
}

This methods is correctly unit tested, but my sonar tells me "Either log or rethrow this exception.". My first reaction is to ignore the sonar rule (they're not mandatory), but I'm not sure if there's a better way to do it without catching an arithmetic exception.


texts: Optimize code block for LINQ and non LINQ

texts:
I have 2 code block to do same a work and have same target create some thing, but I don't know which block is the best (I mean LINQ or non-LINQ)?

First of all, can anyone tell me how to optimize on the code blocks?  And the lastly, help me find the best style between LINQ and non-LINQ:

First block is:

if (tblone.Rows.Count > 0)
        {
            tblone.Rows.Cast<DataRow>().Where(x => (string)x["id"] == "true").ToList()
                .ForEach(x => tbltwo.Rows.Cast<DataRow>().Where(y => y["category"] == x["cate"]).ToList().ForEach(
                    z =>
                    {
                        tblthree.Rows.Cast<DataRow>()
                                          .ToList<DataRow>()
                                          .ForEach(k => datatemp.Rows.Add(k["m"].ToString()));
                        tblfour.Rows.Cast<DataRow>()
                            .ToList<DataRow>()
                            .ForEach(k => datatemp.Rows.Add(k["m"].ToString()));
                    }));
        }

Second block is:

if (tblone.Rows.Count > 0)
        {
            for (var idx = 0; idx < tblone.Rows.Count; idx++)
            {
                if (bool.Parse(tblone.Rows[idx]["subset"].ToString()))
                {
                    for (var kdx = 0; kdx < tbltwo.Rows.Count; kdx++)
                    {
                        if (tbltwo.Rows[kdx]["category"].ToString() == tblone.Rows[idx]["cate"].ToString())
                        {
                            for (var zdx = 0; zdx < tblthree.Rows.Count; zdx++)
                                datatemp.Rows.Add(tblthree.Rows[zdx]["m"].ToString());
                            for (var zdx = 0; zdx < tblfour.Rows.Count; zdx++)
                                datatemp.Rows.Add(tblfour.Rows[zdx]["m"].ToString());
                        }
                    }
                }
            }
        }


texts: My take at ProjectEuler #17 - counting counting characters

texts:
I tried to tackle #17 problem on Project Euler:

  If the numbers 1 to 5 are written out in words:

one, two, three, four, five,

  then there are \$3 + 3 + 5 + 4 + 4 = 19\$ letters used in total.

  If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

I tried to solve it using dictionary. The code is working fine for n = 99, but the solution for 999 is off by 36. Any ideas on what might be going wrong? Any ideas on how I could make it more efficient?

def number_let_count(n):
    sum_let = 0
    numbers = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine',
               10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen'
               ,20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety', 100: 'hundred'}
    for int in range(1,n+1):
        if int in numbers and int != 100:
            sum_let += len(numbers[int])
        else:
            if int in range(21,100):
                sum_let += len(numbers[(int//10) * 10]) + len(numbers[int % 10])
            elif int in range(100,1000):
                if int % 100 == 0:
                    sum_let += len(numbers[(int//100)]) + len(numbers[100])
                else:
                    sum_let += len(numbers[(int//100)]) + len(numbers[100]) + len('and') + len(numbers[((int % 100)//10) * 10]) + len(numbers[(int % 100) % 10])
    return sum_let


texts: Generic function that accepts both Actions and Func's as parameters

texts:
I've created a generic try catch I can apply throughout my code so I'm not repeating myself.

private HttpResponseMessage TryCatch(Action action)
{
    return TryCatch(() => { action(); return "ActionToFunc"; });
}

private HttpResponseMessage TryCatch<T>(Func<T> func)
{
    try
    {
        var result = func();

        if (result.ToString() == "ActionToFunc")
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        return Request.CreateResponse(HttpStatusCode.OK, result);
    }
    catch (ArgumentNullException)
    {
        return Request.CreateResponse(HttpStatusCode.NotFound);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}

I can call it using:

TryCatch(() => myFunction(parameter));

Is there a better way of doing achieving the same result?


texts: Python program to find a word ladder transforming "four" to "five"

texts:
I saw this Puzzling problem and thought I would try to write a Python program to solve it. The task is to transform "four" to "five", forming a new four-letter word at each step, replacing one letter at each step, in as few steps as possible.

But turns out I don't know how to optimize recursion, so I'm posting here for help. I'm mostly just confused on why the code to change the past needs to be at the top of the function, but I would also like advice on how to speed this up in general. Right now it takes about 10x as long for each step up max_depth gets on my computer.

There won't be any matches until you change max_depth - I didn't want anyone copy-pasting and lagging out. There should be a solution at depth 5, according to Puzzling. However, my words file doesn't have the Foud or the word Fous, which that answer uses. Bumping up to max_depth six will take my computer ~10 minutes, which I don't want to try yet.

def hamming(string1, string2):
    assert len(string1) == len(string2)
    return sum(char1 != char2 for char1, char2 in zip(string1, string2))

max_depth = 3
start_word = "five"
end_word = "four"
all_words = open("/usr/share/dict/words", "r").read().lower().splitlines()
all_words = list(filter(lambda word: word.isalpha(), all_words))
all_words = list(filter(lambda word: len(word) == len(start_word), all_words))

sequences = []

def search(current_word, past = []):
    # Needs to be first to be fast for some reason
    past = past[:]
    past.append(current_word)

    if len(past) > max_depth:
        sequences.append(past)
        return

    for word in all_words:
        if hamming(word, current_word) == 1 and word not in past:
            search(word, past)

search(start_word)

sequences = [sequence[:sequence.index(end_word) + 1] for sequence in sequences if end_word in sequence]

if len(sequences) == 0:
    print("No matches")
else:
    print(min(sequences, key=len))


texts:
I feel like there is room for improvement in the push/pop methods. Any suggestions?

#include <exception>

template <typename T>
class List
{
public:

                    List();
                    ~List();
    void            PushBack(const T &data);
    void            PushFront(const T &data);
    void            PopBack();
    void            PopFront();
    void            Clear();
    bool            IsEmpty() const;
    unsigned int    Size() const;
    T&              Front() const;
    T&              Back() const;

private:

    template <typename T>
    struct Node
    {
        Node(const T &data) : data(data), next(NULL) {}
        T      data;
        Node  *next;
    };

    Node<T> *head;
    Node<T> *tail;
};

template <typename T>
List<T>::List()
    : head(NULL),
      tail(NULL)
{

}

template <typename T>
List<T>::~List()
{
    Clear();
}

template <typename T>
void List<T>::PushBack(const T &data)
{
    if ( !head )
    {
        head = new Node<T>(data);
        tail = head;
        return;
    }

    tail->next = new Node<T>(data);
    tail = tail->next;
}

template <typename T>
void List<T>::PushFront(const T &data)
{
    Node<T> *tmp = head;
    head = new Node<T>(data);
    head->next = tmp;

    if ( !tail )
    {
        tail = head;
    }
}

template <typename T>
void List<T>::PopBack()
{
    //empty list
    if ( !head )
    {
        throw std::out_of_range("Can't pop from empty list");
    }

    //list with one element
    if ( head == tail )
    {
        delete head;
        head = NULL;
        tail = NULL;
        return;
    }

    Node<T> *current = head;
    while ( current->next != tail )
    {
        current = current->next;
    }

    delete tail;
    tail = current;
    tail->next = NULL;
}

template <typename T>
void List<T>::PopFront()
{
    //empty list
    if ( !head )
    {
        throw std::out_of_range("Can't pop from empty list");
    }

    //list with one element
    if ( head == tail )
    {
        delete head;
        head = NULL;
        tail = NULL;
        return;
    }

    Node<T> *tmp = head->next;
    delete head;
    head = tmp;
}

template <typename T>
void List<T>::Clear()
{
    Node<T> *current = head;
    while ( head )
    {
        current = head;
        head = head->next;
        delete current;
    }

    head = NULL;
    tail = NULL;
}

template <typename T>
bool List<T>::IsEmpty() const
{
    return ( head == NULL );
}

template <typename T>
unsigned int List<T>::Size() const
{
    unsigned int size = 0;
    for ( Node<T> *current = head; current; current = current->next )
    {
        ++size;
    }

    return size;
}

template <typename T>
T& List<T>::Front() const
{
    if ( !head )
    {
        throw std::out_of_range("Can't return value from empty list");
    }

    return head->data;
}

template <typename T>
T& List<T>::Back() const
{
    if ( !head )
    {
        throw std::out_of_range("Can't return value from empty list");
    }

    return tail->data;
}


texts: Copy the reply button to each comment thread in WordPress. Converted from jQuery to JavaScript

texts:
I converted an old Wordpress Plugin of mine from jQuery to plain JavaScript using a cheat sheet. I was very surprised that it seems to work right out of the box on my first try.
(function ($) {
    $(document).ready(function ($) {

        $('.comment-list > li .comment-reply').each(function () {

            var reply = this;

            /* collect every comment which needs a reply link */
            var allchildren = $(reply).parent().children('.children').children().find(".comment-content");

            $.each(allchildren, function (index, value) {
                $(reply).clone().appendTo(value);
            });

        });
    });
})(jQuery);

Became this:
const replybtns = document.querySelectorAll(".comment-list > li .comment-reply");

for (let i = 0; i < replybtns.length; i++) {
    let replybtn = replybtns[i];
    let replybtncp = replybtn.cloneNode(true);
    let cc = replybtn.parentElement.querySelectorAll('.children div.comment-content');
    let lastcc = cc[Object.keys(cc)[Object.keys(cc).length - 1]];
    lastcc.appendChild(replybtncp);
}

This copies all reply links of all level 1 nested comments and appends them to the last comment.
Is this code okay? Is it really that simple? I tested it with Firefox and Chrome, and it seems to work. I know that it appends the reply link only to the last element. I did that on purpose to make it simpler.


texts:
I am a newb in Angular 4. I have written a component but have some questions.

I used member variables of class and modified variables within functions.
Is this right approach or I should implement it as (input => FUNCTION => output).
This will make testing function easy to test.

It is a simple PIG-GAME. Need guidance with functions like onGameInit(). If I make it like onGameInit(): boolean and If its done return true.
And I check for this true value when I right test case for this function.

import { ViewChild,Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-game-play',
  templateUrl: './game-play.component.html',
  styleUrls: ['./game-play.component.css']
})
export class GamePlayComponent implements OnInit {

  @ViewChild('winScoreInput') winScoreInput: ElementRef;

  playersScore;
  poolScore;
  diceScore: number
  activePlayerId: number;
  winScore: number;
  isGameStarted: boolean;
  // Take input from module
  vsAI: boolean;
  winnerId: number;
  intervalCntrl;

  constructor() { }

  ngOnInit() {
    this.onGameInit();
    this.vsAI = true;
  }

  onGameInit() {
    this.playersScore = { p0: 0, p1: 0 };
    this.poolScore = { p0: 0, p1: 0 };
    this.winScore = 0;
    this.diceScore = 5;
    this.winScoreInput.nativeElement.focus();
    this.isGameStarted = false;
    this.activePlayerId = 0;
    this.winnerId = -1;
  }

  onSetScore() {
    this.winScore = this.winScoreInput.nativeElement.value;
    this.isGameStarted = true;
  }

  onDiceRoll() {
    this.diceScore = Math.floor(Math.random() * 6) + 1;
    console.log('dice is rolled - Value  = ', this.diceScore);
    let { activePlayerId: id, vsAI } = this;
    if (this.diceScore === 1) {
      this.poolScore[`p${id}`] = 0;
      this.toggleActivePlayer();
    } else {
      this.poolScore[`p${id}`] += this.diceScore;
    }
  }

  onScoreHold() {
    let { poolScore, activePlayerId: id } = this;
    this.playersScore[`p${id}`] += poolScore[`p${id}`];
    this.poolScore[`p${id}`] = 0;
    if (this.isWinner()) return this.onGameEnd();
    this.toggleActivePlayer()  // Toggle between 0 and 1
  }

  isWinner() {
    let { activePlayerId: id, winScore } = this;
    if (winScore <= this.poolScore[`p${id}`] + this.playersScore[`p${id}`]) return true;
  }

  onGameEnd() {
    clearInterval(this.intervalCntrl);
    this.winnerId = this.activePlayerId;
    this.isGameStarted = false;
  }

  provideClasses(playerId: number) {
    let { isGameStarted, activePlayerId, winnerId } = this;
    if (playerId === winnerId) return "winner";
    if (playerId === activePlayerId) return "active";

  }

  toggleActivePlayer() {
    this.activePlayerId = 1 - this.activePlayerId;
    if (!this.vsAI || this.activePlayerId !== 1) {
      clearInterval(this.intervalCntrl)
      return;
    };
    //This is running means this is AI turn
    this.intervalCntrl = setInterval(() => {
      this.rollForAI();
    }, 1000)
  }

  rollForAI() {
    let shouldRoll = this.shouldRoll();
    if (shouldRoll) {
      this.onDiceRoll();
    } else {
      this.onScoreHold();
    }
  }

  shouldRoll(): boolean {
    let { winScore } = this;
    console.log(winScore, this.playersScore, this.poolScore);
    let myMainScore = this.playersScore.p1;
    let myPoolScore = this.poolScore.p1;
    let enemyMainScore = this.poolScore.p0;

    console.log(winScore, myMainScore, myPoolScore, enemyMainScore);
    if (myMainScore + myPoolScore >= winScore) {
      return false;
    }
    let myLead = myMainScore - enemyMainScore;
    let wantPool = (myMainScore < 80 && enemyMainScore >= 80) ? 30   // Imminent loss, be aggressive.
                 : (myMainScore >= 80 && (0 < myLead && myLead <= 10)) ? 15 // Comfortable lead
                 : 20;
                                           // General case
    return myPoolScore < wantPool;
  }

}


texts: Get all AD groups and Exchange features of users

texts:
We have about 15000 users and 1000 groups in AD. I have been getting of all AD groups of all AD users and their Exchange features  via script like below. But now I have been waiting for more than 3 hours already. My question is: How can I improve the speed of the script?

$groups = Get-ADGroup -filter * -SearchBase "OU=Security Groups,DC=contoso,DC=com"
$groupsCSV = "Username;"
$groups | foreach {
$groupsCSV += $_.sAMAccountName
$groupsCSV += ";"
}
$groupsCSV += "ActiveSyncEnabled; OWAEnabled; POPEnabled; IMAPEnabled; MAPIEnabled; MAPIBlockOutlookRpcHttp"
$groupsCSV += "`n"
$users = Get-ADUser -filter {Name -like "*"} -SearchBase "OU=test,OU=test,DC=contoso,DC=com"
$users | foreach {
$currentUser = $_
ECHO Examine: $_.Name
$isMemberList=""
$groups | foreach {
$currentGroup = $_
$currentMembers = Get-ADGroupMember $_
$isMember = ""
$currentMembers | foreach  {
if ($_.sAMAccountName -like $currentUser.sAMAccountName )  {
$isMember = "x"
}
}
$isMemberList += $isMember
$isMemberList += ";"
}
$isMemberListCSV += $currentUser.Name
$isMemberListCSV += ";"
$isMemberListCSV += $isMemberList
$MBFeatures = Get-CasMailbox $currentUser.DistinguishedName
if( $MBFeatures.ActiveSyncEnabled){
$isMemberListCSV += "x"
}
$isMemberListCSV += ";"

if( $MBFeatures.OWAEnabled){
$isMemberListCSV += "x"
}
$isMemberListCSV += ";"

if( $MBFeatures.POPEnabled){
$isMemberListCSV += "x"
}
$isMemberListCSV += ";"

if( $MBFeatures.IMAPEnabled){
$isMemberListCSV += "x"
}
$isMemberListCSV += ";"

if( $MBFeatures.MAPIEnabled){
$isMemberListCSV += "x"
}
$isMemberListCSV += ";"

if( $MBFeatures.MAPIBlockOutlookRpcHttp){
$isMemberListCSV += "x"
}
$isMemberListCSV += ";"
$isMemberListCSV += "`n"
}
$fullCSV = $groupsCSV + $isMemberListCSV
ECHO $fullCSV > fullCSV.txt


texts:
I am currently working on writing a library for use with LIFX light bulbs over their UDP API. I have written the code for creating the packet headers, but I'm unsure whether it is the most idiomatic approach, as I am new to Clojure. Please tell me what you think about the following code.

(ns lifx-lib.packet.header
  (:require [clj-struct.core :as struct]))

(def protocol-num 1024)
(def header-size 36)

(defn- frame-header
  [size tagged source]
  (struct/pack
    "<2HI"
    size
    (bit-or protocol-num 0x1000 (if tagged 0x3000 0x0000))
    source))

(defn- address-header
  [address resp ack sequence]
  (struct/pack
    "<2Q"
    address
    (bit-or
      (if resp (bit-shift-left 1 48) 0)
      (if ack (bit-shift-left 1 49) 0)
      (bit-shift-left sequence 56))))

(defn- protocol-header
  [type]
  (struct/pack "<Q2H" 0 type 0))

(defn create-header
  [params]
  (let [
      size     (:size params 0)
      tagged   (:tagged params true)
      source   (:source params 0)
      address  (:address params 0)
      resp     (:resp params false)
      ack      (:ack params false)
      type     (:type params 0)
      sequence (:sequence params 0)]
    (into []
      (concat
        (frame-header size tagged source)
        (address-header address resp ack sequence)
        (protocol-header type)))))


texts: Is Refactoring with different class casting and property calling possible ?

texts:
Can i refactor these code ?

The diffrent between these block of code are.

They are using different casting type.
They call different property

    var objBillOfMaterialRow = (MISheetDataSet.BillOfMaterialRow)pObjDataset.Tables["BillOfMaterial"].Rows[0];
    if (objBillOfMaterialRow.mi1_BillOfMaterial == ShowReport.False)
    {
        pObjDataset.Tables["BillOfMaterial"].Clear();
    }

    var objLayerBuildUpRow= (MISheetDataSet.LayerRow)pObjDataset.Tables["LayerBuildUp"].Rows[0];
    if (objLayerBuildUpRow.mi1_LayerBuildUp == ShowReport.False)
    {
        pObjDataset.Tables["LayerBuildUp"].Clear();
    }

    var objConstructionRow = (MISheetDataSet.ConstructionRow)pObjDataset.Tables["Construction"].Rows[0];
    if (objConstructionRow.mi2_Construction == ShowReport.False)
    {
        pObjDataset.Tables["Construction"].Clear();
    }


texts:
I have written code in the language Go. I wonder if anyone can do it in a very simple and effective way, because every language has its own way to solve this problem. My experience is in JavaScript. Please guide me how I can improve this solution. Thank you in advance.

What I'm doing here:

  Input  -

"I love dogs"
"fun&!! time"

  Output :-

love
time

  Here I return the longest word in the string. If there are two or more
  words that are of same length, return the first word from the string
  with that length.

package main

    import (
        "fmt"
        "regexp"
    )

    func main() {
        re := regexp.MustCompile(`[A-Za-z]+|[*?()$&.,!]`)
        matches := re.FindAllString("fun&!! time", -1)
        var count int
        for i := 0; i < len(matches); i++ {

            if (i+1)%len(matches) > 0 {

                if len(matches[(i+1)%len(matches)]) > len(matches[i]) {
                    count = (i + 1) % len(matches)

                }

            }

        }
        fmt.Println(matches[count])
    }


texts:
Problem : Implement a stack class in Python. It should support 3 APIs:

  stack.top(): prints element at top of stack

  stack.pop(): takes out an element from top of stack,

  stack.push(): adds a new element at top of stack

Does this code covers all the edge cases of implementing a stack?

class Stack():

    def __init__(self):
        self.item = []

    def size(self):
        return len(self.item)

    def top(self):
        if len(self.item) >= 1:
            print self.item[len(self.item) -1]
        else :
            print "Empty list"

    def pop(self):
        if len(self.item) >= 1:
            self.item.pop()
        else:
            raise IndexError

    def push(self,item):
        self.item.append(item)
        print self.item

new_stack = Stack()
new_stack.push(19)
new_stack.push(20)
new_stack.push(119)
new_stack.push(202)
new_stack.push(195)
new_stack.push(205)
new_stack.push(149)
new_stack.push(230)

print new_stack.size()
new_stack.top()
new_stack.pop()
new_stack.top()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.pop()
new_stack.top()


texts:
The code below generates a list of Pascal Coefficients.
e.g pascalList 3 outputs [[1], [1,1], [1,2,1], [1,3,3,1]
Can we write below sample in more idiomatic way

pascalList 0 = [[1]]
pascalList 1 = [[1], [1, 1]]
pascalList n = let pList = pascalList (n-1)
               in pList ++ [([1] ++ pascalCoeff (last pList) ++ [1])]
  where pascalCoeff (x:y:ys) = (x+y) : pascalCoeff (y:ys)
        pascalCoeff (x:[]) = []

Following code prints above list

listtoString :: [Int] -> String
listtoString [] = []
listtoString [x] = show x
listtoString (x:xs) = show x ++ " " ++ listtoString xs

pascalTriangle :: Int -> IO ()
pascalTriangle n = mapM_ putStrLn (((justify n) . map listtoString) (pascalList n))

justify :: Int -> [String] -> [String]
justify n (x:xs) = (concat (replicate n " ") ++ x) : justify (n-1) xs
justify _ [] = []

The sample output of the pascalTriangle 4 will be

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1


texts:
Today I was trying to load navigation bar from another HTML page. Here is code, that I am using. What do you think about it? Is there any other way to do it?

var x = document.getElementsByClassName("PageLoader");
var url = "";

for (var i = 0;i<x.length;i++){
    url = x[i].dataset.url;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.send( null );
    x[i].innerHTML = xmlHttp.responseText;
}


texts:
One year ago I published an F# solution of the same task and there is an old C# solution. But I think it's a simple task and require a simple solution.

What do you think?

using System;
using System.Collections.Generic;

namespace SalesTaxes
{
    class Program
    {
        static void Main(string[] args)
        {
            List<ShoppingCartItem> itemList = getItemsList();

            decimal salestaxes = 0.00m;
            decimal totalprice = 0.00m;

            foreach (ShoppingCartItem item in itemList)
            {
                salestaxes += item.Taxes * item.Quantity;
                totalprice += item.Item.Price * item.Quantity;
                Console.WriteLine(string.Format("{0} {1} : {2}", item.Quantity, item.Item.Name, (item.Item.Price + item.Taxes) * item.Quantity));
            }
            totalprice += salestaxes;
            Console.WriteLine("Sales Taxes : " + salestaxes);
            Console.WriteLine("Total : " + totalprice);
            Console.ReadLine();
        }

        private static List<ShoppingCartItem> getItemsList()
        {
            List<ShoppingCartItem> lstItems = new List<ShoppingCartItem>();
            //input 1

            lstItems.Add(new ShoppingCartItem { Item = new Product { Name = "Book", Price = 12.49m, Type = Product.ProductType.book, IsImport = false }, Quantity = 1 });
            lstItems.Add(new ShoppingCartItem { Item = new Product { Name = "music CD", Price = 14.99m, Type = Product.ProductType.other, IsImport = false }, Quantity = 1 });
            lstItems.Add(new ShoppingCartItem { Item = new Product { Name = "chocolate bar", Price = 0.85m, Type = Product.ProductType.food, IsImport = false }, Quantity = 1 });

            return lstItems;
        }
    }

    public class Product
    {
        public enum ProductType
        {
            food = 1,
            book = 2,
            medical = 3,
            other = 4
        };

        public string Name { get; set; }
        public decimal Price { get; set; }
        public ProductType Type { get; set; }
        public bool IsImport { get; set; }
        public bool IsExempt
        {
            get
            {
                return (int)Type < 4;
            }
        }
    }

    public class ShoppingCartItem
    {
        const decimal TaxRate = 0.1m;
        const decimal ImpTaxRate = 0.05m;
        public Product Item { get; set; }
        public int Quantity { get; set; }
        public decimal Taxes
        {
            get
            {
                return decimal.Ceiling(Item.Price * ((Item.IsExempt ? 0 : TaxRate) + (Item.IsImport ? ImpTaxRate : 0)) * 20) / 20;
            }
        }
    }
}


texts:
I was asked to write a program that sorts three strings alphabetically using only if-else (no sorting algorithms, usage of arrays whatsover). I'm fairly new to C++ programming but I've come up with this program and would like to know if there's any way to make this more efficient while only using if-else? Any help or suggestions would be appreciated. Thank you!
#include <iostream>
using namespace std;

int main()
{
    string word1, word2, word3;
    string temp;

    cout << "Enter three words separated by a space: ";
    cin >> word1 >> word2 >> word3;

    if (word1 > word2 && word1 > word3 && word3 > word2)
    {
        temp = word1;
        word1 = word2;
        word2 = word3;
        word3 = temp;
    }

        else if (word1 > word2 && word1 > word3 && word2 > word3)
        {
            temp = word1;
            word1 = word3;
            word3 = temp;
        }

            else if (word2 > word1 && word2 > word3 && word1 > word3)
            {
                temp = word2;
                word1 = word3;
                word2 = word1;
                word3 = temp;
            }

            else if (word2 > word1 && word2 > word3 && word3 > word1)
            {
                temp = word2;
                word2 = word3;
                word3 = temp;
            }

                else if (word3 > word1 && word3 > word2 && word1 > word2)
                {
                    temp = word1;
                    word1 = word2;
                    word2 = temp;
                }

    cout << "The correct sort is " << word1 << ", " << word2 << ", " << word3 << endl;

    return 0;
}


texts: How to get Chart.js into engineering notation?

texts:
I have been trying to take my x-axis labels and turn them into engineering notation. They are currently in scientific notation using a callback function.
            x: {
                ticks: {
                callback: (val) => (val.toExponential(3))
                }

This above puts it into scientific notation, (ie. 4.652E8) but I need it to be in engineering notation. I have tried changing scale types from linear to logarithmic and it always gave me 1.3E9 when I need more information than that. I need at least 3 digits. 1.24E9. Any help would be appreciated. This is my full chart.js code. The backend is a Python API currently running using flask.
    var options = {
    type: 'line',
    data: {
        labels: {{ labels | safe }},
        datasets: [{
            label: 'Value',
            data: {{ values | safe }},
            backgroundColor: 'white',
            borderWidth: 1,
            order: 2
        },
        {
            label: 'Peak value',
            data: [{
            x: {{ labels2[0] | safe }},
            y: {{ values2[0] | safe }}
            }, {
            x: {{ labels2[1] | safe }},
            y: {{ values2[1] | safe }}
            }, {
            x: {{ labels2[2] | safe }},
            y: {{ values2[2] | safe }}
            }],
            backgroundColor: 'black',
            borderWidth: 5,
            pointRadius: 5,
            showLine: false,
            order: 1
            }
        ]
    },
    options: {
        scales: {
            x: {
                ticks: {
                callback: (val) => (val.toExponential(3))
                }
            }
            }
        }
    }

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, options);

Engineering notation being defined as an exponent to the power of 3, and 1,2, or 3 digits to the left of the decimal point


texts:
I have a question: Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.
Given some queries in the form [a,b,k]:
[[1,5,3],[4,8,7],[6,9,1]]

Add the values of k between the indices a and b inclusive:
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]

And then return the max value which is 10
My attempt is:
from itertools import accumulate

def Operations(size, Array):

    values = [0] * (size+2)
    for a,b,k in Array:
        values[a] += k
        values[b+1] -= k

    values = list(accumulate(values))

    Result = max(values)
    return Result

def main():
    nm = input().split()

    n = int(nm[0])

    m = int(nm[1])

    queries = []

    for _ in range(m):
        queries.append(list(map(int, input().rstrip().split())))

    result = Operations(n, queries)

if __name__ == "__main__":
    main()

This code works, however, hits runtime errors when the arrays get too large. I have no idea how to lower the runtime further.
Example input is as follows:
5 3
1 2 100
2 5 100
3 4 100


texts: Binary search with heurisitcs or something else

texts:
Currently I'm using a binary search algorithm to search an index of a tree that represents an XML file.

Can I use heuristics to improve the search? What can I do to improve this search function?

Here is my search function, in PHP, so far:

public function search($key)
{
    // split the range
    $splitOffset = $this->getSplitOffset();

    // search right side
    $keys = $this->index->getKeyReader()->readKeys($splitOffset, self::DIRECTION_FORWARD);
    $foundKey = $this->findKey($key, $keys);
    // found
    if (! is_null($foundKey)) {
        return $foundKey;

    }
    // check if search should terminate
    if ($this->isKeyRange($key, $keys)) {
        return \reset($keys);

    }

    // If found keys are smaller continue in the right side
    if (! empty($keys) && \end($keys)->getKey() < $key) {
        $newOffset = $splitOffset + $this->index->getKeyReader()->getReadLength();
        // Stop if beyond index
        if ($newOffset >= $this->index->getFile()->getFileSize()) {
            return \end($keys);

        }
        $newLength =
            $this->range->getLength() - ($newOffset - $this->range->getOffset());
        $this->range->setOffset($newOffset);
        $this->range->setLength($newLength);
        return $this->search($key);

    }

    // Look at the key, which lies in both sides
    $centerKeyOffset = empty($keys)
        ? $this->range->getNextByteOffset()
        : \reset($keys)->getOffset();
    $keys = $this->index->getKeyReader()->readKeys($centerKeyOffset, self::DIRECTION_BACKWARD);
    $foundKey = $this->findKey($key, $keys);
    // found
    if (! is_null($foundKey)) {
        return $foundKey;

    }
    // terminate if no more keys in the index
    if (empty($keys)) {
        return null;

    }
    // check if search should terminate
    if ($this->isKeyRange($key, $keys)) {
        return \reset($keys);

    }

    // Finally continue searching in the left side
    $newLength = \reset($keys)->getOffset() - $this->range->getOffset() - 1;
    if ($newLength >= $this->range->getLength()) {
        return \reset($keys);

    }
    $this->range->setLength($newLength);
    return $this->search($key);
}

Perhaps not improvements to this code exactly, but how can I do heuristic, AI, or better search that is possible in PHP?


texts:
I have a trivial function that rotates 2d vectors, and a method in a class representing a polygon that rotates every point in the polygon around an origin. The code is fairly optimized as it is, but I was wondering if there is any faster way of doing it, since the function is called a HUGE amount of times and I need it to be as fast as it can possibly be.

Here is the code for the rotation function (in a file called geo.py):

def rotate_vector(v, angle, anchor):
    """Rotate a vector `v` by the given angle, relative to the anchor point."""
    x, y = v

    x = x - anchor[0]
    y = y - anchor[1]
    # Here is a compiler optimization; inplace operators are slower than
    # non-inplace operators like above. This function gets used a lot, so
    # performance is critical.

    cos_theta = math.cos(angle)
    sin_theta = math.sin(angle)

    nx = x*cos_theta - y*sin_theta
    ny = x*sin_theta + y*cos_theta

    nx = nx + anchor[0]
    ny = ny + anchor[1]
    return [nx, ny]

And here is the code for the polygon object:

import geo

class ConvexFrame(object):
    """A basic convex polygon object."""

    def __init__(self, *coordinates, origin=None):
        self._origin = origin
        # The coordinates in this object are stored as offset values, that is,
        # coordinates that represent a certain displacement from the given origin.
        # We will see later that if the origin is None, then it is set to the
        # centroid of all the points.

        self._offsets = []

        if not self._origin:
            # Calculate the centroid of the points if no origin given.
            self._origin = geo.centroid(*coordinates)
        orx, ory = self._origin
        append_to_offsets = self._offsets.append
        for vertex in coordinates:
            # Calculate the offset values for the given coordinates
            x, y = vertex
            offx = x - orx
            offy = y - ory
            append_to_offsets([offx, offy])

        offsets = self._offsets
        left = geo.to_the_left
        # geo.to_the_left takes three vectors (v0, v1 and v2) and tests if vector v2
        # lies to the left of the line between v0 and v1. The offset values are input
        # in counter-clockwise order, so all points v(i) should lie to the left of the
        # the line v(i-2)v(i-1).
        n = len(offsets)
        for i in range(n):
            v0 = offsets[i-1]
            v1 = offsets[i]
            v2 = offsets[(i+1)%n]
            if not left(v0, v1, v2):
                raise ValueError("""All vertices of the polygon must be convex.""")

    def rotate(self, angle, anchor=(0, 0)):
        # Avg runtime for 4 vertices: 7.2e-06s
        orx, ory = self._origin
        x, y = anchor
        if x or y:
            # Default values of x and y (0, 0) indicate
            # for the method to use the frame origin as
            # the anchor. Since we are rotating the offset
            # values and not actually the coordinates, we
            # have to adjust the anchor relative to the origin.
            x = x - orx
            y = y - ory
        _rot = geo.rotate_vector
        self._offsets = [_rot(v, angle, (x, y)) for v in self._offsets]

If I can get this below 3e-06s for 4 vertices that would be phenomenally helpful.

UPDATE 1:

Just found an optimization; in the list comprehension I say (x, y) every iteration, meaning I have to rebuild the tuple every single iteration. Removing that shaves the time down to between 7e-06 and 6.9e-06s for 4 vertices.

def rotate2(self, angle, anchor=(0, 0)):
    # Avg runtime for 4 vertices: 7.0e-06s
    # Best time of 50 tests: 6.92e-06s
    orx, ory = self._origin
    x, y = anchor
    if x or y:
        # Default values of x and y (0, 0) indicate
        # for the method to use the frame origin as
        # the anchor.
        x = x - orx
        y = y - ory
        anchor = x, y
    _rot = geo.rotate_vector
    self._offsets = [_rot(v, angle, anchor) for v in self._offsets]


texts:
I've started learning C++ and still making my first program. This is a continuation of my last post.

My original aim was to make a linked list at a professional level. But have now changed it to a doubly linked list, to simplify the code. It implements a couple of public functions that should increase the usability of the list significantly.

I also tried to implement an internal iterator. But didn't see a benefit to making a bidirectional iterator, for internal use, to replace getNode.

Whilst I think I improved all problems mentioned in my last post. I mostly focused on implementing the sentinel. I don't think it's a sentinel, as it's doing more than just being my end condition. And so I'd love some feedback on my implementation. But any and all critiques are wanted.

#include <iostream>

template <class T>
class LinkedList {
private:
    class Node {
    public:
        Node* next;
        Node* prev;
        T data;
        // For the sentinal
        Node(): data('\0'), prev(this), next(this) {}
        Node(T data, Node* before)
                : data(data) {
            prev = before;
            next = before->next;
            prev->next = this;
            next->prev = this;
        }
        ~Node() {
            prev->next = next;
            next->prev = prev;
        }
        Node(Node const&)            = delete;
        Node& operator=(Node const&) = delete;
    };
    Node sentinal;
    Node* getNode(int index) {
        if (index >=  0) {
            int i = 0;
            for (Node* node = sentinal.next; node != &sentinal; node = node->next) {
                if (i == index) {
                    return node;
                }
                i++;
            }
        } else {
            int i = -1;
            for (Node* node = sentinal.prev; node != &sentinal; node = node->prev) {
                if (i == index) {
                    return node;
                }
                i--;
            }
        }
        throw std::out_of_range("List doesn't contain that item.");
    }
public:
    LinkedList() {}
    ~LinkedList() {
        clear();
    }
    LinkedList(LinkedList const&)            = delete;
    LinkedList& operator=(LinkedList const&) = delete;

    void clear() {
        while (sentinal.next != &sentinal) {
            delete sentinal.next;
        }
    }

    int length() {
        int length = 0;
        for (Node* node = sentinal.next; node != &sentinal; node = node->next) {
            length += 1;
        }
        return length;
    }

    void append(T data) {
        new Node(data, sentinal.prev);
    }

    T get(int index) {
        return getNode(index)->data;
    }

    void insert(T data, int index) {
        new Node(data, getNode(index)->prev);
    }

    T pop(int index=-1) {
        Node* node = getNode(index);
        T data = node->data;
        delete node;
        return data;
    }
};

int main() {
    LinkedList<char> list;
    list.append('h');
    list.append('l');
    list.append('l');
    list.append('l');
    list.append('o');
    list.insert('e', 1);
    std::cout << list.pop(2) << list.get(-1) << '\n';
    for (int i=0; i < list.length(); i++) {
        std::cout << list.get(i);
    }
    std::cout << '\n';
    list.clear();
    std::cout << list.length() << '\n';
}


texts:
I do not want to use a new data structure but the existing APIs in Java. Here's a solution. I am thinking if this can be made simpler. Input say {"1 2", "4 3", "5 5", "2 3"} and output is [1, 2, 3, 4] [5]

    static void formSet(String[] pairs) {

    List<Set<Integer>> list = new ArrayList<>();
    for(String s : pairs){
        String[] values = s.split(" ");
        Integer val1 = Integer.parseInt(values[0]);
        Integer val2 = Integer.parseInt(values[1]);

        Set<Integer> pairSet = new HashSet<>();
        pairSet.add(val1);
        pairSet.add(val2);

        Set<Integer> val1_set = null, val2_set = null;
        for(Set<Integer> set : list){
            if(set.contains(val1)) {
                val1_set = set;
            }

            if(set.contains(val2)) {
                val2_set = set;
            }
        }
        if(val1_set == null && val2_set == null)
            list.add(pairSet);
        if(val1_set != null && val2_set == null)
            val1_set.addAll(pairSet);
        if(val1_set == null && val2_set != null)
            val2_set.addAll(pairSet);
        if(val1_set != null && val2_set != null){
            list.remove(val2_set);
            val1_set.addAll(val2_set);
        }
    }

    for(Set<Integer> set : list){
        System.out.println(set);
    }
}


texts: Webservice methods using EclipseLink and database entities

texts:
I am wondering if this is a good and correct way to write the implementation of two web service methods (get/set methods).

The setPerson method can be called from different threads from a pool, so I think the best way is to make the method synchronized. Or is it possible to lock the table when editing to avoid the synchronization on Java?

@Override
public synchronized void setPerson(Person person) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonLibPU");
    EntityManager em = emf.createEntityManager();
    if(!em.getTransaction().isActive()) {
       em.getTransaction().begin();
    }
    try {
         em.merge(person);
         em.getTransaction().commit();
         emf.getCache().evict(Person.class);
    } catch (Exception ex) {
         if(em.getTransaction().isActive())
            em.getTransaction().rollback();
    } finally {
        em.close();
    }
}

And here follows the getPerson method. I didn't make it synchronized since it reads from the JPA cache.

@Override
public Person getPerson(int personId) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonLibPU");
    EntityManager em = emf.createEntityManager();
    try {
        return (Person)em.getReference(Person.class, personId);
    } catch (javax.persistence.EntityNotFoundException ex) {
        return new Person(); // return empty person
    } finally {
        em.close();
    }
}


texts: Changing color via JRadioButtons and JButtons

texts:
I've got my full program working as expected. My full program looks like this:

I'm posting a part of my code which changes the color of the circle. The user can change the color of the circle via two ways:

By selecting a JRadioButtonMenuItem from the JMenu.
By pressing one of the colors(JButtons) in the JPanel below the main panel.

Here is the relevant piece of code which works as expected:

    colorbuttons = new JButton[]{new JButton(),
                                 new JButton(),
                                 new JButton(),
                                 new JButton(),
                                 new JButton(),
                                 new JButton(),}; //Different color buttons

    colorbuttons[0].setBackground(Color.WHITE);
    colorbuttons[1].setBackground(Color.GREEN);
    colorbuttons[2].setBackground(Color.RED);
    colorbuttons[3].setBackground(Color.YELLOW);
    colorbuttons[4].setBackground(Color.BLUE);
    colorbuttons[5].setBackground(Color.BLACK); //Setting each color

    for(int i=0; i<colorbuttons.length; i++)
    {
        colorbuttons[i].addActionListener(this);
        colorPan.add(colorbuttons[i]); //Adding into a JPanel
    }

    bar = new JMenuBar();
    menu1 = new JMenu("Edit circle");
    sub1 = new JMenu("Colour");
    colors = new JRadioButtonMenuItem[]{new JRadioButtonMenuItem("White"),
                                        new JRadioButtonMenuItem("Green"),
                                        new JRadioButtonMenuItem("Red"),
                                        new JRadioButtonMenuItem("Yellow"),
                                        new JRadioButtonMenuItem("Blue"),
                                        new JRadioButtonMenuItem("Black",true)};

    ButtonGroup group = new ButtonGroup();
    for(int i=0; i<colors.length; i++)
    {
        group.add(colors[i]);
        sub1.add(colors[i]);
    }
    menu1.add(sub1);
    bar.add(menu1);

    menu1.setMnemonic(KeyEvent.VK_E);
    sub1.setMnemonic(KeyEvent.VK_C);

    ActionListener radiolisten = new ActionListener(){
        public void actionPerformed(ActionEvent e)
        {
            int getIndex = 0;
            JRadioButtonMenuItem temp = (JRadioButtonMenuItem) e.getSource();

            for(int i=0; i<colors.length; i++)
            {
                if(temp == colors[i])
                    break;
                getIndex++;
            }

            color = colorbuttons[getIndex].getBackground();
            repaint();
        }
    };

    for(int i=0; i<colors.length; i++)
        colors[i].addActionListener(radiolisten);

and the actionPerformed method of the class( which the JButtons are added to):

public void actionPerformed(ActionEvent e)
{
    JButton temp = (JButton)e.getSource();
    color = temp.getBackground();
    int getIndex=0;

    for(int i=0; i<colorbuttons.length; i++)
    {
        if(temp == colorbuttons[i])
            break;
        getIndex++;
    }

    colors[getIndex].setSelected(true);
    repaint();
}

color is a global variable that denotes the color of the circle.

I would like to shorten the above code snippet, especially both the actionPerformed methods. How can I do it?


texts:
I have a string like str = " 4+ 6 * 30";. I have to perform an arithmetic operation on this using C#; My solution to this problem is as follows.

     string temp = " 4 + 6 * 5";
     int firstNaum = 0;
     int secondNum = 0;
     int ThirdNum = 0;
     int finalResults = 0;
    //Spliting strings
    string[] withoutOperator = temp.Split('\t',' ','*' , '+');
    //Iterating strings
    int counter = 0;
    foreach (var res in withoutOperator)
    {
        if (!string.IsNullOrEmpty(res) && counter ==1)
        {
            firstNaum = Convert.ToInt32(res);
        }
        if (!string.IsNullOrEmpty(res) && counter== 4)
        {
            secondNum = Convert.ToInt32(res);
        }
        if (!string.IsNullOrEmpty(res) && counter == 7)
        {
            ThirdNum = Convert.ToInt32(res);
        }
        counter += 1;
    }
    finalResults = firstNaum + secondNum * ThirdNum;


texts: Object-oriented model of a machine gun using Pygame

texts:
I just started to use classes in Python, so I don't know all concepts, rules and conventions about it. I made a little program of a machine gun, which simulates firing by user's action. Here it is:

import random, pygame, sys

class MachineGun(object):
    bullets = 200

    def __init__(self):
        self._magazine = 50

    def _get_magazine(self):
        return self._magazine

    def _set_magazine(self, val):
        self._magazine = val

    magazine = property(_get_magazine, _set_magazine)

    def fire(self):
        pygame.mixer.Sound("fire.wav").play()
        while pygame.mixer.get_busy():
            pass

        fired = random.randint(1, 21)
        self.magazine = self.magazine-fired

        if self.magazine <= 0 :
            print("Bullets remaining : 0")
        else :
            print("Bullets remaining : {}".format(self.magazine))

    def reload(self):
        if self.magazine == 50 :
            print("Full")

        else :
            if MachineGun.bullets >= 50 :
                if self.magazine == 0 :
                    self.magazine = 50
                    MachineGun.bullets = MachineGun.bullets-50
                else :
                    tmp = 50-self.magazine
                    self.magazine = self.magazine+tmp
                    MachineGun.bullets = MachineGun.bullets-tmp

            else :
                if self.magazine == 0 :
                    self.magazine = MachineGun.bullets
                    MachineGun.bullets = 0
                else :
                    if self.magazine+MachineGun.bullets > 50 :
                        tmp = 50 - self.magazine
                        self.magazine = self.magazine+tmp
                        MachineGun.bullets = MachineGun.bullets-tmp
                    else :
                        self.magazine += MachineGun.bullets
                        MachineGun.bullets = 0

        pygame.mixer.Sound("reload.wav").play()
        while pygame.mixer.get_busy():
            pass

    def action(self):
        a = "x"

        while a != "e" :
            if a == "" :
                if self.magazine > 0 :
                    self.fire()
                elif self.magazine <= 0 and MachineGun.bullets > 0 :
                    self.magazine = 0
                    print("Reload")
                else :
                    print("End")
                    sys.exit()

            elif a == "r" :
                self.reload()

            a = input()

M = MachineGun()
M.action()

This is somehow my first "complete" implementation using classes. So I don't know if the form is correct. For exemple, I modified the attribute bullets without using a class method. Should I ? Like properties for object attributs ? Is it very necessary to use properties ?