texts:
This originally appeared in Facebook's hacker cup 2013. Solving it was fun, though I find myself looping through similar data quite often.

Challenge:

  Print the maximum beauty of strings.

Specifications:

  The beauty of a string is the sum of the beauty of the letters within.
  The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty.
  Lettercase is irrelevant.
  Your program should accept as its first argument a path to a filename.
  Each line in this file has a sentence.
  Print out the maximum beauty of each sentence.

This means calculate the maximum possible beauty a string can have.
e.g. In test case, "AbBCcC" assign 26 to C, as it occurs the most in the string, followed by 25 to B, and 24 to A. For a maximum beauty of 152.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class BeautifulStrings {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));

        while (input.hasNextLine()) {
            printMaximumBeauty(input.nextLine());
        }
    }

    private static void printMaximumBeauty(String line) {
        System.out.println(
            computeMaximumBeauty(line
                .replaceAll("[^a-zA-Z]", "")
                .toLowerCase()
                .toCharArray()
            )
        );
    }

    private static int computeMaximumBeauty(char[] line) {
        int beauty = 0;
        int beautyVal = 26;
        int count = 0;
        Set<Character> uniqueCharacters = new HashSet<>();
        List<Integer> appearanceCounts = new ArrayList<>();

        for (char c : line) {
            uniqueCharacters.add(c);
        }

        for (char u : uniqueCharacters) {
            for (char c : line) {
                if (u == c) {
                    count++;
                }
            }

            appearanceCounts.add(count);
            count = 0;
        }

        Collections.sort(appearanceCounts, Collections.reverseOrder());

        for (int i : appearanceCounts) {
            beauty += i * beautyVal--;
        }

        return beauty;
    }
}

In an attempt to reduce the amount of loops and work done I thought of a different implementation for computeMaximumBeauty. I think maybe there's a way to do it all in one stream, but I'm not yet well versed with Java 8 (unfortunately all the Java challenges from the challenge site, CodeEval, require Java 7). This isn't a comparative review, so feel free to pick the better one (or both) and pick at its weaknesses or suggest complete alternatives if this approach misguided.

private static int computeMaximumBeauty(char[] chars) {
        int beauty = 0;
        int beautyVal = 26;
        Map<Character, Integer> beautyMap = new HashMap<>();
        Map<Character, Integer> valueSorted;

        for (char c : chars) {
            beautyMap.put(
                c, beautyMap.containsKey(c) ? beautyMap.get(c) + 1 : 1
            );
        }

        valueSorted =  beautyMap.entrySet().stream()
            .sorted(comparing(Entry::getValue))
            .collect(toMap(
                Entry::getKey,
                Entry::getValue,
                (e1, e2) -> e1, LinkedHashMap::new
            )
        );

        beautyVal -= valueSorted.size() - 1;

        for (Map.Entry<Character, Integer> e : valueSorted.entrySet()) {
            beauty += e.getValue() * beautyVal++;
        }

        return beauty;
    }

Sample Input:

ABbCcc
This is from Facebook Hacker Cup 2013.
Ignore punctuation, please :)
Sometimes, test cases are hard to make up.
CodeReview is love. CodeReview is life.

Sample Output:

152
551
491
729
724


texts:
So I have a piece a code that, altough it does what is expected, it doesn't seam very performant to me. I just wanted to know if there's a better way to do this or if my code is alright as it is.

The objective of the code is to recieve an image path, check if the image exists or if it isn't png, if the image isn't png convert it to png and return a byte[] of the stream.

the code:

    // the speed of the method, on my computer, as is, right now, is of 40ms per cycle, this means 10 cycles are around 400ms
    public static byte[] GetBytesFromImage(string imageName)
    {
        byte[] bytes = null;

        string imagePath = "..\\..\\Imagens";
        imageName = imageName == "" ? "\\logotipos-prototipo_logo_prototipo_print.jpg" : imageName;
        string fpath = imagePath + imageName;

            if (File.Exists(fpath) && !imageName.EndsWith("png"))
            {
                using (MemoryStream image = new MemoryStream())
                using (System.Drawing.Image bmpImageToConvert = System.Drawing.Image.FromFile(fpath))
                using (System.Drawing.Image bmpNewImage = new Bitmap(bmpImageToConvert.Width, bmpImageToConvert.Height))
                using (Graphics gfxNewImage = Graphics.FromImage(bmpNewImage))
                {
                    gfxNewImage.DrawImage(bmpImageToConvert, new Rectangle(0, 0, bmpNewImage.Width, bmpNewImage.Height), 0, 0, bmpImageToConvert.Width, bmpImageToConvert.Height, GraphicsUnit.Pixel);

                    bmpNewImage.Save(image, ImageFormat.Png);
                    bytes = image.ToArray();
                }
            }

        return bytes;
    }

1st Update:
As the @Nkosi's answer mentioned, I forgot to make a case for when the image is PNG, and also to deal with the method returning a potencial null byte[].
Also in his change now the MemoryStream is shared in both cases, and the string comparison now ignores the string case.

    readonly string BASEIMAGEPATH = "..\\..\\Imagens\\";
    readonly string DEFAULTIMAGENAME = "logotipos-prototipo_logo_prototipo_print.jpg";

    // the speed of the method, on my computer, as is, right now, is of 40ms per cycle, this means 10 cycles are around 400ms
    public static byte[] GetBytesFromImage(string imageName)
    {
        byte[] bytes = null;
        imageName = imageName == "" ? DEFAULTIMAGENAME : imageName;
        string path = Path.Combine(BASEIMAGEPATH, imageName);
        if (File.Exists(path))
        {
            // Now both cases use the same MemoryStream
            using (MemoryStream image = new MemoryStream())
            {
                // The comparison now ignores case
                if (imageName.EndsWith("png", StringComparison.InvariantCultureIgnoreCase))
                {
                    using (FileStream imageStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                    {
                        imageStream.CopyTo(image);
                        bytes = image.ToArray();
                    }
                }
                else
                {
                    using (System.Drawing.Image bmpImageToConvert = System.Drawing.Image.FromFile(path))
                    using (System.Drawing.Image bmpNewImage = new Bitmap(bmpImageToConvert.Width, bmpImageToConvert.Height))
                    using (Graphics gfxNewImage = Graphics.FromImage(bmpNewImage))
                    {
                        gfxNewImage.DrawImage(bmpImageToConvert, new Rectangle(0, 0, bmpNewImage.Width, bmpNewImage.Height), 0, 0, bmpImageToConvert.Width, bmpImageToConvert.Height, GraphicsUnit.Pixel);
                        bmpNewImage.Save(image, ImageFormat.Png);
                        bytes = image.ToArray();
                    }
                }
            }
        }
        // I changed his code here because `Array.Empty<byte>()` didn't exist.
        return bytes ?? new byte[0];
    }


texts: Directly accessing class attributes in Rock Paper Scissors

texts:
I am reading a beginning Python programming book and in it the author says that you want to avoid accessing a class' attributes directly, but instead to create methods that return attribute values. However, I am finding there are times this seems a little redundant and I am wondering if am just going about this in the wrong way.

An example of this is in the battle function where I access player1.hand directly. Is this a bad idea? Also, does everything else look okay in this or are there any bad practices I should be nipping in the bud?

#a game of rock paper scissors for two computers

#imports
import random

class Hand(object):
    """A hand with which to rock paper scissor"""

    HANDS = ("rock", "paper", "scissors")

    def __init__(self, name, wins = 0, hand = None):
        self.name = name
        self.wins = wins
        self.hand = hand

    def choose_hand(self):
        """Chooses hand for player"""
        self.hand = random.choice(self.HANDS)
        print self.name + " picks " + self.hand + "."

    def increase_wins(self):
        """Increases players wins and declares them this rounds winner"""
        self.wins += 1
        print self.name + " wins."

    def total_wins(self):
        """shows total wins of all rounds played"""
        print self.name + " won " + str(self.wins) + " rounds."

def battle(player1, player2):
    """plays one round of rock paper scissor"""
    #players choose their hands
    player1.choose_hand()
    player2.choose_hand()

    #see who wins the battle
    if player1.hand == "rock" and player2.hand == "scissors":
        player1.increase_wins()
    elif player1.hand == "paper" and player2.hand == "rock":
        player1.increase_wins()
    elif player1.hand == "scissors" and player2.hand == "paper":
        player1.increase_wins()
    elif player1.hand == player2.hand:
        print "It's a tie."
    else:
        player2.increase_wins()

def main():
    player1 = Hand("HAL")
    player2 = Hand("WOPR")

    rounds = 10

    for i in range(rounds):
        print "\nRound " + str(i + 1) + ":"
        battle(player1, player2)

    print "\nFinal Score:"
    player1.total_wins()
    player2.total_wins()
    if player1.wins > player2.wins:
        print player1.name + " wins."
    elif player1.wins == player2.wins:
        print "It's a tie."
    else:
        print player2.name + " wins."

#play the game
main()


texts: Producer Consumer With Multiple Dependents

texts:
I put together a ProducerConsumer class that wraps the C#'s BlockingCollection class with some bells and whistles (producers can have multiple consumers, consumers can have lambdas, built in parallel execution, exceptions thrown on cycles, etc). As you can imagine it uses generics.

var producer = new GhostLine<int>();
var consumerDoubler = new GhostLine<int>();
var consumerTripler = new GhostLine<int>();
producer.AddConsumer(consumerDoubler);
producer.AddConsumer(consumerTripler);

...

consumerTripler.Process = w =>
{
    int x = w * 3;
    Console.WriteLine("Tripled value: " + x);
    return x;
};

The whole thing is (or seems to be working) and both of my unit tests succeed when I run them.

Some areas I am interested in: performance, parallelism (obviously ... including potential deadlocks, best mechanisms between tasks/Parallel.For/threads/etc), ease of use, convenience methods / features, encapsulation, and hosting on github (long time programmer but new to github).

You can find the project here.

The class I am most interested in getting feedback on is
GhostLine.cs:

    public void AddConsumer(GhostLine<T> consumer) {
        if (AncestorDuplicate(consumer) || DescendantDuplicate(consumer))
        {
            throw new CycleException("Adding this consumer would create a cycle.");
        }

        consumer.Parent = this;
        Consumers.Add(consumer);
    }

    ///
    ///Iterates through all the WorkUnits until the producer calls CompleteAdding() and all added WorkUnits have been processed.
    ///
    public void Begin()
    {
        // if the external process doesn't set up a process, just pass the value along
        if (ProcessCompleted.GetInvocationList().Count() == 0 && PassValuesIfNoProcessDelegate)
        {
            Process = w =>
            {
                return w;
            };
        }

        Task.Run(() =>
        {
            InnerWorkLoop();
        });
    }

    private void InnerWorkLoop()
    {
        foreach (var workUnit in WorkUnits.GetConsumingEnumerable())
        {
            // requires WorkUnits to be empty and IsCompleted to be true
            var transformedWorkUnit = Process(workUnit);

            if (!EqualityComparer<T>.Default.Equals(transformedWorkUnit, default(T)))
            {
                foreach (var consumer in Consumers)
                {
                    consumer.WorkUnits.Add(transformedWorkUnit);
                }
            }

            if (ExecuteInParallel)
            {
                Parallel.ForEach(Consumers, (consumer) =>
                {
                    consumer.Begin();
                });
            }
            else
            {
                foreach (var consumer in Consumers)
                {
                    consumer.Begin();
                }
            }
        }
        OnProcessCompleted(EventArgs.Empty);
    }

    ///
    ///This method is called when the Begin() method completes.
    ///</para>If the ProcessCompleted handler has any delegates they will be called here.</para>
    ///
    protected virtual void OnProcessCompleted(EventArgs e)
    {
        if (ProcessCompleted != null)
            ProcessCompleted(this, e);
    }


texts: Scroll to the top of an element when document is loaded

texts:
Intention: Automatically scroll the window to the top of a DOM element when the document is loaded.

via JavaScript:

window.onload = function(){
    document.getElementById('foo').scrollIntoView(true);
};

Questions and Concerns:

Is there a more compact and/or smarter technique?
Does this technique pose issues or potential conflicts?
With the above said, should it matter where on the document it's loaded? If so, what's the best location? I've already studied this question and its references closely and I'm led to believe it's best to have this kind of script located toward the bottom the document.


texts:
Here is the link to the revised version of this code:
Database abstraction class in C# (version 2)

I am new to C# and have coded a database abstraction class that I would like to get comments on.  It uses prepared SQL statements.  I would like this to not get distracted with prepared statements versus non-prepared statements discussion; please just review the code assuming prepared statements are appropriate for this class.

class DatabaseAccess
{
    private SqlCommand alreadyDownloadedCommand;
    private SqlCommand markedDownloadedCommand;

    public DatabaseAccess()
    {
        SqlConnection myConnection = new SqlConnection("user id=username;" +
                                   "password=password;server=serverurl;" +
                                   "Trusted_Connection=yes;" +
                                   "database=database; " +
                                   "connection timeout=30");

        myConnection.Open();
        alreadyDownloadedCommand = getAlreadyDownloadedCommand(myConnection);
        markedDownloadedCommand = getMarkedDownloadedCommand(myConnection);
    }

    private SqlCommand getMarkedDownloadedCommand(SqlConnection connection)
    {
        const string markDownloadedInsert =
        @"insert into dbo.InspectionsDownloaded(FileName)
          values (@FileName)
        ";
        SqlCommand command = new SqlCommand(null, connection);
        command.CommandText = markDownloadedInsert;
        command.Parameters.Add(new SqlParameter("@FileName", System.Data.SqlDbType.Text, 80));

        return command;
    }
    private SqlCommand getAlreadyDownloadedCommand(SqlConnection connection)
    {
        const string alreadyDownloadedQuery =
        @"select count(*) as numDownloaded
            from dbo.InspectionsDownloaded id
           where id.FileName = @FileName
        ";
        SqlCommand command = new SqlCommand(null, connection);
        command.CommandText = alreadyDownloadedQuery;
        command.Parameters.Add(new SqlParameter("@FileName", System.Data.SqlDbType.Text, 80));

        return command;
    }
    public Boolean AlreadyDownloaded(String filename)
    {
        Int32 rowCount;
        alreadyDownloadedCommand.Parameters[0].Value = filename;
        rowCount = (Int32)alreadyDownloadedCommand.ExecuteScalar();
        return (rowCount != 0);
    }
    public void MarkDownloaded(String filename)
    {
        markedDownloadedCommand.Parameters[0].Value = filename;
        markedDownloadedCommand.ExecuteNonQuery();
    }
}


texts:
I am writing a simple compiled programming language. Everything but the bytecode interpreter can run as slow as possible, but I would like the interpreter to fun fast, because that's why I made it compiled.

Now that much of the language is working, I decided to profile it to see where I could improve the interpreter. And I find out that a particular method, the method that enables the interpreter to use space freed up by previously deleted variables, is the major bottleneck.

The function, find_space, takes in the size of the contiguous memory block to find. A nonlocal variable called used_mem stores all the indices that are being used by other variables. To find_space, one must find an index where the next size items are not in used_mem.

The original implementation (also the fastest):

def find_space(size: int) -> int:
    for i in range(256):  # all possible memory indices
        for offset in range(size):  # for index past the starting index in size
            if i+offset in used_mem:  # check that new index is not in the used memory
                break  # oh well, its used, lets move on
            else:
                return i  # it works! lets use it
    return None

My second implementation (slowest):

def find_space(size: int) -> int:
    return next(i for i in range(256) if all(i+offset not in used_mem for offset in range(size)))

My third implementation (middle):

def find_space(size: int) -> int:
    for i in range(256):
        if used_mem.isdisjoint(range(i, i+size)):
            return i
    return None

However, all these implementations still couldn't get the average total time used on calculating the 46th fibonacci number 10 times below 0.086 sec.

I've tried 3 times, and 3rd time is supposed to be the charm. Therefore, I'm asking all you wonderful, talented people of codereview.stackexchange.com to help me in optimizing this code.

How can I optimize this code to run as fast as humanely possible in python?


texts:
I have some dispute with a colleague. I work with some REST-service, from which I get always same type data.

class File():
    def __init__(self, name, created, modified, media_type, path, md5, type, mime_type, size,
                 public_key=None, public_url=None, preview=None):
        self.public_url = public_url
        self.preview = preview
        self.name = name
        self.created = created
        self.modified = modified
        self.path = path
        self.type = type
        self.media_type = media_type
        self.md5 = md5
        self.mime_type = mime_type
        self.size = size

The following code snippet demonstrate, how I work with File class:

def get_list_of_all_files(self):
    url = self._base_url + "/resources/files"
    r = requests.get(url, headers=self.base_headers)
    json_dict = r.json()

    files = []

    for item in json_dict["items"]:
        f = File(**item)
        files.append(f)

    return files

My colleague says that the constructor is very large, and this code is horrible. Is he right? How should look like this code?


texts: Debug merge sort and validate comparison counters

texts:
I am posting the code for my merge sort to see if I can get folks offer suggestions as to where to make comparisons or if I am making the correctly already.

I will post my heap sort and quick sorts in other posts.  I actually have them all in a package that runs them together but separating them out for clarity.

package AlgorithmComparison;

import java.util.*;
import java.math.*;

public class AlgCompareApp
{
  public static void main(String[] args)
  {
  int mSortCnt = 0;
  int numbersNeeded = 5000;  // Number in the array
  double total = logb(numbersNeeded,2);
  double logN = numbersNeeded * total;
  int loopCount = 50;  // Change this for the Loop through each sort

  System.out.print("n log(n) for " + numbersNeeded + " is ");
  System.out.printf(" %.2f",logN);
  System.out.println();
  System.out.println("Merge Sort");
    for(int l = 0; l < loopCount; l++)
    {
    Random rng = new Random();
    // Create initial Array List of numbers
    ArrayList<Integer> arrlist = new ArrayList<Integer>();

    // Populate Initial Array List with numbers and no duplicates
    for (int i = 0; i < numbersNeeded; i++)
    {
      while (true)
      {
        Integer next = rng.nextInt(numbersNeeded * 2);
        if (!arrlist.contains(next))
        {
          arrlist.add(next);
          break;
        }
      }
    }

    // Create QuickSort Int Array from ArrayList
    int[] mergeSortArray = new int[arrlist.size()];
    for (int i = 0; i < arrlist.size(); i++)
    {
      mergeSortArray[i] = arrlist.get(i);
    }
    //System.out.print("\n---------------Merge Sort---------------\n");
    MergeSortRun mgsrt = new MergeSortRun();
    mgsrt.MergeSortRun(mergeSortArray, 0, mergeSortArray.length - 1);
    mgsrt.displayList();
    mSortCnt = mSortCnt +mgsrt.getCounterOne();
      }
    System.out.println("Averages");
    System.out.println((mSortCnt / loopCount));
    System.out.println("Percentage of n log(n)");
    System.out.printf("%.2f",((mSortCnt / loopCount)/logN));
    System.out.println();
  }

  public static double logb( double a, double b )
{
return Math.log(a) / Math.log(b);
}
}

package AlgorithmComparison;

import java.util.*;

public class MergeSortRun
{
    private int counterOne = 0;
   int[] displayList;

  public void MergeSortRun(int array[], int lo, int n)
  {
    int low = lo;
    int high = n;
    if (low >= high)
    {
      return;
    }
    int middle = (low + high) / 2;
    MergeSortRun(array, low, middle);
    MergeSortRun(array, middle + 1, high);
    int end_low = middle;
    int start_high = middle + 1;
    while ((lo <= end_low) && (start_high <= high))
    {
      if (array[low] < array[start_high])
      {
        low++;
      } else
      {
        int Temp = array[start_high];
        for (int k = start_high - 1; k >= low; k--)
        {
          array[k + 1] = array[k];
        }
        array[low] = Temp;
        low++;
        end_low++;
        start_high++;
        //counterOne++;
      }
      counterOne++;
    }
    // counterOne++;
    displayList = Arrays.copyOf(array, n + 1);
  }

  public void displayList()
  {
//    for (int i = 0; i < displayList.length; i++)
//    {
//      System.out.print(displayList[i] + " ");
//    }
    System.out.println(counterOne);
  }

  public int getCounterOne()
  {
    return counterOne;
  }
}

My entire java package is zipped up and can be downloaded from here.


texts: Attempt to save (recover) files from a broken external drive

texts:
My external drive that I use for Backup had some broken files. I feared that I'd lose some (or all) the data in there. So I wanted to copy each and every file to my hard disk.

I first tried using regular Windows methods (Copy, Xcopy). But, these methods took a lot of time and the commands would stop execution after hitting a broken file.

For example:

xcopy E:\sampleSourceDirectory\*.* D:\BACKUP\sampleSourceDirectory\ /s /e

Solution Method:

An iterative script to try to move each file in the sampleSourceDirectory
Report how many files have failed

Note: I preferred MOVING files, instead of COPYING, so that I could retry moving the folder again, hoping that the external drive can read the files upon another trial.

Python script:

import shutil
import os

folderName = 'sampleSourceDirectory'

source = 'E:/' + folderName + '/'
destination = 'D:/BACKUP/' + folderName + '/'

if (os.path.exists(destination) == False):
    os.makedirs(destination)    #Make that Directory

files = os.listdir(source)
filesSource = files

nSuccess = 0        # number of Files
nFail = 0

while len(files)>0:
    for f in files:
        try:
            shutil.move(source + f, destination + f)
            nSuccess = nSuccess + 1
        except OSError as err:
            print("OS error: {0}".format(err))
            files.remove(f)
            nFail = nFail + 1

filesDestination = os.listdir(destination)
if (filesSource == filesDestination) and (len(filesSource) != 0):
    print("Move Successful")
else:
    print("ERROR IN MOVE!!! ****** CHECK WARNINGS!!! \n")
    print ( nFail, ' files failed!')

With this question, I'd like to first answer the basic question: is this an effective way to try saving files?

Secondly, I'd like to receive general feedback on the script itself, and any particular points that I might have misthought/misimplemented.

Final note: this script is not intended to be a secure way and I'd strongly advise not to use it for serious data. (I don't know if it's by chance or not but after a few trials my external drive stopped working completely, and I could only save 10% of the contents.)


texts: Find out whether number is of Power of Two

texts:
The task

is taken from leetcode

  Given an integer, write a function to determine if it is a power of
  two.

  Example 1:

  Input: 1

  Output: true

  Explanation: 20 = 1

  Example 2:

  Input: 16

  Output: true

  Explanation: 24 = 16

  Example 3:

  Input: 218

  Output: false

My solution

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
  if (n <= 0 ) { return false; }
  if (n <= 2) { return true; }
  let num = n;
  do {
    const x = num / 2;
    if ((x | 0) !== x) { return false; }
    if (x === 2) { return true; }
    num = x;
  } while(num);
  return false;
};


texts: Powershell to Convert HTML Table to Array of PSCustomObject

texts:
I created the below script to sent a request to a website, then convert the table in the results to an array of PSObjects which I can work with in PowerShell.  This uses some nasty hacks (e.g. using a regex to strip HTML tags from my XML to try to improve the likelihood of it parsing as valid XML), but I couldn't find cleaner solutions / this seems to work.

Any thoughts on where I may have used a nasty hack where a more elegant solution exists?

function Create-Url {
    [CmdletBinding()]
    param (
        #using parameter sets even though only one since we'll likely beef up this method to take other input types in future
        [Parameter(ParameterSetName='UriFormAction', Mandatory = $true)]
        [System.Uri]$Uri
        ,
        [Parameter(ParameterSetName='UriFormAction', Mandatory = $true)]
        [Microsoft.PowerShell.Commands.FormObject]$Form
    )
    process {
        $builder = New-Object System.UriBuilder
        $builder.Scheme = $url.Scheme
        $builder.Host = $url.Host
        $builder.Port = $url.Port
        $builder.Path = $form.Action
        write-output $builder.ToString()
    }
}

function ConvertFrom-HtmlTableRow {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $htmlTableRow
        ,
        [Parameter(Mandatory = $false, ValueFromPipeline = $false)]
        $headers
        ,
        [Parameter(Mandatory = $false, ValueFromPipeline = $false)]
        [switch]$isHeader

    )
    process {
        $cols = $htmlTableRow | select -expandproperty td
        if($isHeader.IsPresent) {
            write-output $cols
        } else {
            $colCount = ($cols | Measure-Object).Count
            <# extra overhead that I dont care about right now
            if(-not (($headers) -or ($headers -eq $null) -or (($headers | Measure-Object).Count -ne $colCount))) {
                $headers = 1..$colCount | %{("Column_{0:00000}" -f $_)}
            }
            #>
            $result = new-object -TypeName PSObject
            1..$colCount | %{
                $i = $_ - 1
                if($headers[$i] -ne $null) {
                    $colName = $headers[$i]
                    $colValue = $cols[$i]
                    write-debug "$colName = $colValue"
                    $result | Add-Member NoteProperty $colName $colValue
                }
            }
            write-output $result
        }
    }
}

function ConvertFrom-HtmlTable {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        $htmlTable
    )
    process {
        #currently only very basic

...

 structure supported
        #could be improved to better understand tbody, th, nested tables, etc

        #$htmlTable.childNodes | ?{ $_.tagName -eq 'tr' } | ConvertFrom-HtmlTableRow

        #remove anything tags that aren't td or tr (simplifies our parsing of the data
        [xml]$cleanedHtml = '<root>' + ($htmlTable | select -ExpandProperty innerHTML | %{($_ | out-string) -replace '(?:(</?tr)|(</?td))[^>]*(/?>)|(?:<[^>]*>)','$1$2$3'}) + '</root>'
        $headers = $cleanedHtml.root.tr | select -first 1 | ConvertFrom-HtmlTableRow -isHeader
        if ($headers -gt [System.String]::Empty) {
            $cleanedHtml.root.tr | select -skip 1 | ConvertFrom-HtmlTableRow -Headers $headers | select $headers
        }
    }
}

clear-host

[System.Uri]$url = 'http://some.site.with.tables.com/Subnet_Audit.asp' #link to some website
[System.String]$subnet = '123.45.67' #this relates to a specific paramter in the form; in my case the site checks the AV versions of all computers within a given IP range

$rqst = Invoke-WebRequest $url -SessionVariable avsv
$form = $rqst.Forms[0]
$form.Fields["strsubnet"] = $subnet
$url = Create-Url -Uri $url -Form $form
$rqst = Invoke-WebRequest -Uri $url -WebSession $avsv -Method $form.Method -Body $form.Fields
$rqst.ParsedHtml.getElementsByTagName('table') | ConvertFrom-HtmlTable


texts:
I am building a Perl module which I am attempting to use as few non-core dependencies as possible. Should my following code fail, I would add a dependency on HTML::LinkExtor and be done with it, but I want to try. All I want is to extract the href= attributes from  tags. I do it using Text::Balanced which is core as of modern Perls and is installable for others. So yes, I know I should use a HTML library. That said, is this passably ok?

#!/usr/bin/env perl

use strict;
use warnings;

use Data::Dumper;

use Text::Balanced qw/extract_bracketed extract_delimited extract_multiple/;

my $html = q#Some link text stuff. And a little different link text.#;

my @tags = find_anchor_targets($html);

print Dumper \@tags;

sub find_anchor_targets {
  my $html = shift;

  my @tags = extract_multiple(
    $html,
    [ sub { extract_bracketed($_[0], '<>') } ],
    undef, 1
  );

  @tags =
    map { extract_href($_) }  # find related href=
    grep { /^)/) {
    return $1;
  } else {
    return ();
  }
}

This dumps

$VAR1 = [
          'link',
          'link2'
        ];

which is what one would expect.


texts: Kotlin DAO with Exposed: How to reduce redundancy in classes?

texts:
I'm writing a Kotlin app that uses Exposed (https://github.com/JetBrains/Exposed) as a SQL wrapper to write and read objects from databases. The problem I'm facing is that I end up with 3 classes featuring the same variables. For example:

package database

import hashLength
import org.jetbrains.exposed.dao.EntityID
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.IntIdTable
import org.jetbrains.exposed.sql.Table

object LogEntries : IntIdTable() {
    val logId = binary("id", hashLength).primaryKey()
    val prev = binary("prev", hashLength).index()
    val owner = varchar("owner", 32).index()
    val timestamp = long("timestamp").index()
    val action = integer("action")
    val proof = text("proof")
    val nonce = binary("nonce", 8)
    val signature = binary("signature", 32)
}

class LogEntry(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<LogEntry>(LogEntries)

    var logId by LogEntries.logId
    var prev by LogEntries.prev
    var owner by LogEntries.owner
    var timestamp by LogEntries.timestamp
    var action by LogEntries.action
    var proof by LogEntries.proof
    var nonce by LogEntries.nonce
    var signature by LogEntries.signature
}

data class LogEntryHolder(
    var logId: ByteArray,
    val prev: ByteArray,
    val owner: String,
    val timestamp: Long,
    val action: Int,
    val proof: String,
    val nonce: ByteArray,
    val signature: ByteArray
)

The first is the Exposed DAO class (I don't use that directly), the second is a wrapper (companion class) to where I add more functions, this is where I do my CRUD operations on. The third is an in-memory class that I use to 'create' the object before storing it in the database. There are 2 reasons for that:

1: I now can edit the object before persisting it in the database (otherwise if I create a new LogEntry it's immediately saved in the database and I have to edit the log again directly after storing it, which seems counter-intuitive.

2: When processing through a function, I just have to supply the LogEntryHolder instead of passing all the values of the object individually.

Is there are way to reduce the amount of classes needed, so that the final code is less error-prone and redundant? Thanks a lot!


texts: Is my DSL good idea to replace builder pattern?

texts:
I want to build a set of builders for generating test data. On one side I want my builders API to be natural to use for my teammates. On the other side I'm great fun of creating DSLs, because it eliminates writing the same boilerplate code and let you read the code as English sentences.

However, I found those requirements quite incompatible. I've shown my builders to my teammate and what was intuitive to me, was not for him. He would need to learn my DSL.

How would you improve my design decisions in Builder pattern?

Decision #1: Long domain names vs. new short names

I started with traditional withX() methods for setting field X. For X I used names that are well known in our domain and commonly used in the rest of implementation.

Flight.Builder.create()
   .withOrigin(Airport.LAX)
   .withDestination(Airport.JFK)
   .build();

Then I thought this takes too much space, so I used method names that are shorter but uncommon in the rest of the implementation.

Flight.Builder.create()
   .from(Airport.JFK)
   .to(Airport.LAX)
   .build();

Another programmer prefered traditional names from the domain: origin, destination.

Decision #2: Clear method names vs. duplicate methods with type-overloading

Another weak point I found was redundancy of some information. For instance, in the following code:

Flight.Builder.create()
  .withPassenger(Passenger.ADULT) // that's a template
  .withPassenger(Passenger.Builder.create().withName("KENNEDDY"))
  .withStatus(Status.CANCELLED)
  .build();

the redundancy is in passenger-passenger, and in status-status. So I removed redudant words from method names and used type-overloading.

Flight.Builder.create()
  .with(Passenger.ADULT)
  .with(Passenger.Builder.create().withName("KENNEDDY"))
  .with(Status.CANCELLED)
  .build();

The programmer who knows data model underlying this builder and was used to more traditional builder pattern, was confused with my approach.

Decision #3: Changing words order and delegating builder creation

Then I found builder creation kind of boilerplate code that makes it harder to read:

Flight.Builder.create()
   .withPassenger(Passenger.Builder.create().withName("KENNEDDY"))
   .build();

I shortened those constructs. I also found this incompatible with English words order in sentence, where you don't say "what.build()", but "build(what)". Here's the result.

build(flight()
  .withPassenger(passenger().withName("KENNEDDY")));

How would you improve my design decisions?


texts: Delete K nodes in a linked list having their data less than the next node's

texts:
The question is from here.

  Given two numbers N and K where N is the number of nodes and K is the number of nodes to be deleted, delete K nodes whose data is less than their next node's data. If no such nodes exist, delete the last node.

But it is still giving me TLE. I tried all the optimisations that could occur to me. I know this can be done with stacks but I would like to know if it can't done in the allocated time with linked lists.

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

struct Node
{
    int value;
    struct Node *next;
};

void addnode(struct Node** head, struct Node** tail, int data)
{
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
    temp->value = data;
    temp->next = nullptr;
    if( *head == nullptr)
    {
        *head = temp;
        *tail = *head;
        return;
    }
    (*tail)->next = temp;
    *tail = temp;
}

void deleteNode(struct Node** head, struct Node** prev, struct Node** temp)
{
    if( (*prev)->next == *head)
    {
        *head = (*prev)->next->next;
        return;
    }
    (*prev)->next = (*temp)->next;
}

void deletenodeatlast(struct Node** prev)
{
    (*prev)->next = (*prev)->next->next;
}

void display(struct Node* head)
{
    struct Node* p = head;
    while(p != nullptr)
    {
        printf("%d ", p->value);
        p = p->next;
    }
    printf("\n");
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        struct Node* head = nullptr;
        struct Node* tail = head;
        int N, K;
        scanf("%d %d", &N, &K);

        for(int i = 0; i < N; i++)
        {
            int data;
            scanf("%d", &data);
            addnode(&head, &tail, data);
        }
        for(int i = 0; i < K; i++)
        {
            bool isGreater = false;
            struct Node* p = head;
            struct Node* prev = (struct Node*)malloc(sizeof(struct Node));
            prev->value = 1000000;
            prev->next = p;

            while( p->next != nullptr)
            {
                if( p->value < p->next->value)
                {
                    deleteNode(&head, &prev, &p);
                    isGreater = true;
                }
                else
                {
                    prev = p;
                    p = p->next;
                }

                if( isGreater )
                {
                    break;
                }
            }
            if( !isGreater)
            {
                deletenodeatlast(&prev);
            }
        }
        display(head);
    }
    return 0;
}


texts: Python REST API Data Extraction with requests library

texts:
Is there a better way to write this piece of code to extract data from a REST API with the requests library? It currently takes about 10 minutes to finish extracting the data from the REST API. I think the code below may not be the most efficient method.
import time
import requests
import datetime
import pandas as pd

def loan_rest_api():
    '''
    This function calls the rest api and stored the data in a pandas dataframe.
    '''

    search_start = time.time()
    print("Extracting loan data from Rest API...")

    # Declaring variables for the first page number and the list that contains the results for each page in the REST API.
    num = 1
    pages = []

    # Declaring variable to look up the correct table in the REST API.
    table = 'loan'

    # The 'loan' table has about 50 columns, but these are the ones I need.
    # Declaring columns variable to choose the columns I'm interested in.
    columns = '''
                loan_id,
                loan_name,
                loan_parent_id,
                loan_status,
                loan_type,
                loan_classification,
                loan_create_date,
                loan_last_update,
                loan_amount,
                loan_amount_last_update,
                loan_balance,
                loan_balance_last_update,
                loan_interest,
                loan_interest_last_update,
                city,
                office_location,
                project_name
            '''

    # Infinitely loop needed to iterate through all of the pages of data that the loan
    # table contains. Since I don't know how many pages there are, I loop
    # through the entire table until it reaches the end. Once
    # it reaches the end, the While True condition no longer holds so the loop stops.
    while True:

        # Since the loan table in the rest api contains several pages, I had to implement a
        # pagination functionality to prevent the function from either timing out or crashing.
        pagination = {'pageSize': '5000',
                      'pageNumber': str(num),
                      'attributes': columns.replace(' ', '').replace('\n', '')}

        # Send a GET request to the REST API on the corresponding loan table.
        # the params parameter contains the pagination requirements. Start
        # with page 1, then page 2, etc. For each resulting data pull, append
        # the page to the pages list.
        # num increase by 1 on the next loop until it reaches the end.
        response = requests.get(REST_API_LINK + table, params=pagination)
        if response.status_code != 200:
            break
        results = response.json()
        pages.append(pd.DataFrame(results))
        num += 1

    # Create a pandas dataframe. This contains about 200,000 rows and it's
    # 40MB in size when exported as a csv file.
    final_df = pd.concat(pages, ignore_index=True)

    # Right now this takes about 800 seconds.
    search_end = time.time()
    print(f" ...search completed in {search_end - search_start: .2f} seconds.")

    return print('Search Done.')

```


texts: Perform a contains-ignore-case with multiple search-tokens

texts:
I had a look on Stack Overflow etc. on how to perform a contains ignore case with n given strings. Most answers suggested using regex for this task. Although it's a valid option, I prefer doing upper-case for both strings and apply a .contains afterwards.

The solution I came up with looks like this:

(defn desc-matches? [desc search-tokens]
  (let [upper-desc (str/upper-case desc)
        upper-tokens (map str/upper-case search-tokens)]
    (some (partial #(.contains %1 %2) upper-desc) upper-tokens)))

Since I am relatively new to clojure, I'd appreciate if someone could have a look and tell me his/her thoughts on it.

UPDATE 1 - Applied Thumbnails suggestion

(defn desc-matches? [desc search-tokens]
  (let [upper-desc (str/upper-case desc)
        upper-tokens (map str/upper-case search-tokens)]
    (some #(.contains upper-desc %) upper-tokens)))


texts: Using fetch() and a new Promise object to get API results

texts:
I've written an ES6 function using the new fetch() API and returning a new resolved promise with a data object or a rejected promise with an error subclass.

I'm pretty new to both ES6 and Promises, and it looks a little unwieldy, so I'm wondering if there's a better way. I'm also wondering about how this relates to the "explicit promise construction antipattern".

Any suggestions for how to improve or simplify?

function get(url) {
  console.log('Making fetch() request to: ' + url);

  let promise = new Promise((resolve, reject) => {
    fetch(url).then(response => {
      if (response.ok) {
        const contentType = response.headers.get('Content-Type') || '';

        if (contentType.includes('application/json')) {
          response.json().then(obj => {
            resolve(obj);
          }, error => {
            reject(new ResponseError('Invalid JSON: ' + error.message));
          });
        } else if (contentType.includes('text/html')) {
          response.text().then(html => {
            resolve({
              page_type: 'generic',
              html: html
            });
          }, error => {
            reject(new ResponseError('HTML error: ' + error.message));
          });
        } else {
          reject(new ResponseError('Invalid content type: ' + contentType));
        }
      } else {
        if (response.status == 404) {
          reject(new NotFoundError('Page not found: ' + url));
        } else {
          reject(new HttpError('HTTP error: ' + response.status));
        }
      }
    }, error => {
      reject(new NetworkError(error.message));
    });
  });

  return promise;
}


texts:
Would it be better to convert the array in the following code to

$langs = array("en", "de", "fr");

and then reusing the values for both $folder and $flag? If so, how then would my foreach (or maybe a while?) loop be written?

<?php
    $langs = array(
        "en/" => "en.png",
        "de/" => "de.png",
        "fr/" => "fr.png"
    );
    $self    = $_SERVER['REQUEST_URI'];
    $pattern = "{^.*/}i";
    $links   = array();
    foreach ($langs as $folder => $flag) {
        $url  = preg_replace($pattern, "$folder", $self);
        $link = "

";
        array_push($links, $link);
    }
    echo implode($links) . "\n";
?>

I'm trying to "fool proof" the code, by effectively limiting the folder structures and file names that can be used, as I create a basic template of files for quick rolling out of our websites. If you can see any other improvements, that would be much appreciated.


texts: Read file with over 300k words and filter through appropriate filter to return list of matching words

texts:
As a puzzle we were asked to bring out the possibilities in breaking a 4 letter wordlock combination. It was to be a four letter word from the English dictionary. There were 10 possible characters in each place. So \$10^4\$ possibilities of random words. I brute forced my code to return a list of possible words by first reading a file of 300k English words and storing it in a list. Then I applied a filter at each place to narrow down the list of possible words that could work on the combo.

I know I am brute forcing the code down to 1089 possibilities, did I overlook other possibilities? I am a beginner and if I wanted to learn how to improve the efficiency of my code and make it simpler/functioning, what steps can I take?

filterlist2 = ['a','r','t','h','i','v','o','y','l','e',]
filterlist3 = ['a','l','t','o','i','n','s','r','m','f',]
filterlist4 = ['a','m','d','k','e','s','x','p','l','y',]

#filterlist1 basically before I realized I can store parameters in a list
lines = tuple(open("words.txt", 'r'))
char1filter=[]
for element in lines:
    if len(element)==5:
        if element.startswith('b') is True:
            char1filter.append(element)
        elif element.startswith('p') is True:
            char1filter.append(element)
        elif element.startswith('t') is True:
            char1filter.append(element)
        elif element.startswith('s') is True:
            char1filter.append(element)
        elif element.startswith('m') is True:
            char1filter.append(element)
        elif element.startswith('d') is True:
            char1filter.append(element)
        elif element.startswith('c') is True:
            char1filter.append(element)
        elif element.startswith('g') is True:
            char1filter.append(element)
        elif element.startswith('f') is True:
            char1filter.append(element)
        elif element.startswith('l') is True:
            char1filter.append(element)

#print(char1filter)

print(len(char1filter))
#returned 3935 results
#filter 2 for second character
char2filter =[]
for element1 in char1filter:
    if element1[1] in filterlist2:
        char2filter.append(element1)
print('char2 filter applied')
print(char2filter)
print(len(char2filter))
#filter 2 returned 3260 words
#filter 3

char3filter =[]
for element2 in char2filter:
    if element2[2] in filterlist3:
        char3filter.append(element2)
print(char3filter)
print(len(char3filter))
#filter 3 returned 1991 words
#filter 4
char4filter =[]
for element3 in char3filter:
    if element3[3] in filterlist4:
        char4filter.append(element3)
print(char4filter)
print(len(char4filter))

#filter 4 returned 1089 words


texts: Class project: user-editing page for a haiku website

texts:
I am making a website using just HTML and CSS for a classroom project (we are in the 2nd week of boot-camp.) I have my site made, and want to get others' opinion on the code. I am mostly looking to have the site scale properly on different browsers, but other input is appreciated as well.

body {
    font-family: 'Anton', sans-serif;
    margin: auto;
}

.top {
    background-color: #F25266;
    border: #666561 solid 1em;
}

h1 {
    color:#F4EF6B;
    text-decoration: underline;
    text-align: center;
}

.middle {
    background-color:#ECECEC;
    border-left: #666561 1em  solid;
    border-right: #666561 1em solid;
}

.pic {
   display: block;
  margin: auto;
  width: 40%;
}

form > label{
    color: #2E90BF;
    column-count: 1
}

form > input {
    background-color: #2E90BF;
    border-color: #666561;
    width: 14.2%;
    column-count: 1
}

#button_one {
    font-family: 'Anton', sans-serif;
    color:#FFF;
    background: #2E90BF;
    border-color: #000;
    height: 2em;
    width: 100%;
    font-size: 1em;
    cursor: pointer;
    margin-top: 1em;
}

#button_one:active {
  background-color: #2E90BF;
  transform: translateY(4px);
}

.bottom {
    background-color:#F25266;
    border: #666561 solid 1em;
}

ul {
    list-style: none;
    column-count: 10;
}

a:link {
    color: #6DBF2E;
}

a:visited {
    color: #6DBF2E;
}

a:hover {
    color: yellow;
}
<!DOCTYPE html>

        <title>Edit User</title>

        <link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">

        <link type="text/css" rel="stylesheet" href="assets/stylesheets/style.css" />

User Information

        <form>
            E-Mail:
            <input>
            Password:
            <input>
            Confirm Password:
            <input>
            First Name:
            <input>
            Last Name:
            <input>

            <button type="submit" id="button_one">Submit</button>
        </form>

Create Haiku

Edit Haiku

Edit User

Signup User

List

One

Rules

Index

User List

User One


texts:
I'm drawing a background into kivy, and then wrap and place a transparent image on top of it. Each second I move the location of the transparent a little bit.

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.image import Image
from kivy.clock import Clock

class ScrollApp(App):

    def build(self):
        self.bkg = Background()
        self.clock = Clock.schedule_interval(self.bkg.scroll_texture, 1)
        return self.bkg

class Background(Widget):

    plx_2 = ObjectProperty(None)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # set as texture
        self.plx_2 = Image(source=r"assets\plx-2.2.png").texture
        self.plx_2.wrap = 'repeat'
        self.plx_2.uvsize = (1,-1)

    def scroll_texture(self, time_passed):
        # update uvpos
        x,y = self.plx_2.uvpos
        x = x - 0.05 % 1 # this magic number will change later
        self.plx_2.uvpos = (x, y)
        # redraw the image
        texture = self.property('plx_2')
        texture.dispatch(self)

if __name__=='__main__':
    ScrollApp().run()

And the .kv file:

#:kivy 1.11.1

<Background>:
    canvas.before:
        Rectangle:
            size : self.size
            pos : self.pos
            source: "assets\plx-1.png"
        Rectangle:
            size : self.size
            texture: self.plx_2

The code works, but I feel very odd about the way I'm redrawing the texture with dispatching itself as an event. Is there a better way? Second, now if I were to add multiple transparent images on top, I would have to add a lot of code. Is there a a better way than just adding another Rectangle in the .kv file, adding another ObjectProperty in the Background class etc, etc.?


texts:
It accepts string input like '1+1' instead of num1 = 1, num2 = 2, operation = '+' or something like that.

def Numbers(var):
    return var == '0' or var == '1' or var == '2' or var == '3' or var == '4' or var == '5' or var == '6' or var == '7' or var == '8' or var == '9'

def Test4Num(varstr):
    n = 0
    var = ''
    try:
        while Numbers(varstr[n]):
            var += varstr[n]
            n += 1
    except: pass
    return (int(var), n)

def operation(string, num1, num2):
    if string == '+':
        return num1 + num2
    if string == '-':
        return num1-num2
    if string == '*':
        return num1*num2
    if string == '/':
        return num1/num2
    if string == '^':
        return num1 ** num2

def operator(operato):
    return operato == '+' or operato == '-' or operato == '*' or operato == '/' or operato == '^'

negate = False
char = input('')

print(char + '=')
while True:
    try:
        if char[0] == '-': #for negative numbers
            negate = True #because here the numbers are string format
            char = char[1:]
        number1 = Test4Num(char)[0]
        if negate == True:
            number1 = -number1
            negate = False
        end_number1 = Test4Num(char)[1]
        char = char[end_number1:]
        if char == '':
            print(number1)
            break
        op = char[0]
        char = char[1:]
        number2 = Test4Num(char)[0]
        end_number2 = Test4Num(char)[1]
        result = operation(op, number1, number2)
        number1 = result
        char = str(number1) + char[end_number2:]
        print(char)
    except: break
#created by Estoria Wandertag, while he was sitting on the toilet and thought about life and programming

This code is pretty straightforward, I mean it doesn't use class, any imports, etc. (ok, it can just use the 5 main operations in math, but that's extendable) and even though it's easy, I didn't find it on the internet...
So that's the reason I wanted to share this. If you have ideas, please share them. I'm pretty new here and also I haven't been using Python for very long, so there are plenty of things to add, I guess. (Sorry for my awful English, I'm German)


texts: Get Ajax request implementation without jQuery

texts:
I'm writing a pixel library to do an AJAX request so I'm not allowed to use any helper.

function ajax(options) {
  var xhr = new XMLHttpRequest();
  var opts = Object.assign({
    withCredentials: false,
    method: 'GET'
  }, options);

  xhr.withCredentials = options.withCredentials;
  xhr.open(opts.method, opts.url);
  xhr.setRequestHeader('Accept', 'text/plain');
  xhr.send(null);
  return {
    done: function(cb) {
      xhr.onreadystatechange = function onStateChange() {
        if (this.readyState === 4) {
          if (this.status >= 200 && this.status < 300) {
            cb(this.responseText);
          } else {
            cb('error');
          }
        }
      };
      xhr.ontimeout = function(e) {
        console.error(e);
        cb(false);
      };

      xhr.onerror = function(e) {
        console.error(e);
        cb(false);
      };
    }
  }
};

ajax({
  url: '/echo/json'
}).done(function(response) {
  console.log(response);
})

I also have my code in a jsfiddle in case anyone wants to test the code.

Note: This library doesn't support POST as I want to keep the code as less as possible. It will only support GET.


texts: Count Acute, Right and Obtuse triangles from n side lengths

texts:
Problem Statement: We have \$N\$ sticks. The size of the \$i\$th stick is \$A_i\$. We want to know the number of different types of triangles created with each side from a single different stick. Calculate the number of acute triangles, right triangles and obtuse triangles.

Input Format: The first line contains \$N\$. The second line contains \$N\$ integers. The \$i\$th number denotes \$A_i\$.

Constraints:

For full score: \$3 \le N \le 5000\$
For 40% score: \$3 \le N \le 500\$

For all test cases:

\$1 \le A[i] \le 10^4\$
\$A[i] \lt A[i+1]\$ where \$1 \le i \lt N\$

Output Format: Print 3 integers: the number of acute triangles, right triangles and obtuse triangles, respectively.

My Solution: My code runs in the given time for small \$n\$ (~500). It will work for large \$n\$ (~5000) but I get time limit exceeded error on the Online Judge.

using System;

namespace CodeStorm
{
    class Triangles
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            string[] A_temp = Console.ReadLine().Split(' ');
            int[] A = Array.ConvertAll(A_temp, Int32.Parse);
            int[] A_sq = new int[n];

            for (int i = 0; i < n; i++)
            {
                A_sq[i] = A[i] * A[i];
            }

            int n_m_2 = n - 2;
            int n_m_1 = n - 1;

            int acute = 0, right = 0, obtuse = 0;
            for (int i = 0; i < n_m_2; i++)
            {
                for (int j = i + 1; j < n_m_1; j++)
                {
                    int k = j + 1;
                    int AiPlusAj = A[i] + A[j];

                    while (k < n)
                    {
                        int squareSum = A_sq[i] + A_sq[j];
                        if (AiPlusAj <= A[k])
                        {
                            break;
                        }
                        else if (squareSum > A_sq[k])
                        {
                            acute++;
                        }
                        else if (squareSum < A_sq[k])
                        {
                            obtuse++;
                        }
                        else
                        {
                            right++;
                        }
                        k++;
                    }
                }
            }
            Console.WriteLine(acute + " " + right + " " + obtuse);
            Console.ReadLine();
        }
    }
}

The above code runs perfectly and finds the possible triangles.

Input:

6
2 3 9 10 12 15

Output:

2 1 4

The possible triangles are:

  Acute triangles: 10−12−15, 9−10−12

  Right triangle: 9−12−15

  Obtuse triangles: 2−9−10, 3−9−10, 3−10−12, 9−10−15

I want to know a more efficient way to approach the problem so that I can get it executed in the given time limit for \$n\$ (~5000). After I tried to find the complexity, I came up with \$O(n^3)\$. I am not good with complexities. I might be wrong. I would like a more efficient way for the problem.


texts: Method that gets the date from a file according to the name of the client

texts:
I have in this class bellow, a method that gets the date from a file according to the name of the client. For each client, the method to extract the date is different. I want to use heritage or any other way to have a generic class without conditions, by putting all the specific code in somewhere else. I tried to create a class for each client then make the class Parser inherits from all the clients, but it is still not well structured.

import sys
import os
import re
import fnmatch
import csv
import pandas as pd
import numpy as np
from dateutil.parser import parse as parseDate
from datetime import datetime, time, timedelta

class Parser():

    def get_dateFromfile(self, file = None):
        Datefile = None
        if CLIENT == "C1":
            Datefile = parseDate(conf.WORKDIR[-14:])

        elif CLIENT == "C2" and file:
            patternToFindDate = "20H-0H45"
            filename = os.path.splitext(os.path.basename(file))[0]
            Datefile = parseDate(filename[filename.find(patternToFindDate) + len(patternToFindDate):], dayfirst=True)

        elif CLIENT == "C3" and file:
            filename = os.path.splitext(os.path.basename(file))[0]
            Datefile = parseDate(filename.rsplit('_', 1)[1])

        elif CLIENT == "C4" and file:
            filename = os.path.splitext(os.path.basename(file))[0]
            timestamp = filename[-14:]
            date = timestamp[:8].replace(".", "-") + " " + timestamp[-5:].replace(".", ":")
            Datefile = parseDate(date, yearfirst=True)

        elif CLIENT=="C5" and file:
            filename = os.path.splitext(os.path.basename(file))[0]
            timestamp = filename[-19:]
            date = timestamp[:10] + " " + timestamp[-8:].replace("-",":")
            Datefile = parseDate(date)

The method of the class has as an input an CSV file. the name of this file contains a date, and the format of the date changes according to the client. the output of the function is a string : a date in the format YYYYMMDDHHmmss.
I will try all your suggestions.
Any better idea ?


texts: Counting maximum number of elements in right order

texts:
There is an source and target.
example:
source:[a,b,e,d,s,t,c,v,t]
target:[a,e,v,g,r,b,c,v,t]
target and source have same number of elements.
how can I count elements in source ordered correctly according to target?
so, target means that elements in source should be ordered in target's order.
and count maximum number of properly ordered elements in source.
so the answer for example is 5 (a,b,c,v,t).
of course there are two elements in order like (a,e),(a,b) but out put should be maximum elements.
how can I do it neat and compactly?
My code
I used combinations, counting from max element number to 0.
n=len(target)
k=1
for check in range(n,-1,-1):
            while k!=0:
                for j in combinations(souce,check):
                    if j in combinations(target,check):
                        answer_co.append(check)
                        k=0
                        break


texts: Simplified LogService (from concurrency in practice) with shutdown feature

texts:
Brian Goetz provided following code of LogService with shutdown feature:

public class LogService {
    private final BlockingQueue<String> queue;
    private final LoggerThread loggerThread;
    private final PrintWriter writer;
    @GuardedBy("this") private boolean isShutdown;
    @GuardedBy("this") private int reservations;

    public LogService(Writer writer) {
        this.queue = new LinkedBlockingQueue<String>();
        this.loggerThread = new LoggerThread();
        this.writer = new PrintWriter(writer);
    }

    public void start() {
        loggerThread.start();
    }

    public void stop() {
        synchronized (this) {
            isShutdown = true;
        }
        loggerThread.interrupt();
    }

    public void log(String msg) throws InterruptedException {
        synchronized (this) {
            if (isShutdown)
                throw new IllegalStateException(/*...*/);
            ++reservations;
        }
        queue.put(msg);
    }

    private class LoggerThread extends Thread {
        public void run() {
            try {
                while (true) {
                    try {
                        synchronized (LogService.this) {
                            if (isShutdown && reservations == 0)
                                break;
                        }
                        String msg = queue.take();
                        synchronized (LogService.this) {
                            --reservations;
                        }
                        writer.println(msg);
                    } catch (InterruptedException e) { /* retry */
                    }
                }
            } finally {
                writer.close();
            }
        }
    }
}

I think that I have simpler variant(I don't understand why we need reservations counter), please review its safety:

public class LogService {
    private final BlockingQueue<String> queue;
    private final LoggerThread loggerThread;
    private final PrintWriter writer;
    @GuardedBy("this")
    private boolean isShutdown;

    public LogService(Writer writer) {
        this.queue = new LinkedBlockingQueue<String>();
        this.loggerThread = new LoggerThread();
        this.writer = new PrintWriter(writer);
    }

    public void start() {
        loggerThread.start();
    }

    public void stop() {
        synchronized (this) {
            isShutdown = true;
        }
        loggerThread.interrupt();
    }

    public void log(String msg) throws InterruptedException {
        synchronized (this) {
            if (isShutdown)
                throw new IllegalStateException(/*...*/);
            queue.put(msg); // inside synchronized now
        }

    }

    private class LoggerThread extends Thread {
        public void run() {
            try {
                while (true) {
                    try {
                        synchronized (LogService.this) {
                            if (isShutdown && queue.isEmpty())
                                break;
                        }
                        String msg = queue.take();
                        writer.println(msg);
                    } catch (InterruptedException e) { /* retry */
                    }
                }
            } finally {
                writer.close();
            }
        }
    }
}


texts: Control game ticks/frames of updates and rendering separately

texts:
I am working on a bigger project and want to separate game updates from rendering and not end up with a super complicated game loop. So I came up with the idea of isolating the problem and writing a controller for this. My game loop looks like:

public class Game {
    public bool Running;

    public void Loop()
    {
        var update = new FrameController(10, 30, true, Update);
        var render = new FrameController(1, 1000, false, Render);

        while (Running)
        {
            update.TryFrame();
            render.TryFrame();
        }
    }

    public void Update(double delta_time)
    {
        [...]
    }

    public void Render(double delta_time)
    {
        [...]
    }
}

And my tick/frame controller looks like:

public class FrameController
{
    protected double DeltaTime;
    protected readonly double MaxDeltaTime;
    protected readonly double MinDeltaTime;
    protected readonly bool SlowCatchUp;
    protected readonly Action<double> Action;
    protected readonly Stopwatch Watch;

    public FrameController(int min_fps, int max_fps, bool slow_catch_up, Action<double> action)
        : this(slow_catch_up, action)
    {
        MaxDeltaTime = 1.0 / min_fps;
        MinDeltaTime = 1.0 / max_fps;
    }

    public FrameController(double min_delta_time, double max_delta_time, bool slow_catch_up, Action<double> action)
        : this(slow_catch_up, action)
    {
        MaxDeltaTime = min_delta_time;
        MinDeltaTime = max_delta_time;
    }

    protected FrameController(bool slow_catch_up, Action<double> action)
    {
        SlowCatchUp = slow_catch_up;
        Action = action;
        Watch = new Stopwatch();
        Watch.Start();
    }

    public void TryFrame()
    {
        var delta_time = Watch.Elapsed.TotalSeconds;
        Watch.Restart();
        DeltaTime += delta_time;

        if (DeltaTime <= MinDeltaTime)
            // Skip
            return;
        else if (DeltaTime >= MaxDeltaTime)
            DoFrame(SlowCatchUp ? MaxDeltaTime : DeltaTime);
        else
            DoFrame(DeltaTime);
    }

    protected void DoFrame(double delta_time)
    {
        Action(delta_time);
        DeltaTime -= delta_time;
    }
}

The updates will fire 10 to 30 times per second and if the game hangs they will slowly catch up to the current state. Apart from this the rendering will fire 1 to 1000 times per second (just for testing) and if the game hangs they will catch up immediately. If the game is running to fast frame will be skipped.

Any input and critique is welcome!


texts: Groupby, apply custom function to data, return results in new columns

texts:
I want to group by id, apply a custom function to the data, and create a new column with the results. It seems there must be a faster/more efficient way to do this than to pass the data to the function, make the changes, and return the data. Here is an example.

Example

dat = pd.DataFrame({'id': ['a', 'a', 'a', 'b', 'b', 'b'], 'x': [4, 8, 12, 25, 30, 50]})

def my_func(data):
    data['diff'] = (data['x'] - data['x'].shift(1, fill_value=data['x'].iat[0]))
    return data

dat.groupby('id').apply(my_func)

Output

id  x   diff
0   a   4   0
1   a   8   4
2   a   12  4
3   b   25  0
4   b   30  5
5   b   50  20

Is there a more efficient way to do this?


texts: Getting cars and bicycles from a database and writing them into two different arrays

texts:
I've written a simple class which should:

get 10 top cars and 10 top bicycles from database
write them into 2 different arrays

It works, but I'm trying to find a simpler or clearer solution.

class TopVehicles extends Connection {
    private $sql1 = 'SELECT model, price FROM vehicles WHERE type = \'car\' ORDER BY price DESC limit 10';
    private $sql2 = 'SELECT model, price FROM vehicles WHERE type = \'bicycle\' ORDER BY price DESC limit 10';

    function __construct() {
        parent::__construct();
    }

    public function getTopCars() {
        $stmt = $this->mysqli->prepare($this->sql1);
        $stmt->execute();
        $stmt->store_result();
        $row_cnt = $stmt->num_rows;
        $stmt->bind_result($model, $price);

        while ( $stmt->fetch() ) {
            $_result[] =
            array(
                'Model' => $model,
                'Price' => $price
                );
        }

        $stmt->free_result();
        $stmt->close();
        return $_result;
    }

    public function getTopBicycles() {
        $stmt = $this->mysqli->prepare($this->sql2); /*this is the only line which differs these 2 functions!*/
        $stmt->execute();
        $stmt->store_result();
        $row_cnt = $stmt->num_rows;
        $stmt->bind_result($model, $price);

        while ( $stmt->fetch() ) {
            $_result[] =
            array(
                'Model' => $model,
                'Price' => $price
                );
        }

        $stmt->free_result();
        $stmt->close();
        return $_result;
    }

    function __destruct() {
        parent::__destruct();
    }
}

$obj = new TopProducts();
$_TopCars = $obj->getTopCars();
$_TopVehicles = $obj->getTopBicycles();

It works as expected, but it's messy.

Is it possible to somehow rearrange these 2 methods?

getTopBicycles()
getTopCars()

To stick to the rule: DRY? I've tried to divide them, but I am not able to write proper code. Can you please give me a hint on what I should do?


texts: Laravel Single Page Application Using Angular Js

texts:
I have created a Laravel Single Page Application using Angular Js 1.3.14 by learning tutorials in the websites.

index.php:

         Company Name

Home

About Us

web.php:

Route::get('/', function () {
   return view('welcome');
});
Route::get('/home', function () {
   return view('home');
});
Route::get('/aboutus', function () {
    return view('aboutus');
});
Route::get('getusers', 'UserController@users');

UserController.php:

class UserController extends Controller
{
    public function users(Request $request)
    {
        $users = DB::table('users')->get();
        return response()->json($users);
    }
}

aboutus.blade.php:

      Id
      Name
      Email
      Created At

      @{{ data.id }}
      @{{ data.name }}
      @{{ data.email }}
      @{{ data.created_at }}

controller.js:

 var mainApp = angular.module("mainApp", ['ngRoute']);
 mainApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.

    when('/home', {
       templateUrl: '/home',
    }).

    when('/aboutus', {
       templateUrl: '/aboutus',
       controller: 'AddStudentController'
    }).

    when('/services', {
       templateUrl: '/services',
    }).
 }]);

  mainApp.controller('AddStudentController', function($scope, $http) {
    $http.get('getusers').then( function(response) {
      $scope.datas = response.data;
    });
  });

The SPA which i have created working correctly, i have developed this project of my own. Is there any thing i want to change or any mistake in routing or any thing in this project.


texts:
I've recently begun learning Scala, and while I've run into its concepts before (immutability, tuples, first-class functions) I'm not sure whether I'm using the language how it's supposed to be used. My learning project is going to be a simple little dungeon crawler, and while you can see the code on GitHub, I'm copying a simplified version here below.

Example output looks like this, where ?s are potential rooms and #s are actual rooms:

     ?
 ??  #  ?
?## ### #
  ### ####?
  ?? ## #
      ##
      #
    ?##?
     ??

And here's how it's implemented:

class LevelBuilder(random: Random) {

  /** Mapping of positions to the rooms at them. */
  var rooms: mutable.Map[(Int, Int), Room] = mutable.Map()

  /** List of areas where rooms could be generated. */
  var possibilities: Seq[(Int, Int)] = List()

  /**
   * Adds a new room to the map at the given position, and adds the available
   * positions around it to the possibilities list.
   */
  def addRoom(position: (Int, Int), room: Room): LevelBuilder = {
    rooms += position -> room

    // First, remove the room from the list of possibilities.
    possibilities = possibilities.filter(pos => pos != position).++(around(position))

    // Next, add the positions around that one to the list...
    possibilities = possibilities ++ around(position)

    // ...but then remove all of the ones around *those*, so no two paths will ever link up.
    possibilities = possibilities.filter(pos => roomPossibility(around(pos).count(p => rooms.contains(p))) && !rooms.contains(pos))

    this
  }

  /**
   * Determine whether a room should be build based on its number of neighbours.
   */
  private def roomPossibility(neighboursCount: Int): Boolean = {
    neighboursCount <= 1
  }

  /** Adds the given number of rooms to the level. */
  def addRooms(number: Int): LevelBuilder = {
    for (i <- 0 to number) {
      var index = random.nextInt(possibilities.length)        // Pick a random room from the possibilites list...
      addRoom(possibilities(index), Room.randomRoom(random))  // ...and add it
    }

    this
  }

  /** Return the four positions around the given one. */
  def around(position: (Int, Int)): Seq[(Int, Int)] = {
    List(
      (position._1 + 1, position._2),
      (position._1 - 1, position._2),
      (position._1, position._2 - 1),
      (position._1, position._2 + 1)
    )
  }

  /** Return a build layout of this level. */
  def build(): mutable.Map[(Int, Int), Room] = rooms.clone()

  /**
   * Print out a grid view of the level so far, showing both possibilities and
   * created rooms.
   */
  def debug() {
    val miny: Int = rooms.minBy(_._1._2)._1._2 min possibilities.minBy(_._2)._2  // there's got to be a better way to write this
    val maxy: Int = rooms.maxBy(_._1._2)._1._2 max possibilities.maxBy(_._2)._2
    val minx: Int = rooms.minBy(_._1._1)._1._1 min possibilities.minBy(_._1)._1
    val maxx: Int = rooms.maxBy(_._1._1)._1._1 max possibilities.maxBy(_._1)._1

    for (j <- miny to maxy) {
      for (i <- minx to maxx) {
        if (possibilities.contains((i, j))) {
          print("?")
        }
        else if (rooms.contains((i, j))) {
          print("#")
        }
        else {
          print(" ")
        }
      }
      println("")
    }
  }
}

So what do you all think? I've only been using Scala for a few days, so I'm interested to learn things like whether I should prefer using operators to methods, or whether there's a certain style of variable names I should be using, or anything like that.


texts:
I recently wrote a simple Brainfuck interpreter in Ruby:

require "io/console"

$VALID = "+-<>.,"

def parse(code, level=0)
    ast = []
    while !code.empty? do
        c = code.shift
        if c == "]" then
            if level == 0 then
                throw Exception.new "Unmatched brackets"
            else
                return ast
            end
        end
        if c == "[" then
            ast.push parse(code, level+1)
        elsif $VALID.include? c then
            ast.push c
        end
    end
    if level != 0 then
        throw Exception.new "Unmatched brackets"
    end
    ast
end

class BF
    def initialize
        @tape = Array.new 3e4, 0
        @ptr = 3e4.to_i / 2
    end

    def run(ast)
        ast.each {|e|
            if e.kind_of? Array then
                while @tape[@ptr] != 0 do
                    self.run e
                end
            else
                case e
                when "+"
                    @tape[@ptr] += 1
                when "-"
                    @tape[@ptr] -= 1
                when ">"
                    @ptr += 1
                when "<"
                    @ptr -= 1
                when "."
                    STDOUT.write @tape[@ptr].chr
                when ","
                    @tape[@ptr] = STDIN.getch.ord
                end
                @tape[@ptr] &= 0xFF
            end
        }
    end
end

if ARGV[0] == nil then
    puts "Simple BrainFuck interpreter"
    puts "Usage: #{$0} <file>"
    exit 1
end
bf = BF.new
bf.run parse(File.read(ARGV[0]).chars)

I am pretty bad at Ruby, can someone review this?


texts:
I am currently studying c programming, but I'm at a very basic level. So for practice I made a program that reads a string and inverts it. I want to know if the code is readable and how I can improve it.

/*
* Goal: Given a string, invert it, then print the result.
* Author: Lúcio Cardoso
*/

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

/*This is the size of the arrays in this program. It's better to use a
constant, because makes easier to modify the arrays' size, if needed.*/
#define NUM 200

void invert(char *s) //Fucntion responsible for inverting the string.
{
    char aux[NUM];
    int i, j, n; //These variables are all used to control the for loops.

    /*This loop will read the size of the array's string, that's why
    strlen(s) - 1 is used. We don't need to read all contents
    from the array, just the string. As we read the s[] backwards,
    its content is stored in aux[n]. In this case, from zero to the
    size of s[]'s string - 1. Minus 1 is used because we read it from ZERO,
    not i. */
    for (i = strlen(s) - 1, n = 0; n < strlen(s), i >= 0; i--, n++) {
        aux[n] = s[i];
    }

    printf("Included with the super mojo from the string inverter, ");
    printf("this is the result: ");

    //This for loop reads all the content from the aux array, and print it.
    for (j = 0; j < strlen(s); j++) {
        printf("%c", aux[j]);
    }
}

int main(void)
{
    char string[NUM];

    printf("\nWelcome to the super, duper string inverter!\n");
    printf("If you want to see some magic, enter a string:\n>");
    gets(string); //Reads the string.

    //Now, we only need to call the function with string[] as a parameter.
    invert(string);

    return 0;
}


texts:
I am making a Trello clone just for personal project and I wonder if my implementation on mutating the state is good.

My state is basically shaped like this:

boards: [
    {
        id: Number,
        title: String,
        tasks: Array,
        columns: Array,
        columnOrder: Array
    }
]

I want to mutate the state to add the new task to the tasks array given that the payload of the reducer has boardId, columnId, task.

My current implementation of adding a new object to an array:

switch (action.type) {
    case ADD_TASK: {
      console.log(state)
      let newBoard = state.boards.find(
        board => board.id === action.payload.boardId
      )

      let column = newBoard.columns.find(
        column => column.id === action.payload.columnId
      )
      column.tasks = [...column.tasks, action.payload.task]

      newBoard.columns = [...newBoard.columns, column]

      const addToBoard = state.boards.map(board => {
        if (board.id === action.payload.boardId) {
          board = newBoard
        }
        return board
      })

      const newState = {
        boards: addToBoard
      }
      console.log(newState)
      return newState
     //code omitted
 }

Is there a better way to mutate the state rather than my current implementation?


texts: Project Euler #10 and #12 in Java - Prime Numbers

texts:
I am dealing with a huge time taking with primes. I hope you know they are pretty random and that's why create many problem. Both are using the same logic/methods.

/*
 * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all
 * the primes below two million.
 * http://projecteuler.net/problem=10
 */

public static long get10() {
    long sum = 0;// 2 is also a prime
    for (int i = 2; i < 2000000; i++) {
        if (isPrime(i)) {
            sum += i;
        }
    }
    return sum;
}
/*
 * The sequence of triangle numbers is generated by adding the natural
 * numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 =
 * 28. The first ten terms would be:
 *
 * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
 *
 * Let us list the factors of the first seven triangle numbers:
 *
 * 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28:
 * 1,2,4,7,14,28 We can see that 28 is the first triangle number to have
 * over five divisors.
 *
 * What is the value of the first triangle number to have over five hundred
 * divisors?
 * http://projecteuler.net/problem=12
 */
public static long get12() {
    for (int i = 1;; i++) {
        long n_t = Sumk(i);
        int d = getDivisorCount(n_t);
        if (d >= 500) {
            return n_t;
        }
    }
}
public static long Sumk(int n) {
    // Sum of k from 1 to n =n*(n+1)/2 [Also n'th triangular number]
    return n * (n + 1) / 2;
}
public static boolean isPrime(int n) {
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

public static int getDivisorCount(long n) {
    int d = 1;
    for (int i = 2; i <= n;) {
        if (isPrime(i)) {
            int d2 = 0;
            while (n % i == 0) {
                ++d2;
                n /= i;
            }
            d *= (d2 + 1);
        }
        if (i == 2) {
            ++i;
        } else {
            i += 2;
        }
    }
    return d;
}

Currently the output is:

10

  Time taken 4.160109858 seconds

12

  Time taken 6.856344169 seconds


texts:
Here I am doing some exercises for my studies with Python. This is a binary to decimal number converter (currently restricted to that).

These are the very first steps, so there is no error handling. You can even input non-binary numbers and get a result. However it works for converting binary numbers, which is its task.

I'm not sure about all shenanigans going around with the main function and the argument parsing.

import argparse
import sys

###############################################################################

def main(binary_number):
    binary_number = list(binary_number)
    decimal_number = 0

    for digit in range(0, len(binary_number)):
        if binary_number[digit] != '0':
            decimal_number += power_to_the_people(2, len(binary_number)-digit-1)

    print(decimal_number)

###############################################################################

def power_to_the_people(base, exponent):
    # Return 1 if exponent is 0
    if exponent == 0:
        return 1

    power = base
    for j in range(1, exponent):
        power *= base

    return power # to the people

###############################################################################

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Converts a binary to a decimal number.')

    parser.add_argument('binary_number', action="store")

    args = parser.parse_args()

    main(args.binary_number)

(Update: Added parentheses to print so it actually works under 3.4)


texts: Converting the weight of a potato into a letter grade

texts:
I've just started learning C# using Rob Miles' C# Programming Yellow Book and some related lab exercises from his website. I did one of them and produced a solution that works. In Miles' book, he says that nesting if and else brackets is clumsy and introduces the switch. But switch apparently doesn't work with Boolean operators, e.g. case x < 201, so I can't use it. I could just have independent, non-nested if statements, though their conditions would have to be longer. Any other ideas?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static int GetIntNumber(int min, int max, string prompt, string inputPrompt)
    {
        int number;

        Console.Write(prompt);
        do  //loops as long as input is not between min and max
        {
            while (!int.TryParse(Console.ReadLine(), out number)) //loops as long as the input is not an integer
            {
                Console.Write("\nYou must enter an integer number!: ");
            }
            if (number < min || number > max) Console.Write(inputPrompt); //<--| write input prompt if number out of range
        } while (number < min || number > max);

        return number;
    }

    static void printGrade(string grade)
    {
        Console.WriteLine("\nYour potato is grade " + grade);
    }

    static void Main()
    {

        do
        {
            int weight = GetIntNumber(0, 1500, "\nEnter the weight of the potato in grams: ", "\nEnter an integer between 0 and 1500: ");

            if (weight < 201)
            {
                printGrade("X");
            }
            else
            {
                if (weight < 401)
                {
                    printGrade("A");
                }
                else
                {
                    if (weight < 801)
                    {
                        printGrade("B");
                    }
                    else
                        printGrade("Z");
                }
            }
            Console.WriteLine("\nPress any key to check the grade of another potato.");
        } while (Console.ReadKey(true).Key != ConsoleKey.Escape );

        Console.Read();

    }
}


texts: Proper and elegant way of Building a XML Document

texts:
I need to build the following XML document

<?xml version="1.0"?>
<SFDocument>
    <TableID>5415</TableID>
    <PageSize>1</PageSize>
    <PageIndex>1</PageIndex>
    <MultiCompany>No</MultiCompany>
    <Language>1033</Language>
    <Fields>
        <Field>Operation No.</Field>
        <Field>Line No.</Field>
        <Field>Date</Field>
        <Field>Comment</Field>
    </Fields>
    <TableFilters>
        <TableFilter>
            <Field>Status</Field>
            <Filter>3</Filter>
        </TableFilter>
        <TableFilter>
            <Field>Prod. Order No.</Field>
            <Filter>101006</Filter>
        </TableFilter>
    </TableFilters>
    <Key>
        <Field>Routing Reference No</Field>
        <Field>10000</Field>
    </Key>
</SFDocument>

using the following code, it works but is it the proper way of doing it.

internal class Field
{
    public string Name { get; set; }
    public  const string FieldName = "Field";
}
internal class Key
{
    public string Field { get; set; }
    public  const string FieldName = "Field";
}

internal class TableFilter
{
    public string Field { get; set; }
    public string Filter { get; set; }
    public const string FieldName = "Field";
    public const string FilterName = "FilterName";
}

void Main()
{
    //this part is just for the example, obviously, this would be passed as parameter
    var tableId = 5415;
    var pageSize = 1;
    var pageIndex = 1;
    var multiCompany = "No";
    var language = 1033;

    var fields = new List<Field>();
    fields.Add(new Field() {Name = "Operation No."});
    fields.Add(new Field() {Name = "Line No."});
    fields.Add(new Field() {Name = "Date"});
    fields.Add(new Field() {Name = "Comment"});

    var tableFilters = new List<TableFilter>();
    tableFilters.Add(new TableFilter() {Field = "Status", Filter = "3"});
    tableFilters.Add(new TableFilter() {Field = "Prod. Order No.", Filter = "101006"});

    var keys = new List<Key>();
    keys.Add(new Key() {Field = "Routing Reference No"});
    keys.Add(new Key() {Field = "10000"});

    //End of setup

    XDocument doc = new XDocument(new XElement("SFDocument",
                                      new XElement("TableId", tableId),
                                      new XElement("PageSize", pageSize),
                                      new XElement("PageIndex", pageIndex),
                                      new XElement("MultiCompany", multiCompany),
                                      new XElement("Language", language),
                                      new XElement("Fields"),
                                        new XElement("TableFilters"),
                                        new XElement("Key")
                                        )
    );

    var xFields = doc.Element("SFDocument").Element("Fields");

    foreach (Field field in fields)
    {
        xFields.Add(new XElement(Field.FieldName, field.Name));
    }

    var xTableFilters = doc.Element("SFDocument").Element("TableFilters");

    foreach (TableFilter tableFilter in tableFilters)
    {
        var tf = new XElement("TableFilter");
        tf.Add(new XElement(TableFilter.FieldName, tableFilter.Field));
        tf.Add(new XElement(TableFilter.FilterName, tableFilter.Filter  ));
        xTableFilters.Add(tf);
    }

    var xKey = doc.Element("SFDocument").Element("Key");

    foreach (Key key in keys)
    {
        xKey.Add(new XElement(Key.FieldName, key.Field));
    }
    doc.Dump();  //Using LinqPad
}


texts: Am I using Angular directives correctly?

texts:
I'm coming from Backbone and trying to wrap my head around Angular for a new project and would like to get some feedback on whether I'm using it correctly or not.

Plunker

What I'm trying to accomplish is this: I have a list of items that can be very easily rendered with an ngRepeat. Each item starts off in an inactive state. When a user selects one of the items it enters into an expanded active state that shows some extra details and controls for working with the currently selected item. The markup for these two states is different enough that adding & removing some CSS classes won't cut it, so I have separate templates for each state.

The approach I've taken is encapsulating this functionality into a directive that can render the two templates. When the item is initially rendered the inactive template is used. When an item is selected (in the example, by checking a checkbox) then the active template is compiled and the resulting markup put into the element's HTML. When the checkbox is unchecked the same happens for the inactive template.

The ngShow/ngHide directives won't work for me in this case because there could potentially be lots of these things on the page and my understanding is that ngShow/ngHide will render the markup for both states and then show/hide based on some model property. Ultimately only one item will be active at any given time so rendering all that markup for each item only to display one at a time seems wasteful. I also wanted more control over the transition between the inactive & active states.

Is this solution something that would be considered idiomatic Angular or an egregious abuse of directives? Am I exposing myself to any bugs?

The directive:

module.directive("myDirective", ['$compile', '$http', '$templateCache', function($compile, $http, $templateCache) {

  function getTemplate(isActive) {
    var templateLoader,
        baseUrl = 'templates/',
        templateMap = {
          active: 'checked.html',
          inactive: 'unchecked.html'
        },
        templateUrl = baseUrl + templateMap[isActive ? 'active' : 'inactive'];

    return $http.get(templateUrl, { cache: $templateCache });
  }

  function render(scope, element) {
    getTemplate(scope.isActive)
      .success(function(html) {
        element.hide().html(html);
      })
      .then(function(response) {
        element.html($compile(element.html())(scope)).fadeIn();
      });
  }

  function linker(scope, element, attrs) {
    render(scope, element);

    scope.onSelected = function() {
      render(scope, element);
    };
  }

  function controller($scope) {
    $scope.isActive = false;
  }

  return {
    restrict: 'A',
    scope: {
      item: '='
    },
    controller: controller,
    link: linker
  };

}]);

The active template:

{{item.description}}

{{item.details}}

  <input type="checkbox" ng-model="isActive" ng-change="onSelected()">

The inactive template:

  <input type="checkbox" ng-model="isActive" ng-change="onSelected()"> {{item.description}}

And the view:


texts: Fetch records that do not get matched in another table

texts:
I'm trying to fetch records from table PaymentToken if its AccountNumber matched but AccountToken wasn't:

select DISTINCT DTR_PT.Id, DTR_PT.AccountNumber, DTR_PT.CardNumber, DTR_PT.ExpirationDate, DTR_PT.CardHolderName, DTR_PT.AccountToken, DTR_PT.CreatedDate, DTR_PT.Active
from Dev_NeoGateway_DTR.dbo.PaymentToken as DTR_PT
JOIN Dev_NeoGateway_DTA.dbo.DTA_Customer as DTA_C on DTA_C.Id = DTR_PT.AccountNumber
WHERE DTR_PT.AccountToken NOT IN (select DTA_PI.CardToken FROM  Dev_NeoGateway_DTA.dbo.DTA_PaymentInstrument as DTA_PI )

Because of the WHERE clause, this query takes a lot of time as it queries all the table again and again.


texts:
Consider the following function to traverse a BST

(defun bst-traverse (fn bst)          ; [1]
  (when bst
    (bst-traverse fn (node-l bst))
    (funcall fn (node-elt bst))       ; [2]
    (bst-traverse fn (node-r bst))))

;; [1] This is a higher order function - recieves a function which it calls on each node.
;; [2] The traverse which makes sense on a bst is the in-order traverse
;;     (i.e. left first, then node, then right, which this is.)

What are some nice uses of this function?

1) Cause a side effect at each node

(bst-traverse #'princ bst)

2) Cons each elt to a global var (also a side effect)

The idea here is this is a good way to get the BST els in descending order.

(defparameter *result* nil)
(bst-traverse (lambda (obj)
               (setf *result* (cons obj *result*)))
             nums)

This leads me to wondering...

Is this higher order function any use at all without relying on a side-effect?

It seems maybe not. Why? - because it doesn't return anything always returns nil.

So, could we or should we make it return something to solve this 'problem'?

The general question I'm seeking to explore here is the purity or non-purity of higher order functions in practical use cases (and hence, how to use them well).

Any discussion/contributions appreciated.

For the record, I started off with this

(defun in-order-traverse (bst)
  (when bst
    (in-order-traverse (node-l bst))
    (format t "~A" (node-elt bst))
    (in-order-traverse (node-r bst))))

Then, when I wanted to get the BST els in reverse order, realised how completely un-reusable that function is in comparison to bst-traverse above. So, I'd like to get a better understanding of what the real flexibility of bst-traverse actually is and how to use it...

[I've realised - the function passed could return something - but how would the higher order function pick which invocation of the lambda to return the return value of if any?!]

Update

Wondering if this would be along the right lines at all

(defun bst-accumulate (fn bst)
  (let (result)
    (when bst
      (bst-accumulate fn (node-l bst))
      (cons (funcall fn (node-elt bst)) result)
      (bst-accumulate fn (node-r bst)))
  result))

Update 2

bst-accumulate above is wrong. This is not the first time I've fallen into the trap of thinking that consing was setting state - actually the return value of the expression above which does the cons is just lost...
To achieve what I wanted to achieve above, I must firstly wrap the cons in a setf so that result is actually modified. Plus there's a second problem; since bst-accumulate is recursive, it will end up redefining result on every call. To fix that, we need a helper function so that we keep the lexical var result outside of the recursive function, thusly: (this time  I tested it before posting :)

(defun bst-accumulate (fn bst)
  (let (result)
    (labels ((bst-acc (fn2 bst2)
                      (when bst2
                        (bst-acc fn2 (node-l bst2))
                        (setf result (cons (funcall fn2 (node-elt bst2)) result))
                        (bst-acc fn2 (node-r bst2)))))
            (bst-acc fn bst)
            result)))


texts: Python implementation of Conway's Game of life with Pygame

texts:
So I've started learning programming a few months ago and this is one of my first projects. The program works, but I feel like it's a bit slow compared to the other implementations of Conway's Game of life. Is there any ways I could speed up my code ?

import numpy
import copy
import pygame
from pygame.locals import *
import random

pygame.init()

height = 400
width = 400
block_size = 4
window = pygame.display.set_mode((height,width),DOUBLEBUF)
window.set_alpha(None)
alive = (255,255,255)
dead = (0,0,0)

def check(y_axis,x_axis,grid):
    tmp_grid = copy.copy(grid)
    for y in range(1,y_axis-1):
        for x in range(1,x_axis-1):
            a = 0
            for i in range(-1,2):
                for j in range(-1,2):
                    if grid[y+i][x+j] == 1:
                        a += 1
            if grid[y][x] == 1:
                a -= 1
                if a < 2 or a > 3:
                    tmp_grid[y][x] = 0
            elif grid[y][x] == 0:
                if a == 3:
                    tmp_grid[y][x] = 1
    grid = tmp_grid
    return grid

def display(y_axis,x_axis,grid):
    rects = []
    for y in range(1,y_axis-1):
        for x in range(1,x_axis-1):
            rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
            if grid[x][y] == 1:
                rects.append(pygame.draw.rect(window,alive,rect))
            elif grid[x][y] == 0:
                rects.append(pygame.draw.rect(window,dead,rect))
    pygame.display.update(rects)

def generate(y_axis,x_axis,grid):
    for y in range(1,y_axis-1):
        for x in range(1,x_axis-1):
            alive_or_dead = random.randint(0,1)
            if alive_or_dead:
                grid[y][x] = 1
            else:
                grid[y][x] = 0

def main():
    y_axis = height//block_size
    x_axis = width//block_size
    grid = numpy.zeros((y_axis,x_axis))
    generate(y_axis,x_axis,grid)
    while True:
        display(y_axis,x_axis,grid)
        grid = check(y_axis,x_axis,grid)

if __name__ == '__main__':
    main()