texts: Ways to differentiate comments in source code (PyCharm)

texts:
I want to differentiate between comments I make for

(1) myself,
(2) team members,
(3) on business rules,
(4) on watchout notes for hardcoded constants,
(5) on ideas for improvements, and
(6) on general flow of the code.

Right now all my comments look the same.

I'm open to any other tools. I don't know how bookmarking works, or if I really should be adding debug points as a "TODO" (the auto "TODO" font is weird and intrusive), but I'm open to anything.

I use PyCharm.

As for what this code accomplishes, it takes in an input of data on students who tested for a Science exam and filters out the students with errors. That means errors in scoring that a school needs to resolve. Therefore, it gives back a highly filtered list of students (200 rows) from a much larger (40,000 rows) dataset.

import pandas as pd
import numpy as np
import xlrd
import openpyxl
import win32com.client
import paths
import utils as u

'''
Extraction
'''
# (4) SXRX row starts at row 5
# (4) SXRX has 19 rows at its footer
SXRX_df = pd.read_excel(paths.corr_outputs_path, sheet_name='SXRX', header=4, skipfooter=19)
# (4) drop first row because it's blank
SXRX_df = SXRX_df[1:]

# (5) better to do writer?
corr_outputs_df = pd.read_excel(paths.corr_outputs_path, sheet_name='Correct Outputs')

'''
Operations
'''
def reason_incomplete(school_follow_up, site_follow_up, errors):
    """
    We expect mainly P.1 Not Scanned. Teacher errors, while rare, will still exist (especially in Charter schools)

    :param school_follow_up: RCSD school follow up
    :param site_follow_up: RCSD site follow up
    :param errors: RCSD errors, can come in the format of 046/57, sometimes none
    :return: text according to business rules
    """

    # (2) explicitly cast errors as string, because sometimes it will come in as a float and the "in errors" syntax will
    # not work
    errors = str(errors)
    if school_follow_up == 'P.1 Not Scanned':
        return 'P.1 Not Scanned'
    elif site_follow_up == 'FOLLOW UP':
        return 'P.2 Not Scanned'
    elif '40' in errors:
        return 'Abs + Response'
    elif '41' in errors:
        return 'Multiples in Student Answers'
    elif '47' in errors:
        return 'Omits in Teacher Answers'
    elif '46' in errors:
        return 'Multiples in Teacher Answers'
    else:
        return None

df = pd.DataFrame()

# (1) genericize later

df['Last Name'] = SXRX_df['Last Name']

df['First Name'] = SXRX_df['First Name']

df['Student ID'] = SXRX_df['Student Id']

df['School DBN'] = SXRX_df['School DBN']

df['Ofc Cls'] = SXRX_df['Cls']

df['Section'] = SXRX_df['Section']

df['Final Score'] = SXRX_df['Score.1']

df['Reason Incomplete'] = np.vectorize(reason_incomplete)(SXRX_df['Follow Up'],
                                                          SXRX_df['Follow Up.1'],
                                                          SXRX_df['Errors'])

df['Exam'] = 'SXRX'

# (6) filter out Reason Incomplete Nones

# (6) filter out Final Score INV and MIS

# (6) reorder columns
df = df.reindex(columns=corr_outputs_df.columns)


texts: Divide a set of strings into those which contain "a" and those which don't

texts:
I am beginning to learn Python on my own through edX and I was given this basic problem: "Given a list of cities, separate the list into two lists, namely one with cities containing the letter 'a' in their name and one with cities not containing the letter 'a'."

This is my approach. It works, but I can't help but feel like there is a much more concise way to get this result. If anybody could offer some other methods I would be interested:

cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]

a_city, no_a_city = [],[]
for city in cities:
    for x in range(0, len(city)):
        if city[x] == "a":
            a_city.append(city)
            break
        else:
            if x == len(city) - 1:
                no_a_city.append(city)

print("a_city:", a_city)
print("no_a_city:", no_a_city)

I am also interested in learning more about the interaction between nested loops/conditionals and complexity if anybody has some resources.


texts: Test whether a number is a Harshad Number

texts:
A little code I wrote that will check if the entered 4-digit number is Harshad or not (Harshad number is one which divided by the sum of its digits will leave no remainder, special Harshad is the same but will also work with flipped sum of digits, example - 1729/19 (19 is the sum of digits) and when flipped 1729/91 will leave no remainder as well).

I would love to see how it could become better (I'm still new so was limited with the commands I could've used).

; Harshad.asm - check if input from user (4 digits, 1000-9999) is a Harshad number and if so, check if it's a "special" Harshad number
;
    .MODEL SMALL
    .STACK 100h
    .DATA
RequestStr     DB 'Enter a 4 digit number (1000-9999):',13,10,'$'
IsHarshad      DB ' is a Harshad number.',13,10,'$'
SpecialHarshad DB 'It is also a special Harshad number.',13,10,'$'
NotHarshad     DB ' is not a Harshad number',13,10,'$'
IncorrectInput DB 13,10,'Input is incorrect.',13,10,'$'
Num            DW ? ;Will fit a "word" size (16 bits)
DigitSum       DW ? ;Sum of digits
TEN            DW 10
TENbyte        DB 10
Temp           DB ? ;Used to check if number is also special Harshad during the div process
Temp2          DB ? ;Used with special Harshad div process
;
     .CODE
     MOV AX,@DATA                ;DS can be written to only through a register
     MOV DS,AX                   ;Set DS to point to data segment
     MOV AH,9                    ;Set print option for INT 21h
     MOV DX,OFFSET RequestStr    ;Set DS:DX to point to RequestString
     INT 21h                     ;Print RequestStr
;
NumberInput:
    ;First digit
    MOV AH,1        ;Set scanning (input) option for INT 21h
    INT 21h         ;Scan first digit
    MOV DX,0
    SUB AL,'0'      ;Converting from ascii value to numeral value
    CMP AL,1        ;First digit must be between 1 and 9 in order for the number to be of 4 digits
    JB WrongInput   ;Otherwise jump to WrongInput label
    CMP AL,9
    JA WrongInput
    MOV AH,0
    MOV DigitSum,AX ;Store only first digit's value at the variable DigitSum
    MUL TEN         ;Multiply AX by 10
    MOV Num,AX
    ;Second digit
    MOV AX,0
    MOV AH,1
    INT 21h
    SUB AL,'0'
    CMP AL,0
    JB WrongInput
    CMP AL,9
    JA WrongInput
    MOV AH,0
    ADD DigitSum,AX ;Add only second's digit value to DigitSum
    ADD Num,AX      ;Add AX's value (which has been multiplied by 10 with the first digit) to Num variable
    MOV AX,0
    MOV AX,Num      ;Move new Num's value to AX to multiply it by 10
    MUL TEN
    MOV Num,AX
    ;Third digit
    MOV AX,0
    MOV AH,1
    INT 21h
    SUB AL,'0'
    CMP AL,0
    JB WrongInput
    CMP AL,9
    JA WrongInput
    MOV AH,0
    ADD DigitSum,AX
    ADD Num,AX
    MOV AX,0
    MOV AX,Num
    MUL TEN
    MOV Num,AX
    ;Forth digit
    MOV AX,0
    MOV AH,1
    INT 21h
    SUB AL,'0'
    CMP AL,0
    JB WrongInput
    CMP AL,9
    JA WrongInput
    MOV AH,0
    ADD DigitSum,AX ;Now DigitSum contains the sum of each of the 4 digits in the number
    ADD Num,AX ;Num contains full 4 digits number
    JMP CheckHarshad
WrongInput:
    MOV AH,9
    MOV DX,OFFSET IncorrectInput
    INT 21h
    JMP CodeEnd
CheckHarshad:
    MOV AX,0
    MOV DX,0
    MOV AX,Num
    DIV DigitSum ;Number will be stored in AX and the remainder in DX
    CMP DX,0 ;Check if there is remainder or not
    JE CheckSpecialHarshad
    MOV AH,9
    MOV DX,OFFSET NotHarshad
    INT 21h
    JMP CodeEnd
CheckSpecialHarshad:
    MOV AH,9
    MOV DX, OFFSET IsHarshad
    INT 21h
    MOV AX,0
    MOV AX,DigitSum
    DIV TENbyte
    MOV Temp,AL
    MOV Temp2,AH
    MOV AX,0
    MOV AL,Temp2
    MUL TENbyte
    ADD AL,Temp
    MOV Temp2,AL ;Temp2 now has the DigitSum number flipped
    MOV AX,0
    MOV AX,Num
    DIV Temp2
    CMP AH,0
    JNE CodeEnd
    MOV DX,OFFSET SpecialHarshad
    MOV AH,9
    INT 21h
CodeEnd:
    MOV AH,4Ch
    INT 21h
    END


texts:
As part of one of my AP Computer Science labs, I was required to write a function to determine whether a year was a leap year or not. Included as comments are a few reasons why I did things, as well as a more detailed version of the rules for leap years. Is there anything I could do better or have forgotten?

/**
 * Returns if the current year is a leap year
 */
private boolean isLeapYear()
{
    // No leap years occured before 1582 because that is when they were added to the calendar
    if(year > 1582)
    {
        // All code past here only executed when year mod 4 is true
        if(year % 4 != 0)
        {
            return false;
        }

        // Makes sure that it does not register the beginning of centuries as leap years
        // unless they actually are.
        else if(year % 100 == 0 && year % 400 != 0)
        {
            return false;
        }
        // Also is the same as checking for mod 4 and mod 100, since they are factors of 400
        else if(year % 400 == 0)
        {
            return true;
        }
        else
        {
            return true;
        }

        /*
        • A year that is not divisible by 4. - NOT LEAP YEAR

        • A year that is divisible by 4 but not divisible by 100 or 400. - LEAP YEAR

        • A year that is divisible by 4 and 100 but not 400. - NOT LEAP YEAR

        • A year that is divisible by 4 and 100 and 400. - LEAP YEAR

        • A year prior to 1582 that is a leap year. - NOT A LEAP YEAR

        • A year prior to 1582 that is not a leap year. - NOT A LEAP YEAR */
    }
    return false;
}


texts:
I made a little drawing program in OOP.
The game consists of a canvas which is basically a 2d array where the user can draw various shapes on it. There can be multiple shapes overlapped on top of each other at the same spot. The shape that was drawn the last would appear on the top of the canvas and that is what gets printed out when we print the canvas - only those shapes at the top would be printed out.
Here I have two classes Rectangle and Canvas

class Rectangle {
  constructor(positions) {
    this.positions = positions
    this.character = Symbol()
  }

  move(dx, dy) {
    for (const position of this.positions) {
      const nx = position[0] + dx
      const ny = position[1] + dy
      position[0] = nx
      position[1] = ny
    }
  }
}

class Canvas {
  constructor(size) {
    this.canvas = Array.from({ length: size }, () =>
      Array.from({ length: size }, () => null)
    )
  }

  draw(rectangle) {
    const { positions, character } = rectangle
    for (const [row, col] of positions) {
      if (this.canvas[row][col] === null) this.canvas[row][col] = [character]
      else this.canvas[row][col].push(character)
    }
  }

  remove(rectangle) {
    const { positions, character } = rectangle
    if (positions.length === 0) return
    for (const position of positions) {
      const list = this.canvas[position[0]][position[1]]
      list.splice(list.indexOf(character), 1)
    }
  }

  print(palette) {
    let rows = ''

    for (let i = 0; i < this.canvas.length; i++) {
      for (let j = 0; j < this.canvas[i].length; j++) {
        if (this.canvas[i][j] === null || this.canvas[i][j].length === 0) {
          rows += '*' // empty
        } else {
          rows += palette[this.canvas[i][j][this.canvas[i][j].length - 1]]
        }
      }

      rows += '\n'
    }
    console.log(rows)
  }

  moveToTop(rectangle) {
    this.remove(rectangle)
    this.draw(rectangle)
  }

  drag(startPosition, endPosition, map) {
    const list = this.canvas[startPosition[0]][startPosition[1]]
    if (list?.length === 0) return

    const character = list[list.length - 1]

    const rectangle = map[character]
    const dx = endPosition[0] - startPosition[0]
    const dy = endPosition[1] - startPosition[1]
    this.remove(rectangle)
    rectangle.move(dx, dy)
    this.draw(rectangle)
  }
}

And I have a map that maps the Rectangle's character to that Rectangle instance. and another object called palette which tells the canvas how that shape or pixel would look like when being printed (initially palette is part of canvas but I feel like I should decouple them so canvas only holds the state of the current canvas and is not opinionated on how the shapes should look like when they are printed out).
const rectangle1 = new Rectangle(
  [
    [0, 1],
    [1, 2],
    [0, 2],
  ]
)
const rectangle2 = new Rectangle(
  [
    [0, 0],
    [0, 1],
    [1, 0],
  ]
)
const rectangle3 = new Rectangle([[0, 0]])

const palette = {
  [rectangle1.character]: 'A',
  [rectangle2.character]: 'B',
  [rectangle3.character]: 'C',
}

const map = {
  [rectangle1.character]: rectangle1,
  [rectangle2.character]: rectangle2,
  [rectangle3.character]: rectangle3,
}

here is the link to a live demo
Please feel free to give me any feedback. Specifically, I would love to know:

if there is a better to approach the OO design here? Did I do a good job at separating the concerns here? Does every class have the methods here?
I think I need some help to refactor the map and palette. Specifically map, it is manually constructed right now. I am not sure if I need to create two classes for them.
Is there any alternatives to approach implementing such a canvas? What are some of the pros and cons?


texts: Streamlining series of try-except + if-statements for faster loop processing in Python

texts:
I'm processing strings using regexes in a bunch of files in a directory. To each line in a file, I apply a series of try-statements to match a pattern and if they do, then I transform the input. After I have analyzed each line, I write it to a new file. I have a lot of these try-else followed by if-statements (I only included two here as an illustration). My issue here is that after processing a few files, the script slows down so much that it almost stalls the process completely. I don't know what in my code is causing the slowing down but I have a feeling it is the combination of try-else + if-statements. How can I streamline the transformations so that the data is processed at a reasonable speed?

Or is it that I need a more efficient iterator that does not tax memory to the same extent?

Any feedback would be much appreciated!

import re
import glob

fileCounter = 0

for infile in glob.iglob(r'\input-files\*.txt'):

    fileCounter += 1
    outfile = r'\output-files\output_%s.txt' % fileCounter

    with open(infile, "rb") as inList, open(outfile, "wb") as outlist:

        for inline in inlist:

            inword = inline.strip('\r\n')

            #apply some text transformations
            #Transformation #1
            try: result = re.match('^[AEIOUYaeiouy]([bcćdfghjklłmnńprsśtwzżź]|rz|sz|cz|dz|dż|dź|ch)[aąeęioóuy](.*\[=\].*)*', inword).group()
            except: result = None

            if result == inword:
                inword = re.sub('(?<=^[AEIOUYaeiouy])(?=([bcćdfghjklłmnńprsśtwzżź]|rz|sz|cz|dz|dż|dź|ch)[aąeęioóuy])', '[=]', wbWord)

            #Transformation #2 etc.
            try: result = re.match('(.*\[=\].*)*(\w?\w?)[AEIOUYaąeęioóuy]\[=\][ćsśz][ptkbdg][aąeęioóuyrfw](.*\[=\].*)*', inword).group()
            except: result = None

            if result == inword:
                inword =  re.sub('(?<=[AEIOUYaąeęioóuy])\[=\](?=[ćsśz][ptkbdg][aąeęioóuyrfw])', '', inword)
                inword =  re.sub('(?<=[AEIOUYaąeęioóuy][ćsśz])(?=[ptkbdg][aąeęioóuyrfw])', '[=]', inword)

            outline = inword + "\n"
            outlist.write(outline)

    print "Processed file number %s" % fileCounter
print "*** Processing completed ***"


texts: Fill a DataSet with nearly 20,0000 records using SqlDataAdapter

texts:
I want to fill a DataSet with 20,0000 records using a SqlDataAdapter by using this code:

adapter.Fill(dataset);

If I fill a DataSet this way it takes a long time. Is there anything wrong with this?

This is my code:

connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
connection.Open();

SqlCommand command = new SqlCommand("sp_DMS_Report_Generate", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@XML", reportCriteria.XML);
command.CommandTimeout = 1000;

SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(resultSet);

return resultSet.Tables[0];


texts:
I'm working on this problem,

Problem statement,

  Given a Binary Tree, find vertical sum of the nodes that are in same vertical line. Print all sums through different vertical lines.

  Examples:

     1
   /   \
  2      3
 / \    / \
4   5  6   7

  The tree has 5 vertical lines

  Vertical-Line-1 has only one node 4 => vertical sum is 4
  Vertical-Line-2: has only one node 2=> vertical sum is 2
  Vertical-Line-3: has three nodes: 1,5,6 => vertical sum is 1+5+6 = 12
  Vertical-Line-4: has only one node 3 => vertical sum is 3
  Vertical-Line-5: has only one node 7 => vertical sum is 7

  So expected output is 4, 2, 12, 3 and 7

I’m wondering if there is a way to not write recursive code:

from collections import defaultdict
class TreeNode:
    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right
    def vertical_traverse(self, level):
        stack = []
        result = defaultdict(list) # key: level, value: list of node identifier
        stack.append((self,level))
        while len(stack) > 0:
            node, level = stack.pop(-1)
            result[level].append(node.value)
            if node.left:
                stack.append((node.left, level-1))
            if node.right:
                stack.append((node.right, level+1))
        return result

if __name__ == "__main__":
    root = TreeNode(1, TreeNode(2, TreeNode(4, None, None), TreeNode(5, None, None)), TreeNode(3, TreeNode(6, None, None), TreeNode(7, None, None)))
    result = root.vertical_traverse(0)
    for k,v in result.items():
        print k, sum(v)


texts:
While I have never had to swap two files I have always wondered if there was command for swapping two files and recently I decided to see if there was one. Eventually I found out that there wasn't one and as a result I decided to create one.
Here is the code: main.cc
#include <iostream>
#include <filesystem>
#include <cstring>
#include <cassert>

static auto print_help() -> void {
    std::cout << "Usage: swap [file1] [file2]\n";
    std::cout << "swaps the contents of file1 and file2\n";
    std::cout << "use swap --help to print this message\n";
}

static auto validate_files(const std::filesystem::path& file1_path, const std::filesystem::path& file2_path) -> void {
    {
        /* check if file exists */
        const auto file1_exists = std::filesystem::exists(file1_path);
        const auto file2_exists = std::filesystem::exists(file2_path);
        const auto exists = file1_exists && file2_exists;

        if (!exists) {
            if (!file1_exists) std::cerr << "cannot find file " << file1_path << '\n';
            if (!file2_exists) std::cerr << "cannot find file " << file2_path << '\n';
            exit(EXIT_FAILURE);
        }
    }

    {
        if (file1_path == file2_path) {
            std::cerr << "swaping the same two files does nothing\n";
            exit(EXIT_SUCCESS);
        }
    }
}

static auto get_temp_filename(char* template_name) -> void {
    /* tmpnam_s does not work on linux */
#if defined(WIN32) || defined(_WIN32)
    errno_t err = tmpnam_s(template_name, L_tmpnam);
    assert(!err);
#else
    int err = mkstemp(template_name);
    assert(err != -1);
#endif
}

int main(int argc, char** argv) {
    std::ios::sync_with_stdio(false);
    switch (argc) {
        case 2: {
            /* convert the second arg to upper case */
            std::transform(argv[1],
                argv[1] + strlen(argv[1]),
                argv[1],
                ::toupper);
            if (!strcmp(argv[1], "--HELP")) {
                print_help();
                return EXIT_SUCCESS;
            }
            else {
                std::cerr << "Invalid args see --help for usage\n";
                return EXIT_FAILURE;
            }
        }
        case 3:
            break;
        default: {
            std::cerr << "Invalid args see --help for usage\n";
            return EXIT_FAILURE;
        }
    }
    const auto file1_path = std::filesystem::path{ argv[1] };
    const auto file2_path = std::filesystem::path{ argv[2] };

    validate_files(file1_path, file2_path);
    char temp_filename[L_tmpnam] = "XXXXXX";
    get_temp_filename(temp_filename);
    const auto temp_filepath = std::filesystem::path{ temp_filename };
    /* move-swap the files instead of copy-swaping */
    /* renaming a file is the same as moving it */
    std::filesystem::rename(file1_path, temp_filepath);
    std::filesystem::rename(file2_path, file1_path);
    std::filesystem::rename(temp_filepath, file2_path);
}

Here is an example of usage:
swap doc1.txt doc2.txt


texts:
I am trying to create a horizontal accordion using jQuery. The code works fine, but I just want to know if my approach is correct and if there are any improvements I could make to the existing code.

$(document).ready(function () {
$("ul li").children(".Acc_Content").animate({ width: '0px' },{ duration: 1000, queue: false }).addClass("remove");
$(".Acc_Content").first().animate({ width: '600px' }, { duration: 1000, queue: false }).removeClass("remove").addClass("add");
$(".Acc_Name").click(function () {
$(".Acc_Content").animate({ width: '0px' }, { duration: 1000, queue: false }).removeClass("add").addClass("remove");
$(this).next(".Acc_Content").animate({ width: '600px' }, { duration: 1000, queue: false }).removeClass("remove").addClass("add");
});
});
body{font-family: Arial;}
ul{list-style: none;}
.Acc_Name{background-color: #808080;color: white;border:1px solid #000;margin:0px 1px;height:150px;width:30px;float:left;}
.Acc_Name span{margin:5px;float:left;line-height:20px;font-weight:bold;
-moz-transform:rotate(270deg);
-webkit-transform:rotate(270deg)}
.Acc_Content{float:left;height:150px;border:1px solid #000;}
.add{display:block;}
.remove{display:none;}
p{margin: 10px;}

    One

Hello Test1

    Two

Hello Test2

    Three

Hello Test3

    Four

Hello Test4


texts: Getting days count from start day and number of day for a group of days in Java 8

texts:
I have a List of Objects containing following structure

public class DaySpan{
 private LocalDate date;
 private Integer numberOfDays;
..
..
//getters & setters
}

Lets say the list contains 3 instances of above classes with data (date is in dd/mm/yyyy)

04/02/2020 3
03/02/2020 5
01/02/2020 1

Then I need ouput for count of each day that is getting overlapped in number of days
For example the first record will translate to 04/02/2020, 05/02/2020, 06/02/2020
Second record will translate to 03/02/2020, 04/02/2020, 05/02/2020, 06/02/2020, 07/02/2019 and the final record will translate to 01/02/2020
So the output will be

01/02/2020 - 1
03/02/2020 - 1
04/02/2020 - 2
05/02/2020 - 2
06/02/2020 - 2
07/02/2020 - 1

The code I have written is

   public void getDayCount(List<DaySpan> daySpans){

    Map<Object, Long> days = new HashMap();
    days = daySpans.stream()
            .map(this::getDays)
            .collect(
                Collector.of(ArrayList::new,
                    List::addAll,(left, right) -> { left.addAll(right); return left; }
                    )
                )
            .stream()
            .collect(
                Collectors.groupingBy(Function.identity(), Collectors.counting()));

    days.entrySet().forEach(System.out::println);
  }

  public List<LocalDate> getDays(DaySpan daySpan) {
    return Stream.iterate(daySpan.getStartDate(), d -> d.plusDays(1)).limit(daySpan.getNumberOfDays())
        .collect(Collectors.toList());
  }

Is there a better way?


texts:
The following function appends a tuple to two Maybe [a]'s.

tupleToMaybeList :: (a, a) -> Maybe [a] -> Maybe [a] -> Maybe [a]
tupleToMaybeList (a, b) cs ds = do
    x  <- return a
    y  <- return b
    xs <- cs
    ys <- ds
    return ((x : y : xs) ++ ys)

Please critique it for idiomatic Haskell-ness.


texts:
This function arguably has little use as it's so simple, but I'm writing a web application with a lot of SQL statements littered all over the place and I thought this function might reduce code duplication and improve readability. I'm wondering if what I'm doing is a good idea, what the "best practice" is here, and any suggestions to make the function more robust and secure. It seems like attempts to further facilitate querying with PDO often trades efficiency or security for ease of use, which I'm trying to avoid.

<?php
// Configs
define("HOST", "localhost");
define("USER", "username");
define("PASS", "password");
define("NAME", "database");

// Connect to database
try {
  $db = new PDO("mysql:host=".HOST.";dbname=".NAME.";charset=utf8", "".USER."", "".PASS."");
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  // PDO fetch docs: http://php.net/manual/en/pdostatement.fetch.php
  $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
  // User friendly page to show on connection error
  include 'includes/sql-error.php';
  die();
}

// Simple function to handle PDO prepared statements
function sql($db, $q, $params, $return) {
  $stmt = $db->prepare($q);
  $stmt->execute($params);
  if ($return == "rows") {
    return $stmt->fetchAll();
  }
  elseif ($return == "count") {
    return $stmt->rowCount();
  }
}

?>

The usage of this function would look something like this

<?php
// With SELECT
// Call function
$rows = sql($db, "SELECT * FROM table WHERE id = ?", array($id), "rows");
// Get results
foreach($rows as $row) {
    echo $row['field1'].' '.$row['field2']; //etc...
}

// With INSERT
// Call function
sql($db, "INSERT INTO table (field1, field2, field3) VALUES (?, ?, ?)", array($id, $name, $pass));

// With UPDATE
// Call function
sql($db, "UPDATE table SET name = ? WHERE id = ?", array($name, $id));

// With DELETE
// Call function
sql($db, "DELETE FROM table WHERE id = ?", array($id));
?>


texts: Social network broadcast message algorithm

texts:
Working on below problem and post problem and my current code. My idea is to always iterate from the minimal in-degree node which has not been visited before. Then based on this node to do a BFS. I am not sure if there are better ways to implement in terms of performance. If you also find any other code issues or bugs, please point them out as well.

Problem,

Let's suppose that I'd like to spread a promotion message across all people in Twitter. Assuming the ideal case, if a person tweets a message, then every follower will re-tweet the message.

You need to find the minimum number of people to reach out (for example, who doesn't follow anyone etc) so that your promotion message is spread out across entire network in Twitter.

Also, we need to consider loops like, if A follows B, B follows C, C follows D, D follows A (A -> B -> C -> D -> A) then reaching only one of them is sufficient to spread your message.

Input: A 2x2 matrix like below. In this case, a follows b, b follows c, c follows a.

   a b c
a  1 1 0
b  0 1 1
c  1 0 1

Output: List of people to be reached to spread out message across everyone in the network.

My code ,

# below two connectMatrix are just two test cases, you can use either one for the testing, or use new ones
connectMatrix=[
    [1,1,0,0],
    [1,1,1,0],
    [0,0,1,1],
    [1,0,0,1]
]

connectMatrix=[
    [1,1,0],
    [0,1,1],
    [1,0,1]
]
inDegree = [0] * len(connectMatrix)
visited = [0] * len(connectMatrix)
allVisited = 0

# if (x,y) == 1, it means x follows y
# if (x,y) == 1, it means y can send message to x

def BFS(connectMatrix, visitedPersons, personID):
    global allVisited
    visitQueue = []
    result = []
    visitQueue.append(personID)
    result.append(personID)
    visitedPersons[personID]=1
    allVisited += 1
    while len(visitQueue) > 0:
        personID = visitQueue.pop(0)
        # downstream: check what other person this person can reach to
        for i in range(len(connectMatrix)):
            if connectMatrix[i][personID] == 1 and visitedPersons[i] == 0:
                visitedPersons[i] = 1
                visitQueue.append(i)
                allVisited += 1
                result.append(i)

    return result

if __name__ == "__main__":

    for j in range (len(connectMatrix)):
        degree = 0
        for i in range(len(connectMatrix)):
            if connectMatrix[i][j] == 1:
                degree += 1
        inDegree[j] = degree

    results = []

    # find non-visited person with minimal in-degree
    while allVisited < len(connectMatrix):
        minDegree = max(inDegree) + 1
        nextIndex = -1
        # find next person to iterate
        for i in range(len(connectMatrix)):
            if (visited[i] == 0) and inDegree[i] < minDegree:
                nextIndex = i
                minDegree = inDegree[i]
        results.append(nextIndex)
        print BFS(connectMatrix, visited, nextIndex)

    print 'persons to send message, ', results


texts:
I'm fairly new at programming and made a tic tac toe game to see if I could handle it. I managed to get it to work but I feel like my code is faaaar from perfection. I wanted to ask for some advices on how to improve it

class Game:

    def __init__(self):
        self.board = [0, 1, 2, 3, 4, 5, 6, 7, 8]
        self.win_conditions = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 4, 8), (2, 4, 6), (0, 3, 6), (1, 4, 7), (2, 5, 8))
        self.moves_count = 0

    def create_board(self):
        print()
        print(self.board[0], self.board[1], self.board[2])
        print(self.board[3], self.board[4], self.board[5])
        print(self.board[6], self.board[7], self.board[8])
        print()

    def p1(self):
            try:
                print("PLAYER X")
                question = int(input("Type where your X should be placed\n"))
                if self.board[question] != "X" and self.board[question] != "O":
                    self.board[question] = "X"
                    self.create_board()
                    self.moves_count += 1
                else:
                    print("someone already took that row")
                    self.p1()
                self.check_win()
            except ValueError:
                print("Write a NUMBER from 0 to 8")
                self.p1()

    def p2(self):
        try:
            print("PLAYER 0")
            question = int(input("Type where your 0 should be placed\n"))
            if self.board[question] != "X" and self.board[question] != "O":
                self.board[question] = "O"
                self.create_board()
                self.moves_count += 1
            else:
                print("someone already took that row")
                self.p2()
            self.check_win()
        except:
            print("Write a NUMBER from 0 to 8")
            self.p2()

    def check_win(self):
        for a in self.win_conditions:
            if self.board[a[0]] == self.board[a[1]] == self.board[a[2]] == "X":
                print("PLAYER X WINS")
                self.play_again()
            if self.board[a[0]] == self.board[a[1]] == self.board[a[2]] == "O":
                print("PLAYER O WINS")
                self.play_again()
            elif self.moves_count == 9:
                print("A DRAW!")
                exit()

    def play(self):
        while True:
            self.p1()
            self.p2()

    def run(self):
        self.create_board()
        self.play()

    def play_again(self):
        while True:
            question = input("Do you want to play again? Type y or n\n")
            if question == "y":
                print("GLHF")
                self.board = [0, 1, 2, 3, 4, 5, 6, 7, 8]
                self.run()
            elif question == "n":
                print("See you next time!")
                quit()
            else:
                print("Thats not a valid option")

cos = Game()
cos.run()


texts: Abstraction of NSNotification that removes the existing observer for a notification when a new observer is added

texts:
I ran into a problem in my app where under some conditions, a view controller might be loaded more than once before its deinit (where I was previously removing the observer) is ever called. So the notification was being added twice occasionally and causing some problems.

To fix this issue, I just made a new model to abstract NSNotification:

//  Description: Model to use with NSNotification. Automatically handles removing observers for notifications that have already been added
import Foundation

struct CustomNotifications{
    static var observers = [String:AnyObject]()//pairs a notification name with an observer so that we can reference it, even when the observer doesn't have a reference to self

    static func postNotification(name:String, object:AnyObject?){
         NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: name , object: object))
    }

    static func addObserver(observer: AnyObject, selector: Selector, name:String, object: AnyObject?){
        //if an observer with this name already exists, remove it
        if (self.observers[name] != nil){
            self.removeObserverForNotification(name, object: object)
        }

       //add the observer to NSNotificationCenter
       NSNotificationCenter.defaultCenter().addObserver(observer, selector: selector, name: name, object: object)
       self.observers[name] = observer
   }

    static func removeObserver(observer:AnyObject){
        //remove an observer and all of the notifications it observes. This should usually only be done on a class's deinit
        NSNotificationCenter.defaultCenter().removeObserver(observer)
    }

    static func removeObserverForNotification(name:CurtsyNotificationName, object:AnyObject?){
        //remove the specified notification from its observer
        if let observer = self.observers[name]{
            NSNotificationCenter.defaultCenter().removeObserver(observer, name: name.rawValue, object: object)
        }
    }
}

This ensures that noNSNotification can be added more than once, but is there any downside? Intuitively, I can't think of a case when I'd want to add a notification to more than one observer, but even if that case arises, I can easily modify this to check for class types so that no notification is added to a given class type more than once.

I guess the main issue here is that I don't understand why this isn't already automatic. Am I missing some crucial information that would discourage me from doing something like this?


texts:
This code finds all the divisors of a given number.  Can it be shortened?

import java.util.Scanner;

public class PrimeNum2{
    public static void main(String args[]){
        Scanner x=new Scanner(System.in);
        System.out.print("Enter the number :  ");
        long y=x.nextInt(),i;
        System.out.print("Divisors of "+y+" = 1 , ");

        for( i=2;i<y;i++){
            long z=y%i;
            if(z!=0)continue;
                System.out.print(i+" , ");

        }System.out.println(y);
    }
}


texts:
I have a WebPostRequest class which looks like this:

public class WebPostRequest
{
    public const string Success = "OK";

    private WebRequest _webRequest;
    private List<string> _paramsList;

    public WebPostRequest(string url)
    {
        try
        {
            _webRequest = WebRequest.Create(url);
        }
        catch (Exception)
        {
            throw;
        }
        _webRequest.Method = "POST";
        _webRequest.ContentType = "application/x-www-form-urlencoded";
        _paramsList = new List<string>();
    }

    public void Add(string key, string value)
    {
        _paramsList.Add(String.Format("{0}={1}", key, HttpUtility.UrlEncode(value)));
    }

    public void UploadPdf(string postKey, string name, params UserControl[] userControls)
    {
        string fileName = FileHelper.GetTimestampedName(name, "pdf");
        string filePath = PdfHelper.Save(fileName, userControls);
        FtpHelper.UploadFile(filePath);
        this.Add(postKey, fileName);
    }

    public void UploadImage(string postKey, string name, Image image)
    {
        if (image != null)
        {
            string fileName = FileHelper.GetTimestampedName(name, "jpg");
            FtpHelper.UploadFile(fileName, image.ToByteArray());
            this.Add(postKey, fileName);
        }
    }

    public string GetResponse()
    {
        // Build a string containing all the parameters
        string parameters = String.Join("&", _paramsList.ToArray());
        _webRequest.ContentLength = parameters.Length;

        try
        {
            // Write the parameters into the request
            using (StreamWriter streamWriter = new StreamWriter(_webRequest.GetRequestStream()))
            {
                streamWriter.Write(parameters);
            }

            // Execute the query
            HttpWebResponse httpWebResponse = (HttpWebResponse)_webRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            return streamReader.ReadToEnd();
        }
        catch (Exception)
        {
            throw;
        }
    }
}

The WebPostRequest class uses a WebRequest object to POST to a web server and get the response.

The class is used like this:

bool success = false;
try
{
    WebPostRequest webPostRequest = new WebPostRequest(url);

    webPostRequest.Add("key_1", "value_1");
    webPostRequest.Add("key_2", "value_2");

    webPostRequest.UploadPdf("key_3", "pdf_name_1", userControl1);
    webPostRequest.UploadPdf("key_4", "pdf_name_2", userControl2);

    webPostRequest.UploadImage("key_5", "picture_name_1", image1);
    webPostRequest.UploadImage("key_6", "picture_name_1", image2);

    string response = webPostRequest.GetResponse();
    if (response != WebPostRequest.Success)
    {
        throw new Exception(response);
    }
    success = true;
}
catch (Exception ex)
{
    //display error messaage
}
if (success)
{
    //display success message
}

What i would like to do is add a window to display a status message and a progress bar (with marquee style). The window needs to be displayed from the WebPostRequest class, because this class is used in multiple locations in the app. The uploading tasks which may take a long time need to be executed on a different thread so that the UI thread remains responsive. Note that all the files need to be uploaded before the POST is made, so the GetResponse method needs to wait for the uploading tasks to finish. Note also that the helper methods can throw errors which are handled outside the WebPostRequest class.

What tips/suggestions can you give me? Any idea is appreciated.


texts:
I'm writing an application that will end up with a set of standard CRUD operations for a bunch of object types, and I thought it would help simplify things if all the separate controllers had some common functionality.  This will be using a view interface for everything rather than RESTful responses.  I haven't been able to find a lot of examples of this type of thing and I'm concerned I'm just creating code smell.  In addition to providing common functionality, this allows me to pass the view template and handle most of the differences between objects there.

Some questions:

in the case of E, I'm unable to specify that it should be an implementer of @Entity, though that would be an accurate statement.  Is there a better way?  Should I just create an identifying interface for those classes?
is there a better way to address the ID type of the repository?  The entities will all have either a Long or String primary key. While this works, I know it's wrong, but don't know how to correct it. (note, I didn't include the overload method for editObject that would accept a Long)
I feel like the this may not be the right/best way to construct a new object based on the generic type.  Is there a better way?
has this approach been tried and discarded as a poor one (which is why there aren't a lot of examples)?

@Slf4j
class AbstractController<E, R extends JpaRepository<E, ? super Object>> {
    private final R repository;
    private Class<E> eClass;
    private String TEMPLATE_PREFIX;

    String getList() {
        return TEMPLATE_PREFIX + "/list";
    }

    protected AbstractController(R repository, String templatePrefix) {
        this.repository = repository;
        this.TEMPLATE_PREFIX = templatePrefix;
    }

    ModelAndView listObjects(@RequestParam(required = false) Integer page,
                             @RequestParam(required = false) Integer size) {
        ModelAndView modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/list");
        modelAndView.addObject("items", repository.findAll(getPageRequest(page, size)));
        return modelAndView;
    }

    ModelAndView newObject() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        ModelAndView modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/edit");
        modelAndView.addObject("item", eClass.getConstructor().newInstance());
        return modelAndView;
    }

    ModelAndView editObject(String id) {
        ModelAndView modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/edit");
        modelAndView.addObject("item", repository.findById(id));
        return modelAndView;
    }

    ModelAndView saveObject(E entity,
                            BindingResult result) {
        ModelAndView modelAndView;
        if (result.hasErrors()) {
            LOGGER.debug("error result: {}", result.getAllErrors());
            modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/edit");
        } else {
            repository.save(entity);
            modelAndView = new ModelAndView("redirect:/" + TEMPLATE_PREFIX + "/list");
        }
        return modelAndView;
    }

    String deleteObject(final String id,
                        final RedirectAttributes redirectAttributes) {
        repository.deleteById(id);
        redirectAttributes.addAttribute("css", "success");
        redirectAttributes.addFlashAttribute("msg", "The entry has been deleted.");

        return "redirect:/" + TEMPLATE_PREFIX + "/list";
    }

    /**
     * Provides defaults for a page request
     *
     * @param page which page
     * @param size number of items
     * @return page request parameters
     */
    private PageRequest getPageRequest(Integer page, Integer size) {
        return PageRequest.of(
                (null == page) ? 0 : page,
                (null == size) ? 10 : size);
    }
}
```


texts:
What do you think about this code?

#include <iostream>
using std::cout;
using std::endl;

#include <vector>
using std::vector;

#include <ctime>
#include <cstdlib>

template < typename T >
vector < T > concatenate( vector < T > _a_, T piv, vector < T > _b_ )
{
  vector < T > v_list;
  v_list.insert( v_list.begin(), _a_.begin(), _a_.end() );
  v_list.push_back( piv );
  v_list.insert( v_list.end(), _b_.begin(), _b_.end() );
  return v_list;
}

template < typename T >
vector< T > quick( vector< T > vec )
{
  vector< T > v_less, v_greater, v_list;
  vector< T > aux1, aux2;
  typename vector < T >::const_iterator iter_Const;
  if( vec.size() <= 1 )
    return vec;
  int piv = *(vec.end() - 1);
  vec.pop_back();
  for( iter_Const = vec.begin(); iter_Const != vec.end(); ++iter_Const )
  {
    if( *iter_Const < piv )
      v_less.push_back( *iter_Const );
    else
      v_greater.push_back( *iter_Const );
  }
  return concatenate( quick( v_less ), piv, quick( v_greater ) );
}

int main() {
  vector < int > lista;
  srand( 1 );
  cout << "VECTOR" << endl;
  for( int i = 0; i < 10000; i++ )
  {
      lista.push_back( rand() % 100 );
      cout << lista[i] << " | ";
  }
  cout << endl;
  cout << "******" << endl;
  cout << "QUICKSORT" << endl;
  lista = quick( lista );
  vector < int > :: const_iterator it;
  for( it = lista.begin(); it != lista.end(); ++it )
    cout << *it << " | ";
  cout << endl;
}


texts:
Given a text and the length limit I need to trim the text to the word which is nearest to the limit.

function trim(text, limit) {
  if (text.length < limit) return text;

  let end = -1;
  var i;
  for (i = 0; i < limit - 1; i++) {
    let current = text.charAt(i);
    let next = text.charAt(i + 1);
    if (current !== ' ' && next === ' ') {
      end = i;
    }
  }
  if (i === text.length - 1) {
    end = i;
  }

  return text.substring(0, end + 1);
}

[0, 2, 4, 6, 8, 10, 12, 50].forEach((limit) => {
  console.log(trim('Hello World', limit));
});

O/P:

//

Hello
Hello
Hello
Hello World
Hello World


texts: Copy a stream to a file using Universal .NET

texts:
I have answered to a question on Stackoverflow where Andy struggled to cancel a Stream copy to file operation using the Universal .NET Framework:

Apparently, cancelling the cts CancelOperation token had not the expected behavior.

await httpResponseContent.Content.WriteToStreamAsync(streamToWrite.AsOutputStream()).AsTask(cts, progressDownload);

So I suggested to do it another way using a chunks-based stream reading and writing. So I provided this code which has been tested and accepted:

async Task Download(Uri uriToWork, CancellationToken cts, IProgress<int> progress) {
    using(HttpClient httpClient = new HttpClient()) {

        var chunkSize = 1024;
        var buffer = new byte[chunkSize];
        int count = 0;
        string fileToWrite = Path.GetTempFileName();

        using(var inputStream = await httpClient.GetInputStreamAsync(uriToWork)) {
            using(var streamToRead = inputStream.AsStreamForRead()) {
                using(Stream streamToWrite = File.OpenWrite(fileToWrite)) {
                    int size;
                    while((size = await streamToRead.ReadAsync(buffer, 0, chunkSize, cts).ConfigureAwait(false)) > 0) {
                        count += size;
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => progress.Report(count));
                        // progress.Report(count);
                        await streamToWrite.WriteAsync(buffer, 0, size, cts).ConfigureAwait(false);
                    }
                }
            }
        }
    }
}

Although it works, I am not that familiar with the Universal .NET and I am not sure this code is optimal. A casual .NET solution would be shorter.

I am very sensitive about code quality and canonicity and I wonder whether some parts of this code are redundant and can be removed, and I would like it to match the most "Universal .NET" oriented as possible.


texts:
Mask.html

        <link rel="stylesheet" type="text/css" href="mask.css">

Mask.js

(function ($) {
    $.fn.Mask = function () {

    if ($(this).find('.Mask').length > 0) return null;
        var __ctrl = $(this)[0];
        if (__ctrl.tagName != 'DIV') return null;

        var containerCssPaddingTop = $(__ctrl).css('padding-top');
        var containerCssPaddingRight = $(__ctrl).css('padding-right');
        var containerCssPaddingBottom = $(__ctrl).css('padding-bottom');
        var containerCssPaddingLeft = $(__ctrl).css('padding-left');

        $(__ctrl).css('position', 'relative');
        $(__ctrl).css('overflow', 'hidden');

        var mask = '

';
        $(__ctrl).prepend(mask);

        var m = $(this).find('.Mask');
        var mc = $(this).find('.MaskContent');

        m.css('margin-top', '-' + containerCssPaddingTop);
        m.css('margin-right', '-' + containerCssPaddingRight);
        m.css('margin-bottom', '-' + containerCssPaddingBottom);
        m.css('margin-left', '-' + containerCssPaddingLeft);

        // The 16 just comes from the fact that the image displayed is 32x32
        mc.css('left', m.width()/2 - 16 + "px");

        var toReturn = {
            RemoveMask: function () {
                m.remove();
            }
        };

        return toReturn;
    };
})(jQuery);

mask.css

.Mask {
    background-image: -webkit-radial-gradient(center, ellipse farthest-side, #FFFFFF 0%, #EEEEEE 100%);
    height: 100%;
    opacity: 0.8;
    position: absolute;
    width: 100%;
    z-index: 4;
}

.MaskContent {
    background: none;
    position: absolute;
    top: 30%;
    z-index: 5;
}

The real code I would like reviewed/criticized is in Mask.js and Mask.css

The idea is that this extends jQuery so you can block a div while it is being updated.

You would use it by running

v = $('#div1').Mask()

then, to remove it, one would do

v.RemoveMask();


texts:
I am working on a Simon game using python and tkinter, just now it is incomplete, but I don't know if I am doing it right because it looks messy, and I would like to have a check on my code for corrections and suggestions on how to improve it.

This is the first game I'm making, and I don't have to much experience in programming.

This is my actual entire code:

from Tkinter import *
import Tkinter
import random

base = Tkinter.Tk()

fr = Tkinter.Frame(base, bg="black", width="238", height="250")

score = Tkinter.Label(base, bg="black", fg="white", text="Score:")
score.place(x = 30, y = 15)

s = 0

scoreNum = Tkinter.Label(base, bg="black", fg="white", text = s)
scoreNum.place(x = 70, y = 15)

best = Tkinter.Label(base, bg="black", fg="white", text="Best:")
best.place(x = 155, y = 15)

b = 0

bestNum = Tkinter.Label(base, bg="black", fg="white", text = b)
bestNum.place(x = 188, y = 15)

clicks = []
color = 0

def yellowClick():

    yellow.configure(activebackground="yellow3")
    yellow.after(500, lambda: yellow.configure(activebackground="yellow"))

    global clicks
    global color

    color = 1
    clicks.append(color)

yellow = Tkinter.Button(base, bd="0", highlightthickness="0",
                       width="7", height="5", activebackground="yellow",
                       bg="yellow3", command = yellowClick)

yellow.place(x = 30, y = 50)

def blueClick():

    blue.configure(activebackground="medium blue")
    blue.after(500, lambda: blue.configure(activebackground="blue"))

    global clicks
    global color

    color = 2
    clicks.append(color)

blue = Tkinter.Button(base, bd="0", highlightthickness="0",
                     width="7", height="5", activebackground="blue",
                     bg="medium blue", command = blueClick)

blue.place(x = 125, y = 50)

def redClick():

    red.configure(activebackground="red3")
    red.after(500, lambda: red.configure(activebackground="red"))

    global clicks
    global color

    color = 3
    clicks.append(color)

red = Tkinter.Button(base, bd="0", highlightthickness="0",
                    width="7", height="5", activebackground="red",
                    bg = "red3", command = redClick)

red.place(x = 30, y = 145)

def greenClick():

    green.configure(activebackground="dark green")
    green.after(500, lambda: green.configure(activebackground="green4"))

    global clicks
    global color

    color = 4
    clicks.append(color)

green = Tkinter.Button(base, bd="0", highlightthickness="0",
                      width="7", height="5", activebackground="green4",
                      bg="dark green", command = greenClick)

green.place(x = 125, y = 145)

def scoreUp():

    global s

    s = s + 1

    scoreNum.configure(text = s)

r = random.randint(1, 4)

sequence = []

def checkSequence():

    global clicks
    global sequence

    if clicks == sequence:

        scoreUp()

def showSequence():

    global r
    global sequence

    if r == 1:

        yellow.configure(bg="yellow")
        yellow.after(1000, lambda: yellow.configure(bg="yellow3"))

        sequence.append(r)

        base.after(5000, checkSequence)

    elif r == 2:

        blue.configure(bg="blue")
        blue.after(1000, lambda: blue.configure(bg="medium blue"))

        sequence.append(r)

        base.after(5000, checkSequence)

    elif r == 3:

        red.configure(bg="red")
        red.after(1000, lambda: red.configure(bg="red3"))

        sequence.append(r)

        base.after(5000, checkSequence)

    elif r == 4:

        green.configure(bg="green4")
        green.after(1000, lambda: green.configure(bg="dark green"))

        sequence.append(r)

        base.after(5000, checkSequence)

base.after(2000, showSequence)

fr.pack()

base.resizable(False, False)
base.mainloop()

Actually I'm checking the sequence with time because I can't find another to do it.


texts: Advent of Code Day 6: toggling lights in a grid with Powershell

texts:
I am using the "Advent of Code" series to help with my PowerShell education. The Day 6 puzzle has a 1000 × 1000 grid of lights. After processing instructions to turn on, turn off, or toggle rectangles of lights in the grid, how many lights are on at the end?

I am confident that this script will produce the right answer. However, it is going way too slow. I am interested in optimizing this script for performance. I am not against coming up with an alternative way to solve this problem with PowerShell.

$lightson = New-Object Collections.Generic.HashSet[string]
$strings = Get-Content C:\test\lights.txt

foreach ($string in $strings){
    $numbers = [regex]::matches($string,"\d+")
    $minX = [convert]::ToInt32($numbers[0],10)
    $minY = [convert]::ToInt32($numbers[1],10)
    $maxX = [convert]::ToInt32($numbers[2],10)
    $maxY = [convert]::ToInt32($numbers[3],10)
    $x = $minX
    $y = $miny

    write-host $string
    write-host $x $y

    if ($string -like "turn on*"){
            write-host "turn on"
            while ($x -le $maxX){
                while ($y -le $maxY){
                    $light = "$x,$y"
                    if ($light -notin $lightson){
                        [void]$lightson.Add("$x,$y")
                        #write-host $lightson.Count
                    }
                    $y +=1
                }
                $x += 1
                $y = $miny
            }
            write-host $lightson.Count "`n"
        }

    if ($string -like "turn off*"){
        write-host "turn off"
        while ($x -le $maxX){
            while ($y -le $maxY){
                $light = "$x,$y"
                if ($light -in $lightson){
                    [void]$lightson.Remove("$x,$y")
                    #write-host $lightson.Count
                }
                $y +=1
            }
            $x += 1
            $y = $miny
        }
        write-host $lightson.Count "`n"
    }

    if ($string -like "toggle*"){
        write-host "toggle`n"
        while ($x -le $maxX){
            while ($y -le $maxY){
                $light = "$x,$y"
                if ($light -in $lightson){
                    $lightson.Remove("$x,$y")
                    #write-host $lightson.Count
                }
                else{[void]($lightson.Add("$x,$y"))}
                $y +=1
            }
            $x += 1
            $y = $miny
        }
        write-host $lightson.Count "`n"
    }
}

There are a million different lights that can be on or off. This massive number is obviously causing the long process time. At the moment, I can not think of any alternatives.


texts: Clojure programming exercise for calculating change

texts:
I'm learning Clojure and have written a small function to calculate change. I don't like few things about the code and would primarily like to replace recursive call with something more idiomatic. Could you please comment on the code and suggest a better (more Clojure-like) way of implementing it?

(def in-bank #{1 2 5 10})

(defn smaller-than? [compare-input metric]
  (>= compare-input metric))

(defn get-max-smaller-than [input]
  (apply max (filter (partial smaller-than? input) in-bank)))

(defn change-calc [change-requested change-given]
  (let [calculated
    (get-max-smaller-than change-requested)]
    (let [upd-change-given
      (conj change-given calculated)]
        (let [sub-request (- change-requested calculated)]
          (if (= sub-request 0)
            upd-change-given (recur sub-request upd-change-given))))))


texts: Automatic Databinding of controls to Model

texts:
I have developed a prototype framework (MVVM) where control on the form is bound to a model property using a naming convention and its UI behavior is controlled using custom attributes.

As of now the control name is divided into two parts - 3 part prefix and then the Name of the property in model to bind to.

For eg txtFirstName textbox is bound to FirstName in model. During construction/load, all controls are looped through -

BaseEdit baseEdit = (BaseEdit) control;
baseEdit.DataBindings.Add("EditValue", viewModelBindingSource,
                          baseEdit.Name.Remove(0, 3),
                          true, DataSourceUpdateMode.OnPropertyChanged);

There are some other attributes such as [ReadOnly], [Unbound] which are used to control the UI behavior.

baseEdit.Properties.ReadOnly = Util.GetReadOnlyAttributeValue(
    control.Name.Remove(0, 3), viewModel.GetType());

I am thinking of doing the looping the other way around, ie the Model properties, using a Bound attribute. Bound[ControlName, PropertyName]

Bound["txtFirstName", "EditValue"]
FirstName

All the dropdown type controls, combobox, dropdown, checkeddropdown etc are autofilled by using a 'Key' from their tag property.

if (control.GetType() == typeof(LookUpEdit) &&
    !string.IsNullOrEmpty(Convert.ToString(control.Tag))) //Exact match
{
       LookUpEdit lookUpEdit = (LookUpEdit)control;
       DataBinding.InitializeLookUpEdit(lookUpEdit, lookUpEdit.Tag.ToString());
}

I took the biggest data-entry form with around 45 controls and tested the framework.

Is the above approach suitable for a big project? Any suggestions for improving the framework?


texts: Loop to streamline pandas dataframe to_sql

texts:
This code gives me what I am looking for. But I'm just thinking how I can streamline the if statements because I would be repeating myself a couple of times, and that's not really good isn't it?

import requests
import pandas
from sqlalchemy import create_engine
import os
import numpy
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By

def _format_data_frame(dataframe_source, df_id):
"""Format the dataframe source that is retrieved from 'my_function()' and put into SQL"""

    for each_dataframe in dataframe_source: # Formatting the columns
        if "Unnamed: 2" in each_dataframe.columns:
            each_dataframe.drop(each_dataframe.index[0], inplace=True)
            each_dataframe.rename(columns={"Fare Per Ride (cent)": "Card", "Unnamed: 2": "Cash"}, inplace=True)
        if "Card Fare Per Ride (cent)" in each_dataframe.columns:
            each_dataframe.rename(columns={"Card Fare Per Ride (cent)": "Card"}, inplace=True)
        if "Card Fare (cent)" in each_dataframe.columns:
            each_dataframe.rename(columns={"Card Fare (cent)": "Card"}, inplace=True)
        if "Description" in each_dataframe.columns:
            each_dataframe.rename(columns={"Description": "Distance"}, inplace=True)

    # Each dataframe_source has a total of 5 dataframes extracted.
    # I don't need the last dataframe, and this portion is just to separate the dataframes out.
    truck_services = dataframe_source[0]
    feeder_services = dataframe_source[1]
    express_services = dataframe_source[2]
    other_services = dataframe_source[3]

    ### How can I streamline the below code?  ###

    if df_id == "df1":
        engine = create_engine("sqlite:///abc.db", echo=False)
        connection = engine.connect()
        pandas.DataFrame.to_sql(truck_services, name="Truck Services", con=engine, if_exists="append")
        pandas.DataFrame.to_sql(feeder_services, name="Feeder Services", con=engine, if_exists="append")
        pandas.DataFrame.to_sql(express_services, name="Express Services", con=engine, if_exists="append")
        pandas.DataFrame.to_sql(other_services, name="Other Services", con=engine, if_exists="append")
        connection.close()

    if df_id == "df2":
        engine = create_engine("sqlite:///defg_Fares.db", echo=False)
        connection = engine.connect()
        pandas.DataFrame.to_sql(truck_services, name="Truck Services", con=engine, if_exists="append")
        pandas.DataFrame.to_sql(feeder_services, name="Feeder Services", con=engine, if_exists="append")
        pandas.DataFrame.to_sql(express_services, name="Express Services", con=engine, if_exists="append")
        pandas.DataFrame.to_sql(other_services, name="Other Services", con=engine, if_exists="append")
        connection.close()

    if df_id == "df3":
        engine = create_engine("sqlite:///hijk_Fares.db", echo=False)
        ## Same thing
        connection = engine.connect()

    if df_id == "df4":
        engine = create_engine("sqlite:///lmno_Fares.db", echo=False)
        ## Same thing
        connection = engine.connect()

    if df_id == "df5":
        engine = create_engine("sqlite:///pqr_Fares.db", echo=False)
        ## Same thing
        connection = engine.connect()


texts: Turning a Java console app into a server

texts:
I'm not familiar with Java at all, so I'd like to get some feedback on this piece of code.

I made it by looking at a few Hello World-esque Java server examples, so it may have drawbacks I'm not aware of.

My task was turning an existing Java console app into a single-threaded server listening on some port. Each connection should “launch” what previously was the console app, where actual “arguments” are passed by the client. Anything that was written by console app to stdout, should go into process' stdout; but what was previously written to stderrm needs to be redirected to the client. Finally, when the processing has finished, if there was no error, the client should receive "OK" and get disconnected. (And the next client should be processed.)

Here's the original and my version side by side:

// Change: we want to run this as a server instead

// public static void main(String [] args) {
//     (new Main(args)).execute();
//     System.exit(0);
// }

public static void main(String args[]) throws Exception {
    int port = Integer.parseInt(args[0]);
    ServerSocket welcomeSocket = new ServerSocket(port);

    System.out.format("Listening on %d\n", port);
    PrintStream defaultStderr = System.err;

    while (true) {
        // Establish a connection
        Socket connectionSocket = welcomeSocket.accept();
        BufferedReader input = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());

        // Hook System.err
        System.setErr(new PrintStream(output));

        try {
            // Run Batik as if we ran console app, but without the launch overhead
            (new Main(input.readLine().split(" "))).execute();
        } catch (Throwable t) {
            // Normally, we shouldn't get here (as Batik should not crash).
            // If we *do* get here, print to stderr, which we redirect to output stream anyway.
            t.printStackTrace();
        }

        // Let the client know how it went
        if (output.size() == 0) {
            output.writeBytes("OK");
        }

        output.close();

        // Restore stderr
        System.setErr(defaultStderr);
    }
}

What can I make better? I want to clarify I do not want to change any other method in the app to keep it easy to merge upstream changes.


texts:
How can I make this code snippet be improved to become more professional?

(function($){

  $.fn.showMenu = function(options){

    return this.each(function(){

      $this = $(this);
      var high         = $this.outerHeight(),
          scrollHeight = $this.get(0).scrollHeight;

      $this.bind('mouseenter',function(){
        $this.css({overflow:'visible'})
             .stop()
             .animate({height:scrollHeight},'fast');
      }).bind('mouseleave',function(){
        $this.animate({height:high}, function(){
          $this.css({overflow:'hidden'});
        });
      });
    });

  }//the end of $.fn.showMenu

  $('#theme_content').showMenu();

});


texts:
I'm new to Haskell, and I figured that pairwise summation is something I could do easily. I wrote this:
pairwiseSum :: (Num a) => [a] -> a
pairwiseSum [] = 0
pairwiseSum [x] = x
pairwiseSum (x:xs) = (pairwiseSum (everyOther (x:xs))) + (pairwiseSum (everyOther xs))

everyOther :: [a] -> [a]
everyOther [] = []
everyOther [x] = [x]
everyOther (x:_:xs) = x : everyOther xs

Given [0,1,2,3,4,5,6,7], this computes (((0+4)+(2+6))+((1+5)+(3+7))), whereas my C(++) code computes (((0+1)+(2+3))+((4+5)+(6+7))). How does this affect optimization?
How easy is it to read? Could it be written better?
How can I test it? I have three tests in C++:

add the odd numbers [1,3..(2*n-1) and check that the sum is n²;
add 100000 copies of 1, 100000 copies of 0.001, ... 100000 copies of 10^-18 and check for the correct sum;
add 0x36000 terms of a geometric progression with ratio exp(1/4096).

To test execution time, I use 1000000 copies and 16 times as many terms of exp(1/65536).


texts: Making zip file with custom content per user

texts:
What I tried to do:

In my main project folder I have directory downloadable_app with these files/folders inside:

index.html
js/app.f54b97d7097bcf4226c0.js

I need to allow users to download this downloadable_app folder as zip archive
In app.f54b97d7097bcf4226c0.js file I have axios.defaults.headers.common['Authorization'] = 'Bearer <BEARER_TOKEN>'
I need to replace <BEARER_TOKEN> by request.user token

This is how I did this:

settings.py:

PROJECT_PATH = os.path.abspath(os.path.dirname(__name__))
DOWNLOADABLE_APP_ROOT = os.path.join(PROJECT_PATH, 'downloadable_app')

views.py:

import datetime
import binascii
import os
from datetime import timedelta
import shutil
...

from oauth2_provider.models import Application, AccessToken

class DownloadAppView(LoginRequiredMixin, View):
    def dispatch(self, request, *args, **kwargs):
        if not self.request.user.plan:
            raise Http404
        self.token = self._get_or_create_user_token()
        return super(DownloadAppView, self).dispatch(
            request, *args, **kwargs)

    def _add_token_to_downloadable_app(self, token):
        with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
            filedata = file.read()

        filedata = filedata.replace('<BEARER_TOKEN>', token)

        with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
            file.write(filedata)

    def _reset_token_in_downloadable_app(self, token):
        with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'r') as file:
            filedata = file.read()

        filedata = filedata.replace(token, '<BEARER_TOKEN>')

        with open(os.path.join(settings.DOWNLOADABLE_APP_ROOT, 'js/app.f54b97d7097bcf4226c0.js'), 'w') as file:
            file.write(filedata)

    def _get_or_create_user_token(self):
        app, created = Application.objects.get_or_create(
            client_type=Application.CLIENT_CONFIDENTIAL,
            authorization_grant_type=Application.GRANT_CLIENT_CREDENTIALS,
            redirect_uris='https://www.example.com/',
            name='downloadable_app',
            user=User.objects.filter(is_superuser=True, is_staff=True).first()
        )
        access_token, created = AccessToken.objects.get_or_create(
            user=self.request.user,
            scope='read write',
            application=app,
            defaults={'expires': timezone.now() + timedelta(days=1000), 'token': binascii.hexlify(os.urandom(20)).decode()}
        )
        return access_token.token

    def get(self, request):
        self._add_token_to_downloadable_app(self.token)

        # create_zip_archive
        shutil.make_archive('downloadable_app_archives/my_app_{}'.format(request.user.pk), 'zip', settings.DOWNLOADABLE_APP_ROOT)
        response = HttpResponse(
            open(os.path.join(
                settings.PROJECT_PATH, 'downloadable_app_archives/my_app_{}.zip'.format(request.user.pk)), 'rb').read(), content_type='application/zip')
        self._reset_token_in_downloadable_app(self.token)
        return response

management.commands.delete_zip_archives.py:

class Command(BaseCommand):
    help = 'Delete downloadable app zip archives'

    def handle(self, *args, **options):
        shutil.rmtree(os.path.join(settings.PROJECT_PATH, 'downloadable_app_archives'))

Can you please take a look and let me know how can I improve this?


texts: Autowiring publishers/listeners with reflection in Unity Framework

texts:
I'm currently building an application with the Microsoft Unity Framework. I also use a simple system of message publishers/listeners inspired from MVVM light and caliburn:

The listener interface

public interface IMessageListener<T>
{

    void Handle(T Message);
}

The messenger interface

public interface IMessagePublisher<T>
{

    void Subscribe(IMessageListener<T> subscriber);

    void Unsubscribe(IMessageListener<T> subscriber);

    void Publish(T message);
}

I started to find it boring to have to inject my messengers to my listeners so they can subscribe, so I thought: "Hey, my Unity container can do that". I've coded a UnityExtension which autowires all resolved listener objects with their appropriate messenger(s) by using reflection. Of course, my messengers are ContainerLifeTimeManaged.

public override void PostBuildUp(IBuilderContext context)
        {
            base.PostBuildUp(context);

            foreach (Type interf in context.Existing.GetType().GetInterfaces().Where(i => i.IsGenericType))
            {
                //If the interface is of type IMessageListener
                if (interf.GetGenericTypeDefinition() == typeof(IMessageListener<object>).GetGenericTypeDefinition())
                {
                    //Get the generic parameter type
                    Type genericParameter = interf.GetGenericArguments().FirstOrDefault();
                    //Build the messenger type
                    Type messengerType = typeof(IMessagePublisher<object>).GetGenericTypeDefinition().MakeGenericType(genericParameter);
                    //Resolve the messenger
                    object messenger = _container.Resolve(messengerType);
                    //Find the subscribe method
                    MethodInfo subscribeMethod = messenger.GetType().GetMethod("Subscribe");
                    //Subscribe the listener (the array is ugly, but i just keep getting an error without it)
                    subscribeMethod.Invoke(messenger, new []{context.Existing});
                }
            }
       }

I've removed the exception handling on purpose. I've struggled a bit to achieve this, and I'm not sure that it's the most efficient way.


texts:
I am wondering if someone can do a code re"vue" specifically for my star rating component ([complete code available on github).

I am looking for feedback on best practices, any glaring code crimes I might have committed and bad code.

The code is also deployed to #Heroku here

Problems I saw with the code previous code are also included.

The partial star sometimes just gets the default colors, even if the DOM has the colors assigned via props.
Change in data (using Vue Dev Tools) does not re-render my star rating component. For the benefit for the code reviewers, I have hosted the component on Heroku, so if you have the Vue dev tools, you can test this
too.

Edit - Inlined the code to follow the code-review standards.

Edit - 10/23 - I have updated the code since I first posted this and seem to have resolved all the issues with my previous code. The link to Github is here. Also the inlined code is now newer... I have added comments in the code, where I would love some feedback and comments.

    <template>
    <div>
        <!-- Is this use of dynamic component correct? -->
        <component v-for="n of this.totalStarsData" :key="n" :is="currentComponent(n)" :fillColor="ratingData - n > -1 ? fillColorData : baseColorData" :baseColor="baseColorData" :rating="ratingData"></component>
    </div>
    </template>

    <script>
// Can Star and PartialStar components be dynamically imported?
import Star from "./Star"
import PartialStar from "./PartialStar"

// Using a global variable like this - Good or bad?
let isPartialRendered = false
export default {
    name: 'star-rating',
    components: {
        Star,
        PartialStar
    },
    props: {
        totalStars: {
            type: Number,
            default: 5
        },
        rating: {
            type: Number,
            required: true
        },
        fillColor: {
            type: String,
            default: '#C00'
        },
        baseColor: {
            type: String,
            default: '#666'
        },
    },
    data(){
        return {
            // Any better way of converting props to data?
            // Also maybe naming convention best practices?
            totalStarsData: this.totalStars,
            ratingData: this.rating,
            fillColorData: this.fillColor,
            baseColorData: this.baseColor,
        }
    },
    methods: {
        currentComponent: function (count) {
            const int_part = Math.trunc(this.ratingData);
            if(count > int_part && isPartialRendered === false) {
                isPartialRendered = true;
                // Re-setting the isPartialRendered flag here, for cases where the Partial SVG is the last SVG
                if(count === this.totalStarsData){
                    isPartialRendered = false;
                }
                return 'PartialStar'
            } else {
                if(count === this.totalStarsData){
                    isPartialRendered = false;
                }
                return 'Star'
            }

        }
    }
}
</script>

<style scoped>

</style>


texts:
This is a script I made while having trouble with xautolock and dimming of the screen right before locking it. I would like some tips for making it a bit more robust and to know of any disadvantages of it. I don't know how it works with multiple screens but I suspect it does not.

#!/bin/bash

# Lock screen in:
minutes=15
seconds=0

# How many seconds it takes to dim
dim_secs=5

idle_secs=$(( $minutes * 60 + $seconds )) # Screen timeout in seconds
idle_ms=$(( $idle_secs * 1000 ))

timeout=$idle_secs

while true; do
    sleep $timeout

    if pgrep xflock4 > /dev/null; then
        timeout=$idle_secs
        continue
    fi

    # After sleeping, check user idle time
    if [ $(xprintidle) -ge $idle_ms ]; then
        WINDOW=$(echo $(xwininfo -id $(xdotool getactivewindow) -stats | \
                        egrep '(Width|Height):' | \
                        awk '{print $NF}') | \
                sed -e 's/ /x/')
        SCREEN=$(xdpyinfo | grep -m1 dimensions | awk '{print $2}')

        # If greater than timeout check if something's not in fullscreen and active
        if [ "$WINDOW" != "$SCREEN" ]; then
            interrupted=false # If dimming's been interrupted

            screen=$(xrandr -q | grep " connected" | awk '{print $1;}') # Connected screen
            brightness=$(xrandr --verbose | grep -i brightness | cut -f2 -d ' ') # Current brightness

            start_time=$(date "+%s.%N") # Current time
            while true; do
                # Current brightness(0 to $brigtness), decided by time since dimming started
                br=$(echo "$brightness-$brightness*(($(date "+%s.%N")-$start_time)/$dim_secs)" | bc -l)
                if [ $(echo "$br >= 0" | bc) -eq 1  ]; then
                    # Set the current brightness and sleep for a short while
                    xrandr --output $screen --brightness $br
                    sleep 0.01
                else
                    # If brightness is less than 0 then it means that the
                    # time since starting dimming is greater than $dim_secs
                    break
                fi

                # If the user gave an input that's less than $idle_ms
                # Will always be less than $idle_ms if it was interrupted during dimming
                if [ $(xprintidle) -lt $idle_ms ]; then
                    interrupted=true
                    break
                fi
            done
            if $interrupted; then
                # If it was interrupted during dimming, reset brightness
                xrandr --output $screen --brightness $brightness
            else
                xset dpms force off # Turn screen off
                xrandr --output $screen --brightness $brightness # Reset brightness

                xflock4 # Lock screen
            fi
        fi
    fi

    # Timeout before checking idle time again
    timeout=$(echo "$idle_secs - $(xprintidle) / 1000 " | bc -l)
done


texts: Perform loop through process on all sheets at once

texts:
I have workbook having multiple sheets and having same data on it. Currently I am using macro that .autofilterand copy paste on respective sheets. I am using looping process like:-

   Sub SCRIPT()
    Application.ScreenUpdating = False
    Sheets("SCRIPT").Range("A3:P100").ClearContents
    Dim ws As Worksheet, lrc As Long, LR1 As Long, LR2 As Long
    Dim key1 As String
    key1 = InputBox("Type Script Name", "Title")
    For Each ws In ActiveWorkbook.Worksheets
    If (ws.Name <> "SCRIPT") And (ws.Name <> "MARKET") And (ws.Name <> "CHAIN") Then
    ws.Range("AE1:AJ500").ClearContents
    ws.Range("CB1:CH500").ClearContents
    ws.Range("A1").AutoFilter Field:=1, Criteria1:=key1
    ws.Range("A1").AutoFilter Field:=2, Criteria1:="28-Jan-16"
    lrc = ws.Range("D" & Rows.Count).End(xlUp).Row
    ws.Range("D1:D" & lrc).AutoFilter Field:=4, Criteria1:="CE"
    ws.Range("L2:L" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AG2")
    ws.Range("C2:C" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AE2")
    ws.Range("L2:L" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("CD2")
    ws.Range("C2:C" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("CB2")
    ws.Range("C2:C" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AH2")
    ws.Range("I2:I" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AJ2")
    ws.Range("I2:I" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("CH2")
    ws.Range("M2:M" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("CF2")
    AutoFilterMode = False
    ws.Range("D1:D" & lrc).AutoFilter Field:=4, Criteria1:="PE"
    ws.Range("L2:L" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AF2")
    ws.Range("L2:L" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("CC2")
    ws.Range("I2:I" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AI2")
    ws.Range("I2:I" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("CG2")
    ws.Range("M2:M" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("CE2")
    AutoFilterMode = False
    ws.Range("A1").AutoFilter
    ws.Columns("AE:AJ").Sort key1:=ws.Columns("AE"), Order1:=xlDescending
    ws.Columns("CB:CH").Sort key1:=ws.Columns("CB"), Order1:=xlDescending

    ws.Range("P1").AutoFilter Field:=1, Criteria1:=key1
    ws.Range("P1").AutoFilter Field:=2, Criteria1:="EQ"
    ws.Range("R2:U" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AM2")
    ws.Range("Z2:Z" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AL2")
    ws.Range("P2:P" & lrc).SpecialCells(xlCellTypeVisible).Copy Destination:=ws.Range("AK2")
    AutoFilterMode = False
    ws.Range("P1").AutoFilter
    End If

    If (ws.Name <> "SCRIPT") And (ws.Name <> "MARKET") And (ws.Name <> "CHAIN") Then
    LR1 = Sheets("SCRIPT").Range("A" & Rows.Count).End(xlUp).Row + 1
    LR2 = ws.Range("D" & Rows.Count).End(xlUp).Row
    ws.Range("AK2:AZ" & LR2).Copy
    Sheets("SCRIPT").Range("A" & LR1).PasteSpecial xlPasteValues
    ws.Range("AK2:AR" & LR2).Copy
    Sheets("CHAIN").Range("A" & LR1).PasteSpecial xlPasteValues
    End If

    Application.CutCopyMode = False
    Next ws
    Application.Goto (ActiveWorkbook.Sheets("SCRIPT").Range("A1"))
    Application.Goto (ActiveWorkbook.Sheets("CHAIN").Range("A1"))
    Application.ScreenUpdating = True
    End Sub

Filtering huge data on each sheet. Therefore takes lot of time to finished process while looping each sheet. Does there any other way that perform looping task on all sheets at once?


texts: Plot random generated 'n' non-colliding circles using Matplotlib

texts:
I have a function which plots n randomly generated non-colliding circles. The circle is a Circle object, part of matplotlib.patches. We will generate each random circle by its center and r, for example : r = random.uniform(min_r, max_r).

To make circles with no collision, no two circles (with c1, r1 and c2, r2 as the center and radius) can have :
distance(c1, c2) < r1  + r2.

Here is the imports:

import random
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
import numpy

The implementation is done by the function below, how to make the script more compact and the implementation more efficient (faster)? Thanks.

The main function:

def nocollide_random_unif_circles():

    def add_circle(ax, center=(0,0), r=1, face_color=(0,0,1,1), edge_color=(0,0,1,1), line_width = None):
        C = Circle(center, radius = r, facecolor = face_color, edgecolor = edge_color, linewidth = line_width)
        ax.add_patch(C)

    def dist2d(p, q):
        distance = numpy.sqrt( (p[0]-q[0])**2 + (p[1]-q[1])**2 )
        return distance

    def collide(center, rad, centers, rads):
        for c, r in zip(centers, rads):
            if dist2d(c, center) < r + rad:
                return True
        return False

    ncircle = 1000
    min_r = 1
    max_r = 200
    color = 'blue'

    sizex = [0, 1000]; sizey = [0, 1000]

    fig, ax = plt.subplots(1, 1)

    centers = [(random.uniform(sizex[0], sizex[1]), \
               random.uniform(sizey[0], sizey[1]))]
    rads = [random.uniform(min_r, max_r)]
    add_circle(ax, center = centers[0], r = rads[0],\
               face_color = color, edge_color = (0, 0, 0, 0))
    for n in range(ncircle-1):
        center = (random.uniform(sizex[0], sizex[1]), \
               random.uniform(sizey[0], sizey[1]))
        rad = random.uniform(min_r, max_r)
        while collide(center, rad, centers, rads):
            center = (random.uniform(sizex[0], sizex[1]), \
               random.uniform(sizey[0], sizey[1]))
            rad = random.uniform(min_r, max_r)
        centers.append(center); rads.append(rad)
        add_circle(ax, center = centers[-1], r = rads[-1],\
               face_color = color, edge_color = (0, 0, 0, 0))
        print(n)

    ax.axis('equal')
    ax.set_xlim(sizex); ax.set_ylim(sizey)
    ax.tick_params(colors = (0,0,0,0))
    ax.set_title('min radius = {}, max radius = {}, n = {} circles'.format(min_r, max_r, ncircle))

    fig.tight_layout()
    fig.show()

Example result with n=4000 (took quite some time):


texts:
I have created an algorithm that can generate all possible combinations of a string given its length, and character set (it uses a custom numeral system to do this). How could I improve its performance and readability?

using System;
using System.Text;

public class Program
{
    public static void Main(string[] args)
    {
        Bruteforce brute = new Bruteforce(9, new Range(0, Helpers.Chars.Length - 1));
        brute.PrintResults();

        Console.ReadKey(true);
    }
}

public class Bruteforce
{
    private int _Length;
    private Range _Range;

    public int Length
    {
        get
        {
            return _Length;
        }
    }

    public Range Range
    {
        get
        {
            return _Range;
        }
    }

    public Bruteforce(int length, Range range)
    {
        _Length = length;
        _Range = range;
    }

    public Bruteforce(int length, int min, int max)
    {
        _Length = length;
        _Range = new Range(min, max);
    }

    public void PrintResults()
    {
        int num = this.Range.Max;
        int[] arr = new int[this.Length];
        for (int c = 0; c < arr.Length; c++) arr[c] = this.Range.Min;
        while (true)
        {
            arr[0]++;
            if (arr[0] > this.Range.Max)
            {
                for (int i = 1; i < arr.Length; i++)
                {
                    if (arr[i - 1] > this.Range.Max)
                    {
                        arr[i - 1] = this.Range.Min;
                        arr[i]++;
                    }
                }
            }

            int num2 = arr[0];
            for (int i = 1; i < arr.Length; i++) num2 += arr[i];

            Console.WriteLine(Helpers.ArrayToString(arr));

            if (num2 == this.Range.Max * arr.Length) break;
        }
    }

    private void PrintArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            if (i == arr.Length - 1)
            {
                Console.WriteLine(arr[i]);
            }
            else
            {
                Console.Write(arr[i] + ", ");
            }
        }
    }
}

public class Helpers
{
    public static char[] Chars = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    public static string ArrayToString(int[] arr)
    {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i] >= 0)
            {
                builder.Append(Helpers.Chars[arr[i]]);
            }
            else
            {
                throw new Exception();
            }
        }
        return builder.ToString();
    }
}

public class Range
{
    private int _Max, _Min;

    public int Max
    {
        get
        {
            return _Max;
        }
    }

    public int Min
    {
        get
        {
            return _Min;
        }
    }

    public Range(int min, int max)
    {
        _Max = max;
        _Min = min;
    }
}


texts: Using metaclass to decorate derived classes to be `attrs` classes

texts:
I am currently developing a framework to facilitate writing controller programs for scientific instruments.  I use attrs extensively in the internal parts of the code.  I have some parts of the code which exposes classes to be derived from, but I don't want to call @attr.s in the beginning whenever I derive a class.  I have an ad-hoc solution, but I would like to know if this decision will give me headaches on the way.

I am using a metaclass when declaring the base class to be further derived from.  I use the __new__ of the metaclass to decorate the base class.

Here is a stripped down version of my code:

import typing as t
import attr

def setting(
        unit: str = "",
        nicename: t.Optional[str] = None,
        default: t.Optional[t.Any] = None):
    """Returns a setting attribute field to be used in InstrumentSettings
    derived classes.

    Args:
        nicename:  (optional) A unique nice name for referring to the
            setting in texts.
    """

    metadata = dict(
            metatype='setting',
            unit=unit,
            nicename=nicename)
    return attr.ib(metadata=metadata, default=default)

class _InstrumentSettingsMeta(type):
    def __new__(cls, clsname, supers, attrdict):
        newcls = super().__new__(cls, clsname, supers, attrdict)
        decorated = attr.s(auto_attribs=True)(newcls)

        return decorated

class InstrumentSettings(metaclass=_InstrumentSettingsMeta):
    pass

# Usage
class FooSettings(InstrumentSettings):
    bar: int = setting(default=1)

foosettings = FooSettings()

So the above implementation gives the correct behavior as FooSettings is perfectly attrs decorated.  The thing is that I don't really wanna fiddle with metaclasses because I don't think I fully grok them.  I would appreciate very much if someone could state the downsides & upsides to my approach.  I am also open to other suggestions.


texts: Using Span and Memory to read UTF8 from a socket

texts:
I am experimenting with Span<> and Memory<> and checking how to use it for example for reading UTF8 text from a NetworkStream using Read(Span<Byte>). I created a fake method that simulates the byte read, and although this code works for the test, I am wondering if this is the right way of doing the most with these new structures in terms of efficiency and memory.

static void Main(string[] args)
{
    Memory<byte> byteMemory = new byte[3];
    Memory<char> charMemory = new char[1024];

    var byteMemoryPos = 0;
    var byteMemoryReaded = 0;
    var charMemoryPos = 0;
    var readed = -1;

    var decoder = Encoding.UTF8.GetDecoder();

    do
    {
        // pass the sliced part of the memory where I want to write as span
        readed = FakeNetworkStreamRead(byteMemory.Slice(byteMemoryPos + byteMemoryReaded).Span);
        Console.WriteLine($"Readed {readed} bytes");

        byteMemoryReaded += readed;

        // pass the sliced part of the memory I want to parse, and the part
        // of the char buffer where I want to write
        decoder.Convert(byteMemory.Slice(byteMemoryPos, byteMemoryReaded).Span,
                        charMemory.Slice(charMemoryPos).Span,
                        false, out int bytesUsed, out int charsUsed, out bool completed);

        // update offsets and counts
        byteMemoryPos -= bytesUsed;
        charMemoryPos += charsUsed;
        byteMemoryReaded -= bytesUsed;

        // reset offset if nothing to read
        if (byteMemoryReaded == 0)
            byteMemoryPos = 0;
    }
    while (readed != 0);

    Console.WriteLine(new string(charMemory.Slice(0, charMemoryPos).Span));
}

static int _position = 0;
static byte[] _data = Encoding.UTF8.GetBytes("Hi this is test!!");

/// <summary>
/// Pretends to be NetworkStream.Read, that only manages to read 5 bytes each time
/// </summary>
/// <param name="span"></param>
/// <returns></returns>
static int FakeNetworkStreamRead(Span<byte> span)
{
    var pending = Math.Min(_data.Length - _position, span.Length);
    pending = Math.Min(pending, 5);
    for (int i = _position, j = 0; i < _position + pending; j++, i++)
    {
        span[j] = _data[i];
    }
    _position += pending;
    return pending;
}


texts:
I am solving the Prime Reduction challenge on Kattis.

  Consider the following process, which we’ll call prime reduction. Given an input x:

  if x is prime, print x and stop
  factor x into its prime factors p1, p2, …, pk
  let x = p1 + p2 + ⋯ + pk
  go back to step 1

  Write a program that implements prime reduction.

  Input

  Input consists of a sequence of up to 20000 integers, one per line, in the range 2 to 109. The number 4 will not be included in the sequence (try it to see why it’s excluded). Input ends with a line containing only the number 4.

  Output

  For each integer, print the value produced by prime reduction executed on that input, followed by the number of times the first line of the process executed.

I have already solved it using Java. Now I am trying to solve it in python. My code did well on the sample tests, but on the second test my code fails due to time limit exceeded.

Someone could tell me what I did wrong?

My python code:

import sys
from math import sqrt, floor

def is_prime_number(number):
    if number == 2:
        return True
    if number % 2 == 0:
        return False
    return not any(number % divisor == 0 for divisor in range(3, floor(sqrt(number)) + 1, 2))

def sum_prime_factors(number):
    factors = 0
    while number % 2 == 0:
        factors += 2
        number = floor(number / 2)
    if is_prime_number(number):
        factors += number
        return factors
    for factor in range(3, floor(sqrt(number)) + 1, 2):
        if is_prime_number(factor):
            while number % factor == 0:
                factors += factor
                number = number / factor
            if number == 1:
                return factors
    factors += number
    return factors

def print_output(x, i):
    if is_prime_number(x):
        print(x, i)
        return
    i = i + 1
    factors = sum_prime_factors(x)
    print_output(factors, i )

[print_output(item, 1) for item in map(int, sys.stdin) if item != 4]


texts: Populate Drop Down List from SQL Database

texts:
I am populating a drop down list from my SQL database. List should be able to be displayed with active only, inactive only or both at the same time.

OfficeRepository.cs:

    public static List<OfficeRollups> ListOfficeRollups(bool active, bool inactive)
    {
        List<DataRow> listDataRow = null;

        string whereClause = string.Empty;

        if (active && !inactive)
            whereClause += @" And Active = 1";
        else if (!active && inactive)
            whereClause += @" And Active = 0";

        string srtQry = @"
Select OfficeRollupID, OfficeRollupName, Active
From OfficeRollups
Where 1 = 1 " + whereClause + @"
Order By OfficeRollupName
";

        using (SqlConnection conn = new SqlConnection(Settings.ConnectionString))
        {
            using (SqlCommand objCommand = new SqlCommand(srtQry, conn))
            {
                objCommand.CommandType = CommandType.Text;
                DataTable dt = new DataTable();
                SqlDataAdapter adp = new SqlDataAdapter(objCommand);
                conn.Open();
                adp.Fill(dt);
                if (dt != null)
                {
                    listDataRow = dt.AsEnumerable().ToList();
                }
            }
        }

        var listOfficeRollups = (from o in listDataRow
                           select new OfficeRollups
                           {
                               OfficeRollupID = o.Field<int>("OfficeRollupID"),
                               OfficeRollupName = o.Field<string>("OfficeRollupName"),
                               Active = o.Field<bool>("Active")

                           }).ToList();

        return listOfficeRollups;
    }

    public static IEnumerable<SelectListItem> ListOfficeRollupsForDD(bool active, bool     inactive)
    {
        var listOfficeRollups = OfficeRepository.ListOfficeRollups(active, inactive);

        return from o in listOfficeRollups.ToList()
               where o.OfficeRollupName.Length != 0
               orderby o.OfficeRollupName
               select new SelectListItem
               {
                   Text = o.OfficeRollupName,
                   Value = o.OfficeRollupID.ToString()
               };
    }

HomeController.cs:

    public ActionResult Create()
    {
        Office currentOffice = new Office();

        var listOfficeRollups = OfficeRepository.ListOfficeRollupsForDD(true, false);
        currentOffice.OfficeRollups = listOfficeRollups;

        return View(currentOffice);
    }

Create.cshtml:

@model Office
@using (Html.BeginForm())
{
    @(Html.DropDownList("OfficeRollupID", Model.OfficeRollups))
}

Office.cs:

public class Office
{
    [Required]
    [Display(Name = "Office Rollup")]
    public IEnumerable<SelectListItem> OfficeRollups { get; set; }

    public Int32 OfficeRollupID { get; set; }
}


texts:
I wanted to write a generic abs function that would correctly work for every type. Basically, I wanted to use the following algorithm:

If the type is a built-in integer, use std::abs from <cstdlib>.
If the type is a built-in floating-point, use std::abs from <cmath>.
If the type is a user-defined type with a namespace-level abs, use it.
Otherwise, call a generic abs algorithm.

Here is what I came up with:

#include <cmath>
#include <cstdlib>

namespace math
{
    namespace detail
    {
        // generic abs algorithm
        template<typename T>
        constexpr auto abs(const T& value)
            -> T
        {
            return (T{} < value) ? value : -value;
        }
    }

    template<typename T>
    constexpr auto abs(const T& value)
        -> T
    {
        using std::abs;
        using detail::abs;
        return abs(value);
    }
}

The idea is to create a generic detail::abs algorithm, then to create another abs function that will choose the function to call thanks to the argument-dependant lookup. Here is what I tried to take into account:

While the generic algorithm also works for built-in integral and floating point types, std::abs may produce optimized code for these types. Using std::abs when possible will probably generate an optimized executable. That said, std::abs lacks constexpr, which is a desirable feature, and the compiler might recognize a absolute value-like construct and optimize it away...
Some types have a namespace-level abs that does not behave like the generic algorithm. Therefore, we have to call this namespace-level function if it exist.
Some types may be huge. Therefore, I chose to take the parameter by const& since some namespace-level abs may also take their parameter by const&.
Some types only provide operator< to represent the ordering, but not the other relational operators. Therefore, calling operator< in the generic algorithm is more likely to work.
I chose to use T{} instead of 0 for the comparison in the generic algorithm in order to be able to represent the default value for any given type. A type is not guaranteed to be comparable to an integer.

Here is a test case to demonstrate what the function can achieve (you can also test it online):

namespace eggs
{
    struct Foo
    {
        Foo(int val):
            val(val)
        {}

        int val;
    };

    Foo abs(Foo foo)
    {
        return { std::abs(foo.val) };
    }
}

struct Bar
{
    Bar(int val=0):
        val(val)
    {}

    Bar operator-() const
    {
        return { -val };
    }

    int val;
};

bool operator<(const Bar& lhs, const Bar& rhs)
{
    return lhs.val < rhs.val;
}

int main()
{
    using namespace std::literals;

    std::cout << math::abs(-5) << '\n';
    std::cout << math::abs(-5.3f) << '\n';
    std::cout << math::abs(-5i+2.0) << '\n';

    eggs::Foo foo = { -8 };
    std::cout << math::abs(foo).val << '\n';

    Bar bar = { -9 };
    std::cout << math::abs(bar).val << '\n';
}

What do you think of such a function? Did I miss any obscure error? Do you see anything that could be improved (in the implementation, I don't care about the test case)?