texts: Converting Date object in CoffeeScript to string (with a weird format)

texts:
I'm trying to convert a Date object into a weird format, like so:

03/30/2017 11:37:14:082 -0500

The issue that really trips me up is the timezone offset. There's no way that screams at me as easy to do, so here's my implementation (in coffeescript, hopefully it's easy enough to understand without intimate knowledge of coffeescript):

  timeStamp = new Date()
  offsetHours = timeStamp.getTimezoneOffset() / 60 * 100
  if offsetHours <= -1000
    offsetString = "+" + Math.abs(offsetHours)
  else if offsetHours == 0
    offsetString = "+0000"
  else if offsetHours < 0 and offsetHours > -1000
    offsetString = "+0" + Math.abs(offsetHours)
  else if offsetHours >= 1000
    offsetString = "-" + offsetHours
  else
    offsetString = "-0" + offsetHours
  timeStampString = (timeStamp.getMonth() + 1) + '/' + timeStamp.getDay() +
    '/' + timeStamp.getFullYear() + " " + timeStamp.getHours() + ":" +
    timeStamp.getMinutes() + ":" + timeStamp.getSeconds() + ":" +
    timeStamp.getMilliseconds() + " " + offsetString

I realize my implementation isn't handling time-zones that have 30 minute offsets (which will get fixed) but I am looking to see if anyone can poke any other holes they see here. This code kind of smells to me and I feel like there should be an easier way to accomplish this.

I've spoofed the date prototype for JS to test a variety of time-zones and haven't found anything weird yet. This is to support interop with another application so "use a different scheme" unfortunately isn't an option. I'd like to avoid using libraries as well.


texts:
I need to create a database which stores details products, Manufactures,Suppliers. So initially I divided Products into categories and subcategories.

These are the tables I created.

Manufacturer, Category, Sub_Category, Products,
ProductSpecs, ProductAvailability, Supplier

Manufacturer table contains Brand Details (Ex: Apple,Windows..etc).
Supplier table should contain supplier details and price they are offering.
Category contains provides details like Electronics, Sports...etc.
Subcategory table should contains subcategories like Electronics(Mobiles,Laptops...).
Products table have only basic product details like ID,Name.
ProductSpecs contains specifications. Based on product we should have separate separate table for each subcategory.
ProductAvailability should contains product price and availability.

I am not good at database design. But managed to create the below one. Could you please anyone review this? Please help me if it needs any corrections.

CREATE TABLE Supplier
  (
  SupplierID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  SupplierName VARCHAR(30) NOT NULL DEFAULT '',
  SupplierTag  VARCHAR(30) NOT Null DEFAULT '',
  );

CREATE TABLE Category
    (
    CategoryID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    CategoryName VARCHAR(30) NOT NULL DEFAULT '',
    CreatedBy VARCHAR(30) NOT NULL DEFAULT '',
    CreatedOn DATETIME NOT NULL
    );

CREATE TABLE Sub_Category
    (
    SubCategoryID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    SubCategoryName VARCHAR(30) NOT NULL,
    CategoryID INT FOREIGN KEY REFERENCES CATEGORY(CategoryID),
    CreatedBy VARCHAR(30) NOT NULL,
    CreatedOn DATETIME NOT NULL
    );

CREATE TABLE Manufacturer
    (
    ManufacturerID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    ManufacturerName VARCHAR(30) NOT NULL DEFAULT '',
    SubCategoryID INT FOREIGN KEY REFERENCES SUB_CATEGORY(SubCategoryID),
    );

CREATE TABLE Products
  (
  ProductID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  ProductName   VARCHAR(50) NOT NULL DEFAULT '',
  CategoryID INT FOREIGN KEY REFERENCES CATEGORY(CategoryID),
  SubCategoryID INT FOREIGN KEY REFERENCES SUB_CATEGORY(SubCategoryID),
  ManufacturerID INT FOREIGN KEY REFERENCES Manufacturer(ManufacturerID)
  );

CREATE TABLE ProductSpecs
(
  RowID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  ProductID INT FOREIGN KEY REFERENCES Products(ProductID),
  SubCategoryID INT FOREIGN KEY REFERENCES SUB_CATEGORY(SubCategoryID),
  ProductSpec1 VARCHAR(30),
  ProductSpec2 VARCHAR(30),
  ProductSpec3 VARCHAR(30),
)

CREATE TABLE ProductAvailability
(
  RowID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
  ProductID INT FOREIGN KEY REFERENCES Products(ProductID),
  SupplierID INT FOREIGN KEY REFERENCES Supplier(SupplierID),
  SupplierWEB Varchar(30) NOT NULL,
  ProductPrice decimal(6,2) NOT NULL,
)


texts: More functional way of writing this palindrome extractor?

texts:
I wrote this palindrome extractor.  And even though it works, and I can solve the challenge with it, it feels very Java-like. I was wondering what adjustments I could make in order for it to be more functional.

import collection.mutable._

object Level1 {
    def palindrome(input:String) = input.reverse == input

    def extractPalindromes(input:String) =
    {
        var counter = 0
        val palindromes = new ListBuffer[String]()
        while(counter < input.length)
        {
            var localCounter = 2
            while((counter + localCounter) < input.length)
            {
                //println("counter:"+counter+" localCounter:"+localCounter)
                val tempString = input.substring(counter, input.length - localCounter)
                if(palindrome(tempString)) palindromes += tempString
                localCounter += 1
            }
            counter += 1
        }
        palindromes
    }

    def main(args:Array[String]) = {
        val input = "I like racecars that go fast"
        extractPalindromes(input).filter(_.length > 4).foreach(println)
    }
}


texts:
Is there any way of optimizing this code?

private void ModifyDataTable(DataTable dt)
{
    if (dt != null)
    {
        bool b_dataValue = false;
        decimal rowreport_data0Sum, rowreport_data1Sum, rowreport_data2Sum, rowreport_data3Sum, rowreport_data4Sum;
        rowreport_data0Sum = rowreport_data1Sum = rowreport_data2Sum = rowreport_data3Sum = rowreport_data4Sum = 0;
        foreach (DataRow row in dt.Rows)
        {

            if (row.ItemArray[1].ToString() == "$150,000 & Over" || row.ItemArray[1].ToString() == "$150,000 - $199,999" || row.ItemArray[1].ToString() == "$200,000 - $299,999" || row.ItemArray[1].ToString() == "$300,000 & Over")
            {

                rowreport_data0Sum += GetRowValue(row, "report_data0");
                rowreport_data1Sum += GetRowValue(row, "report_data1");
                rowreport_data2Sum += GetRowValue(row, "report_data2");
                rowreport_data3Sum += GetRowValue(row, "report_data3");
                rowreport_data4Sum += GetRowValue(row, "report_data4");
            }
        }
        if (dt.Columns.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {

                if (row.ItemArray[1].ToString() == "$150,000 & Over")
                {
                    foreach (DataColumn col in dt.Columns)
                    {
                        if ((col.ColumnName == "report_data0") || (col.ColumnName == "report_data1") || (col.ColumnName == "report_data2") || (col.ColumnName == "report_data3") || (col.ColumnName == "report_data4"))
                        {

                            if (!row.IsNull(col))
                            {
                                b_dataValue = true;
                                if (b_dataValue)
                                {
                                    if (col.ColumnName == "report_data0") row[col] = rowreport_data0Sum + "%";
                                    else if (col.ColumnName == "report_data1") row[col] = rowreport_data1Sum + "%";
                                    else if (col.ColumnName == "report_data2") row[col] = rowreport_data2Sum + "%";
                                    else if (col.ColumnName == "report_data3") row[col] = rowreport_data3Sum + "%";
                                    else if (col.ColumnName == "report_data4") row[col] = rowreport_data4Sum + "%";
                                }
                                else
                                {

                                    dt.Rows.Remove(row);

                                }
                            }
                        }
                    }

                }
            }
            if (b_dataValue)
            {
                for (int i = dt.Rows.Count - 1; i >= 0; i--)
                {
                    DataRow row = dt.Rows[i];
                    if (row.ItemArray[1].ToString() == "$150,000 - $199,999" || row.ItemArray[1].ToString() == "$200,000 - $299,999" || row.ItemArray[1].ToString() == "$300,000 & Over")
                    {
                        dt.Rows.Remove(row);
                    }
                }

            }
        }
    }
}


texts:
I need help in optimizing my code for this challenge. I think my algorithm is fine and I pass all sample tests but get took longer than 12000ms to complete error for final one.

I guess there are a lot of unnecessary variables but this is all my beginners Ruby brain could think of. :)

I have started learning coding 2 weeks ago so style-wise this is most certainly horrible.

Kata link

  Instructions :

  Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.
  Negative numbers and duplicate numbers can and will appear.

  NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.

def sum_pairs(numbers, sum)
  # Idea was :
  #  1. To iterate over array elements take their sum and add
  #     it to hash if it is equal to "sum".
  #  2. Sort hash by value to find lowest second parameter since
  #     we need entire pair to be first not just first element.
  #  3. Convert that hash to array so that I could take value
  #      of those elements and return actual numbers.
  #     (Didn't know to do it from hash directly :))
  x = 0
  h = {}
  while x < numbers.length
    y = 0
    while y < numbers.length
      sum_test = numbers[x] + numbers[y]
      if sum_test == sum && x != y && x < y
        h[x] = y
      end
      y += 1
    end
    x += 1
  end
  if h.empty?
    return nil
  else
    final_positions = h.sort_by {|key, value| value}.first.to_a
    return numbers[final_positions[0]], numbers[final_positions[1]]
  end
end


texts: Parsing a sequence of bits out of a bit field

texts:
For homework, I had to parse CPUID instruction output in C, which required a lot of specific bit-manipulation like:

(eax & CACHE_LEVEL) >> 5

I calculated the mask CACHE_LEVEL and the amount that was needed to be right-shifted by hand. It was a pain, so I decided to write a couple Python functions to help with this.

For example:

>>> eax = 0x4004121  # Taken from a register after executing a CPUID instruction with leaf-4 indicated
>>> parse_out_bits(eax, 5, 7)  # Return the value at bits 5 to 7 (inclusive)
1  # This is an L1 cache

Indices are 0-based and inclusive.

Where eax is the following, and I want the value of the bits from S to E:

                        E S
100 0000 0000 0100 0001 0010 0001

I'd like notes on anything here, but specifically how this could be done better in terms of bit manipulation.

from typing import Generator

def bit_place_values(start_index: int, end_index: int) -> Generator[int, None, None]:
    acc = 1 << start_index
    for _ in range(start_index, end_index + 1):
        yield acc
        acc <<= 1

def parse_out_bits(bit_field: int, start_index: int, end_index: int) -> int:
    mask = sum(bit_place_values(start_index, end_index))
    return (mask & bit_field) >> start_index


texts: Positive, Negative or zero in a 2D array python

texts:
I'm trying to find a way to know if a number on a matrix is positive, negative or zero. Below is my code, but I'm wondering if there is a more Pythonic way to write that. Any ideas?
array = np.random.randint(-10,10, size=(10,10))

def function(array):
    case1 = np.where(array < 0, -1, array)
    case2 = np.where(case1 > 0, 1, case1)
    case3 = np.where(case2 == 0, 0, case2)
    return case3

print(function(array))


texts: Show results of a runners' competition with details about each runner

texts:
This is about to show the results of a runners' competition.  It shows us the runner's number, the sex ( 1 = man, 0 = woman ), age and time.  After showing the results of these runners, it shows the winner of each sex.

package *;
public class ArraysSix {
    public static void main(String[] args) {
      //int pm = position man, pw = position woman
      int pm = 0;
      int pw = 0;

      String[] a = {"Runner", " Sex", " Age", "    Min"};
      String[][] b = {
            {"  3457", "   1", "  41", "     39"},
            {"   344", "   1", "  30", "     38"},
            {"  3333", "   0", "  28", "     45"},
            {"  3450", "   0", "  45", "     50"},
            {"   101", "   1", "  21", "     52"},
            {"   455", "   1", "  37", "     41"},
            {"   100", "   0", "  40", "     37"},
      };
      //array int
      int[][] c = {
            { 3457, 1 , 41 , 39 },
            { 344 , 1 , 30 , 38 },
            { 3333, 0 , 28 , 45 },
            { 3450, 0 , 45 , 50 },
            { 101 , 1 , 21 , 52 },
            { 455 , 1 , 37 , 41 },
            { 100 , 0 , 40 , 37 },
     };
     //for print title
     for (int i = 0; i < a.length; ++i) {
        System.out.print("|"+a[i]+"|");
     }
     System.out.println("\n-----------------------------");
     //for print numb
     for (int i = 0; i < b.length; ++i) {
        for(int j = 0; j < b[i].length; ++j) {
            System.out.print("|"+b[i][j]+"|");
        }
        System.out.println("\n-----------------------------");
     }
     //for to find the minimun time of man
     for ( int i = 0 ; i < 7 ; i++) {
        if ( c[i][1] == 1 ) {
            if ( c[i][3] < c[pm][3] ) {
                pm = i ;
            }
        //else to find the minimum of woman
        } else {
            if ( c[i][1] == 0 ) {
                if ( c[i][3] < c[pw][3] ) {
                    pw = i ;
                }
            }
        }//end else
    }//end for

    //for to print the winners
    for (int i = 0 ; i < 1 ; i++ ) {
        System.out.print("Runner num "+c[pm][0]
                +" with an age of "+c[pm][2]
                +" and time of "+c[pm][3]
                +" min is the male winner.");
        System.out.println("");

        System.out.print("Runner num "+c[pw][0]
                +" with an age of "+c[pw][2]
                +" and time of "+c[pw][3]
                +" min is the female winner.");
    }//end for
 }//end method
}//end class

So I think there's is a better way to make this piece of program, but I don't have the knowledge yet.


texts: Retrieving MAC addresses based on PCI interface connections and SQL queries

texts:
I am currently using this C# method to retrieve MAC addresses from a user's computer as a sort of unique identification. It retrieves the MAC address based on the fact that the physical card is connected to the PCI interface.

public static string returnMAC()
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select MACAddress, PNPDeviceID FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND PNPDEVICEID IS NOT NULL");
    ManagementObjectCollection mObject = searcher.Get();

    foreach (ManagementObject obj in mObject)
    {
        string pnp = obj["PNPDeviceID"].ToString();
        if (pnp.Contains("PCI\\"))
        {
            string mac = obj["MACAddress"].ToString();
            mac = mac.Replace(":", string.Empty);
            return mac;
        }
    }
    return "Nothing happened...";
}

A method I used previously was pulled straight from MSDN, but due to some issues it inherently had (like pulling the wireless' MAC instead of the LAN line), I switched it out for this one.

I have tested this method on Windows 7 and 8.1 systems, and it works fine in retrieving the physical MAC address. With that said - it uses SQL queries to search for strings, instead of a more typical method that uses System.Net.XXX - a more "built-in" and "native" method. Correct me if I am wrong on this.

Is there any way to make this better? I can't think of what would make it better, but on the top of my head - LINQ queries? Native methods? I'm not sure.


texts: Handling workflow rules for a job application process

texts:
For some reason I always have a negative feeling towards having many if statements in my JavaScript functions. But I've got some code that is processing an object that defines rules of an event. I need to determine one or many things to do based on the "rules" outlined in each object.

(Particularly four if statements deep within a for loop just gives me the heebie-jeebies for some reason.)

Is there a faster way to handle this type of rules-like processing? Clearly I could break this into some smaller functions to clean up the syntax, but I am mostly looking for feedback/suggestions around speed of processing the request.

The idea here is to capture customer conversion events throughout a user's interaction with a job application. Each conversion has an 'initiate' and a 'complete'. The "rules" which determine when to initiate and when to complete each conversion are setup in a JSON file which I then parse into a JavaScript object: applicationConversionEvents.

The JSON looks something like so:

[
  {
    "eventId": "view",
    "eventName": "App View to Start",
    "initiateOnStepNumber": 100,
    "completeIfAuthenticated": true,
    "completeOnElementClick": "first_name"
  },
  {
    "eventId": "submit",
    "eventName": "App Start to Submit",
    "initiateOnEventComplete": "view",
    "completeOnStepNumber": 450,
    "completeOnEventInitiate": "decline"
  },
  {
    "eventId": "decline",
    "eventName": "App Decline",
    "initiateOnStepNumber": 350,
    "completeOnStepNumber": [
      350,
      375
    ]
  }
]

I am then using the following function to parse the rules for each conversion event, and when appropriate fire off a new event either as an 'initiate' or a 'complete'. I also track what events fire in sessionStorage to avoid duplicates per application.

var _processApplicationConversionEvents = function(pageInfoArrayIndex, options) {
    _log('Processing application conversion events.', LOG_LEVEL.INFO);

    if(!Array.isArray(applicationConversionEvents)) return;
    if(!_isValidPageInfoArrayIndex(pageInfoArrayIndex)) pageInfoArrayIndex = 0;

    _log('Conversions for pageInfoArrayIndex: ' + pageInfoArrayIndex, applicationConversionEvents, LOG_LEVEL.DEBUG);

    var pageInfo = _getPageInfo(pageInfoArrayIndex, options);
    _log('pageInfo details for conversion events:', pageInfo, LOG_LEVEL.DEBUG);

    for(var i = 0, len = applicationConversionEvents.length; i < len; i++) {
        var conversionEvent = applicationConversionEvents[i];
        if(typeof conversionEvent !== 'object') continue;

        if(conversionEvent.initiateOnStepNumber) {
            var appStepNumber = _asArray(conversionEvent.initiateOnStepNumber);

            if(appStepNumber.indexOf(+pageInfo.appStepNumber) > -1) {
                _newConversionEvent('initiate', conversionEvent, pageInfo);

                if(_toLowerCaseString(conversionEvent.completeIfAuthenticated) === 'true'
                   && pageInfo.authenticated) {
                    _newConversionEvent('complete', conversionEvent, pageInfo);

                    if(!conversionEvent.completeOnElementClick) continue;
                    _removeConversionOnClickListener(conversionEvent.completeOnElementClick);
                }
            }
        }

        if(conversionEvent.completeOnStepNumber) {
            var appStepNumber = _asArray(conversionEvent.completeOnStepNumber);

            if(appStepNumber.indexOf(+pageInfo.appStepNumber) > -1) {
                _newConversionEvent('complete', conversionEvent, pageInfo);
                continue;
            }
        }

        if(conversionEvent.completeOnElementClick) {
            _addConversionOnClickListener('complete', conversionEvent, pageInfo);
        }
    }
}


texts:
This is an updated version of my previously posted "Blackjack game made in Python 3". I think I did almost everything @Austin Hastings recommend me to do and I hope you like it.

from random import shuffle
import os

def shuffled_shoe():
    shoe = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']*4
    shuffle(shoe)
    return shoe

def deal_card(shoe, person, number):
    for _ in range(number):
        person.append(shoe.pop())

def deal_hand(shoe, player, dealer):
    deal_card(shoe, player, 2)
    deal_card(shoe, dealer, 2)

def score(person):
    non_aces = [c for c in person if c != 'A']
    aces = [c for c in person if c == 'A']
    total = 0
    for card in non_aces:
        if card in 'JQK':
            total += 10
        else:
            total += int(card)
    for card in aces:
        if total <= 10:
            total += 11
        else:
            total += 1
    return total

def display_info(player, dealer, player_stands):
    os.system('cls' if os.name == 'nt' else 'clear')
    print("Your cards:   [{}] ({})".format("][".join(player), score(player)))
    if player_stands:
        print("Dealer cards: [{}] ({})".format("][".join(dealer), score(dealer)))
    else:
        print(f"Dealer cards: [{dealer[0]}][?]")

def hit_or_stand():
    while True:
        print("What do you choose?")
        print("[1] Hit")
        print("[2] Stand")
        ans = input("> ")
        if ans in '12':
            return ans

def player_play(shoe, player, dealer, player_plays, dealer_plays, player_stands):
    while not player_stands:
        if hit_or_stand() == '2':
            player_plays = False
            dealer_plays = True
            player_stands = True
            display_info(player, dealer, True)
        elif not player_stands:
            deal_card(shoe, player, 1)
            display_info(player, dealer, False)
            if score(player) >= 21:
                player_plays = False
                break
    return (player_plays, dealer_plays, player_stands)

def dealer_play(shoe, dealer, DEALER_MINIMUM_SCORE, player):
    while score(dealer) <= DEALER_MINIMUM_SCORE:
        deal_card(shoe, dealer, 1)
    display_info(player, dealer, True)
    return False

def results(player, dealer, player_stands, first_hand, still_playing):
    if score(player) == 21:
        print("Blackjack! You won")
        still_playing = False
    elif first_hand and score(dealer) == 21:
        print("Dealer got a blackjack. You lost!")
        still_playing = False
    elif score(player) > 21:
        print("Busted! You lost!")
        still_playing = False
    if player_stands:
        if score(dealer) > 21:
            print("Dealer busted! You won")
        elif score(player) > score(dealer):
            print("You beat the dealer! You won!")
        elif score(player) < score(dealer):
            print("Dealer has beaten you. You lost!")
        else:
            print("Push. Nobody wins or losses.")
        still_playing = False
    return still_playing

def main():
    shoe = shuffled_shoe()
    player = []
    dealer = []
    player_plays = True
    still_playing = True
    dealer_plays = False
    player_stands = False
    deal_hand(shoe, player, dealer)
    display_info(player, dealer, player_stands)
    still_playing = results(player, dealer, player_stands, True, still_playing)
    while still_playing:
        while player_plays:
            (player_plays, dealer_plays, player_stands) = player_play(shoe, player, dealer, player_plays, dealer_plays, player_stands)
        while dealer_plays:
            dealer_plays = dealer_play(shoe, dealer, 17, player)
        still_playing = results(player, dealer, player_stands, False, still_playing)

if __name__ == '__main__':
    main()


texts:
I took some time to try and solve a problem. I am building a basic Node + Express API. In the app I have created a models folder and will be adding new models as I continue development.

I attempted to write a small autoloader for a directory to automatically load and export my models. This code snippet should work for any modules not just my models folders.

See the following code:

loader.js

const fs = require('fs');
// Autoload modules.
module.exports = fs.readdirSync(__dirname)
                    // Ignore current file (loader.js)
                    .filter(f => !__filename.includes(f))
                    // Require all files in directory
                    .map(f => require( `./${f}` ))
                    // Add to final module.exports object using class name
                    .reduce((prev, curr) => ({...prev, [curr.name]: curr}), {});

My folder structure for the models:

How I import the models into my Routes file:

author.route.js

const { AppResponse, Author } = require('../models/loader');

The question:

Is this a good idea to do something like this? My reasoning is that it would minimize changes when I commit and not require any modifications to my code should I decide to add new functionality to my routes and models folders.

What caveats are there to doing this and would there be a better approach?

Thanks for taking the time to look at this!


texts: Using Array.prototype.filter() and Array.prototype.map()

texts:
I need to first filter items for an array of objects {type: 'genre', value: '123'} and after combine in a string content for property value only.

Any suggestions on how to improve the following code?

this.flattenCategories = function () {
    // flatten in a single string all categories so to be easily visaulised in the dom
    var categories = this.information.filter(function (item) {
        if (item.type === 'genre') {
            return item;
        }
    });
    this.categoriesFlatten = categories.map(function (item) {
        return item.value;
    }).join(CONFIG.app.categoriesSeparator)
},


texts:
Can I do something better with this code?  It's just a snippet of a library I wrote.

<?php
/*
 * Variable.class.php
 * (c) 2013 sinan eker`enter code here`
 * */
 class Variable extends Config {
     protected static $vars = array();
     final public static function variables(){
         return static::$vars;
     }
     final public static function clear(String $name){
         unset(static::$vars[$name->getString()]);
     }
     final public static function destruct(){
         unset(static::$vars);
         static::$vars = array();
     }
     final public static function override(String $name, $value){
         static::clear($name);
         static::register($name, $value);
     }
     final public static function get(String $name){
         $name = $name->getString();
         return (isset(static::$vars[$name]) ? static::$vars[$name] : null);
     }
     final public static function register(String $name, $value){
         return (!is_null(static::get($name)) ? false : static::$vars[$name->getString()] = $value);
     }
 }


texts: HTML page compiling LaTeX code to nice mathematics display - 2nd attempt

texts:
I have this page that allows a user to quickly compile \$\LaTeX\$ code into a mathematical display. Whenever the user compiles the code, that page also generates an URL from which it is possible to view the output simply by visiting the URL:

index.html (Note that this Stack Snippet generates non-working URLs because it is on a different domain):

<!DOCTYPE html>

        <title>LaTeX console</title>
        <meta charset="UTF-8">

Type in the LaTeX code and press Compile!

                {06f672e0-065e-445d-8e16-0790142de8ab}

Input area

            <textarea id="latex_input" rows="5" cols="80">{bcd26d9d-9bcd-40d8-9357-ef17752144a1}</textarea>

            <button type="button" id="compile_button">Compile!</button>

URL to share

            <textarea id="encoded_url_textarea" rows="5" cols="80"></textarea>

As always, any critique is appreciated.


texts: Write premake4.lua file that builds and links to static libraries using premake

texts:
I am trying to write a premake4.lua file that builds and links to static libraries using premake.

library mbm was originally designed to be built using cmake. So to go around this issue I call ./configure then I build it using premake4 gmake.
library jansson was originally designed to be built using cmake. But calling ./configure was not enough to build it, since cmake was also generating jansson_config.h that is needed for the build. So I ended up calling premake with prebuildcommands to build jansson using cmake first.

I don't think the way I built jansson is nice at all. Any idea how I can make this better?

premake.lua:

local homepath = os.getenv("HOME")

newoption {
   trigger     = "create-static-libs",
   description = "Creates all the necessary dependencies to build the ProjectA"
}

solution "ProjectA"
  configurations { "Debug", "Release"}

  configuration { "Debug" }
    objdir "../build/debug"
    targetdir "../install/bin/debug"

  configuration { "Release" }
    objdir "../build/release"
    targetdir "../install/bin/release"

  if _ACTION == "clean" then
    os.rmdir("../install")
    os.rmdir("../build")
  end

  project "mbm"
    kind "StaticLib"
    language "C"
    includedirs { "mbm/" }
    files{ "mbm/src/**.h","mbm/src/**.c"}

    configuration { "create-static-libs" }
      prebuildcommands { "cd mbm; ./configure; cd -; rm -rf config.log" }

  project "ProjectA"
    kind "ConsoleApp"
    language "C++"
    links {"mbm", "jansson"}
    includedirs { "include/**", "mbm/**", "jansson-2.7/**" }
    files { "bin/**.h", "bin/**.cpp" }

    configuration { "Debug*" }
      libdirs { "../install/bin/debug/" }
      defines { "_DEBUG", "DEBUG" }
      flags   { "Symbols" }

      if _OPTIONS[ "create-static-libs" ] then
        prebuildcommands { "cd jansson-2.7;./configure --prefix=".. homepath .."/eclipse_workspace/ProjectA/build/jansson --disable-shared;make config=debug;make install;cd -" }
        prebuildcommands { "mkdir -p ../install/bin/debug; mv ../build/jansson/lib/libjansson.a ../install/bin/debug/" }
      end

    configuration { "Release*" }
      libdirs { "../install/bin/release/" }
      defines { "NDEBUG" }
      flags   { "Optimize" }

      if _OPTIONS[ "create-static-libs" ] then
        prebuildcommands { "cd jansson-2.7;./configure --prefix=".. homepath .."/eclipse_workspace/ProjectA/build/jansson --disable-shared;make config=release;make install;cd -" }
        prebuildcommands { "mkdir -p ../install/bin/release; mv ../build/jansson/lib/libjansson.a ../install/bin/release/" }
      end


texts: Three-table queryset (full outer join?) in Django

texts:
I've got three tables I need query to display to a user for a web application I've written. Each table (Url, Note, Quote) has a foreign key relation to the User table. For every User, I need to sort all Bookmarks, Notes and Quotes based on a _date_created_ field, then deliver that to the template as one iterable. This is for a toy/self-learning project so I don't really need to worry about scale.

The approach I've taken is this:

from operator import attrgetter

from app.models import Url, Note, Quote

date_dict = {}

for url in Url.objects.filter(user=request.user):
    date_dict[url.date_created] = Url.objects.get(date_created=url.date_created)

for note in Note.objects.filter(user=request.user):
    date_dict[note.date_created] = Note.objects.get(date_created=note.date_created)

for quote in Quote.objects.filter(user=request.user):
    date_dict[quote.date_created] = Quote.objects.get(date_created=quote.date_created)

my_query = sorted((date_dict[i] for i in date_dict.iterkeys()),
                  key=attrgetter("date_created"),
                  reverse=True)

I have also tried this:

from operator import attrgetter
from itertools import chain

from app.models import Url, Note, Quote

items = sorted(chain(Url.objects.filter(user=request.user),
                     Note.objects.filter(user=request.user),
                     Quote.objects.filter(user=request.user)),
               key=attrgetter("date_created"),
               reverse=True)

I'm concerned how expensive this would get if I had huge data sets (I don't), but from what I've read the second is faster.

This code works and does what I expect it to, but is there a better/faster approach?


texts:
def users_list
  html = ''
  self.users.each do |user|
    html << user.link_avatar_tag
  end
  html.html_safe
end

I feel that it is possible to write shorter.

Is it possible get rid of the temporary variable(html)?


texts: Debounce counter for PIC micro - Suggestions for improvement

texts:
I developed this code for a vertical debounce counter for the PIC micro (PIC16F57). The code is called every 512 microseconds. It takes 5 bits from PORTB and compares it to a last known debounced state. If an active input has been stable for 64 calls it is accepted as changed. Though it is sufficiently good for the current application, I am interested in possible improvements to speed up overall execution time. I am not interested in prematurely leaving the loop in case there is nothing to update.
                        cblock              0x08
gpcounter:1                                         ; general purpose counter
debstate:1
delta:1
toggle:1
vcounter:6
                        endc

    ; Button debounce
                            ; A button state is considered stable if it has not changed in 64 polls each 512 usec
        debounce            ; Read input state. Only bits 0-4 are inputs
                            movf            PORTB, W
                            andlw           0x1f
                            ; Any input bits that have changed with respect to the last known state
                            ; will be set to 1's in delta and toggle.
                            ; delta remains fixed, toggle will act as a carry while looping
                            ; Because toggle bits will be reset only, toggle will always be a subset of delta.
                            xorwf           debstate, W
                            movwf           delta
                            movwf           toggle
                            ; Load first counter row in index register
                            movlw           vcounter
                            movwf           FSR
                            ; Counter has 6 rows
                            movlw           0x06
                            movwf           gpcounter
        debounceloop        ; Reset row for all bits which  have not changed states
                            movf            delta, W
                            andwf           INDF, F
                            ; Flip row bits according to toggle mask.
                            ; Because the 1's in toggle are a subset of those in delta,
                            ; any reset counter bits can never be toggled back to 1
                            movf            toggle, W
                            xorwf           INDF, F
                            ; If any bits were toggled from 1 to 0, retain carry bit, else discard it
                            comf            INDF, W
                            andwf           toggle, F
                            ; We're done with this row
                            incf            FSR, F
                            decfsz          gpcounter, F
                            goto            debounceloop
                            ; toggle will now contain 1's for any counters
                            ; that have overflown, so it can be used as xor mask
                            ; to update the last known debounced state
                            movf            toggle, W
                            xorwf           debstate, F
                            retlw           0x00


texts:
I wrote a program to find the greatest common divisor between two numbers. How do I improve this program?

#include<iostream>
using namespace std;

int main() {

int first_number;
cout<<"Enter First Number : ";
cin>>first_number;

if(first_number < 0)
cout << "Please enter a positive number" << endl;
cin >> first_number;

int  second_number;
cout<<"Enter Second Number: ";
cin>>second_number;

if(second_number < 0)
cout << "Please enter a positive number" << endl;
cin >> second_number;

int  gcd;
for(int i=1;i<=first_number&&i<=second_number;i++){

if(first_number%i==0 && second_number%i == 0 ){

gcd=i;

   }

}

cout<<"Greatest Common Divison (GCD):"<<gcd<<endl;
return 0;
}


texts: Kotlin reflection to generate one class from class similar with similar properties

texts:
This code is intended to generate a class (domain) from a class with class with similar/identical properties (api). Motivation is to speed development time when using clean architecture.

import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import javax.inject.Inject
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.findAnnotation

class DomainApiReflectionAdapter<DOMAIN : Any, API : Any> constructor(
        val clazz: KClass<DOMAIN>
) {

    fun fromApi(apiModel: API): DOMAIN {
        return apiToDomain(apiModel, clazz)
    }

    inline fun <API : Any, DOMAIN : Any> apiToDomain(apiModel: API, clazz: KClass<DOMAIN>): DOMAIN {
        val factory = Factory(clazz)
        val apiProperties = toPropMap(apiModel)
        val constructorMap = mutableMapOf<KParameter, Any?>()
        for (param in factory.params) {
            param.findAnnotation<AdapterValues>()?.let {
                val iclass = param.type.classifier as KClass<*>
                println(iclass)
                constructorMap[param] = innerFactory.simpleConstruct(apiProperties)
            } ?: {
                if (param.name in apiProperties) {
                    constructorMap[param] = when {
                        param.type.classifier == List::class -> {
                            val itype = param.type.arguments[0].type!!.classifier as KClass<*>
                            (apiProperties[param.name] as List<*>).map {
                                it?.toDomain(itype)
                            }
                        }
                        param.type.classifier == DateTime::class -> DateTime(apiProperties[param.name] as Long, DateTimeZone.forID("UTC"))
                        else -> apiProperties[param.name]
                    }
                }
            }()
        }

        return factory.construct(constructorMap)
    }

    fun <K : Any> toPropMap(model: K): Map<String, Any?> {
        return model.javaClass.kotlin.declaredMemberProperties
                .map { prop ->
                    prop.name to prop.get(model)
                }.toMap()
    }

    companion object {
        inline fun <reified DOMAIN : Any, API : Any> instance(): DomainApiReflectionAdapter<DOMAIN, API> {
            return DomainApiReflectionAdapter(DOMAIN::class)
        }
    }

    inner class Factory<DOMAIN : Any>(clazz: KClass<DOMAIN>) {
        private val constructor = clazz.constructors.first()
        val params = constructor.parameters

        fun construct(map: Map<KParameter, Any?>): DOMAIN {
            return constructor.callBy(map)
        }

        fun simpleConstruct(apiProperties: Map<String, Any?>): DOMAIN {
            val innerMap = mutableMapOf<KParameter, Any?>()
            for (ip in params) {
                innerMap[ip] = apiProperties[ip.name]
            }
            return construct(innerMap)
        }
    }
}

fun <DOMAIN : Any, API : Any> API.toDomain(clazz: KClass<DOMAIN>): DOMAIN {
    val adapter = DomainApiReflectionAdapter<DOMAIN, API>(clazz)
    return adapter.fromApi(this)
}

abstract class Adapter<A, B> : (B) -> A

@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class AdapterClass()

@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class AdapterValues(val parameters: Array<String>)


texts:
I happened to need to find both the maximum and the minimum of an array, so I decided to implement a minMax function in D.

Questions:

Is this an efficient implementation?
Is it readable?
Any general feedback is appreciated.

Thanks!

import std.range;
import std.traits;
import std.typecons;
import std.functional;

class EmptyContainerException : Exception {
    this(string msg, string file = __FILE__, size_t line = __LINE__) {
        super(msg, file, line);
    }
}

// returns a tuple containing the minimum and maximum elements of a finite InputRange
template minMax(alias pred = "a") {
    alias map = unaryFun!pred;

    auto minMax(Range)(Range r)
    if(isInputRange!Range && !isInfinite!Range && is(typeof(map(r.front)))) {
        if(r.empty) {
            throw new EmptyContainerException(
                "minMax expected a container with at least 1 element, got an empty container."
            );
        }
        auto front = r.front;
        auto frontMap = map(front);

        auto min = front;
        auto max = front;
        auto minMap = frontMap;
        auto maxMap = frontMap;

        r.popFront;
        while(!r.empty) {
            front = r.front;
            frontMap = map(front);
            if(frontMap > maxMap) {
                max = front;
                maxMap = frontMap;
            }
            if(frontMap < minMap) {
                min = front;
                minMap = frontMap;
            }
            r.popFront;
        }
        return tuple!("min", "max")(min, max);
    }
}

unittest {
    import std.exception : assertThrown;

    int[] test1 = [1, 2, 3, 4, 5];
    auto test1result = test1.minMax;
    assert(test1result.min == 1 && test1result.max == 5);

    string test2 = "Hello, World!";
    auto test2result = test2.minMax;
    assert(test2result.min == ' ' && test2result.max == 'r');

    int[] test3 = [];
    assertThrown!EmptyContainerException(test3.minMax);

    string[] test4 = ["who", "is", "the", "longest", "word"];
    auto test4result = test4.minMax!"a.length";
    assert(test4result.min == "is" && test4result.max == "longest");
}


texts: Calculator using Shunting Yard algorithm

texts:
I have implemented a simple calculator using the Shunting Yard algorithm. It takes infix expression as an input "3 + 5 * 2", which evaluates and returns the value 13.

public class ShuntingYardAlgorithm{
    private static  Map<String, Operator> operatorMap = initializeOperatorMap();

    private static Map<String, Operator> initializeOperatorMap()
    {
        operatorMap = new HashMap<>();
        operatorMap.put(Operator.ADD.sign, Operator.ADD);
        operatorMap.put(Operator.SUBTRACT.sign, Operator.SUBTRACT);
        operatorMap.put(Operator.MULTIPLY.sign, Operator.MULTIPLY);
        operatorMap.put(Operator.DIVIDE.sign, Operator.DIVIDE);
        return operatorMap;
    }

    public ShuntingYardAlgorithm()
    {
        // Default Constructor
    }

    private enum Operator
    {
        ADD(1, "+"),
        SUBTRACT(2, "-"),
        MULTIPLY(3, "*"),
        DIVIDE(4, "/");

        final int precedence;
        final String sign;

        Operator(int precedence, String sign)
        {
            this.precedence = precedence;
            this.sign = sign;
        }
    }

    private static boolean isHighPrecedence(String currentToken, String peekedOperator)
    {
        return operatorMap.containsKey(peekedOperator) && operatorMap.get(peekedOperator).precedence >= operatorMap.get(currentToken).precedence;
    }

    public static Integer evaluateExpression(String infix)
    {
        Stack<String> operatorStack = new Stack<>();
        Stack<Integer> outputStack = new Stack<>();

        for (String currentToken : infix.split("\\s"))
        {

            if ("(".equalsIgnoreCase(currentToken))
            {
                operatorStack.push(currentToken);
            } else if (operatorMap.containsKey(currentToken))
            {
                while (!operatorStack.isEmpty() && isHighPrecedence(currentToken, operatorStack.peek()))
                {
                    String higherPrecedenceOperator = operatorStack.pop();
                    Integer operandLeft = outputStack.pop();
                    Integer operandRight = outputStack.pop();
                    outputStack.push(evaluate(operandLeft, operandRight, higherPrecedenceOperator));

                }
                operatorStack.push(currentToken);
            } else if (currentToken.equalsIgnoreCase(")"))
            {
                while (!"(".equalsIgnoreCase(operatorStack.peek()))
                {
                    String higherPrecedenceOperator = operatorStack.pop();
                    Integer operandLeft = outputStack.pop();
                    Integer operandRight = outputStack.pop();
                    outputStack.push(evaluate(operandLeft, operandRight, higherPrecedenceOperator));
                }
                operatorStack.pop();
            } else
            {
                outputStack.push(Integer.valueOf(currentToken));
            }
        }

        while (!operatorStack.empty())
        {
            String higherPrecedenceOperator = operatorStack.pop();
            Integer operandRight = outputStack.pop();
            Integer operandLeft = outputStack.pop();
            outputStack.push(evaluate(operandLeft, operandRight, higherPrecedenceOperator));

        }
        return outputStack.pop();
    }

    private static Integer evaluate(Integer operandLeft, Integer operandRight, String operator)
    {
        BigDecimal retVal = BigDecimal.ZERO;
        BigDecimal left = BigDecimal.valueOf(operandLeft);
        BigDecimal right = BigDecimal.valueOf(operandRight);
        if (operator.equals(Operator.MULTIPLY.sign))
        {
            retVal = left.multiply(right);
        } else if (operator.equals(Operator.ADD.sign))
        {
            retVal = left.add(right);
        } else if (operator.equals(Operator.SUBTRACT.sign))
        {
            retVal = left.subtract(right);
        } else if (operator.equals(Operator.DIVIDE.sign))
        {
            retVal = left.divide(right);
        }
        return retVal.intValue();
    }
}


texts:
I have a young friend of mine who is starting to learn Python in school and asked me to give him a little assignment. I am in no way a teacher nor a Python expert, but I accepted.
At first I thought it would be fun to start with a bit of parsing for the operation's input, like:
Enter your operation : 3+3

But it seemed a bit overwhelming for him so we agreed to separate it in three parts (first number, operand and second number).
I did a little correction but I find it clumsy and the point of the exercise is to show him some good practices.
So here is my code:
calculate = True
while calculate:
    try:
        number1 = float(input("Enter the first number : "))
    except ValueError:
            print("Incorrect value")
            exit()
    symbol = input("Enter the operation symbol (+,-,/,*,%) : ")
    try:
        number2 = float(input("Enter the second number : "))
    except ValueError:
            print("Incorrect value")
            exit()
    operande = ["+", "-", "*", "/", "%"]
    resSentence = "Result of operation \"{} {} {}\" is :".format(number1, symbol, number2)
    if symbol not in operande:
        print("Incorrect symbol")
    elif symbol == "+":
        print(resSentence, number1 + number2)
    elif symbol == "-":
        print(resSentence, number1 - number2)
    elif symbol == "*":
        print(resSentence, number1 * number2)
    elif symbol == "/":
        print(resSentence, number1 / number2)
    elif symbol == "%":
        print(resSentence, number1 % number2)
    restart = input("Do you want to do another calcul (Y/n) ? ")
    while restart.lower() != "y" and restart.lower() != "n":
        print(restart.lower(), restart.lower(), restart.lower()=="n")
        restart = input("Please, enter \"y\" to continue or \"n\" to exit the program : ")
    if restart.lower() == "n":
        calculate = False

I would have wanted to do a loop when number1 or number2 is not a valid float until the user enter a valid value, but I did not found a clean way to do it. I would gladly accept advices about this (even though I know this is not a question for this Stack Exchange, a good Pythonic way for doing this would be cool :) ).


texts:
I was working on an assignment in my Python class to sort 10 numbers but I wanted to be able to sort any set of numbers be it large or small. The assignment didn't really cover any sorting algorithms other than bubble sort so I started working and decided to just do something simple find the smallest number and remove it then put it in a temp list and then assign that list to the original to make it sorted. I was able to compress this down into the first sorting.

But I wanted to see if I could make it faster by also looking for the max and popping them both out in separate lists. But I was told python runs on a single thread and there were far more things to run than the first.

So why is the second sort slightly faster despite having more instructions than the first?

I ran this on python 3.8

import time
import random
rand_list = []
for i in range(0,10000):
    n = random.randint(1,100000)
    rand_list.append(n)
print('Random List Creation Complete')

list_to_sort1 = rand_list[:]
list_to_sort2 = rand_list[:]

''' Sort Smallest to Largest'''
start_time = time.time()

templist=[]
while 0 < len(list_to_sort1):
    templist.append(list_to_sort1.pop(list_to_sort1.index(min(list_to_sort1))))
list_to_sort1 = templist

print('\nSorting Complete: My sort took', time.time() - start_time, "to run")

''' Sort Smallest to Largest'''
start_time = time.time()

min_half = []
max_half = []
max_pos = 0
min_pos = 0
while 0 < len(list_to_sort2):
    max_pos = list_to_sort2.index(max(list_to_sort2))
    min_pos = list_to_sort2.index(min(list_to_sort2))

    if len(list_to_sort2) != 1:
        if max_pos > min_pos:
            max_half.append(list_to_sort2.pop(max_pos))
            min_half.append(list_to_sort2.pop(min_pos))
        else:
            min_half.append(list_to_sort2.pop(min_pos))
            max_half.append(list_to_sort2.pop(max_pos))
    else:
        min_half.append(list_to_sort2.pop(0))

max_half.reverse()
list_to_sort2 = min_half + max_half

print('\nSorting Complete: My sort 2 took', time.time() - start_time, "to run")

time.sleep(20)


texts:
This library provides methods for storing items into an inventory. the container is based on a grid as well as the items going into that container.

can you please review the code in any way?

public interface GridContainer {
    public Collection<GeoPoint> getContainer();
    public Collection<GridShape> getContent();
    public boolean fitsInside(GridShape container, GeoPoint location);
    public void add(GridShape shape, GeoPoint location);
    public GridShape remove(GeoPoint location);
}

public interface GridShape {
    public boolean fitsInside(GridContainer container, GeoPoint pointer);
    public Collection<GeoPoint> getShape();
    public GeoPoint getPointer();
    public Collection<GeoPoint> getRelativeShape(GeoPoint point);
}

so far we have an implementation for rectangle shaped containers and items

public class RectangleContainer implements GridContainer {

    private final List<GeoPoint> shape;
    private final Map<GeoPoint, GridShape> content;

    public RectangleContainer(int width, int height){
        shape = Collections.unmodifiableList(RectangleUtility.createShape(width, height));
        content = new HashMap<>();
    }

    @Override
    public Collection<GeoPoint> getContainer() {
        return shape;
    }

    @Override
    public Collection<GridShape> getContent() {
        return content.values();
    }

    @Override
    public boolean fitsInside(GridShape shape, GeoPoint location) {
        Collection<GeoPoint>relativeShape = shape.getRelativeShape(location);
        boolean hasIntersections = hasIntersection(relativeShape);
        boolean isInBounds = isInBounds(relativeShape);
        return !hasIntersections && isInBounds;
    }

    private boolean isInBounds(Collection<GeoPoint>relativeShape) {
        for (GeoPoint point: relativeShape){
            if (!shape.contains(point)){
                return false;
            }
        }
        return true;
    }

    private boolean hasIntersection(Collection<GeoPoint>relativeShape) {
        for (Map.Entry<GeoPoint, GridShape> entry: content.entrySet()){
            for (GeoPoint pointOfContent: entry.getValue().getRelativeShape(entry.getKey())){
                if (relativeShape.contains(pointOfContent)){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void add(GridShape shape, GeoPoint location) {
        content.put(location, shape);
    }

    @Override
    public GridShape remove(GeoPoint location) {
        return content.remove(location);
    }
}

public class RectangleItem<I> implements GridShape, ItemHolder<I> {

    private final List<GeoPoint> shape;
    private I item;

    public RectangleItem(int width, int height){
        shape = Collections.unmodifiableList(RectangleUtility.createShape(width, height));
    }

    @Override
    public boolean fitsInside(GridContainer container, GeoPoint pointer) {
        return container.fitsInside(this, pointer);
    }

    @Override
    public Collection<GeoPoint> getShape() {
        return shape;
    }

    @Override
    public GeoPoint getPointer() {
        return shape.get(0);
    }

    @Override
    public Collection<GeoPoint> getRelativeShape(GeoPoint point) {
        return shape.stream().map(p -> new GeoPoint(p.getX()+point.getX(), p.getY() + point.getY())).collect(Collectors.toList());
    }

    @Override
    public I getItem() {
        return item;
    }

    @Override
    public void setItem(I item) {
        this.item = item;
    }
}

Note: i've skipped the test classes and the RectangleUtility class, the geoLib project  and the ItemHolder since they are not scope of the review. If they are required please feel free to add a comment asking for them, then i'll add them. (i think this question is already bloated, that's the reason for deciding so)


texts:
Can you say, is this a bad code for registration in Django? Do I need to fix something or use a pip instead? (I am learning)

def register(request):

    error_messages = {}

    if request.POST:
        form = UserCreationForm(request.POST)

        if form.is_valid():
            new_user = form.save()

            user = authenticate(username=request.POST["username"], password=request.POST["password1"])
            login(request, user)

            return redirect('index')
        else:
            form = UserCreationForm()
            return redirect('register')

    return render(request, 'account/register.html',
            {'title': 'Registration', 'error_messages': error_messages})


texts: Alternative way to extract the most recent file using LINQ

texts:
All, I have written some code to get the latest files from a directory, the files I am looking for contain the string sProcScript = "sProcScript" and in the selected directory I might have several versions:

sProcScriptBigGuns1001.sql
sProcScriptBigGuns1007.sql
sProcScriptEdAggVal1006.sql
sProcScriptEdAggVal1007.sql
...

and I want to pick up the latest version only (the version number being the number after the file name i.e. 1007 etc.). So in the above this would be sProcScriptBigGuns1007.sql and sProcScriptEdAggVal1007.sql. To do this I wrote the following snippet (as part of a larger method), where strPath is the path to the relevant directory

DirectoryInfo dirInfo = new DirectoryInfo(strPath);
List<FileInfo> listFileInfo = new List<FileInfo>();
listFileInfo = dirInfo.EnumerateFiles().ToList<FileInfo>();

// Loop in to locate special processes.
List<FileInfo> specialProcList = new List<FileInfo>();
foreach (FileInfo fi in listFileInfo)
    if (Path.GetFileNameWithoutExtension(fi.FullName).Contains(sProcScript))
        specialProcList.Add(fi);

// Get distinct.
List<string> nameList = new List<string>();
foreach (FileInfo fi in specialProcList)
{
    string strsProc =
        Path.GetFileNameWithoutExtension(Regex.Replace(fi.Name, @"[\d]", String.Empty));
    if (!nameList.Contains(strsProc))
        nameList.Add(strsProc);
}
List<FileInfo> tmpList;
List<string> tmpNameList = new List<string>();
tmpList = specialProcList.OrderByDescending(f => f.Name).ToList();
foreach (string name in nameList)
{
    foreach (FileInfo fi in tmpList)
    {
        if (fi.Name.Contains(name))
        {
            tmpNameList.Add(fi.Name);
            listFilesFound.Add(fi);
            break;
        }
    }
}

which works great. However, I think there will be a much better and neater way of doing this using LINQ but I am new to LINQ and can't seem to get started with it (the attempts I have made are poor enough to not want to post them here!). Can someone demonstate a better way of doing the above operation using LINQ?

Thanks for your time.


texts: Designing a sorting algorithm from scratch

texts:
I'm taking a Python course and the current assignment is to create an algorithm that sorts numbers in ascending order (without using built-in sorting functions). I've had no programming experience before taking this course, so this might be a bit rough.

I got my script to successfully sort the numbers by figuring out the smallest number in the list each time through and moving it to a new list. This is obviously not very efficient since it has to loop dozens of times just for a short list, but I'm happy I finally got something to work! (Also, I think I need another elif to account for lists with repeat numbers.)

How can I clean it up? Is it more complex than it needs to be? I know there are far more efficient ways to sort, but I don't want to just copy someone else's established algorithm. I'd like to keep as much of this code in tact as possible while nipping and tucking.

def sortFunc(*arg):

    numList = list(arg)                     # Converts arguments into a list
    print('Before sorting: ',numList)       # Prints that list before sorting happens
    numSort = []                            # Creates an empty list to put sorted numbers into
    i = 0                                   # This is the index
    a = 1                                   # 'a' is the comparison number (this is the magic sauce)

    while numList:                          # As long as numList has numbers in it, loop the following

        if numList[i] == numList[-1] and\
           numList[i] <= a:                 # If we're at the final index AND that last number is smaller than 'a'
            basket = numList.pop(i)         # then place that number in a basket
            numSort.append(basket)          # and dump the basket into the new list (numSort)
            i = 0

        elif numList[i] == numList[-1]:     # Otherwise, if we reach the last position in numList
            i = 0                           # reset the index back to the first position
            a = a+1                         # and make the comparison number a little bigger

        elif numList[i] <= a:               # If we're anywhere else in the list and that number is smaller than 'a'
            basket = numList.pop(i)         # then pop that number into the basket
            numSort.append(basket)          # and dump it unceremoniously into the new list (numSort)
            i = 0                           # Then reset the index back to the first position
            a = a+1                         # and make the comparison number a little bigger

        else:                               # If none of those things happen
            i = i+1                         # then move on to the next number in the list

    print('After sorting: ',numSort)        # Once the while loop is up, print the result!

sortFunc(67, 45, 2, 13, 1, 998)


texts: Php Login Class - Security and Logic check

texts:
I write a simple php login class that only operate on php sessions to login user in the system.

My Question is that this class is secure enough to be used on production environment ?

NOTE : Die Statements are used only for testing of scripts

class.login.inc.php

class Login
{

//setSessionFunction sets a login session with user id and all user details array

private function setSession($user_id,$user_details)
{
  $_SESSION['user_id'] = $user_id;
  $_SESSION['user_details'] = $user_details;
  $_SESSION['key'] = $this->hashSession();
}

//GetIp function is used to get ip address of client
private function hashSession()
{
return sha1($_SERVER['HTTP_USER_AGENT'] . getIP());
}

//get sessions and verify them
public function getSession(){

if(isset($_SESSION['user_id']) && ($_SESSION['user_id']!== '') )
 if($this->verifySessionUser($_SESSION['user_id']) === true )
  if($this->hashSession() == $_SESSION['key'])
return true;
else
 return false;

}

//Logout Function
public function logout(){
   $_SESSION['user_id'] = null;
   $_SESSION['key'] = null;
   $_SESSION = array();
   session_unset();
   session_destroy();
}
public function verifyUser($username,$password){
  $password = sha1($password);
  $conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
  if(!$conn) die("Connection Error To DATABASE" . mysqli_connect_errno());
  $sql = "SELECT * FROM user WHERE username = ?";
  $mysqli = $conn->prepare($sql);
  if(!$conn) die("Query Error To DATABASE In Class Session" . mysqli_errno($conn));
  $mysqli->bind_param("s",$username);
  $mysqli->execute();
  $result = $mysqli->get_result();
  $mysqli->close();
  $conn->close();
   if($result->num_rows > 0)
      {
           $r = $result->fetch_assoc();
          if($r['password'] === $password)
          {
     $this->setSession($r['user_id'],$r);
     return true;
          }else return false;
     }
     else
        return false;
        return false;

}

//Private DataBase Verification of User Credentials
private function verifySessionUser($user_id){
$conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
  if(!$conn) die("Connection Error To DATABASE" . mysqli_errno());
  $sql = "SELECT * FROM user WHERE user_id = ?";
  $mysqli = $conn->prepare($sql);
  if(!$conn) die("Query Error To DATABASE In Class Session" . mysqli_errno());
  $mysqli->bind_param("d",$user_id);
  $mysqli->execute();
  $result = $mysqli->get_result();
  $mysqli->close();
  $conn->close();
   if($result->num_rows > 0)
      {
     return true;
     }
     else
        return false;
  }
}

securepage.php

$user = new Session();
   if($user->getSession() == true)
      {
         header("location: admin.php");
         exit();
       }

Is there any security measures i should consider in future ?


texts: Input any time, output timezones that are currently that time

texts:
I made a program that will take in a time and a weekday, and return which parts of the
world are at times closest to the one specified. Part of the program focuses on extracting a date and country out of a user input.
Here are some example inputs and outputs:
"In what part of the world is it 4:00 PM Friday right now?" (datetime.datetime(2021, 1, 1, 16, 0), 'World')
"Where in America is it 6:40 AM Thu?"                       (datetime.datetime(2020, 12, 31, 6, 40), 'America')
"It is 10:30 pm fri in which part of Asia?"                 (datetime.datetime(2021, 1, 1, 22, 30), 'Asia')
"Where would the time be 10:10 AM Sat?"                     (datetime.datetime(2021, 1, 2, 10, 10), 'World')
"Which state of brazil has the time 8:30 AM Saturday now?"  (datetime.datetime(2021, 1, 2, 8, 30), 'Brazil')

The reason that the only part of the date that needs to be given is the weekday,
is because the maximum possible days in difference between a timezone and the timezone
the user is currently at is one day, either ahead or behind.
So the program checks if the weekday given is at the current day, one day before the current day, or one day after the current day, and can return the rest of the date.
Here is my code:
import pytz
from datetime import datetime, timedelta
import re

def return_words(string):
    return re.findall(r'\b\S+\b', string.lower())

def string_to_datetime(string):
    weekdays = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
    string = string.lower()
    words = sorted(return_words(string), key=len)[::-1]
    countries = [t.split("/")[0] for t in pytz.all_timezones]

    for word in words:
        in_day = [weekday for weekday in weekdays if word in weekday]
        if len(in_day) == 1: # Make sure that the word found is a weekday name, not just something like "day"
            weekday = in_day[0]
            break
    else:
        return

    for word in words:
        if word.title() in countries:
            country = word.title()
            break
    else:
        country = "World" # If no country name found, use "World"

    date = datetime.now()
    one_day = timedelta(days=1)
    if (datetime.now() + one_day).strftime("%A").lower() == weekday:
        date += one_day
    elif (datetime.now() - one_day).strftime("%A").lower() == weekday:
        date -= one_day
    elif datetime.now().strftime("%A").lower() != weekday:
        return

    year, month, day = date.year, date.month, date.day
    hours_minutes = re.findall("\d+\:\d+", string)[0]

    half = re.findall(f"(?<={hours_minutes}).{{0,3}}[ap]m", string) # Play it safe, and only extract the am or pm that is at most 3 steps away from the hours:minutes
    if half: # If found an am or pm
        half = half[0].strip()
    else: # If not found when playing it safe, resort to finding any am or pm in the string
        half = re.findall("[ap]m", string)[0].strip()
    string = f"{year} {month} {day} {hours_minutes} {half}"
    try:
        return datetime.strptime(string, "%Y %m %d %I:%M %p"), country
    except ValueError:
        return

while True:
    print(string_to_datetime(input("Input your string >>> ")))

Can you show me how to improve the efficiency of my code? Also, any tips on tidying up would be of big help.


texts: Decoding request object before use it in an Insert query

texts:
I want to decode a request object before use it in an insert query.

Request object containes the following JSON body:

{
  "device":"887B53",
 "data":"89582c60",
 "station":"B0A6",
 "rssi":"-99.00",
 "time":"1586121398"
}

That's the way I solved it:

const convert = {
        bin2dec : s => parseInt(s, 2).toString(10),
        bin2hex : s => parseInt(s, 2).toString(16),
        dec2bin : s => parseInt(s, 10).toString(2),
        dec2hex : s => parseInt(s, 10).toString(16),
        hex2bin : s => parseInt(s, 16).toString(2),
        hex2dec : s => parseInt(s, 16).toString(10)
      };

const binnumber = convert.hex2bin(request.payload.data);

const MSB = binnumber.slice(8, 12);
const LSB = binnumber.slice(18, 24);
const LSB_MSB = convert.bin2dec(MSB.concat(LSB));
const number1 = (LSB_MSB-200)/8 ;

const hum = convert.bin2dec(binnumber.slice(24, 32));
const number2 =  hum * 0.5

const MSB2 = binnumber.slice(0, 1);
const LSB2 = binnumber.slice(8, 12);
const LSB_MSB2 = convert.bin2dec(MSB2.concat(LSB2));
const battery = LSB_MSB2*0.05*2.7 ;

const device = request.payload.device;
const data = request.payload.data;
const station = request.payload.station;
const rssi = request.payload.rssi;
const time = request.payload.time;

The converted Data shows as following:

It looks really confusing and I'm sure there is a way to solve it cleaner and nicer. Does anywone have a suggestion?


texts: Generic cached value class mimicking Lazy

texts:
Before I wrote this I searched and found a number of solutions that make use of a caching provider to handle a set of items. I felt that was too cumbersome of an approach and set out to create a class that could cache a single value, similar to the way Lazy<T> manages the initialization of a single value.

I'm having trouble determining the thread-safety of this implementation, specifically where lock statements should be used. Can any experts on working with multi-threaded applications spot where I may have gone wrong? Or is this approach sound?

public class Cached<T> {
    private readonly TimeSpan _duration;
    private DateTime _expiration;
    private Lazy<T> _value;
    private readonly Func<T> _valueFactory;

    public T Value {
        get {
            // Do I need locking while checking the expiration?
            if (DateTime.Now >= _expiration)
                RefreshValue();

            return _value.Value;
        }
    }

    public Cached(Func<T> valueFactory, TimeSpan duration) {
        _duration = duration;
        _valueFactory = valueFactory;

        RefreshValue();
    }

    private void RefreshValue() {
        // Is this sufficient while updating the expiration and value?
        lock (this) {
            _value = new Lazy<T>(() => _valueFactory());
            _expiration = DateTime.Now.Add(_duration);
        }
    }
}

I'm using Lazy<T> for the value getter because it's possible that the cached value will be (1) expensive to load and (2) not immediately needed.


texts:
Is this merge sort following good coding standards? What are some improvements I can make to make it cleaner?

public final class MergeSort {

    private MergeSort() {

        // prevent instantiation

    }

    private static Object[] temp;

    public static <T extends Comparable<? super T>> void sort(List<T> array){

        Object[] a = array.toArray();

        temp = new Object[a.length];

        sort(a, 0, a.length - 1);

        ListIterator<T> i = array.listIterator();

        for (int j=0; j<a.length; j++) {

            i.next();

            i.set((T)a[j]);

        }

    }

    private static void sort(Object[] a, int lo, int hi) {

        if(hi <= lo){

            return;

        }

        int mid = lo + (hi - lo)/2;

        sort(a, lo, mid);// sort left part

        sort(a, mid+1, hi); // sort right part

        merge(a, lo, mid, hi);

    }

    private static void merge(Object[] a, int lo, int mid, int hi) {

        int i = lo, j = mid+1;

        System.arraycopy(a, lo, temp, lo, hi + 1 - lo);

        for(int k = lo;k <= hi; k++){

            if (i > mid) a[k] = temp[j++];

            else if (j > hi ) a[k] = temp[i++];

            else if (((Comparable)temp[j]).compareTo(temp[i]) <= -1) a[k] = temp[j++];

            else a[k] = temp[i++];

        }

    }

}


texts:
I'm working on my first Clojure project, which is a parser. Since it's my first project I'm unsure of many aspects, from my general approach to solving this problem to the small implementation details. I also don't know anyone proficient in Clojure so any guidance is welcome.

In higher terms, my implementation will take a string (which is one message to be parsed) and break it into fields. Each field it will apply some function to (often a dictionary lookup), and finally return a dictionary of results.

(use 'clojure.string)

;; This defines the breakdown of each line in the file. The line contains an entry and start with something
;; like "1AXYZ ". In this case the first two characters ("1A") are the "Record Type" and the next four
;; ("XYZ ") are the "Entering Firm". This data structure holds that information.
(def parser
  {:shared '(  ; These are the entries shared amongst all types of message

          ;; Field-Name  num-chars
             Record-Type 2
             Entering-Firm 4
             Clearing-Number 4
             Symbol 11
             Lot-Indicator 1
             ;;...
             )

   :1A     '(      ; this is one type of message, indicated with record-type=1A

          ;; Field-Name  num-chars
             Filler 9
             Poss-Dupe 1
             Booth-Booked-Indicator
             Order-Time 6
             Order-Date 8
             ;; ...
             )
   }
)

;; if no implementation is found for a field, just return a map to its contents.
(defn default [header x]
  {(str header) (trim (join x))})

;; most of the fields that dont use the default function will just be a dictionary lookup
(defn Poss-Dupe [[x]] (default 'Poss-Dupe ({\1 "Odd Lot" \D "Rule 902" \E "Poss Dupe Rule 902"
                                            \F "Auto Execution" \G "Poss Dupe of Auto-Execution"
                                            \H "Non-auto Execution" \I "Poss Dupe of Non-auto Execution"
                                            \0 "" \space ""}
                                               x (str "ERROR: " x))))

(defn Booth-Booked-Indicator [[x]] (default 'Booth-Booked-Indicator ({\0 "Post" \1 "Booth" \2 "Booked"} x (str "ERROR: " x))))

(defn Order-Time [x] (default 'Order-Time (->> x (partition 2) (map join) (join ":")  ))) ; "HHMMSS" -> "HH:MM:SS"

(defn Order-Date [x] (default 'Order-Date
                       (join "-" (map join (list (take 4 x) (take 2 (drop 4 x)) (drop 6 x)))))) ; "YYYYMMDD"->"YYYY-MM-DD"

(defn Filler [x] nil)

(defn try-call [f subseq]
  (try
    ((eval f) subseq)
    (catch Exception e  ; f not defined -> call default
      (default f subseq))))

;; Where the recursion happens
(defn grab-call [[f n & rest-instructions] line]
  (let [[field rest-line] (split-at n line)]
    (if (or (empty? line) (not f))
      nil
      (merge (try-call f field) (grab-call rest-instructions rest-line)))))

;;; Entry point
(defn parse-line [line]
  (grab-call (concat (:shared parser)
                     ((keyword (subs line 0 2)) parser))
    line ))

If you care to know the particulars of what is being parsed, that can be found at NYSE MRO specs.


texts: Method that returns an integer chosen by user

texts:
Can I make this:

if (oneFour == 1 || oneFour == 2 || oneFour == 3 || oneFour == 4)

shorter, especially if I'm gonna need a wider range of integers?
Do I need to use a string _warning twice like I did?

static string _warning = "Please, enter a number from 1 to 4!";

static int oneToFour()
{
    int oneFour = 0;
    bool isError = true;
    while (isError)
    {
        try
        {

            oneFour = Convert.ToInt32(Console.ReadLine());
            if (oneFour == 1 || oneFour == 2 || oneFour == 3 || oneFour == 4)
                isError = false;
            else
                Console.WriteLine(_warning);
        }
        catch { Console.WriteLine(_warning); }
    }

    return oneFour;
}


texts:
I'm working on simple code that is to read input where:

The first line is a number of cases to consider.
The next lines are integers separated by a space that will be tested lately.

Possible input:

2
3 4
4 5

Possible output (just some multiplication example):

12
20

Questions:

I would like to know if there are 'better' ways to handle this kind of input.
What could be done to make this code more universal? For example, there is a variable int lineLength=3 and I have to modify It for other similar input (where lineLength is bigger):

2
3 4 5
4 5 6

What validation should be implemented (if someone gives bad input, maybe it could be done in X ways (the handling))?
Do I break any good-programming rules? (I intended to write this only in class Main)

import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;

public class Main {

public static void main(String[] args) throws IOException {

/** Reading number of tests (NO VALIDATION) **/
/** nextInt() doesnt read the last newline character of input **/
Scanner read = new Scanner(System.in);
int numberOfTests = read.nextInt();

/** Consuming newline character**/
read.nextLine();

String line[] = new String[numberOfTests];

/** Reading line excluding line separator at the end (NO VALIDATION) **/
for (int i = 0; i < numberOfTests; i++)
    line[i] = read.nextLine();

/** Printing array of String(lines) **/
System.out.print(Arrays.toString(line));

/** Creating the array of ints (NO VALIDATION) **/
int lineLength = 3;
int num[][] = new int[numberOfTests][lineLength];

/** Extracting integers from line **/
for (int i = 0; i < numberOfTests; i++) {
    int k = 0;
    for (int j = 0; j < lineLength; j++) {
        if (Character.isSpaceChar((line[i].charAt(j))) != true) {
            num[i][k++] = Character.getNumericValue(line[i].charAt(j));
        }
    }
}

/** Printing array of integers to test **/
int numToTests = 2;
for (int i = 0; i < numberOfTests; i++) {
    System.out.println();
    for (int j = 0; j < numToTests; j++) {
        System.out.print(num[i][j]+" ");
    }
}
}
}


texts: Passing a true/false value to a model used in a controller

texts:
This passes the value of true/false to model which I can use in my controller.

How can this be cleaned up?

        Auto :
        <select name="IsAuto" class="togglehidden" id="IsAuto" data-role="slider" data-hidden-id="#autohidden">
            <option value="false">No</option>
            <option value="true">Yes</option>
        </select>
        @Html.HiddenFor(m => m.IsAuto, new { id = "#IsAuto", value="#IsAuto" })
        <input type ="hidden" name ="autorel" id="autorel" value="@(Model.IsAuto = "#IsAuto".AsBool())" />


texts:
I'm creating some age-verification functionality for an iOS app. The user is presented with a UIDatePicker object, and the latest selectable date should be today minus 18 years. How vulnerable to inaccuracy is my code? How could it be leaner?

-(void)validateAge {

    NSDateComponents *today = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    NSInteger day = [today day];
    NSInteger month = [today month];
    NSInteger year = [today year];

    int correctYear = year - 18;

    NSDateComponents *correctAge = [[NSDateComponents alloc] init];
    [correctAge setDay:day];
    [correctAge setMonth:month];
    [correctAge setYear:correctYear];

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    UIDatePicker *agePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 240, 320, 200)];
    [agePicker setDatePickerMode:UIDatePickerModeDate];
    [agePicker setMaximumDate:[calendar dateFromComponents:correctAge]];
    [self.view addSubview:agePicker];
    return;
}


texts:
If you have an interface served by a NodeJS API, what is the most clean way to propagate status changes to the interface?

For example, I have a page that has 2 statuses, user logged in and guest. How would you send to the interface that information, without rendering the page server side?  Same thing applies to permissions.

I have been working with 2 solutions, have a flag in the cookie (login = true/false) and then validate that server side on the page or resource request or render the page server side... but I don't think that neither of this is "clean". The first one because is insecure and "lose" and the last one because interface should be independent.

How are you doing this?

The user logs in and in that function I create a cookie that is sent in response:

var authData = new Array();
authData[0] = loginData.userid;
(...)
    var cookie = [];
    cookie[0] = { 'hash': etree.findtext('./hash'), 'login': 'true', 'customerid': loginData.customerid };

    response.cookie('systemAuth', JSON.stringify(cookie), { maxAge: 86400000, path: '/', domain: url });
    utils.sendResponse(__filename, __line, request, response, 201, "text/plain", "Logged");

After that if, in my interface, if I want to check if the user is logged in or if is just a guest, I have to parse the cookie and check the value of that cookie.login:

var cookie = JSON.parse($.cookie('systemAuth'));
if(cookie[0]['login'])
    console.log("Logged in.");
else
    console.log("Show login options...");

That's the first option.

My second is to use ejs to render the page server side:

<% if(user.loginid){ %>
    logged in
<% }else{ %>
    Login
<% } %>

How can I clean this up?


texts: To construct a pyramid with uses of alphabets. Would you propose any better solution?

texts:
Expected Input:
Enter the number of rows: 5
Expected Output:
        A
      A B A
    A B C B A
  A B C D C B A
A B C D E D C B A

I have solved this problem in this way->
//Write a program to build a pyramid with uses of alphabets
#include <stdio.h>
int
main(void){

//Put variables here
int space,num_of_rows,p=1,t=0;
char alphabet[100]={'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'};

printf("Enter the number of rows : ");
//Getting the input from the user
scanf("%d",&num_of_rows);

//Handling total row issues
for(int i=0; i<num_of_rows; i++){

//Handling space issues
for(space=0; space<num_of_rows-i; space++)
    printf(" ");

    //Handling alphabets
    for(int j=1; j<=p; j++){

            //To construct the first row and first position of each of the row as A
            if(i==0 || j==1){

                    alphabet[t]='A';

            }
            //To construct the last position of each of the row as A
            else if(j==p){

                    alphabet[t]='A';

            }
            //Handling the middle position issues
            else if(i+1>=j){

                    alphabet[t]++;

                }

            else{
                    alphabet[t]--;

                }
            printf("%c",alphabet[t]);

    }
    printf("\n");
    p+=2;

   }
 }

Now what I want to accomplish from you: How can I simplify my solution?. Will I face any problem for some conditions? Is it possible to solve this problem without using an array? Then what will be the strategy?. Thank you in advance.


texts:
I wrote this script to add some config to a Juniper device.  It works well but the whole user input validation section (yes or no section) seems a little messy.

Is there a better way I could have done it?

from jnpr.junos import Device
from jnpr.junos.utils.config import Config
import getpass

#Grab credentials
username = raw_input("Enter your username:")
password = getpass.getpass("Enter your password:")

#Confirmation of commands
commands = open("commands" , "r")
commands_to_commit = commands.read()
print ""
print "The commands you are about to commit are: "
print commands_to_commit
print ""
print "Do you want to continue to run these commands?"
confirm = raw_input("Y or N: ")
    if confirm in ['n','no','N','NO','No']:
            print "Exiting..."
            quit()
while confirm not in ['y','Y','yes',"Yes",'YES','n','N','NO','No','no']:
    print "Invalid Choice, Try again"
    confirm = raw_input("Y or N: ")
    if confirm in ['n','no','N','NO','No']:
            print "Exiting..."
            quit()
    elif confirm in ['y','Y','yes',"Yes",'YES']:
            continue

#Open a file called swichlist which has a list of devices to modify
with open('switchlist') as infile:
    for host in infile:
            try:
                    print "Working on:", host,
                    #Connect to devices in switchlist
                    dev = Device(host=host.strip(),  user=username, password=password)
                    dev.open()
                    cu = Config(dev)
                    #Looks for a file named commands with the list of commands to run
                    incmd = open('commands')
                    set_cmd = incmd.read()
                    cu.load(set_cmd, format="set")
                    cu.commit()
                    dev.close()
                    print "Completed:", host
            except Exception,e: print "Error:", e
            continue


texts:
I think many people for some reason use a singleton class to handle the PDO connection (?) but I was thinking it would be nice to have a parent abstract class initializing the connection and the child DAO classes would just have to extend that class and use a $db variable. Code below (I didn't test it so sorry if there are some syntax mistakes) and more explanation below the code.

abstract class AbstractDao {
    protected static $_db = NULL;

    public function __construct() {
        if(is_null(self::$_db)) {
            throw new MyDBException('No DB connection available');
        }
    }

    public static function loadDB($config) {
        static $lastConfig = NULL;
        if($config == $lastConfig) return self::$_db;
        self::$_db = self::connect($config);
        $lastConfig = $config;
        return self::$_db;
    }

    private static function connect($config) {
        $dsn = sprintf('mysql:dbname=%s;host=%s;port=%d;', $config['database'], $config['hostname'], $config['port']);
        $db = new PDO($dsn, $user, $pass);
        $db->exec("SET NAMES utf8");
        return $db;
    }
}

The $_db variable is static because I want to avoid to open many connections if I initialize many DAO classes (and thus if the $_db variable is static, I'll have one open connection for all my DAO classes). On the other hand it confuses me a bit because I have seen no one doing something like self::$_db->prepare(...). Maybe I am doing something wrong ?

Note also that loadDB with a default config array needs to be called in the application bootstrap.


texts:
I'm sure my question exists on the internet, i just don't know the right formulations.

I have a data-sample as input for a NN. This sample has the shape (1, 8, 28, 80).
Basically it is 80 timesteps of an image. -> y=8, x=28, time=80

i can extract the image at time=0 with:

np_img = image.data.numpy()   # shape (1, 8, 28, 80)
t0 = np_img[:, :, :, 0][0]

in order to be able to plot the images at each timestamp below each other, resulting in an array of (640, 28), ergo concatenating along the y-axis I do:

amount_timeslots = img.shape[-1]
new_array = img[:, :, :, 0][0]

for i in range(1, amount_timeslots):
    ti = img[:, :, :, i][0]
    new_array = np.concatenate((new_array, ti))

new_array.shape  # (640, 28)

Is there a more pythonic way by using build in numpy magic to do this?


texts: Creating a Deprecated/Obsolete behavior for methods in a JavaScript library

texts:
A friend of mine has a popular open source JavaScript library which is quite well used in the community.  He is now going through a process of refactoring and applying best practices and conventions and is wanting to upper case all constructor functions.  So in the past where he may have defined a chart object, he now wants it to be called Chart to stick with convention.

Because the library is well used, he would rather warn devs when they use the old function names and eventually deprecate them.

I've recommended using a helper function :

var ObsoleteWithReplacement = function(replacementFunction, oldFnName, newFnName) {
    var wrapper = function() {
       console.warn("WARNING! Obsolete function called.  Function '" + oldFnName + "' has been deprecated, please use the new '" + newFnName + "' function instead!");

        replacementFunction.apply(this, arguments);
    }
    wrapper.prototype = replacementFunction.prototype;

    return wrapper;
}

Which could be called as follows : http://jsfiddle.net/rLNep/1/

Is this a good way to go about it?  Can you recommend a better way?


texts:
Within our application I need to work a lot with simple IDs (just integers).

They are used to make queries against a database. For performance reasons I don't want to materialize them to Entities before the query.

Example:

// not really *that* static typed
public void DoQuery(int userId, int groupId)
{
}

Because I want to make our application more static typed (preventing errors like accidentally switching parameters around), I'm looking for a way to make this all more static typed, like:

public struct UserId
{
     int _UserId;

     public UserId(int userId)
     {
          _UserId = userId;
     }

    public static implicit operator int (UserId userId)
    {
        return userId._Id;
    }
}

and then:

// will throw compilation errors when I try to shoehorn a UserId into a GroupId
public void DoQuery(UserId userId, GroupId groupId)
{
}

Do I need to override equals operators and hascode, or would this be enough?
Are there any important performance penalties (during a highload)? For i.e. garbage collection.
What could be any more negative consequences from this?


texts: Using objects to make state with AJAX functions as properties

texts:
I'm using bootstrap 3.0 to display a tooltip (this example isn't specific to boot-strap) where the html inside the tooltip is fed from an AJAX call.  In the future I want to be able to use the same element to fire different AJAX calls (something like fire a different AJAX call if the shift+click was used).  To make that easy, I decided to use a tooltipManager object.  This object currently has two properties:

title: in bootstrap, this is the html represented when an element is hovered over
placement: the values for this are left,right,top,bottom

EDIT: I just got the program working, but I need to know WHY it's working because I tried something like this for hours and had nothing but bad luck.  Why is setPlacement able to return the correct value?

 $(document).ready(function () {
        //in the future there will be n amount of these
        //each will have the ability to use different urls to make different AJAX calls (not implemented yet)
        var tooltipManager = {
            title: function () {
                //ajax code to get title from database
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Service.asmx/GetDrugs",
                    dataType: "json",
                    success: function (data) {
                        //bootstrap uses the title attribute to set the html inside the tooltip
                        //here it's set to the results of the AJAX
                        $('#click').attr('title', data.d)
                                   .tooltip({
                                       trigger: 'click',
                                       html: false,
                                       //using the sizer function the tooltip is placed where it needs to be.
                                       placement: tooltipManager.placement.setPlacement(data.d)
                                       //it seems to me that it would be better design to call the tooltipManager
                                       //setPlacement function, but since it's an async request, it fails

                                   }).click();
                    },
                    error: function (xhr) {
                        console.log('failed: ' + xhr.status);
                    }
                });

            },
            placement: {
                left: 'left',
                top: 'top',
                right: 'right',
                bottom: 'bottom',
                setPlacement: function (data) {
                    if (data.length > 4) {
                        return this.bottom;
                    }
                    else {
                        return this.right;
                    }
                }
            }
        }
        $('#click').one('click', function () {
            //how can I pass the entire state of the object here, instead of invoking these methods one by one.
            tooltipManager.title();
        });
        //not sure if this is good design to have this not a property of the tooltipManager object
        //this works currently for placing the tooltip in the correct position
        function sizer(data) {
            if (data.length > 4) {
                return tooltipManager.placement.bottom
            }
            else {
                return tooltipManager.placement.right
            }
        }

    });


texts: Handler for a UI to select multiple days of the week for notifications

texts:
In the app I am currently working on, there is a part where user can set multiple local notifications for specific weekdays.

The array of buttons is represented by a separate class, which utilises stack view. When any of the buttons is clicked, its index is stored in an array, and with this array I can properly display selected buttons later on.

The class that is responsible for storing information about notifications is called Reminder, and have the following properties:

let reminderId: UUID
var reminderMessage: String
var dateComponents: DateComponents
var daysOfWeek = [Int]()

Property daysOfWeek is responsible for storing information about on which days of week to fire a notification. However, in reality it stores indices of selected buttons representing days of week. So for 7 buttons representing weekdays, this property can have multiple values from 0 to 6 accordingly. Hence, when loading saved reminders from memory and showing them in table view, I use this information to correctly display days of week button array with selected days.

As we know, the DateComponents class has a .weekday property which is pretty self explanatory. Each week day has its own index, which can be shown as:

let weekDaysDict = [1: "Sunday", 2: "Monday", 3: "Tuesday", 4: "Wednesday", 5: "Thursday", 6: "Friday", 7: "Saturday"]

However, in my Reminder class the same properties would be represented as such:

let originalDays = [0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday", 6: "Sunday",]

Hence, in the separate class called NotificationsManager, for scheduling and unscheduling local notifications I have to transform the indices stored in the Reminder class' daysOfWeek: [Int] property to appropriately represent weekdays. As a result, I use a simple function:

private static func shiftNumbers(array: [Int]) -> [Int] {
    var newArray = [Int]()
    for i in 0..<array.count {
        if array[i] == 6 {
            newArray.append(1)
        }
        else {
            newArray.append(array[i] + 2)
        }
    }
    newArray.sort()
    return newArray
}

With all this information this is how my method for scheduling multiple notifications looks:

static func scheduleMultipleNotifications(reminder: Reminder) {
    let daysToSchedule = shiftNumbers(array: reminder.daysOfWeek)
    for i in 0 ..< daysToSchedule.count {
        let id = "\(reminder.reminderId)_\(weekDaysDict[daysToSchedule[i]]!)"
        let message = reminder.reminderMessage
        let components = reminder.dateComponents
        let weekDay = daysToSchedule[i]

        scheduleNotification(notificationRequestId: id, notificationMessage: message, dateComponents: components, weekDay: weekDay)
    }
}

I believe it should be the responsibility of Reminder class to store correctly converted indices of weekdays, and that the NotificationsManager class should only be responsible for scheduling notifications and not transforming one array of indices into another.

Another problem is that my Reminder class in its current form, only stores a single reminder id, and later on for scheduling multiple notifications, since UNNotificationRequest requires unique identifier for each new request, I have to create several ids as shown in the code snippet from above method:

for i in 0 ..< daysToSchedule.count {
        let id = "\(reminder.reminderId)_\(weekDaysDict[daysToSchedule[i]]!)"
        ...

Where weekDaysDict is a dictionary representing names of weekdays and their indices. So a single id will look something like this: 0A3276DE-FEDF-4BC6-BA79-2DCC374D4BA9_Thursday - consists of UUID of reminder class and added weekday name at the end. The same array of ids must be created when deleting multiple notifications. I was thinking maybe I should use an array of ids in the Reminder class, rather than single id, where each id will be responsible for each weekday.

Based on all of the information provided how would you guys suggest I design my Reminder class, so that it is more cohesive?


texts: I am trying to filter a queryset based on dates, I keep getting a duplicate error on the for loops,How do I refactor these code to remove duplicates?

texts:
I am trying to filter the events table to get ongoing events and complete events, but pycharm keeps underlining my code because of duplicated code. How do I prevent for loop code duplicates on the two functions below?
Better yet, how do I optimally refactor these two functions?
Thanks

def get_ongoing_events():
    ongoing_events = Events.objects.filter(
            Q(event_begin_datetime__lte=current_time),
            Q(event_end_datetime__gt=current_time),
        )
    for event in ongoing_events:
        event.event_status = 'ongoing'
        event.save()

        event.venue.status = 'booked'
        event.venue.save()

        reserve_data = dict()
        reserve_data["sensor_id"] = event.venue.sensor_id
        reserve_data["status"] = event.venue.status

        return reserve_data

def get_complete_reservation():
    """
    Update reservations and sensors
    :return:
    """
    completed_events = Events.objects.filter(
            Q(reservation_begin_datetime__lt=current_time),
            Q(reservation_end_datetime__lte=current_time),
        )

    for event in completed_events:
        event.reservation_status ='complete'
        event.save()

        event.venue.status = 'free'
        event.venue.save()
        reserve_data = dict()
        reserve_data["sensor_id"] = event.venue.sensor_id
        reserve_data["status"] = event.venue.status
        return reserve_data
```


texts: Select a location on the map depending on which button is clicked

texts:
I have code like below. By default the location is myloc. When user clicks btn-a it selects myloc and when btn-b is clicked it select myloc1. In my code I repeat the code L.circle three times, which is bad practice. So can anybody help me? How can I optimize this code, DRY it up and improve the quality as well?

var myloc = new L.LatLng(13.7433242, 100.5421583);
var myloc1 = new L.LatLng(14.979900, 102.097771);
$(function () {
    var circle;
    var slider = document.getElementById('myRange');
    var output = document.getElementById('demo');
    output.innerHTML = slider.value + scale;

    slider.oninput = function (val) {
        output.innerHTML = this.value + scale;
        circle.setRadius(this.value);
    }

    circle = L.circle(myloc, {
        color: '#7a7777',
        weight: 0.1,
        fillColor: '#7a7777',
        fillOpacity: 0.2,
        radius: 0
    }).addTo(map);

    $('.btn-a').on('click', function(e){
        if ($(this).val() == 'First') {
            circle = L.circle(myloc, {
                color: '#7a7777',
                weight: 0.1,
                fillColor: '#7a7777',
                fillOpacity: 0.2,
                radius: 0
            }).addTo(map);

        } else if($(this).val() == 'Second') {
            circle = L.circle(myloc1, {
                color: '#7a7777',
                weight: 0.1,
                fillColor: '#7a7777',
                fillOpacity: 0.2,
                radius: 0
            }).addTo(map);
        }
    });
});