texts:
I'm studying JavaScript and jQuery and I did an implementation of a simple cat clicker game:

class Cat {
  constructor(name, picture) {
    let self = this;

    self.name = name;
    self.picture = picture;
    self.count = 0;

    let mainDiv = $('#cats');
    let catDiv = $('

');

    mainDiv.append(catDiv);

    self.img = $(`<img src="${self.picture}">`);
    catDiv.append(self.img);

    self.counter = $('

');
    catDiv.append(self.counter);

    self.img.click(function() {
      self.count++;
      self.counter.text(`You clicked ${self.name} ${self.count} times.`);
      self.counter.css("font-size", "+=0.5");
    });
  }
}

$(document).ready(function() {
  new Cat('Kimmy', 'http://newmediarockstars.com/wp-content/uploads/2014/07/femcat.png');
  new Cat('Logan', 'http://svoctopussy.com/wp-content/uploads/2013/02/Grumpy-Cat.jpg');
});

Cat Clicker

I wanted it to be dynamic, so if I want to add more cats, I just have to instance a new object of the Cat class, like it's done in the document.ready function.

The Cat constructor adds a new cat in the HTML (it appends the cats div), using div, h1, img and p. Everytime you click the img (), the p element text is updated with the click count.

I'm a complete beginner in JS. What can I refactor here to make the code more legible and idiomatic?

EDIT: In the third line, there's a let self = this;. I did that because I needed to access the Cat instance inside the img.click callback function. I don't know if that's how it's done nor how I can improve that.


texts: Best Algorithm for solving USACO: Photoshoot - Python

texts:
I was trying to solve this problem with Python 3.8. I couldn't find a way other than to brute-force calculate all the possible permutations then check which permutation was valid. The program works fine, but as it's O(n!) time complexity (I think) it takes extraordinarily long when the input has a length of, say, 1000.
My code:
from itertools import permutations as permute

fin = open("photo.in", "r")
fout = open("photo.out", "w+")

useless, line = fin.readlines()

nums = [int(i) for i in line.split(" ")]

def main(nums):
    foo = [i+1 for i in range(len(nums)+1)]
    bar = permute(foo)

    for permutation in bar:
      boo = False
      for i in range(1, len(permutation)):
          if permutation[i]+permutation[i-1] != nums[i-1]:
              boo = False
              break
          else:
            boo = True

      if boo:
          return permutation

final = " ".join([str(i) for i in main(nums)])
fout.write(final)

fin.close()
fout.close()

I'm not sure how to optimize this code. Should I create my own permutation generator function and then check along the way instead of getting the whole thing at once? Or is there an algorithm that I'm not seeing?
A short problem description:
Given a list N of length n integers, find a permutation of the numbers 1 through n+1 in which every element of the permutation plus the next one is equal to the corresponding number of N.
Edit: The generator approach did not work.


texts: Normalizing an apartment rental database

texts:
We are to normalize a database, though it is mostly all theoretical, we aren't actually plugging in the SQL. This is the Data we have normalized to these tables..

and here is our SQL for normalizing it. I'd just like to know if anyone spots any glaring issues.

insert into bldg_table (bldg)
Select distinct bldg from apartmentmaster order by bldg;

----------------------------------------------------------

insert into id_rec (id, firstName, lastName)
Select id, tenantfirstname, tenantlastname from apartmentmaster where apt not in (603, 602);

----------------------------------------------------------

insert into apt_bldg_table(aptNumber, baseRent, bldg)
select apartmentmaster.apt, apartmentmaster.baseRent, apartmentmaster.bldg
from apartmentmaster;

---------------------------------------------------------

insert into tenant_apt_table (id, aptbldg, begdate, baseRent)
select apartmentmaster.id, aptbldg_table.rec_no, "2015-01-01", aptbldg_table.baseRent
from apartmentmaster
join apt_table
on apartmentmaster.apt = aptbldg_table.aptNumber and
apartmentmaster.bldg = aptbldg_table.bldg;

----------------------------------------------------------

insert into rent_rec (tenant_apt_id, paid_date, paid_amt)
select
    tenant_apt_table.rec_no, apartmentmaster.janPaid, apartmentmaster.janRent
from apartmentmaster
join apt_bldg_table
on apartmentmaster.Apt = apt_bldg_table.aptNumber and apartmentmaster.Bldg = apt_bldg_table.bldg
join
    tenant_apt_table
on tenant_apt_table.aptBldg = apt_bldg_table.rec_no

/*and we repeat this query five more times for February, March, etc.*
----------------------------------------------------------


texts: Automatically growing label in Python Tkinter (just for fun)

texts:
#!/usr/bin/env python3

from tkinter import *

root = Tk()

class GrowLabel(Label):
    def __init__(self, master):
        Label.__init__(self, master)
        self.counter = 12
        self.config(text=str(self.counter), fg="blue", font=("verdana", self.counter, "bold"))
        self.pack()
        button = Button(self.master, text="Stop", command=self.master.destroy)
        button.pack()

    def count(self):
        self.counter += 1
        self.config(text=str(self.counter), fg="blue", font=("verdana", self.counter, "bold"))
        self.after(1000, self.count)

label = GrowLabel(root)
label.count()

root.mainloop()


texts: Using a class to create a custom wrapper for including files

texts:
I am using PHP in order to create a custom wrapper for including files, for this I have written this class:

<?php
class Refrences
{
    #region properties
    private $_basePath;
    #endregion

    #region public members
    public function __construct() { $this->_basePath = $this->cleanDirName(dirname(__FILE__)); }

    public function includeFile($f) { $this->ior(1, $f); }

    public function requireFile($f) { $this->ior(2, $f); }

    public function includeFileOnce($f) { $this->ior(3, $f); }

    public function requireFileOnce($f) { $this->ior(4, $f); }

    public function includeArray(array $files)
    {
        foreach ($files as $f) { $this->ior(1, $f); }
    }

    public function requireArray(array $files)
    {
        foreach ($files as $f) { $this->ior(2, $f); }
    }

    public function includeArrayOnce(array $files)
    {
        foreach ($files as $f) { $this->ior(3, $f); }
    }

    public function requireArrayOnce(array $files)
    {
        foreach ($files as $f) { $this->ior(4, $f); }
    }
    #endregion

    #region private members
    private function cleanDirName($f) { return rtrim(str_replace("\\", "/", dirname($f)), "/") . "/"; }

    private function fileExists($f) { return (!file_exists($f)) ? false : true; }

    private function isFile($f) { return (is_dir($f) || !is_file($f)) ? false: true; }

    private function ior($switch, $file)
    {
        switch ($switch)
        {
            case 1:
                if ($this->checkIsFile($file)) include ($file);
                else die("Cannot load file.");
                break;
            case 2:
                if ($this->checkIsFile($file)) require ($file);
                else die("Cannot load file.");
                break;
            case 3:
                if ($this->checkIsFile($file)) include_once ($file);
                else die("Cannot load file.");
                break;
            case 4:
                if ($this->checkIsFile($file)) require_once ($file);
                else die("Cannot load file.");
                break;
        }
    }

    private function checkIsFile($f) { return ($this->fileExists($f) && $this->isFile($f)) ? true : false; }
    #endregion
}

And all functionality etc. works, but is this a good thing to do? Does it allow me greater control over the files that are included? Is there a better way to do this?


texts:
I have the following code and I think it's almost impossible to read and to maintain. I prefer self-explaining and modular code where variable and function names tell what I'm trying to do, but I don't know how to change the part using Eval and inside an ascx.

I'm doing much research but I still cannot understand it completely well. The performance of this part is not critical, the readability is!

How can I refactor it and split into many variable assignments?

<tr class="GridRowE" visible='<%#((String.IsNullOrEmpty(Eval("IDLanguage").ToString()) OrElse Eval("IDLanguage").ToString().Replace(" ", "").Split(","c).Contains(WebProfile.Current.IDLanguage.ToString())) And (String.IsNullOrEmpty(Eval("Roles").ToString()) OrElse Roles.IsUserInRole(WebProfile.Current.UserName, Eval("Roles").ToString())))%>' runat="server">


texts: Generate JSON File from a given YAML file

texts:
I'm didn't use java for a long time(5 years ± ) and in the following code the  user should provide yaml file and it converting it to json file.

The code is working as expected but since I didn't use java for  a long time I want to see if I can write this code better and learn new things :-) in the latest java (currently with use of java8 not 9)

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicReference;

public class yaml2json {

    public static void main(String[] args) {

        //Get File Path
        String sourceFilePath = getSourceFilePath(args);

        //Load File content
        AtomicReference<String> content = new AtomicReference<String>();
        try {
            content.set(readYamlFile(sourceFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Json string
        String jsonStr = null;
        try {
            jsonStr = convertYamlToJson(content.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //Print json file
        sourceFilePath = sourceFilePath.substring(0, sourceFilePath.length() - 3);
        sourceFilePath = sourceFilePath + "json";

        try {
            FileWriter fileWriter = new FileWriter(sourceFilePath);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(jsonStr);
            bufferedWriter.close();
            System.out.println("Success " + sourceFilePath);
        } catch (IOException err) {
            System.out.println("Error writing to file: " + err );
        }

    }

     private static String readYamlFile(String pathname) throws IOException {

        File file = new File(pathname);
        StringBuilder fileContents = new StringBuilder((int)file.length());
        Scanner scanner = new Scanner(file);
        String lineSeparator = System.getProperty("line.separator");

        try {
            while(scanner.hasNextLine()) {
                fileContents.append(scanner.nextLine() + lineSeparator);
            }
            return fileContents.toString();
        } finally {
            scanner.close();
        }
    }

    private static String getSourceFilePath(String[] args) {
        String inFile;
        if (args.length != 0) {
            inFile   = args[0];
        }else {
            inFile = "/Users/rayn/IdeaProjects/myproj/a.yml";

        }
        return inFile;
    }

    private static String convertYamlToJson(String yaml) throws IOException {

        ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
        Object obj = yamlReader.readValue(yaml, Object.class);

        ObjectMapper jsonWriter = new ObjectMapper();
        return jsonWriter.writeValueAsString(obj);
    }

}


texts: Creating a Basic Success Function for Http

texts:
I got sick of every time I make an Http request validating that the response was a success. I did a lot of:

if response.class == Net::HTTPOK

or

if response.is_a? Net::HTTPSuccess

I wanted something a little prettier so I came up with the following. I don't write a lot of class extensions like this so I wanted some input.

require 'net/http'
class Net::HTTPResponse
  def success?
    return false if ! self.is_a? Net::HTTPSuccess
    return true
  end
end

Now once the file is included I can say:

if response.success?


texts: Send messages in TCP-based communication system

texts:
I am working on a TCP-based Communication System.

I wrote a working function for sending Textmessages and remotely opening a MessageBox. I would like to know how elegant this piece of code is and how I may improve it, cause it seems messy to me.

Client:

private void btnSend_Click(object sender, EventArgs e)
{
    NetworkStream stream = client.GetStream();

    BinaryWriter w = new BinaryWriter(stream);

        byte[] msg = new byte[4096];
        msg = Encoding.ASCII.GetBytes("%" + txtMsg.Text + "&");

        w.Write(msg, 0, msg.Length);

}

private void btnMsgBox_Click(object sender, EventArgs e)
{
    NetworkStream stream = client.GetStream();

    byte[] msg = new byte[4096];

    msg = Encoding.ASCII.GetBytes("%DisplayRemoteMessageBox&" + txtMsg.Text + "#");
    stream.Write(msg, 0, msg.Length);
}

Server:

while(true)
{
    while(client.Connected)
    {
        byte[] msg = new byte[4096];
        var count = stream.Read(msg, 0, msg.Length);

        string returnData = Encoding.ASCII.GetString(msg, 0, count);

        string command = returnData.Substring((returnData.IndexOf("%") + 1), (returnData.IndexOf("&") -1));

        switch(command)
        {
        case "DisplayRemoteMessageBox":
                returnData = returnData.Replace("%DisplayRemoteMessageBox", "");
                int startInd = returnData.IndexOf("&");
                int len = returnData.IndexOf("#");

                returnData = returnData.Substring((startInd + 1), (len - 1));
                MessageBox((IntPtr)0, returnData, "TestBox", 0);
                 break;
        case "":
                client.Client.Disconnect(true);
                Console.WriteLine("User disconnected");
                 break;
        default:
                returnData = returnData.Substring(1, (returnData.Length - 2));
                Console.WriteLine(returnData);
                 break;
        }
    }
}


texts:
Given a string s consisting of lowercase Latin Letters, find the
  first  non repeating character in s.

  Input:

  The first line contains T denoting the number of testcases. Then
  follows description of testcases. Each case begins with a single
  integer N denoting the length of string. The next line contains the
  string s.

  Output:

  For each testcase, print the first non repeating character present in
  string.    Print -1 if there is no non repeating character.

  Constraints:

1<=T<=50
1<=N<=100

  Example:

  Input :

3
5
 hello
12
zxvczbtxyzvy
6
xxyyzz

  Output :

h
c
-1

My approach:

/*package whatever //do not write package name here */

import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.*;

class GFG {
    private static int firstNonRepNum (String str, int size)
        {
            Hashtable <Character, Integer> count = new Hashtable<>();
            int occurs;

            for (char ch: str.toCharArray())
                {
                    if (!count.containsKey(ch))
                        {
                            count.put(ch,1);
                        }
                    else
                        {
                            occurs = count.get(ch);
                            count.put(ch, occurs+1);
                        }
                }

           for (char ch: str.toCharArray())
            {
                int val = count.get(ch);

                if (val == 1)
                    {
                        return ch;
                    }
            }

        return -1;
        }

    public static void main (String[] args) throws IOException{
        //code
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //String line = br.readLine();
        Scanner sc = new Scanner(System.in);

        int numTests = sc.nextInt();

        String line2;
        int size;
        String str;

        for (int i = 0; i < numTests; i++)
            {

                size = sc.nextInt();
                str = sc.next();
                if (firstNonRepNum(str,size) == -1)
                    {
                        System.out.println("-1");
                    }
                else
                    {
                        System.out.println((char)firstNonRepNum(str, size));
                    }

            }
    }
}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?

Reference


texts:
I need to create an structure to control dynamically locks. For example, I have 100 threads running, and each thread will "process" a "key". Sometimes two threads could be processing the same "key", and if it occurs, a dynamic lock needs to be created and used by both, to process one at a time.

I create the following structure and I would like a code review, to find possible bugs (even if it is extremely rare):

  // This is the class who control to create one different lock for each key.
    public class DynamicLockGenerator
{
    private static Dictionary<string, object> _locksByKeys = new Dictionary<string, object>();

    private static object _lock = new object();

    public static objectGetLock(string key)
    {
        lock (_lock)
        {
            if (!_locksByKeys.ContainsKey(key))
                _locksByKeys.Add(key, new object());

            return _locksByKeys[key];
        }
    }

    public static void RemoveLock(string key)
    {
        lock (_lock)
        {
            //This line is extremely important: One lock object can only be removed
            //if no thread are using it.
            if (Monitor.TryEnter(_locksByKeys[key]))
            {
                _locksByKeys.Remove(key);
            }
        }
    }
}

//This is the use of the class. All threads do the same thing, but with different (or equal) keys.
object lockObj = DynamicLockGenerator.GetLock(key);

lock (lockObj)
{
    //PROCESS THE KEY
}

DynamicLockGenerator.RemoveLock(key);


texts: Replacing DOM elements that have no attributes

texts:
The institution I work for uses an application that has an awful software bug causing useless span tags to appear next to "misspelled" words in iframes.

For instance, HTML that should look like this:

Hello! My name is Tabitha.

...might look like this instead:

Hello! My name is Tabitha.

My band-aid solution, while we wait for a fix from the application developer, has been to add a script that finds all attribute-less span tags and replaces them with a new textNode. This works because these extra tags are always the direct parent of the textNode containing the misspelled word (or another extra span element). Any formatting or inline styling would occur outside that scope and would thus be unaffected.

But, something tells me there's got to be a better way to do it. Any thoughts?

function fixSpan(iframe) {
    var doc = iframe.contentDocument;
    var spans = doc.getElementsByTagName('span'); //find all  elements
    for (var i = 0; i < spans.length; i++) {
        var span = spans[i];
        var tag = span.outerHTML.slice(0,6);
        if (tag === '') { //if the span has no attributes
            //replace it with a new textNode containing its textContent
            console.log('FOUND: ' + span.textContent + '');
            span.parentNode.replaceChild(document.createTextNode(span.textContent), span);
        }
    }

    if (doc.documentElement.innerHTML.includes('')) {
        //if any attribute-less tags remain, run the method again
        console.log('Fix not complete, re-running...');
        fixSpan(iframe);
    } else {
        console.log('Fix complete.');
    }
}


texts: htaccess with compression, caching, and rewrite rules for SEO

texts:
I have the following htaccess and I want it to be the perfect htaccess for my website so that it uses less bandwidth and meets the requirements of a good SEO.

I am on an apache server and my files are html, php, js(minified and normal), css, ttf fonts, images.

How can I improve this htaccess file?

RewriteBase /
RewriteEngine On

RewriteCond %{REQUEST_FILENAME}.php !-f
RewriteRule ^room/([A-Za-z0-9]+)$ playground.php?room=$1 [L]

RewriteCond %{REQUEST_FILENAME}.php !-f
RewriteRule ^join/([A-Za-z0-9]+)$ index.php?room=$1&action=join [L]

RewriteCond %{REQUEST_FILENAME}.php !-f
RewriteRule ^([\w-]+)$ $1.php [L]

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

#Cache-control
<IfModule mod_headers.c>
    <FilesMatch ".(jpg|jpeg|png|gif|ico)$">
       Header set Cache-Control "max-age=2628000, public"
    </FilesMatch>
    <FilesMatch ".(css|js)$">
       Header set Cache-Control "max-age=604800, public"
    </FilesMatch>
</IfModule>


texts: Printing a singly linked list in reverse order

texts:
I am preparing for interview and I want to write the function in the way that the interviewers will expect me to write.

private static void printReverse(ListNode l1){
        if(l1 != null){
            printReverse(l1.next);
            System.out.print(l1.val + " ");
        }
    }

However, this function does not do anything if l1 is null. Should I take care of this case? If yes, how?


texts: Return a key when a function returns true

texts:
I've no idea what to call this, so I called it Classify since that's how I use it.

Basically, the idea is to pass a Dictionary<TResult, Func<TValue, bool>> which is evaluated for an input, and the first Func<TValue, bool> returning true will return the TResult key.

The intention is to make this a generic extension method.

public TResult Classify<TValue, TResult>(TValue input, Dictionary<TResult, Func<TValue, bool>> classifications)
{
    foreach (var classification in classifications)
    {
        if (classification.Value.Invoke(input))
        {
            return classification.Key;
        }
    }

    return default(TResult);
}

Pretty simple, but pretty useful (for me at least) as well.

Usage:

<td class='<%#Classify(((ApiBatchLog)Container.DataItem).RequestsPerSecond, new Dictionary<string, Func<double, bool>> { ["good"] = x => x >= 3, ["neutral"] = x => x > 2, ["bad"] = x => true }) %>'>
    <%#((ApiBatchLog)Container.DataItem).RequestsPerSecond.ToString("0.00") %>
</td>


texts: Optimising multiplication of matrix rows with matrix slice/page

texts:
I've recently vectorized most of the code for an optimization problem but this one still eludes me. As the procedure and not the actual values are important here, I have replaced the original matrices with random dummies.

Problem:
Given a matrix A of shape (m x n) and a three dimensional matrix B of shape (n x (n-1)*r x m) multiply the i-th row of A with the i-th slice/page of B
for i=1,...,m . This yields a matrix of shape m x (n-1)*r.
Note that I have arranged the m two dimensional matrices in a three dimensional matrix B, which is not necessarily a given. B can as well be modeled as a block matrix or other applicable shapes.

Criterion:
As this code is evaluated very often as part of the optimization, it is crucial that it is as fast as possible. Memorywise it does not need to be optimal, but it should remain within feasible limits, as m=6000, n=6 and r=2 are rather the lower end of the expected dimension of the problem.

What I have tried:

The code below is the first solution that came to my mind and the one that so far has proven the fastest. I have tried replacing the for-loop by using cellfun, but this has not proven to be faster.
Trying to approach this in a vectorized fashion, I also tried structuring B instead of a 3D matrix as a 2D, horizontal block matrix B* with the 'slices' of B simply appended as columns. Then matrix multiplication can then be used to obtain a (m x (n-1)*r*m) matrix where the solution is found on the diagonal + some offset. However, this is of course horribly inefficient, as most of the result matrix isn't required and such a matrix becomes intractable from a memory perspective pretty quickly.

rng(1)
m = 6000;
n = 6;
r = 2;
A = rand(m,n);
B = rand(n,(n-1)*r,m);
result = zeros(m,(n-1)*r);
for i=1:m
    result(i,:) = A(i,:) * B(:,:,i);
end


texts:
I've been messing with metaprogramming and variadic templates in C++, and I came up with this very primitive implementation of a tuple:

constexpr bool GreaterThanZero(int N)
{
    return N > 0;
}

template <int, typename...>
struct Helper;

template <int N, typename Head, typename... Tail>
struct Helper<N, Head, Tail...>
{
    typedef typename Helper<N-1, Tail...>::type type;
};

template <typename Head, typename... Tail>
struct Helper<0, Head, Tail...>
{
    typedef Head& type;
};

template <int, typename...>
class TupleImpl;

template <>
class TupleImpl<-1>
{

};

template <typename Head>
class TupleImpl<0, Head>
{
protected:
    Head head;

public:
    template <int Depth>
    Head& get()
    {
        static_assert(Depth == 0, "Requested member deeper than Tuple");
        return head;
    }

    template <int Depth>
    const Head& get() const
    {
        static_assert(Depth == 0, "Requested member deeper than Tuple");
        return head;
    }
};

template <int N, typename Head, typename... Tail>
class TupleImpl<N, Head, Tail...>
{
protected:
    Head head;
    TupleImpl<N-1, Tail...> tail;

public:
    template <int M>
    typename std::enable_if<M == 0, Head&>::type get()
    {
        return head;
    }

    template <int M>
    typename std::enable_if<GreaterThanZero(M), typename Helper<M, Head, Tail...>::type>::type get()
    {
        return tail.get<M-1>();
    }

    template <int M>
    typename std::enable_if<M == 0, const Head&>::type get() const
    {
        return head;
    }

    template <int M>
    typename std::enable_if<GreaterThanZero(M), typename Helper<M, Head, Tail...>::type>::type get() const
    {
        return tail.get<M-1>();
    }
};

template <typename... Elements>
class Tuple : public TupleImpl<sizeof...(Elements)-1, Elements...>
{
public:
    static constexpr std::size_t size()
    {
        return sizeof...(Elements);
    }
};

int main()
{
    using namespace std;

    Tuple<int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int> test;
    Tuple<> test2;

    test.get<0>() = 1;
    test.get<1>() = 2;

    cout << test.size() << endl;
    cout << test.get<0>() << endl;
    cout << test.get<1>() << endl;
}

Being template metaprogramming, of course it looks terrible. Are there any ways I can clean it up? I've been picking up the nitty-gritty details of how templates work by messing around with stuff like this, but I'm sure I'm missing something that would simplify this.


texts: jQuery code to display images served by PHP, without reloading

texts:
My php page displays a slider of images and when the user clicks on an image(.item), the div below (#team_single) changes the content without reloading the page. Content of the div changes also when the user clicks the arrow of the slider (.slick-prev, .slick-next, .slick-arrow).

I'm looking for a way to improve the following code :

function team_push($image, $position, $sousposition, $title, $content) {
    $('#team_single .single-img').html($image);
    $('#team_single .position').html($position);
    $('#team_single .sousposition').html($sousposition);
    $('#team_single .title').html($title);
    $('#team_single .description').html($content);
}

var image = $('.slick-current').find("img").clone();
var position = $('.slick-current .position').html();
var sousposition = $('.slick-current .sousposition').html();
var title = $('.slick-current .title').html();
var content = $('.slick-current .content').html();
team_push(image, position, sousposition, title, content);

$('#team_slider .item').on('click', function(){
    var image = $(this).find("img").clone();
    var position = $(this).find('.position').html();
    var sousposition = $(this).find('.sousposition').html();
    var title = $(this).find('.title').html();
    var content = $(this).find('.content').html();
    team_push(image, position, sousposition, title, content);
});

$('#team_slider .slick-arrow').on('click', function(){
    var image = $('.slick-current').find("img").clone();
    var position = $('.slick-current .position').html();
    var sousposition = $('.slick-current .sousposition').html();
    var title = $('.slick-current .title').html();
    var content = $('.slick-current .content').html();
    team_push(image, position, sousposition, title, content);
});
$('#team_single .slick-prev').on("click", function(e){
    e.preventDefault();
    $('#team_slider').slick('slickSetOption', 'slidesToScroll', 1, true);
    $('#team_slider').slick('slickPrev');
    var image = $('.slick-current').find("img").clone();
    var position = $('.slick-current .position').html();
    var sousposition = $('.slick-current .sousposition').html();
    var title = $('.slick-current .title').html();
    var content = $('.slick-current .content').html();
    team_push(image, position, sousposition, title, content);
});
$('#team_single .slick-next').on("click", function(e){
    e.preventDefault();
    $('#team_slider').slick('slickSetOption', 'slidesToScroll', 1, true);
    $('#team_slider').slick('slickNext');
    var image = $('.slick-current').find("img").clone();
    var position = $('.slick-current .position').html();
    var sousposition = $('.slick-current .sousposition').html();
    var title = $('.slick-current .title').html();
    var content = $('.slick-current .content').html();
    team_push(image, position, sousposition, title, content);
});


texts: Example Multiple Async Await Calls Javascript

texts:
I need to make an unknown number of api calls, up to 5 max probably. But most samples I've seen show only a couple of async calls so are effectively hard coded to the number of calls being made.

This is what I came up with as a demonstration, it has an array with three sleep times in it to simulate an API call of variable duration. The main function should wait until all three calls are finished.

It works but is this the right way to go about it?

const sleep = async(milliseconds) => {
  await sleepMain(milliseconds);
  console.log(`Awake: ${milliseconds}`);
  let value = {
    sleep: milliseconds
  };
  return value;
}

const sleepMain = (milliseconds) => {
  console.log(`Sleeping ${milliseconds}`)
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const asyncTest = async() => {

  arrayTest = [1000, 3000, 5000];
  arrayTestResult = Array();

  arrayTest.forEach(function(element) {
    console.log('Start Sleep: ' + element);
    arrayTestResult.push(sleep(element));
  });

  const syncThing = await Promise.all(arrayTestResult);

  console.log(syncThing);
  return syncThing;

}

const main = async() => {
  console.log('Start Main');
  document.getElementById('message').innerHTML = 'Running...';
  await asyncTest();
  console.log('Finish Main');
  document.getElementById('message').innerHTML = 'Finished - See Console Log';
}

main();

Multi Thread Async Test

Runs the array of sleep lengths (in async) and completes when all done

sleep and sleepMain are used to simulate an API call of variable response time

https://jsfiddle.net/kanineAU/yv21Leqf/


texts:
This was an interview question I was asked. My answer is below, but I wonder if there is a more efficient way. Possible a combinatorics type function, or is an exhaustive generation + count the only way?

Rules: Given a character, the next character can be any one of How many N character combinations can you make? For example

a -> i,e
e -> i,o
i -> a,e,o
u -> a,e,i,o
o -> i,u,o

For N = 1 possible string combinations are a , e, i ,o ,u
for N = 2 possible string combinations are [ai, ae], [ei ,eo] ,[ia , ie , io],[ua,ue,ui,uo],[oi,ou,oo]
and so on.
I solved it by constructing a tree and then counting the leaves

struct Node {
    Node(char v) : v_(v) {}
    void                     add_child(shared_ptr<Node> n) { children.emplace_back(n); }
    char                     v_ = 0;
    vector<shared_ptr<Node>> children;
};

void add_child(shared_ptr<Node> root, int n, int depth, const map<char, vector<char>> &combo) {
    if (depth == n) return;
    auto ch = root->v_;
    auto it = combo.find(ch);
    for (auto ch : it->second) {
        //printf("Adding to %c to %c\n", ch, root->v_);
        root->add_child(make_shared<Node>(ch));
    }
    ++depth;
    for (auto &child : root->children) { add_child(child, n, depth, combo); }
}

int count_leaf(shared_ptr<Node> root) {
    if (root->children.size() == 0) return 0;
    int sum = 0;
    for (auto &child : root->children) sum += count_leaf(child);
    return sum > 0 ? sum : root->children.size();
}
void password_combination() {
    // Find combos until this depth
    int n = 3;

    map<char, vector<char>> combo;
    combo.insert(make_pair('a', vector<char>{'i', 'e'}));
    combo.insert(make_pair('e', vector<char>{'i', 'o'}));
    combo.insert(make_pair('i', vector<char>{'a', 'e', 'o'}));
    combo.insert(make_pair('u', vector<char>{'a', 'e', 'i', 'o'}));
    combo.insert(make_pair('o', vector<char>{'i', 'u', 'o'}));

    // Create a N depth tree and count leaves
    // Count all children until n = 3;
    auto root  = make_shared<Node>(0);
    int  depth = 0;
    for (auto &c : combo) { root->add_child(make_shared<Node>(c.first)); }
    for (auto child : root->children) { add_child(child, n, depth, combo); }
    printf("%d\n", count_leaf(root));
}

Is there a better way. Critique on the code/bugs, and if there's a c++14 idiomatic way of doing it, even better.


texts:
I hate working with std::integer_sequence. Each time I want to write a function foo I have to write an another function foo_impl where the actual stuff is happening. Therefore I'm polluting the space with additional function and the code is kind of scattered around. I came up with an alternative and I would love to know your opinion.

Let's define integral_sequence<N>. Here we use the damned std::integer_sequence for the last time!

template <std::size_t... I>
constexpr auto integral_sequence_impl(std::index_sequence<I...>) {
  return std::make_tuple(std::integral_constant<std::size_t, I>{}...);
}

template <int N>
auto integral_sequence = integral_sequence_impl(std::make_index_sequence<N>{});

To demonstrate its use, lets redo the example code for std::integral_sequence:

// Convert array into a tuple
template <typename T, std::size_t N>
decltype(auto) a2t(const std::array<T, N> &a) {
  auto impl = [&](auto... I) { return std::make_tuple(a[I]...); };

  return std::apply(impl, integral_sequence<N>);
}

// pretty-print a tuple
template <class Ch, class Tr, class... Args>
decltype(auto) operator<<(std::basic_ostream<Ch, Tr> &os,
                          const std::tuple<Args...> & t) {

  auto impl = [&](auto... I) {
    ((os << (I == 0 ? "" : ", ") << std::get<I>(t)), ...);
  };

  os << "(";
  std::apply(impl, integral_sequence<sizeof...(Args)>);
  return os << ")";
}

int main() {
  std::array<int, 4> array = {1, 2, 3, 4};

  // convert an array into a tuple
  auto tuple = a2t(array);
  static_assert(
      std::is_same<decltype(tuple), std::tuple<int, int, int, int>>::value, "");

  // print it to cout
  std::cout << tuple << '\n';
}

The trick with integral_sequence is kind of the same as with integer_sequence. However, because it can be used with generic lambda you do not have to define an extra function, all code can be neatly together and it reduces visual clutter.

So what do you think? Are there any disadvantages?

The only problems I can see now is that it is only c++17 and integral_sequence<400> takes really long time to compile.


texts: Picking 10 distinct words 'randomly' from List of unique words

texts:
My goal is to pick 10 unique words randomly from a List containing 20 unique words.

I would remove the duplicate word from the List whenever a duplicate word is added and decrement the for loop counter by 1.

List<String> words = new ArrayList<String>();
/* code to add 20 words */

List<String> word10 = new ArrayList<String>();
for (i = 0; i < 10; i++) {
  int randomIndex = new Random().nextInt(words.size());
  if (word10.contains(words.get(randomIndex)) == true) {
    word10.remove(words.get(randomIndex));
    i--;
  }
  word10.add(words.get(randomIndex));
}
System.out.println("word10 List: " + word10);

Output

word10 List: [aah, abalone, aback, abandonee, abandonedly, abandon, abacus, aahed, aardvarks, abacuses]
word10 List: [a, aardvarks, aahing, abalones, abacuses, aahed, abacus, aah, abaft, abandoned]
word10 List: [abalones, ab, abaci, a, abacuses, abandonedly, aah, aahs, aardwolf, aardvark]

The code given is working properly. Is there a better approach?


texts:
I don't know if it is any good. I've never done this, thus, I noticed it is kinda slow.

Can you suggest improvements? I may use it in actual software in the future.

private int secgen(int minvalue, int maxvalue)
    {
        Func<int, int, int, int> modular = (a, b, mod) =>
        {
            long rem;
            Math.DivRem((long)a + (long)b, (long)mod, out rem);

            if (rem < minvalue)
                rem += minvalue;

            return (int)rem;
        };

        byte[] entropyBytes = new byte[257];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        rng.GetBytes(entropyBytes);
        int value = entropyBytes[0];
        for (int i = 1; i < 257; i++)
        {
            value = modular(value, entropyBytes[i], maxvalue);

        }

        //MessageBox.Show(value.ToString());
        return value;
    }


texts: Superior improved stack implementation using a linked list

texts:
This is a followup to

Improved stack implementation using a linked list
Simple stack implementation using linked list

Please review my hopefully improved stack implementation

As suggested by some answers to my previous code, some of the functions can be overloaded to provide versions of return by value, return by reference and const or pass by value, pass by reference and const, but the function definitions are almost the same so I did not add it here.
Regarding pointers, I know std::unique_ptr will be better and I already saw an implementation through an answer to my previous code, but I like to play with normal pointers right now.

template<class T>
class Stack {
    using stacksize = std::size_t;
public:
    Stack() : first{nullptr}, n{0} {}
    stacksize size() const { return n; }
    bool empty() const { return n == 0; }
    Stack(const Stack&);
    Stack(Stack&&);
    Stack& operator=(Stack);
    Stack& operator=(Stack&&);
    T& operator[](const stacksize& i) {
        Node* traverse = first;
        stacksize x = 0;
        while (x < i) {
            traverse = traverse->next;
            ++x;
        }
        return traverse->item;
    }
    void push(const T&);
    void pop();
    T& peek() const;
    ~Stack() {
        while (!empty()) {
            pop();
        }
    }
private:
    struct Node {
        T item;
        Node* next;
        Node(const T& t, Node* link) :item{t}, next{link} { }
    };
    Node* first;
    stacksize n;
};

template<class T>
Stack<T>::Stack(const Stack& s) :first{nullptr}, n{0}{
    for (auto t = s.first; t != nullptr; t = t->next) {
        push(t->item);
    }
}

template<class T>
Stack<T>& Stack<T>::operator=(Stack s) {
    std::swap(first,s.first);
    std::swap(n,s.n);
    return *this;
}

template<class T>
Stack<T>::Stack(Stack&& s) :first{s.first}, n{s.n} {
    s.first = nullptr;
    s.n = 0;
}

template<class T>
Stack<T>& Stack<T>::operator=(Stack&& s) {
    std::swap(s.n,n);
    std::swap(s.first,first);
    return *this;
}

template<class T>
void Stack<T>::push(const T& t) {
    first = new Node{t,first};
    ++n;
}

template<class T>
void Stack<T>::pop() {
    Node* oldfirst = first;
    first = first->next;
    delete oldfirst;
    --n;
}

template<class T>
T& Stack<T>::peek() const {
    return first->item;
}


texts: Identifying originating country of an IP address

texts:
I have a small assignment to read IP addresses and from a bunch of external text files identify which country the IP address comes from. I opted to use XmlReader and read the ranges from an XML file but unfortunately the performance has been quite abysmal (an average search time of around 7000 milliseconds).

Obviously serializing the ranges isn't an option as we're talking about 142,222 entries. Is there anything I can do to optimize my method or is there a quicker way to search this, without resorting to SQL?

class IPRangeRepository : IDisposable
    {
        public IPRangeRepository(string fileName)
        {
            this.fileName = fileName;
            xmlReader = XmlReader.Create(fileName);
        }

        private XmlReader xmlReader;
        private string fileName;

        public string GetIPCountry(IPAddress adress)
        {
            while (xmlReader.Read())
            {
                // Ok instantiate object and then do comparison...
                if (xmlReader.Name == "IPRange") {
                var ipRange = IPRange.TryParse(xmlReader["Value"]);
                if (ipRange.IsIPAddressInRange(adress)) return xmlReader["Country"];
                }
            }

            //Return empty string if we don't find anything
            return string.Empty;
        }

        public void Dispose()
        {
            xmlReader.Dispose();
        }
    }


texts:
I am a newbie to Python and have started object-oriented programming recently. I have implemented a "Rock Paper Scissors" application in OOP. I would like for you to evaluate my code, and tell me where can I improve my code and how I can better organize the functionality.

import random

class RockPaperScissors(object):
    def setUserOption(self,val):
        self.__option = val

    def getValueFromList(self,option):
        l = ['rock','scissors','paper']
        return l[option]

    def __getRandomValue(self,max):
        val = random.randint(1,max)
        return self.getValueFromList(val-1)

    def __getResult(self,t):
        self.__d = {('rock','scissors'):'rock breaks scissors - User has won',('rock','paper'):'rock is captured by paper - User has won',('scissors','paper'):'Scissors cut paper - User has won',
                    ('scissors','rock'):'rock breaks scissors - Computer won',('paper','rock'):'rock is captured by paper - Computer won',('paper','scissors'):'Scissors cut paper - Computer won'}
        return self.__d[t]

    def __computeResult(self,computerOption):
        if computerOption == self.__option:
            return 'The user and computer choose the same option'
        else:
            return self.__getResult((self.__option,computerOption))

    def printResult(self):
        computerOption = self.__getRandomValue(3)
        print 'User choice: ',self.__option
        print 'Computer choice: ',computerOption
        print self.__computeResult(computerOption)

if __name__ == "__main__":
    print 'Welcome to rock paper scissors'
    print '1. Rock, 2. Paper, 3. Scissor'
    val = int(raw_input('Enter your choice Number: '))
    if val >=1 and val <= 3:
        obj = RockPaperScissors()
        obj.setUserOption(obj.getValueFromList(val-1))
        obj.printResult()
    else:
        raise ValueError('You are supposed to enter the choice given in the menu')


texts:
I am new to programming and I am taking CS50 2014 online through iTunes University. This is the change-making problem in Problem Set 1:

  Write a program that first asks the user how much change is owed and then spits out the minimum number of coins with which said change can be made. Assume that the only coins available are quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢).

I am pretty sure that my code is super "hacky." I would love understandable input on how I could have made a better algorithm or how I should have broken down the problem or "You did 'x' here"..."it would be better if you did 'y'."

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{

    // declare float
    float money;

    // Get user input and check if input is positive
    do
    {
        printf("Please input the some amount of money you would like to make change for:  \n");
        money = GetFloat();
    } while (money < 0);

    // Get the Dollars from the Float
    int getDollars = money;

    // Get the cents from the Float
    float getCents = roundf((money * 100) - (getDollars * 100));
    int convertCents = getCents;

    // Greedy Algorithm for Dollars
    int getHundreds = getDollars / 100;
    int getFifties = ((getDollars) - (100 * getHundreds)) / 50;
    int getTwenties = ((getDollars) - (50 * getFifties) - (100 * getHundreds)) / 20;
    int getTens = ((getDollars) - (20 * getTwenties) - (50 * getFifties) - (100 * getHundreds)) / 10;
    int getFives = ((getDollars) - (10 * getTens) - (20 * getTwenties) - (50 * getFifties) - (100 * getHundreds)) / 5;
    int getOnes = ((getDollars) - (10 * getTens) -(5 * getFives) - (20 * getTwenties) - (50 * getFifties) - (100 * getHundreds)) / 1;

    //Greedy Algorithm for Cents
    int getQuaters = convertCents / 25;
    int getDimes = ((convertCents) - (getQuaters * 25)) / 10;
    int getNickles = ((convertCents) - (getQuaters * 25) - (getDimes * 10)) / 5;
    int getPennies = ((convertCents) - (getQuaters * 25) - (getDimes * 10) - (getNickles * 5)) / 1;

    printf("\n");
    if (convertCents == 0)
    {
        printf("The least possible steps you can make change from $%i.%i0 is %i. \n", getDollars, convertCents, (getHundreds + getFifties + getTwenties + getTens + getFives + getOnes + getQuaters + getDimes + getNickles + getPennies));
    }
    else if (convertCents < 10 && convertCents > 0)
    {
        printf("The least possible steps you can make change from $%i.0%i is %i. \n", getDollars, convertCents, (getHundreds + getFifties + getTwenties + getTens + getFives + getOnes + getQuaters + getDimes + getNickles + getPennies));
    }
    else
    {
        printf("The least possible steps you can make change from $%i.%i is %i. \n", getDollars, convertCents, (getHundreds + getFifties + getTwenties + getTens + getFives + getOnes + getQuaters + getDimes + getNickles + getPennies));
    }
}

Also please forgive me I kind of went out of the scope of the problem. I appended it knowing the fact that I would like to use currently circulating paper denominations as well as coins.


texts:
This game is a variation of the Greed dice game. Imagine we have 5 dice. We roll, them, and jot down the results. Then, based on this chart:

Three 1's => 1000 points
Three 6's =>  600 points
Three 5's =>  500 points
Three 4's =>  400 points
Three 3's =>  300 points
Three 2's =>  200 points
One   1   =>  100 points
One   5   =>   50 point

We calculate the score. This program exactly does that. It has two functions, one is greed() which takes a vector of 5 integers between 1 and 6 and calculates the score, and the other is greed_rand() which first generates the vector randomly, and then calculates the score.

#include <iostream>
#include <vector>
#include <random>
#include <map>

std::random_device seeder;
std::mt19937 engine(seeder());
std::uniform_int_distribution<int> dist(1, 6);

typedef std::vector<int> list_type;

int greed(list_type die_rolls)
{
    int ret = 0;
    std::map<int, int> cnt;

    for (int i = 1; i <= 6; ++i)
    {
        cnt[i] = 0;
    }

    for (auto &d : die_rolls)
    {
        ++cnt[d];
    }

    if (cnt[1] == 3)
    {
        ret += 1000;
    }
    if (cnt[1] == 2)
    {
        ret += 200;
    }
    if (cnt[1] == 1)
    {
        ret += 100;
    }
    if (cnt[1] == 4)
    {
        ret += 1100;
    }
    if (cnt[1] == 5)
    {
        ret += 1200;
    }
    if (cnt[2] == 3)
    {
        ret += 200;
    }
    if (cnt[3] == 3)
    {
        ret += 300;
    }
    if (cnt[4] == 3)
    {
        ret += 400;
    }
    if (cnt[5] == 1)
    {
        ret += 50;
    }
    if (cnt[5] == 2)
    {
        ret += 100;
    }
    if (cnt[5] == 3)
    {
        ret += 500;
    }
    if (cnt[5] == 4)
    {
        ret += 550;
    }
    if (cnt[5] == 5)
    {
        ret += 600;
    }
    if (cnt[6] == 3)
    {
        ret += 600;
    }

    return ret;

}

int greed_rand()
{
    list_type rolls_rand;

    for (int i = 1; i <= 5; ++i)
    {
        rolls_rand.push_back(dist(engine));
    }

    return greed(rolls_rand);
}

int main() {

    list_type rolls = {1, 1, 1, 5, 5};
    std::cout << greed(rolls) << std::endl;
    std::cout << greed_rand() << std::endl;

    return 0;
}

The output of this program is:

1100
150

Note: If you're on Windows, change the random seeder to time(NULL).


texts:
This script, once added to the Windows Scheduler, automatically creates a backup of your Google Chrome bookmarks.

import shutil
import os
import datetime

def setup():
    print ('Enter your Chrome bookmark directory.')
    print ('Standard one is: C:\\Users\\<USER>\\AppData\\Local\\Google\\Chrome\\User Data\\Default')
    bookmarkfolder = input('> ')

    print ('Enter the folder you want to save the backup files in.')
    print ('For example: C:\\Users\\<USER>\\Desktop\\Chrome Bookmarks')
    backupfolder = input('> ')

    with open('user.txt', 'w') as txt:
        txt.write(bookmarkfolder + '\n' + backupfolder)

    copy()

def copy():
    userList = []
    date = datetime.date.today()

    with open('user.txt', 'r') as txt:
        for line in txt:
            userList.append(line.strip())

    shutil.copy(userList[0] + '\\Bookmarks', userList[1])
    try:
        os.rename('Bookmarks', 'Bookmarks' + str(date).replace('-',''))
    except WindowsError:
        os.remove('Bookmarks' + str(date).replace('-',''))
        os.rename('Bookmarks', 'Bookmarks' + str(date).replace('-',''))

def checksetup():
    with open('user.txt', 'r') as setupfile:
        setupfile.seek(0)
        for line in setupfile:
            if '\\' in line:
                copy()
            else:
                setup()

checksetup()


texts: Fill upper triangular matrix from a list

texts:
I am looking a good way to fill up the elements of a lower triangular matrix from a list.

I currently have this:

PadRight[#, s] & /@
 Prepend[Take[elems, # + {1, 0}] & /@
   Partition[Accumulate[Range[0, s - 1]], 2, 1], {}]

where elems is the elements-list and s is its length.

Perhaps the best way is preallocation plus a clear, procedural Do-loop.  What do you think?

You can test the above with:

s = 5
elems = Range[s(s-1)/2]


texts: Scrape a reddit post submission for comments and save comments to JSON file

texts:
Edit: For a revision to this code according to the comments, see here: "here."

In regards to the code involving shortlinks and submission:
this script is meant to be used in conjunction with a different script not displayed here, which initializes the data.json with the appropriate keys. Code related to submission, comment.list(), praw all deal with the reddit API.

How it works:
Retrieves post information from data.json, using the shortlinks as reference, scrapes the aforementioned post for all of its comments, and then matches the group of comments to its corresponding shortlink in order to write the information to the JSON file.

#!/usr/bin/python3
import json
import os
import praw

"""
Scrapes posts for comments and saves the comment ID and comment text to the
accompanying JSON file.
"""

JSON_DEFAULT_LOC = os.environ.get('JSON_LOCATION') or os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data.json")

def login():
    """ Create a reddit instance according to praw.ini configuration.
    Call reddit.user.me() as a check.
    Return reddit instance.
    """
    print("Authenticating")
    reddit = praw.Reddit("appname", user_agent="Chrome:com.example.bot-"
                                                "name:v1 (by /u/)")
    print("Authenticated as {}".format(reddit.user.me()))
    return reddit

def load_manager(fp=None):
    """ Load the accompanying JSON data which holds reddit post information.
    """
    if fp is None:
        fp = JSON_DEFAULT_LOC
    with open(fp, "r") as file:
        data = json.load(file)
    return data

def scrape(reddit):
    """ For each post specified in the JSON dict, scrape the comments within
    the post and write the comments to the JSON dict to the key: "responses".
    """
    data = load_manager()
    shortlinks = [data[sub][0]["shortlink"][-6:] for sub in data]

    for sl_id in shortlinks:
        submission = reddit.submission(id=sl_id)
        try:
            write_comments_to_file(submission, sl_id, data)
            print("Comments from '{}' "
                  "saved to file".format(submission.subreddit))
        except Exception as e:
            print("Could not write to file: {}".format(e))

def write_comments_to_file(submission, sl_id, data, fp=None):
    """ Takes a reddit submission object, shortlink ID, and JSON data.
    Retrieves the comments per submission, and for each submission within the
    JSON data, also write its comments.
    """
    submission.comments.replace_more(limit=0)
    cmt_data = [{comment.id: comment.body}
                for comment in submission.comments.list()]
    for i in data:
        if sl_id in data[i][0]["shortlink"]:
            data[i][1]["responses"] = cmt_data
    if fp is None:
        fp = JSON_DEFAULT_LOC
    with open(fp, "w") as fp:
        json.dump(data, fp)

def main():
    reddit = login()
    scrape(reddit)

if __name__ == "__main__":
    main()

I am interested in making the code more Pythonic. I'm especially unconfident about the way that my functions are structured/grouped.
Help much appreciated!


texts: Customizing Django built-in views such as LoginView

texts:
Which way is preferred to customize Django built-in views such as LoginView:

Define a line in urls.py:

path(route='login/', view=views.django_auth_views.LoginView.as_view(template_name='accounts/login.html', authentication_form=forms.LoginForm, extra_context=None, redirect_authenticated_user=True), name='login'),

Where, views.py contains:

from django.contrib.auth import views as django_auth_views

Or:

In views.py, define a new class:

class LoginView(django_auth_views.LoginView):
    template_name = 'accounts/login.html'
    authentication_form = LoginForm
    extra_context = None
    redirect_authenticated_user = True

And then, define in urls.py:

path(route='login/', view=views.LoginView.as_view(), name='login'),

Will both ways work the same, and is one of them preferred from a software engineering / programming perspective?


texts: Overriding operator delete/new to check correct pairs of (non-)array variants

texts:
A legacy project I am maintaining in my freetime uses overrides of operator delete / operator new. These overrides over-allocate by some bytes using malloc (and free) and treat said bytes as a prefix filled with a signature different between new and new[]. Checking the signature on delete allows to discover accidental cases of "new ... delete[]" or "new[] ... delete". Returned is the malloc'ed pointer offset by the size of the prefix.

These overrides are put behind an #ifdef that does not evaluate in release mode.

I recently rewrote this part, using guidance from the relevant cppreference page and find that I am left with three questions I have trouble to satisfyingly answer. These are my questions:

Is this code even still necessary or could I replace it with some builtin feature or plugin? (Currently using latest non-preview MSVC++ toolchain, might switch to MinGW-w64 at some indeterminate time in the future... currently the project does not compile on GCC though.)
Did I avoid UB at least in the non-pathological use cases? (And even if, examples of such cases are welcome.)
The original legacy code implements both operator delete and delete[] by calling free, essentially meaning their implementation (prefix handling aside) is identical... if that must be so, then why bother in the first place?

Of course, considerations beyond those pertaining to this list are also welcome.

Code to be reviewed:

#include <cstring>

constexpr char PREFIX_ARRAY [] = "STR2MED";
constexpr char PREFIX_OBJECT[] = "str1med";
constexpr auto OFFSET_ARRAY  = std::size(PREFIX_ARRAY);
constexpr auto OFFSET_OBJECT = std::size(PREFIX_OBJECT);
using OFFSET_TYPE = decltype(OFFSET_ARRAY + OFFSET_OBJECT);

template<OFFSET_TYPE OFFSET>
inline void * guardDelete(void * pointer, const char PREFIX[OFFSET])
{
  if(pointer == nullptr)
    return pointer;
  else
  {
    char * prefix = reinterpret_cast<char*>(pointer) - OFFSET;
    ASSERT(std::memcmp(prefix, PREFIX, OFFSET) == 0);

    return prefix;
  }
}

void __cdecl operator delete  (void * pointer) { std::free(guardDelete<OFFSET_OBJECT>(pointer, PREFIX_OBJECT)); }
void __cdecl operator delete[](void * pointer) { std::free(guardDelete<OFFSET_ARRAY> (pointer, PREFIX_ARRAY)); }

template<OFFSET_TYPE OFFSET>
inline void * guardNew(void * pointer, const char PREFIX[OFFSET])
{
  ASSERT(pointer != nullptr); // Out of virtual memory?
  std::memcpy(pointer, PREFIX, OFFSET);

  return reinterpret_cast<char*>(pointer) + OFFSET;
}

void * __cdecl operator new  (std::size_t size) { return guardNew<OFFSET_OBJECT>(std::malloc(size + OFFSET_OBJECT), PREFIX_OBJECT); }
void * __cdecl operator new[](std::size_t size) { return guardNew<OFFSET_ARRAY> (std::malloc(size + OFFSET_ARRAY),  PREFIX_ARRAY); }

External dependency (ASSERT implementation; still legacy code; not to be reviewed):

// This spawns a handy Windows error message allowing one to start VS
// and attach the debugger while the context is still intact;
// with debugger already attached, it acts as a breakpoint.
void _AssertDebug(char * strAssertion, char * strFile, unsigned int uLine)
{
  static char str[1024];
  sprintf(str, "\n---  Assertion failed: %s file:%s line:%u  ---\nDo you still want to continue?", strAssertion, strFile, uLine);
  switch(MessageBox(GetActiveWindow(), str, "Fatal error!", MB_ABORTRETRYIGNORE|MB_DEFBUTTON3|MB_TOPMOST))
  {
    case IDABORT:
      std::abort();
      break;
    case IDRETRY:
      DebugBreak();
      break;
  }
}

#define ASSERT(f) \
  if (f)          \
  {}              \
  else            \
    _AssertDebug((#f), __FILE__, __LINE__)


texts:
below vbscript code took me 3hours just to complete trimming whitespaces of a 24MB file any tips to speed up the process below?

dim filename, path \'variables
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     Set objFile = objFSO.GetFile(Wscript.ScriptFullName)
     strFolder = objFSO.GetParentFolderName(objFile)
     filename = replace(strFolder,"jobs\SCRIPTS","shared\file") & "\DCS.txt"
     converter(filename)
     objFile.Close
     function converter(filename)
     Const ForReading = 1
     Const ForWriting = 2
     Set objFSO = CreateObject("Scripting.FileSystemObject")
     PATH = filename
     Set objFile = objFSO.OpenTextFile(PATH, ForReading)
     Do Until objFile.AtEndOfStream
        strLine = objFile.Readline
        strLine = Trim(strLine)
        If Len(strLine)  0 Then
            strNewContents = strNewContents & strLine & vbcrlf
        End If
     Loop
     objFile.Close
     Set objFile = objFSO.OpenTextFile(PATH, ForWriting)
     objFile.Write strNewContents
     objFile.Close
     msgbox "done trim on " & filename
     end function


texts:
I found that in PHP (or I probably can't find it) a proper is_numeric_array($array) function is missing. So I created one. The problem is that I don't think it's great and I don't know how to improve it.

Any suggestion?

My first function

function is_numeric_array($array)
{
    $i = 0;
    foreach ($array as $a => $b) { if (is_int($a)) { ++$i; } }
    if (count($array) === $i) { return true; }
    else { return false; }
}

is_numeric_array(array(0,0,0,0,0)); // true
is_numeric_array(array('str' => 1, 'str2' => 2, 'str3' => 3)); // false

Example

As asked, I provide an example on how this could be any useful.

function is_numeric_array($array)
{
    # Code below
}

function someFunction($array)
{
    if (is_numeric_array($array))
    {
        $query = $array[0];
        $param = $array[1];
        $fetch = $array[2];
    }
    else
    {
        $query = $array['query'];
        $param = $array['param'];
        $fetch = $array['fetch'];
    }

    # Do your sql/pdo stuff here
}

# This use is the same of ...
someFunction(array(
    'PDO SQL STATEMENT',
    array('param1' => 1, 'param2' => 2, 'param3' => 3),
    true
));

# ... this one.
someFunction(array(
    'query' => 'PDO SQL STATEMENT',
    'param' => array('param1' => 1, 'param2' => 2, 'param3' => 3),
    'fetch' => true
));

# To choose one form instead of the other is coder's decision
# Also I know it is useless but I was just wondering why anybody actually looked forward this function


texts:
I wrote an Array class with iterators:

#include <iostream>
using namespace std;
template <class T>
class Array
{
    T* data;
    int size;
public:
    class mException { };
    Array(int nsize=1)try:data(new T[nsize]),size(nsize)
    {

    }
    catch(bad_alloc& r)
    {
        cout<< "Cant allocate";
        throw;
    }
    Array(const Array& rhs):data(new T[rhs.size]),size(rhs.size)
    {
        for(int i=0;i<size;i++)
        {
            data[i] = rhs.data[i];
        }
    }
    Array& operator=(const Array& rhs)
    {
        if(this== &rhs) return *this;
        delete [] data;
        size = rhs.size;
        data = new T[size];
        for(int i=0;i<size;i++)
        {
            data[i] = rhs.data[i];
        }
        return *this;
    }
    T& operator[](int index) throw (mException)
    {
        if(index<0 || index>=size) throw mException();
        return data[index];
    }
    const T& operator[](int index) const throw(mException)
    {
        if(index<0 || index>=size) throw mException();
        return data[index];
    }
    const Array operator++(int) //postfix
    {
        Array temp = *this;
        ++*this;
        return temp;
    }
    Array& operator++()
    {
        for(int i=0;i<size;i++)
            data[i]++;
        return *this;
    }
    friend ostream& operator<<(ostream& out, const Array& rhs)
    {
        out << "(";
        for(int i=0;i<rhs.size;i++)
        {
            out << rhs.data[i];
            if(i<rhs.size-1)
             out <<  " ";
        }
        out << ")" << endl;
        return out;
    }
    friend istream& operator>>(istream& in,Array& rhs)
    {
        cout << "enter " << rhs.size << " digits to fill the array" << endl;
        for(int i=0;i<rhs.size;i++) in >> rhs.data[i];
        return in;
    }

    ~Array()
    {
        delete [] data;
    }
    bool empty() const
    {
        return size==0;
    }
     T front()
    {
        return data[0];
    }
     T back()
    {
        return data[size-1];
    }
    class iterator
    {
        const Array* data;
        int index;
        friend class Array;
    public:
        iterator(const Array* arr,int size): data(arr),index(size) { }
        const T& operator*() const
        {
            return data->data[index];
        }
        const iterator operator++(int)
        {
            iterator temp = *this;
            ++*this;
            return temp;
        }
        iterator& operator++()
        {
            ++index;
            return *this;
        }
        friend bool operator==(const iterator& rhs,const iterator& lhs)
        {
            return !(rhs.index!=lhs.index);
        }
        friend bool operator!=(const iterator& rhs, const iterator& lhs)
        {
            return !(rhs.index==lhs.index);
        }
    };
    iterator begin() const{ return iterator(this,0); }
    iterator end() const{ return iterator(this,size); }
};

I have a few questions:

Should I throw exceptions in the iterator class?

I have exceptions in templates, and I have a catch for every type in main alone, and this could be a problem.
Is throwing exceptions from exception (like I did) a good choice?

I know this is not a complete version. This is for educational purposes and I need to know where I did badly.


texts: Implementing HTTP data range representation class

texts:
I need a class representing a parsed Range HTTP header value. I've done it like this:

namespace net {

namespace http {

    class DataRange {
    public:
        static const uint64_t UnspecifiedBytePos;
        static const DataRange Full;

        explicit DataRange(uint64_t firstBytePos, uint64_t lastBytePos);
        DataRange(const DataRange& other);

        uint64_t FirstBytePos() const;
        uint64_t LastBytePos() const;

        uint64_t Size() const;

        bool HasUnspecifiedBytePos() const;

        bool operator==(const DataRange& other) const;
        bool operator!=(const DataRange& other) const;

    private:
        uint64_t firstBytePos_;
        uint64_t lastBytePos_;
    };

    typedef std::list<DataRange> DataRanges;

    DataRange SpecifyDataRangeBytePos(const DataRange& dataRange, uint64_t dataSize);

} // namespace http

} // namespace net

I don't show the implementation here since it's quite simple. In this implementation, DataRange may have unspecified borders, representing Range headers like this one:

Range: -1234

To turn DataRange to one with specified borders, I've made a function SpecifyDataRangeBytePos:

DataRange SpecifyDataRangeBytePos(const DataRange& dataRange, uint64_t dataSize) {

    uint64_t specifiedFirstBytePos = dataRange.FirstBytePos();

    if ((dataRange.FirstBytePos() == DataRange::UnspecifiedBytePos) &&
            (dataRange.LastBytePos() != DataRange::UnspecifiedBytePos)) {

        uint64_t rangeUpperBorder = std::min(dataSize, dataRange.LastBytePos());
        specifiedFirstBytePos = dataSize - rangeUpperBorder;
    }

    if ((dataRange.FirstBytePos() == DataRange::UnspecifiedBytePos) &&
            (dataRange.LastBytePos() == DataRange::UnspecifiedBytePos)) {

        specifiedFirstBytePos = 0;
    }

    uint64_t specifiedLastBytePos = dataRange.LastBytePos();

    if ((dataRange.LastBytePos() != DataRange::UnspecifiedBytePos) &&
            (dataRange.FirstBytePos() == DataRange::UnspecifiedBytePos)) {

        specifiedLastBytePos = (dataSize > 0) ? (dataSize - 1) : dataSize;
    }

    if ((dataRange.LastBytePos() == DataRange::UnspecifiedBytePos) &&
            (dataRange.FirstBytePos() != DataRange::UnspecifiedBytePos)) {

        specifiedLastBytePos = (dataSize > 0) ? (dataSize - 1) : dataSize;
    }

    if ((dataRange.LastBytePos() == DataRange::UnspecifiedBytePos) &&
            (dataRange.FirstBytePos() == DataRange::UnspecifiedBytePos)) {

        specifiedLastBytePos = (dataSize > 0) ? (dataSize - 1) : dataSize;
    }

    DataRange result(specifiedFirstBytePos, specifiedLastBytePos);
    assert(!result.HasUnspecifiedBytePos());

    return result;
}

There are plenty of ifs, which seems very awkward, but I cannot do better. Any suggestions?


texts:
My BLL's function is like:

 public Categorymaster GetByPrimaryKey(CategorymasterKeys keys)
        {
            return _dataObject.SelectByPrimaryKey(keys);
        }

// above funciton is calling function written below

 public Categorymaster SelectByPrimaryKey(CategorymasterKeys keys)
        {
            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.CommandText = "dbo.[categorymaster_SelectByPrimaryKey]";
            sqlCommand.CommandType = CommandType.StoredProcedure;

            // Use connection object of base class
            sqlCommand.Connection = MainConnection;

            try
            {

                sqlCommand.Parameters.Add(new SqlParameter("@category_id", SqlDbType.Int, 4, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, keys.Category_id));

                if (MainConnection.State == ConnectionState.Closed)
                {
                    MainConnection.Open();
                }

                IDataReader dataReader = sqlCommand.ExecuteReader();

                if (dataReader.Read())
                {
                    Categorymaster businessObject = new Categorymaster();

                    PopulateBusinessObjectFromReader(businessObject, dataReader);

                    return businessObject;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Categorymaster::SelectByPrimaryKey::Error occured.", ex);
            }
            finally
            {
                MainConnection.Close();
                sqlCommand.Dispose();
            }

        }

In my web page i have written below code:

BusinessLayer.Product_category_transFactory pctf = new Product_category_transFactory();

        Categorymaster cm = cmf.GetByPrimaryKey(new CategorymasterKeys(catid));//throws exception when it returns null

Now the issue i am facing is that when there is no result for the query then it returns null and throw exception.

The same model is used in whole application.
Please tell me what all minimum and optimum changes should i do handle null (when no result).

NOTE: i am using .net framework 4.0

Thanks


texts:
I have written a small program that converts a decimal number into a reduced fraction representation. I also designed this little program to be fairly robust, so that it can give the correct output for various inputs.

For example:

./a.out 3,000.375
24003/8
./a.out "3 000,375"
24003/8
./a.out 3.000,375
24003/8
./a.out 3000.375
24003/8

Here is the complete code for the program:

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

int isDigit(char);
void simplify(unsigned long long *, unsigned long long *);

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Please enter a number to fractionize.\n");
        return EXIT_FAILURE;
    }
    char *input = argv[1];
    int i;
    char c;
    unsigned long long previous, denominator = 1, numerator = 0;
    for (i = strlen(input) - 1; i >= 0; i--, denominator *= 10) {
        c = input[i];
        if (!isDigit(c)) {
            break;
        }
        previous = numerator;
        numerator = (c - '0') * denominator + numerator;
        if (previous > numerator) {
            return EXIT_FAILURE;
        }
    }
    if (c == '-' || isDigit(c)) {
        printf("%llu/1\n", numerator);
        return EXIT_SUCCESS;
    }
    simplify(&numerator, &denominator);
    int j, negative = 0;
    unsigned long long whole = 0;
    for (j = 0; j < i; j++) {
        char c = input[j];
        if (c == '-') {
            negative = 1;
        } else if (isDigit(c)) {
            previous = whole;
            whole = whole * 10 + (c - '0');
            if (previous > whole) {
                return EXIT_FAILURE;
            }
        }
    }
    previous = numerator;
    numerator += whole * denominator;
    if (previous > numerator) {
        return EXIT_FAILURE;
    }
    simplify(&numerator, &denominator);
    if (negative) {
        printf("-");
    }
    printf("%llu/%llu\n", numerator, denominator);
    return EXIT_SUCCESS;
}

int isDigit(char c) {
    return c >= '0' && c <= '9';
}

void simplify(unsigned long long *numerator, unsigned long long *denominator) {
    while (1) {
        if ((*numerator % 2 == 0) && (*denominator % 2 == 0)) {
            *numerator   /= 2;
            *denominator /= 2;
        } else if ((*numerator % 5 == 0) && (*denominator % 5 == 0)) {
            *numerator   /= 5;
            *denominator /= 5;
        } else {
            break;
        }
    }
}

My algorithm is basically to first process the number right to left. As soon as a non-digit is detected, the part of the input that has been processed is deemed the "fractional part". This fractional part is then simplified (when possible). For example "12.34" would be processed as 34 and 100, which would then be simplified to 17 and 50.

Then, the input is processed left to right up to the point where the first scan terminated. Any non-digit characters are ignored (except the minus sign), and digits are accumulated (12 in this case). This is deemed the "whole part".

Then, the whole part is multiplied by the (simplified) denominator and it is added to the (simplified) fractional part (in this case, the fraction would be 617 over 50). The fraction is then again simplified (when possible) and the result is printed out.

My main concern is how I handle overflow. Because I am using unsigned types, overflow would simply cause the number to wrap around towards 0, so I simply check if the number before the computation (stored in previous) is larger than the number after the computation. If it is, then overflow has occurred. This seems like a fairly naive way to do it, but it seems to work for the inputs that I have tried.

Otherwise, any stylistic or performance-related inputs are always appreciated.


texts:
I've recently started switching from JQuery to Angular and it's awesome at making my HTML expressive and easy to read but every reusable module I make has its own script which leads to a massive script loading area. I suppose I could closure compile them or something but is there a better way?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Control Page</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap-switch.min.css">
    <link rel="stylesheet" href="assets/css/bootstrap-theme.css">
    <link rel="stylesheet" href="assets/css/navbar.css">
    <link rel="stylesheet" href="assets/css/popup.css">

    <extension-navbar></extension-navbar>

        <status-monitor-area></status-monitor-area>

                    <state-message></state-message>

                    <enable-switch></enable-switch>

            <state-progress-bar></state-progress-bar>

                <review-request></review-request>


texts: Displaying a new image document in Picturebox

texts:
I'm using WinForms and have a picturebox in my form. This program looks in "C:\image\" directory to find a specified image document, in my case a tif file. There is always only one picture in "C:\image\" directory.

After it locates the file, the program displays the image document in the picturebox.

When I was running this, I saw that the CPU usage was high. My goal is to make performance better or find out if there is a better way of coding this.

I have to manually go into my C:\image\ directory and delete the current image document then place a new image document in there so my picturebox will show the new image document.

int picWidth, picHeight;

private void Form1_Load(object sender, EventArgs e)
{
    timer1_Tick(sender, e);
}

private void File_Length()
{
    try
    {

        string path = @"C:\image\";
        string[] filename = Directory.GetFiles(path, "*.tif"); //gets a specific image doc.

        if (filename.Length > 0)
        {
            FileInfo fi = new FileInfo(filename[0]);
            byte[] buff = new byte[fi.Length];
            using (FileStream fs = File.OpenRead(filename[0]))
            {
                fs.Read(buff, 0, (int)fi.Length);
            }
            MemoryStream ms = new MemoryStream(buff);
            Bitmap img1 = new Bitmap(ms);
            //opened = true; // the files was opened.
            pictureBox1.Image = img1;

            pictureBox1.Width = img1.Width;
            pictureBox1.Height = img1.Height;
            picWidth = pictureBox1.Width;
            picHeight = pictureBox1.Height;
        }
    }
    catch(Exception)
    {

    }
}

public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick); //calls method
    timer1.Interval = 2000; // in miliseconds (1 second = 1000 millisecond)
    timer1.Start(); //starts timer
}

private void timer1_Tick(object sender, EventArgs e)
{
    File_Length(); //checking the file length every 2000 miliseconds
}


texts: Project Euler 39: Integer right triangles

texts:
I just finished Project Euler 39:

  If p is the perimeter of a right angle triangle with integral length sides, {a, b, c} … For which value of p ≤ 1000, is the number of solutions maximised?

I'm pretty satisfied with my solution. I derive the formula for the hypotenuse as follows:

$$\begin{align}
a + b + c &= p \tag{Def. perimeter}\\
b + c &= p - a \tag{2}\\
\\
a^2 + b^2 &= c^2 \tag{Pythagorean}\\
a^2 &= c^2 - b^2 \\
a^2 &= (c - b)(c + b) \\
a^2 &= (c - b)(p - a) \tag{from (2)} \\
\frac{a^2}{p - a} &= c - b \tag{7} \\
\\
(c - b) + (c + b) &= \frac{a^2}{p - a} + (p - a) \tag{from (7) and (2)}\\
2c &= \frac{a^2}{p - a} + \frac{(p - a)^2}{p - a} \\
2c &= \frac{a^2 + (p - a)^2}{p - a} \\
c &= \frac{a^2 + (p - a)^2}{2\ (p - a)}
\end{align}$$

Any optimization would be appreciated.

from timeit import default_timer as timer

start = timer()
def find_pythagorean_triples(perimeter):
    count = 0
    for a in range(3, perimeter / 2 - 1): # triangle inequality
        c = (a**2 + (perimeter - a)**2) / (2*(perimeter - a)) # derived formula
        b = (c**2 - a**2)**0.5
        if b.is_integer() and a + b + c == perimeter:
            count += 1
    return count

def find_most_solutions_upto(limit):
    data = {"most": 0, "num": 0}
    for p in range(limit/2, limit + 1): # scale upwards
        if find_pythagorean_triples(p) > data['most']:
            data['most'] = find_pythagorean_triples(p)
            data['num'] = p
    return data['num']

ans = find_most_solutions_upto(1000)
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts: Subclassing Profile.Profile to use it as a context manager

texts:
I was profiling my code and annoyed by the continuous calls of

Profile.run(my_function())
Profile.run(my_next_function())

so I decided to make a context manager instead.  This seems pretty straightforward but I wanted to make sure nothing about it was bad - I was a little surprised that you couldn't use it as a context manager to begin with which makes me suspect someone had a reason to not implement it.

try:
    import cProfile as Profile
except ImportError:
    import profile as Profile
finally:
    import pstats
    import sys

class context_profiler(Profile.Profile):

    def __init__(self, sortby='cumulative', stream=sys.stdout, **kwargs):
        super(context_profiler, self).__init__(**kwargs)
        self.sortby = sortby
        self.stream = stream

    def __enter__(self):
        self.enable()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.disable()
        self.print_data()

    def print_data(self):
        ps = pstats.Stats(self, stream=self.stream).sort_stats(self.sortby)
        ps.print_stats()

if __name__ == '__main__':
    with context_profiler() as pr:
        for i in xrange(2):
            for j in range(10000):
                pr.stream.write(str(i+j))


texts:
I created this countdown timer as a tool to count down the remaining time on a test a few months ago. However, I looked at the code today and it looks like it needs some improvement, but I'm not sure what to fix.

Some problems I've already identified:

It makes a call to a macOS-specific command: say.
It uses the bell character to make noise (which generally seems like a nuisance).

import os
import time
import sys
class cl: # Thank you SO for these colors
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
def countdown(secs, graceperiod):
    os.system("clear")
    for i in range (secs, -graceperiod, -1):
        if (i > 0):
            print cl.BOLD + cl.UNDERLINE + "%s:%02d" % (str((i)/60),(i)%60) + cl.ENDC
        elif (i == 0):
            print "STARTING GRACE PERIOD"
        else:
            print "EXTRA TIME: %s:%02d" % (str((-i)/60),(-i)%60)
        time.sleep(1)
        os.system("clear")
    print "\a"
    time.sleep(0.25)
    print "\a"
    time.sleep(0.25)
    print "\a"
    time.sleep(0.25)
    print "\a"
    time.sleep(0.25)
    os.system("say \"Time up! Put down your pencil!\"")
    print "\aTime up!"

raw_input("Ready? Press [Enter] to start. ")
timemins = 2
gracemins = 0
try:
    countdown(timemins,gracemins)
except KeyboardInterrupt:
    print cl.BOLD + cl.FAIL + "\nExiting Countdown" + cl.ENDC
    sys.exit(0)


texts: Logging conditionally repetitively in code

texts:
I am using Log4j2 for logging. Multiple operations return success code. If status 0 is received, it means operation is successful, else failed. If operation is successfully, I log "*** is successfully." and if it fails I logs "*** failed with status : " + status. This is kind of repetitive  in code.
public class ReadCallbackManager {

  //Log Object
  private static final Logger LOGGER = LogManager.getLogger(ReadCallbackManager.class);

  private static ReadCallback readCallback;

  private static final int SUCCESS_STATUS = 0;

  public int setHook(final ICallback aCallBack) {

    readCallback = new ReadCallback(aCallBack);

    final int status = readCallback.setHook();

    if (status == SUCCESS_STATUS) {
      LOGGER.info("Read callback hook is set successfully!!!");
    } else {
      LOGGER.info("Read Callback hook set failed with status : " + status);
    }

    return status;

  }

}

So I though to create a wrapper around the Logger class to handle this if else condition as below:
public final class BacStacLogger {

  public static final int SUCCESS_STATUS = 0;

  //Log Object
  private Logger logger;

  public BacStacLogger(final Class<?> className) {
    if (logger == null) {
      logger = LogManager.getLogger(className);
    }
  }

  public void infoHookByStatus(final int status, final String successMessage, final String failureMessage) {
    if (status == SUCCESS_STATUS) {
      logger.info(successMessage);
    } else {
      logger.info(failureMessage + " : " + status);
    }
  }

}

And I have updated my previous code as :
public class ReadCallbackManager {

  //Log Object
  private static final ProjectLogger LOGGER = ProjectLogger(ReadCallbackManager.class);

  private static ReadCallback readCallback;

  public int setHook(final ICallback aCallBack) {

    readCallback = new ReadCallback(aCallBack);

    final int status = readCallback.setHook();

    LOGGER.infoHookByStatus(status, "Read hook set successfully.", "Read hook set failed.");

    return status;

  }

}

Would you please provide your comments on it? Or if required, any improvements?


texts:
This is my version of a LZ-77 lossless compression algorithm for text. It maintains a sliding window of 4095 characters and can pick up patterns up to 15 characters long. Basically, the compressed file is made of tuples (length, pos), with length on 4 bits and pos on 12 bits which makes 2 bytes each time. Besides, if I have to write a character that is not in the window, I set length=0, then I have 4 empty bits and the 8 bits left are used to encode the character.

I've spent a few hours on it correcting little bugs and it seems functional, although it appears not to work entirely for big files (size > window) but I'll correct this later. Anyway I'm not here for algorithm but for code design so tell me what's good or bad about this code, don't hesitate.

Also, I haven't implemented any file-manager system but the functions' names are quite explicit on how to use them.

#include <iostream>
#include <string>
#include <tuple>
#include <bitset>
#include <sstream>
#include <fstream>

using namespace std;

/**
Given two strings s1 and s2, find the longest prefix of s2 that is in s1
and returns the position of the prefix' first character in s1 and its length in a pair

If s1 = "lossless compression in opposition to " and s2 = "lossy compression", the longest prefix is "loss"
and the function returns (0, 4).
*/
pair<int, int> longest_prefix(string s1, string s2)
{
    int pos {0};
    int length {0};

    for(int i = 0; i < s1.size(); i++)
    {
        int l {0};
        while(i+l < s1.size() && l < s2.size() && s1[i+l] == s2[l])
            l++;

        if(l > length)
        {
            pos = i;
            length = l;
        }

        if(i == s1.size() - length || length == s2.size())
            return pair<int,int>(pos, length);
    }

    return pair<int,int>(pos, length);
}

/**
we have a sliding window of fixed size and instead of rewriting text that already is in the window,
we just refer to it with its position in the window and its size
*/
string lz77_compress(string s)
{
    string compressed { "" };
    int window_size { 4095 };
    int pattern_size { 15 };
    int i { 0 };

    while(i < s.size())
    {
        string s1 { i >= window_size ? s.substr(i - window_size, window_size) : s.substr(0, i) };
        string s2 { s.substr(i, min(pattern_size, (int)s.size() - i)) };
        pair<int,int> match = longest_prefix(s1, s2); // fst = pos; snd = length

        if(match.second == 0) // length = 0: no match, we just add a char (0, char)
        {
            compressed += (char)0;
            compressed += s[i];

            i++;
        }
        else // match, then we add (pos, length)
        {
            bitset<4> length(match.second);
            bitset<12> pos(match.first);
            bitset<16> concat(length.to_string() + pos.to_string()); // change a 4-bit and a 12-bit number into two 8-bits numbers
            bitset<8> bit1(concat.to_string().substr(0,8));
            bitset<8> bit2(concat.to_string().substr(8,8));
            compressed += (char)bit1.to_ulong();
            compressed += (char)bit2.to_ulong();

            i += match.second;
        }
   }

    return compressed;
}

string lz77_decompress(string compressed)
{
    string s { "" };
    int window_size { 4095 };

    for(int i = 0; i < compressed.size(); i += 2)
    {
        bitset<8> bit1(compressed[i]);
        bitset<8> bit2(compressed[i+1]);
        bitset<16> concat(bit1.to_string() + bit2.to_string());
        bitset<4> length_b(concat.to_string().substr(0,4));
        int length = length_b.to_ulong();

        if(length == 0)
        {
            bitset<8> c(concat.to_string().substr(8, 8));
            s += (char)c.to_ulong();
        }
        else
        {
            bitset<12> pos(concat.to_string().substr(4, 12));

            s += s.substr(max(0, i - window_size) + pos.to_ulong(), length);
        }
   }

    return s;
}


texts: Ranking players in a league by sorting the contents of an OrderedDict

texts:
I'm new to python.  I'm having second thoughts on my approach to this problem:

The LeagueTable class tracks the score of each player in a league. After each game, the player records their score with the record_result function.
The player's rank in the league is calculated using the following
logic:

The player with the highest score is ranked first (rank 1). The player with the lowest score is ranked last.
If two players are tied on score, then the player who has played the fewest games is ranked higher.
If two players are tied on score and number of games played, then the player who was first in the list of players is ranked higher.

Implement the player_rank function that returns the player at the
given rank.
example:
table = LeagueTable(['Mike', 'Chris', 'Arnold'])
table.record_result('Mike', 2)
table.record_result('Mike', 3)
table.record_result('Arnold', 5)
table.record_result('Chris', 5)
print(table.player_rank(1))

All players have the same score. However, Arnold and Chris have played fewer games than Mike, and as Chris is before Arnold in the list of players, he is ranked first. Therefore, the code above should display "Chris".

I have a solution, but I want to know if there is a more optimised approach to this.
from collections import Counter
from collections import OrderedDict

class LeagueTable:
    def __init__(self, players):
        self.standings = OrderedDict([(player, Counter()) for player in players])
    def record_result(self, player, score):
        self.standings[player]['games_played'] += 1
        self.standings[player]['score'] += int(score)# print(self.standings)# print("")
    def player_rank(self, rank): #res = OrderedDict()
        x=self.standings
        d=self.standings
        def swap_list(xl,co):
            xl[co],xl[co+3]=xl[co+3],xl[co]
            xl[co+1],xl[co+4]=xl[co+4],xl[co+1]
            xl[co+2],xl[co+5]=xl[co+5],xl[co+2]
            return(xl,co)

        player_list=[]
        lc=len(x)
        lc1=lc
        lc=lc*3
        for p,c in x.items():
            player_list.append(p)
            player_list.append(c["score"])
            player_list.append(c["games_played"])
        for j in range(lc1):
            for i in range(0,lc-3,3):
                # print(i+4)
                if (player_list[i+1] < player_list[i+4]):
                    swap_list(player_list,i)
                elif (player_list[i+1]==player_list[i+4]):
                    if(player_list[i+2]>player_list[i+5]):
                        swap_list(player_list,i)
                    elif(player_list[i+2]==player_list[i+5]):
                        pass

        return(player_list[(rank-1)*3])

table = LeagueTable(['Mike', 'Chris', 'Arnold'])
table.record_result('Mike', 2)
table.record_result('Mike', 3)
table.record_result('Arnold', 5)
table.record_result('Chris', 5)
rk=int(input("enter rank \n"))
print(table.player_rank(rk))


texts:
I know that Python has a built-in list data structure, but I want to implement my own linked list and stack data structures for practice.

I have three classes Node, Stack and List.

The code works, but I feel there is a better way to do this.

I would like to have some general critique.

class Node:
    def __init__(self):
        self.item = None
        self.link = None

class Stack:
    def __init__(self):
        self.top = 0
        self.head = Node()

    def isEmpty(self):
        return top == 0

    def push(self, item):
        oldHead = self.head
        self.head = Node()
        self.head.item = item
        self.head.link = oldHead
        self.top += 1

    def pop(self):
        item = self.head.item
        self.head = self.head.link
        self.top -= 1
        return item

class List:
    def __init__(self):
        self.top = 0
        self.head = Node()

    def get(self, *args):
        if not args:
            return self.head.item
        elif type(args[0]) is int:
            pos = args[0]
            current = self.head
            count = 0
            while count < pos - 1 and current.link != None:
                current = current.link
                count += 1
           return current.item
       else:
            raise TypeError

    def pop(self, *args):
        if not args:
            item = self.head.item
            head = self.head.link
            return item

    def append(self, item):
        oldhead = self.head
        self.head = Node()
        self.head.item = item
        self.head.link = oldhead
        self.top += 1

    def insert(self, item, pos):
        current = self.head
        count = 0
        while count < pos - 1 and current.link != None:
            current = current.link
            count += 1
        node = Node()
        node.item = item

        node.link = current.link
        current.link = node
        self.top += 1


texts: Bash script to truncate subject line of incoming email

texts:
I'm going to put this script into production in a mail server /etc/aliases file: we have a system that receives email but the subject line must be limited to a certain size. The proposed usage in the aliases file:

alias_name: "| email_filter.sh -s 200 actual.recipient@example.com"

It will be deployed on a gnu/linux system. I'd appreciate any feedback.

#!/bin/bash
shopt -s extglob

usage="$(basename $BASH_SOURCE) [-h] [-s n] recipient"
where="where: -s n == truncate the subject to n characters"
subject_length=''

while getopts :hs: opt; do
    case $opt in
        h) echo "$usage"; echo "$where"; exit ;;
        s) subject_length=$OPTARG ;;
        *) echo "Error: $usage" >&2; exit 1 ;;
    esac
done
shift $((OPTIND - 1))

# validation
if [[ "$#" -eq 1 ]]; then
    recipient=$1
else
    echo "Error: $usage" >&2
    exit 1
fi
if [[ -n $subject_length ]] && [[ $subject_length != +([0-9]) ]]; then
    echo "Error: subject length must be a whole number"
    exit 1
fi

sed_filters=()
if [[ -n $subject_length ]]; then
    sed_filters+=( -e "s/^(Subject: .{1,$subject_length}).*/\1/" )
fi
# other filters can go here

if [[ ${#sed_filters[@]} > 0 ]]; then
    cmd=( sed -E "${sed_filters[@]}" )
else
    # no command line filters given
    cmd=( cat )
fi

# now, filter the incoming email (on stdin) and pass to sendmail
"${cmd[@]}" | /usr/sbin/sendmail -oi "$recipient"


texts:
ok spent ages on this simple problem (I'm not good at XML) below code is probably self explanatory and it works, but i think this could be done a lot easier

Sample XML

<data>
        <id name="ch01">
                <channel>test channel 1</channel>
                <gpio>3</gpio>
                <cont>front</cont>
        </id>

        <id name="ch02">
                <channel>test channel 2</channel>
                <gpio>5</gpio>
                <cont>back</cont>
        </id>
</data>

The code used, which I eventually got working after reading a few posts on here:

from xml.dom import minidom
dom = minidom.parse('/usr/local/sbin/logger/chaninfo_test.xml')
id=dom.getElementsByTagName('id')
for node in id:
        chanid=node.getAttribute('name')
        print chanid
        clist=node.getElementsByTagName('channel')
        for c in clist:
                print c.childNodes[0].nodeValue

        glist=node.getElementsByTagName('gpio')
        for g in glist:
                print g.childNodes[0].nodeValue

        colist=node.getElementsByTagName('cont')
        for co in colist:
                print co.childNodes[0].nodeValue
        print

Can this be improved or cleaned up? The XML will increase in size but contents won't change, multiple IDs with one channel, gpis and cont field each.

The first thing that I'm thinking about is combining is and name is channel id='name', etc.


texts:
When one writes c++ code to manipulate LinkedLists, Trees, etc. one creates a tmp pointer that points to the start/root and changes that pointer as one traverses along.
What would be the equivalent way of doing that in smart pointers?
For example, I wrote a Trie code using unique_ptrs to understand how to pass pointers around. To make the program work, I had to dive inside the smart pointer and access the underlying raw pointer. Is this the right way of doing things? Or is it infact possible to pass the unique_ptr around. I believe std::move will not be a good idea here since it will a destructive operation.
My code is as follows. Special call out to .get() op to get the raw pointer.
#include <iostream>
#include <memory>
#include <map>

class TrieNode
{
public:
    bool isLeaf{ false };
    std::map<char, std::unique_ptr<TrieNode>> children;
};

class Trie
{
    std::unique_ptr<TrieNode> root{nullptr};

public:
    Trie()
    {
        root.reset(new TrieNode());
    }

    void insert(const std::string& word)
    {
        auto node = root.get();
        for (auto ch : word)
        {
            if (node->children.find(ch) == node->children.end())
            {
                node->children[ch] = std::make_unique<TrieNode>();
            }
            node = node->children[ch].get();
        }
        node->isLeaf = true;
    }

    bool search(const std::string& word) const
    {
        auto node = root.get();
        for (auto ch : word)
        {
            if (node->children.find(ch) == node->children.end())
            {
                return false;
            }
            node = node->children[ch].get();
        }
        return (node && node->isLeaf);
    }
};

int main()
{
    Trie trie;
    trie.insert("application");
    std::cout << "does apple there in the trie? " << (trie.startsWith("app") ? "yes" : "no") << std::endl;
    std::cout << "is application there in the trie? " << (trie.search("apple") ? "yes" : "no") << std::endl;

    return 0;
}
```