texts: Fetching records, optionally including deleted records

texts:
I have an original method that almost does what I want (a method I did not create), but now I need to find records that were deleted so I added another method GetAllGuideRecords minus the delete condition in the where clause.

But now I kind have repeated code so I decided to pack everything in one method, with an optional parameter. I sometimes like using optional parameters because it gives me the flexibility to not break existing code.

Should I create overload method instead, stick with what I have, or is there a better way?

Original code:

 public ED010_GUIDE GetNonDeletedGuideRecords(int guideId, int versionId)
        {
            var rec = ErgDb.ED010_GUIDE.FirstOrDefault(a => a.ERG_EDITION_ID == versionId && a.GUIDE_ID == guideId && a.DATE_DELETED_DTE == null);
            return rec;
        }

public ED010_GUIDE GetAllGuideRecords(int guideId, int versionId)
    {
        var rec = ErgDb.ED010_GUIDE.FirstOrDefault(a => a.ERG_EDITION_ID == versionId && a.GUIDE_ID == guideId);
        return rec;
    }

New code:

  public ED010_GUIDE GetGuideRecord(int guideId, int versionId, bool getDeletedAndActiveRecords )
        {

            var rec = ErgDb.ED010_GUIDE.FirstOrDefault(a => a.ERG_EDITION_ID == versionId && a.GUIDE_ID == guideId);

            if (!getDeletedAndActiveRecords)
            {
                return  (rec != null && rec.DATE_DELETED_DTE == null)? rec:null;
            }
            else
            {
                return rec;
            }

        }


texts: NSManagedObject in need of smart setters

texts:
I'm just beginning my foray into iOS development and need a code review.  I have a custom NSManagedObject that needs some smart setters.  I'm new to Objective-C, iOS, and core-data development, so I don't trust myself yet.  I come from a Java background, so smart setters are what I know, but might not be best when using Core Data.

+(void)initialize
{
    scoredKeys = @[@"fullSwings", @"putts", @"fairwayBunkers", @"greenBunkers", @"chipsOrPitches", @"rescue", @"wastedOrPenalty"];
}

-(id) initWithHoleNumber:(int)holeNumber
{
    self = [super init];
    if (self) {
        [self setHoleNumber:[NSNumber numberWithInt:holeNumber]];
    }
    return self;
}

-(void) incrementItem:(NSString *)key
{
    [self willAccessValueForKey:key];
    NSNumber *value = [self primitiveValueForKey:key];
    int intValue = value.intValue;
    [self didAccessValueForKey:key];

    [self willChangeValueForKey:key];
    [self setPrimitiveValue:[NSNumber numberWithInt: intValue++] forKey:key];
    [self didChangeValueForKey:key];

    [self recalculateScore];
}

-(void) recalculateScore
{
    NSString *key;
    NSNumber *current;
    int tally = 0;

    for (key in scoredKeys) {
        [self willAccessValueForKey:key];
        current = [self primitiveValueForKey:key];
        tally = tally + current.intValue;
        [self didAccessValueForKey:key];
    }

    [self willChangeValueForKey:@"score"];
    [self setPrimitiveValue:[NSNumber numberWithInt:tally] forKey:@"score"];
    [self didChangeValueForKey:@"score"];
}

I am also seeking general comments about my approach.

In the core-data docs, it says the auto generated accessors are much faster than anything a developer can write, so is this a good idea?
Should I not even have a score property, and just have a method that returns the tally?


texts:
I've got the following code. I want to loop through my dataset (which is a matrix) in steps of let's say 50.000 and perform biglm on it.

lengthdata <- 100340
stepsize <- 50000

for (i in seq(1, lengthdata, stepsize)){
  if(i+stepsize > lengthdata){
    ## call function (i, lengthdata)
    print(paste(i, " - ", lengthdata))
    }
  else {
   ## call function (i, i+stepsize)
   print(paste(i, " - ", i + stepsize))
    }
}

This is my output:

[1] "1  -  50001"
[1] "50001  -  100001"
[1] "100001  -  100340"

Is there a more effective or cleaner way of coding this? I'm quite unexperienced using R!


texts: apt alternative for proxy environment with bash shell

texts:
As I am new to bash scripting, and want to use apt-get in my university.  I know that many people have issues when trying to do so.  My focus is simplicity and ease of use, but still need to be somewhat robust.

#!/bin/bash
string="install"
errormsg="\n\tInvalid input\n You should run this script with the following structure:\n\n sudo apt-proxy-install.sh install USERNAME PASSWORD\n\n "
DIRECTORY=~/bin/
if [ "$1" = "$string" ] && { ! ([ -z "$3" ] || [ -z "$3" ]) }
   then
         if [ ! -d "$DIRECTORY" ]; then
            mkdir ~/bin/
         fi
         printf "#!/bin/bash\nhttp_proxy=""http://$2:$3@10.20.10.50:3128"" sudo apt-get \${@:2}" > ~/bin/apt-proxy
         chmod 777 ~/bin/apt-proxy
         PATH=~/bin:$PATH
         addpath="export $PATH"
         sudo cat ~/.bashrc $addpath > ~/.bashrc
   else
         printf "$errormsg"
fi

My question is: is this code acceptable, or should I improve it? If the answer is not, then please give me some hints.


texts:
I've been working in PHP since almost three years ago. In this time I built a framework as base for my projects.

I want it to be improved, and which other best option there are that use StackExchange?, so I decided to post this here.

The framework is hosted in GitHub:
https://github.com/CPedrini/Delos

Now, the problem:
I think that there is a mess in the Input class, particularly in how the base's query string is parsed, I have problems to make a definitely decision of how manage URI's parameters.

I've created a .htaccess, which rewrites the URI like this:

From this: 127.0.0.1/home/initialize/param1:value1/param2:value2

To this: 127.0.0.1/index.php?p=home/initialize/param1:value1/param2:value2

Obviously, this is not needed, it's just a fancy stuff. If mod_rewrite is disabled then all the links on the web must be changed to the rewritten form.

So, in input class constructor the query string p is parsed.

I explode the $_GET['p'] var with separation slashes and delete empty values.

Then if first value doesn't contain a : char I store it in $_GET['section'] var, it will be the control to be instantiated.

Then, if section was there, in the second exploded value, if there isn't a : char then this is the method of the control to be called. I store it in $_GET['method'].

Finally, all the others stripped vars are parsed and stripped with the : char. In the previous example, to this:

$_GET['param1'] = value1

Do you guys think that it's uniform? What changes do you suggest?

EDIT: Added code in question.

$a = explode('/', $_GET['p']);

foreach ($a as $key => $value) {
    if($value == ''){
        unset($a[$key]);
    }
}

$b = 0;

if(isset($a[0]) && !strstr($a[0],':')){
    $_GET['section'] = $this->security->sanitize($a[0]);
    $b+=1;

    if(isset($a[1]) && !strstr($a[1],':')){
         $_GET['method'] = $this->security->sanitize($a[1]);
         $b+=1;
    }
}

if(isset($a[$b])){
    for($b = $b; $b < count($a); $b ++){
        if(!strstr($a[$b],'method') && !strstr($a[$b],'section')){

            $c = explode(':',$a[$b]);
            $_GET[$this->security->sanitize($c[0])] = isset($c[1]) ? $this->security->sanitize($c[1]) : '';
        }
    }
}
unset($_GET['p']);


texts: Parsing huge xml file with lxml.etree.iterparse in python

texts:
After solving the error in SO (like suggested) I return now for codereview. :-)

The task is to parse a huge file dblp.xml (~800 MB) presented by DBLP. The records in this huge file do look for example like this or this. In particular:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
    record_1
    ...
    record_n
</dblp>

I wrote some code, that shall get me ech tag of some records (will bes tored in a database).

I adapted this approach from an article from IBM developerWorks which refers to the article Incremental Parsing on effbot.org. Is this the correct approach for this task? Or is there a better way?

import sys
import os
import MySQLdb
from lxml import etree

def fast_iter2(context, cursor):
    # Available elements are:   article|inproceedings|proceedings|book|incollection|phdthesis|mastersthesis|www
    elements = set(['article', 'inproceedings', 'proceedings', 'book', 'incollection', 'phdthesis', "mastersthesis", "www"])
    # Available tags are:       author|editor|title|booktitle|pages|year|address|journal|volume|number|month|url|ee|cdrom|cite|
    #                           publisher|note|crossref|isbn|series|school|chapter
    childElements = set(["title", "booktitle", "year", "journal", "ee"])

    paper = {} # represents a paper with all its tags.
    authors = []   # a list of authors who have written the paper "together".
    paperCounter = 0
    for event, element in context:
        tag = element.tag
        if tag in childElements:
            if element.text:
                paper[tag] = element.text
                # print tag, paper[tag]
        elif tag == "author":
            if element.text:
                authors.append(element.text)
                # print "AUTHOR:", authors[-1]
        elif tag in elements:
            paper["element"] = tag
            paper["mdate"] = element.get("mdate")
            paper["dblpkey"] = element.get("key")
            # print tag, element.get("mdate"), element.get("key"), event
            if paper["element"] in ['phdthesis', "mastersthesis", "www"]:
                pass # throw away "unwanted" records.
            else:
                populate_database(paper, authors, cursor)
            paperCounter += 1
            print paperCounter
            paper = {}
            authors = []
            # if paperCounter == 100:
            #     break
            element.clear()
            while element.getprevious() is not None:
                del element.getparent()[0]
    del context

def main():
        cursor = connectToDatabase()
        cursor.execute("""SET NAMES utf8""")

        context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
        fast_iter(context, cursor)

        cursor.close()

if __name__ == '__main__':
    main()


texts: Optimizing mcrypt encryption class further

texts:
The following is a very simple implementation of an Encryption class using mcrypt whereby the functions encrypt and decrypt are called statically by a PHP script on GET and on POST respectively:

class Encryption
{
    const CIPHER...

    static function encrypt($plaintext)
    {
        $td = mcrypt_module_open(self::CIPHER, "", self::MODE, ""); # <= move this outside?
        mcrypt_generic_init($td, self::KEY, 0);
        $ciphertext = mcrypt_generic($td, $plaintext);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return base64_encode($ciphertext);
    }

    static function decrypt($ciphertext)
    {
        $td = mcrypt_module_open(self::CIPHER, "", self::MODE, ""); # <= repeated
        mcrypt_generic_init($td, self::KEY, 0);
        $plaintext = mdecrypt_generic($td, base64_decode($ciphertext));
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return $plaintext;
    }
}

Ignoring other aspects of this stripped down code, what I want to achieve is to reduce code duplication by perhaps moving $td = mcrypt_module_open(self::CIPHER, "", self::MODE, ""); outside. Can this be done without combining the two methods or is what I have already at the optimum?


texts:
I am using following code to implement pagination functionality. All items are rendering on page load and li elements greater than page set are hidden with CSS.

I want to make this code reusable so that any static pagination in my project can use this snippet with dynamic parameters.

var countShown = $('ul li').not('.hidden').length;
$('.load-more').on('click', function(){
    var countHidden = $('ul li.hidden');
    for(var i=0; i < countShown; i++) {
        countHidden.eq(i).removeClass('hidden');
    }
});

JS Fiddle

Please help me with suggestions to improve above written code.


texts:
I wrote this jQuery/JavaScript code for slideshow of my dynamic webapp. Is this too much jQuery code for carousel? It seems to work fine on my PC, but with bigger images it gets slower (7MB+) which is normal I suppose? Or am I doing whole thing wrong? I know I could do it with a JavaScript for loop or something, but I think it is easier with jQuery. Is jQuery less power-efficient than plain JavaScript? I wouldnt like to change it all as it has kind of "sentimental" value for me.

$(".prev-btn").on("click", function(){
  current = $(".li-placeholder").find("li.active");
  next = current.prev()
  if (current.index() == 0 ){
    next = $(".li-placeholder li").last();
    src = $(next).attr("src");
    $(".content").attr("src", src);
    $(".download-link").attr("href", src);
    $(next).addClass("active");
    $(current).removeClass("active");
  }
  else {
  src = next.attr("src");
  $(".content").attr("src", src);
  $(".download-link").attr("href", src);
  $(next).addClass("active");
  $(current).removeClass("active");
}
})

$(".next-btn").on("click", function(){
  current = $(".li-placeholder li.active");
  next = current.next()
  if (current.index() == $(".li-placeholder li").last().index()){
    next = $(".li-placeholder li:eq(0)");
    src = $(next).attr("src");
    $(".content").attr("src", src);
    $(".download-link").attr("href", src);
    $(next).addClass("active");
    $(current).removeClass("active");

  }
  else {
  src = next.attr("src");
  $(".content").attr("src", src);
  $(".download-link").attr("href", src);
  $(next).addClass("active");
  $(current).removeClass("active");
}

})

$(".exam-span-file").on("click", function(){
  wrapper = $(this).closest(".exam-span-wrapper");
  src = $(wrapper).find("li:eq(0)").attr("src");
  $(".content").attr("src", src);
  $(".download-link").attr("href", src);
  $(".imgmodal").show();
  exam_id = $(this).closest(".parent").attr("exam-id");
  $(".imgmodal").attr("exam-id", exam_id);
  $(wrapper).find("li:eq(0)").addClass("active");
  clone = $(wrapper).find(".exam-ul").clone();
  $(".li-placeholder").html(clone);

  if ($(".li-placeholder li").length == 1 ){
    $(".prev-btn").hide();
    $(".next-btn").hide();
  }
  else {
    $(".next-btn").show();
    $(".prev-btn").show();
  }


texts: Basic login script for educational purposes

texts:
I have created a login script to demonstrate the usage of sessions in PHP. The focus is not on security, databases or encryption. The idea is to exemplify how you can use sessions to protect pages from user access.

Key points to focus on:

Logical structure (return early, missing checks, error handling).
Compliance with PSR-1 and PSR-2.
Possible errors in the code.

<?php
  // Step 1. Start session management.
  session_start();

  // Step 2. Check if user is already logged in.
  if (isset($_SESSION['log']) && !empty($_SESSION['log'])) {
    // If true, redirect user to protected content
    header('Location: index.php');
  }

  // Step 3. Check if form was submitted through POST.
  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Create array to store possible error messages.
    $errors = array();

    // Step 4. Check if username or password has been left empty by user.
    if (empty($_POST['user']) || empty($_POST['pass'])) {
      // If true, create an error message.
      $errors[] = 'Please check that you have filled in username and password.';
    }

    // Declare username and password.
    // These are only used to exemplify usage of sessions and should as standard be
    // stored in an encrypted form in a database (salt/hash).
    $user = 'admin';
    $pass = 'test';

    // Step 5. Check if username and password from form match with those declared.
    if ($_POST['user'] == $user && $_POST['pass'] == $pass) {
      // If true, create a session variable with assigned value true.
      $_SESSION['log'] = true;

      // Redirect user to protected content.
      header('Location: index.php');
    }
    else {
      // If username or password are incorrect, create an error message.
      $errors[] = 'Incorrect username or password.';
    }
  }
  else {
    // Error message if form has not been submitted through POST.
    $errors[] = 'Form has not been submitted through POST.';
  }
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>login.php</title>
    <link rel="stylesheet" href="style.css">

    <?php
      // Prints out error messages raised by login script
      if (count($errors) > 0) {
        foreach($errors as $e) {
          echo $e . '
';
        }
      }
    ?>
    <form method="post" action="login.php">
      <fieldset>
        <legend>Enter user information</legend>

            Username
            <input name="user" type="text">

            Password
            <input name="pass" type="password">

      </fieldset>
      <fieldset>
        <button type="submit" name="submit">Login</button>
      </fieldset>
    </form>


texts:
Currently I have

var l1 = [...];
var l2 = [...];
if (l1.length > l2.length){
    var i = l2.indexOf(l1[0]);
    if (i !== -1){
        action_a(i);
    }else{
        action_c();
    }
} else if (l1.length < l2.length){
    var i = l1.indexOf(l2[0]);
    if (i !== -1){
        action_b(i);
    }else{
        action_c();
    }
} else {
    action_c();
}

Which I have could refactor into the following

function foo() {
    var l1 = [...];
    var l2 = [...];
    var i = -1;
    if (l1.length > l2.length){
        i = l2.indexOf(l1[0]);
    } else if (l1.length < l2.length){
        i = l1.indexOf(l2[0]);
    }
    if (i === -1 || l1.length == l2.length) {
        action_c();
        return;
    }
    if (l1.length > l2.length){
        action_a(i);
    } else if (l1.length < l2.length){
        action_b(i);
    }
}

It's a bit better, but I'm checking for the length of the two array twice.  It's also still not as readable as I would like it to be.

Can you review the above code and offer recommendations on how to do this better?


texts: Makefile for building classwork from markdown files and LaTeX

texts:
The following makefile builds my classwork for my various college classes and builds pdfs to hold the notes I took during class. I would like feedback on my directory structure and any optimizations that can be thought of to help improve it. I've been using and updating it for the past 18 months. I know that I should probably document it a bit better

The directory structure of the classes is as follows

ROOT
|- (class short code)
|  |- various subdirs for classwork
|- .. repeated for each of the classes I'm taking this semester
|- old
|  |- s1 (classes from semester 1)
|  |- s2 (classes from semester 2)
|- mybib.bib (biblatex file for sources)

The makefile is then as follows

# Makefile for college essays
#

PANDOC  := pandoc
#LATEX_FLAGS := -interaction=batchmode

SEARCHDIR  := $(shell find ./* -prune -type d \( ! -name "old*" \) -print)
LATEXFILES := $(shell find ${SEARCHDIR} -name '*.tex')
MARKDOWN   := \
    $(shell find ${SEARCHDIR} \( -name '*.md' -and ! -path '*node_modules*' \))
DOT_GRAPHS := $(shell find ${SEARCHDIR} -name '*.dot')
SLIDESHOWS := $(shell find ${SEARCHDIR} -name '*.slideshow')

# Pandoc Stuff
TEMPLATE   := college.latex
BIBFILE    := mybib.bib

PDFS       := $(MARKDOWN:.md=.pdf) $(LATEXFILES:.tex=.pdf)
#DOCX       := $(MARKDOWN:.md=.docx)
GRAPHOUT   := $(DOT_GRAPHS:.dot=.eps)
SLDESHWOUT := $(SLIDESHOWS:.slideshow=.ss.pdf)
NULLREDIR:= #> /dev/null

# Begin Primary Target
all: $(PDFS) $(GRAPHOUT) $(SLDESHWOUT)

# target to just build the latex documents
latex-out: $(LATEXFILES:.tex=.pdf)

# Clean up targets
clean: mdclean texclean dotclean
mdclean:
    rm -f $(PDFS)
texclean:
    rm -f *.aux
    rm -f *.bbl
    rm -f *.bbl
    rm -f *.log
    rm -f *.blg
    rm -f *.xml
    rm -f *.out
    rm -f *.bcf
dotclean:
    rm -f $(GRAPHOUT)
    rm -f $(DOT_GRAPHS:.dot=-eps-converted-to.pdf)

#######################################
# Build Rules for Various File Types
#######################################
%.pdf: %.md college.latex apa.csl
    $(info $@ from $<)
    @${PANDOC} --bibliography ${BIBFILE} --filter pandoc-citeproc \
        $< -o $@ --template ${TEMPLATE}

%.pdf: %.tex mybib.bib
    -$(info $@ from $<)
    -pdflatex ${LATEX_FLAGS} $< $(NULLREDIR)
    -if [ -e $(notdir $(basename $<)).bcf ] ; then \
            biber $(notdir $(basename $<)).bcf $(NULLREDIR) ; \
        else \
            bibtex $(notdir $(basename $<)).aux $(NULLREDIR) ; \
        fi
    -pdflatex ${LATEX_FLAGS} $< $(NULLREDIR)
    -pdflatex ${LATEX_FLAGS} $< $(NULLREDIR)
    -mv $(notdir $@) $@ $(NULLREDIR)
    -rm -f $(basename $<).aux

%.ss.pdf: %.slideshow
    pandoc --bibliography ${BIBFILE} -f markdown \
        -t beamer $< -o $@

%.eps: %.dot
    dot -Teps $< -o $@

%.png: %.dot
    dot -Tpng $< -o $@

include depend.makefile


texts: Matrix2x2 struct operators implementation in C++

texts:
Will be grateful if anyone would reasonably comment on my code. I am interested in the style only. If there will be any comments which are not related to the style I am glad to read them as well.

Main.cpp

#include "Matrix.h"

int main(void)
{
    Matrix2x2 m;
    std::cout << m << std::endl;
    std::cin >> m;
    std::cout << m << std::endl;

    Matrix2x2 m1{1, 2, 3, 4};
    Matrix2x2 res1{ 5 * m1 };
    std::cout << res1 << std::endl;

    Matrix2x2 m2{ 1, 2, 3, 4 };
    Matrix2x2 res2{ 5+m2 };
    std::cout << res2 << std::endl;

    Matrix2x2 m3{ 1, 1, 1, 1 };
    Matrix2x2 m4{ 1, 2, -1, -1 };
    Matrix2x2 m5 = m3 + m4;
    std::cout << m5 << std::endl;

    m4 += m5;
    std::cout << m4 << std::endl;

    return 0;
}

Matrix2x2.h

#pragma once

#include <iostream>

struct Matrix2x2
{double _00, _01, _10, _11;};

std::istream& operator>>(std::istream&, Matrix2x2&);
std::ostream& operator<<(std::ostream&, Matrix2x2&);
const Matrix2x2 operator*(const double&, const Matrix2x2&);
const Matrix2x2 operator+(const double&, const Matrix2x2&);
const Matrix2x2 operator+(const Matrix2x2&, const Matrix2x2&);
Matrix2x2& operator+=(Matrix2x2&, const Matrix2x2&);

Matrix2x2.cpp

#include "Matrix.h"

std::istream& operator>>(std::istream& is, Matrix2x2& m)
{
    return is >> m._00 >> m._01 >> m._10 >> m._11;
}

std::ostream& operator<<(std::ostream& os, Matrix2x2& m)
{
    return os << m._00 << ' ' << m._01 << std::endl
        << m._10 << ' ' << m._11 << std::endl;
}

const Matrix2x2 operator*(const double& c, const Matrix2x2& m)
{
    Matrix2x2 res{c*m._00, c*m._01, c*m._10, c*m._11};
    return res;
}

const Matrix2x2 operator+(const double& c, const Matrix2x2& m)
{
    Matrix2x2 res{ c+m._00, c+m._01, c+m._10, c+m._11 };
    return res;
}

const Matrix2x2 operator+(const Matrix2x2& m1, const Matrix2x2& m2)
{
    Matrix2x2 almostRes{m1};
    return almostRes+=m2;
}

Matrix2x2& operator+=(Matrix2x2& trg, const Matrix2x2& src)
{
    trg._00 += src._00;
    trg._01 += src._01;
    trg._10 += src._10;
    trg._11 += src._11;
    return trg;
}


texts: Python address index +1 with list comprehension

texts:
Task from CodingBat:

  Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

My original answer to the problem:

def sum13(nums):
  sum = 0
  for idx,val in enumerate(nums):
    if val == 13 or (idx != 0 and nums[idx-1] == 13):
      pass
    else:
      sum = sum + val

  return sum

Doing this with list comprehension,  I came up with

return sum([x if x!=13 and nums[idx-1 if idx >0 else 0] !=13 else 0 for idx,x in enumerate(nums)])

Is there a way to make this cleaner?


texts: Listing sessions within folders in API results

texts:
I have this code with nested foreach loops that is getting out of hand.

Is there a better and/or cleaner way of doing this?

Basically, what it's doing, is take the results from an API call, and then looping through each layer.

I check to make sure that each layers Results.Length is greater than zero before I start the next loop.

Anyway, here's my crazy ugly mess of code:

parentFolderResponse = GetFolders(parentFolder, sessionMgr, SessionManagementAuth, pagination);

        if (parentFolderResponse.Results.Length > 0)
        {
            foreach (Folder folder in parentFolderResponse.Results)
            {
                Console.WriteLine("\n + Class Of =  " + folder.Name);

                ListFoldersResponse childFolderResponse = GetFolders(folder.Id, sessionMgr, SessionManagementAuth, pagination);
                if (childFolderResponse.Results.Length > 0)
                {
                    foreach (Folder childFolder in childFolderResponse.Results)
                    {
                        Console.WriteLine("\n \t Course Name =  " + childFolder.Name);
                        ListSessionsResponse courseSessionResponse = GetPresentations(sessionMgr, SessionManagementAuth, pagination, childFolder.Id);
                        if (courseSessionResponse.Results.Length > 0)
                        {
                            foreach (Session session in courseSessionResponse.Results)
                            {
                                Console.WriteLine("n \t \t Session Name = " + session.Name);
                            }
                        } else {
                            Console.WriteLine("\n No sessions found!");
                        }
                    }
                } else {
                    Console.WriteLine("\n No course folder(s) found!");
                }

            }
        } else {
            Console.WriteLine("\n No class of folder(s) found!");
        }

If anyone has any suggestions, I'd love to hear them.


texts: Assembly: Sum up the single bytes of a 32bit-register to a checksum

texts:
Exercise description:

"Write a program that takes a double word (4 bytes) as an argument, and then adds all the 4 bytes. It returns the sum as output.
Note that all the bytes are considered to be of unsigned value.

Example: For the number 03ff0103 the program will calculate 0x03 + 0xff + 0x01 + 0x3 = 0x106, and the output will be 0x106

HINT: Use division to get to the values of the highest two bytes."

Full description on GitHub: xorpd

The code I've  written:

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:
    mov     eax,    0x01020304

    xor     ebp,    ebp
process_eax:
    movzx   ebx,    al
    add     ecx,    ebx
    movzx   ebx,    ah
    add     ecx,    ebx
    cmp     ebp,    0x1
    je      print_result
    xor     edx,    edx
    mov     ebx,    0xffff
    div     ebx
    mov     ebp,    0x1
    jmp     process_eax
print_result:
    mov     eax,    ecx
    call    print_eax   ; Provided by the teacher. Prints eax to the console.

exitProgram:
    ; Exit the process:
    push    0
    call    [ExitProcess]

include 'training.inc'

I think it works. I've tried it with different values and the sums were correct.

Screenshot with the output of the code above (with 0x01020304 as the hardcoded value).

But it's surely not the most efficient way to solve the exercise.


texts:
I have solved this problem from SPOJ and the code runs well. I want to improve this code using C++11 or C++14.

  Using two characters: . (dot) and * (asterisk) print a grid-like pattern. The grid will have l lines, c columns, and each square shaped element of the grid will have the height and width equal to s.

  Moreover, each of the grid elements will have a diagonal. The diagonal of the first square in the first line of the grid is directed towards down and right corner - use the \ (backslash) character to print it; while the next diagonal will be directed towards upper right corner - use the / (slash) character to print it. Print the successive diagonals alternately (please consult the example below).

Input

  You are given t - the number of test cases and for each of the test case three positive integers: l - the number of lines, c - the number of columns in the grid and s - the size of the single square shaped element.

Output

  For each of the test cases output the requested pattern (please have a look at the example). Use one line break in between successive patterns.

Example

  Input:

3

3 1 2

4 4 1

2 5 2

  Output:

****
*\.*
*.\*
****
*./*
*/.*
****
*\.*
*.\*
****

*********
*\*/*\*/*
*********
*/*\*/*\*
*********
*\*/*\*/*
*********
*/*\*/*\*
*********

****************
*\.*./*\.*./*\.*
*.\*/.*.\*/.*.\*
****************
*./*\.*./*\.*./*
*/.*.\*/.*.\*/.*
****************

  Time Limit 1s

  Source Limit 50000 B

  Memory Limit 1536 MB

Here is the code

#include <iostream>

using namespace std;

int main()
{
  int t;
  cin>>t;
  while(t--)
  {
    int l, c, s;
    cin >> l >> c >> s;
    int breadth = (c * (s + 1)) + 1;
    int height = (l * (s + 1)) + 1;
    for(int i = 0; i < height; i++)
    {
      for(int j = 0; j < breadth; j++)
      {
        if(i % (s+1) == 0 || j % (s+1) == 0)
        {
          cout << "*";
        }
        else if((i/(s+1) + j/(s+1)) % 2 == 0)
        {
          if(i % (s+1) == j % (s+1))
          {
            cout << "\\";
          }
          else
          {
             cout << ".";
          }
        }
        else
        {
          if(i % (s+1) == (s+1) - (j % (s+1)))
          {
            cout <<"/";
          }
          else
          {
            cout << ".";
          }
        }
      }
      cout << "\n";
    }
    cout << "\n";
   }
}


texts: Creating lstlistings for Java files in multiple Java folders

texts:
I did write it to have a solution for my problem. But I don't know if my code is ok. Can you please check it?

Problem:

I want to include all my Java files from all my projects (created with Netbeans), the projects are stored in one folder, into a LaTeX document. I solved it with this code:

package dir;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Dir {

    private static String fileType;
    private static String fileName;
    private static String pathName;
    private static String folderName;
    private static String oldFolderName = "";

    public static void main(String[] args) {
        File currentDir = new File(".");
        content(currentDir);
    }

    public static void content(File dir) {
        try {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    pathName = file.getName();
                    if (pathName.equals("src")) {
                        pathName = "main";
                    }
                    content(file);
                } else {
                    fileType = Files.probeContentType(Paths.get(file.getAbsolutePath()));

                    if (fileType.equals("text/x-java")) {
                        fileName = file.getName();
                        folderName = file.getParentFile().getName();

                        if(folderName.equals("src")){
                            folderName = file.getParentFile().getParentFile().getName();
                        }else{
                            folderName = file.getParentFile().getParentFile().getParentFile().getName();
                        }

                        if(!folderName.equals(oldFolderName)){
                            System.out.println("\\section{" + folderName + "}");
                        }

                        if(!pathName.equals("")){
                        System.out.println("\\subsection{" + pathName + "}");
                        }

                        System.out.println("\\subsubsection{" + fileName + "}");
                        System.out.println("\\lstinputlisting[language=java]{" + file.getCanonicalPath() + "}");
                        System.out.println("");
                        pathName = "";
                        oldFolderName = folderName;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

I am especially frustrated about following part:

if(folderName.equals("src")){
    folderName = file.getParentFile().getParentFile().getName();
}else{
    folderName = file.getParentFile().getParentFile().getParentFile().getName();
}

Is there a better way to loop through all the .getParentFile() until you get the .getParentFile().getName() of the folder named "src"?

Furthermore one question: my code doesn't iterate sorted through my folders and files. I mean, if the subfolder of the folder I am in are like 3, 4, 5 and 6, the code just don't open folder 3 first, but just chooses a random file. It would be nice if you could help me to fix it.


texts:
I'm working on the prefix search problem:

  Given a set of words, for example words = ['a', 'apple', 'angle', 'angel', 'bat', 'bats'], for any given prefix, find all matched words. For example, if input is ang, return 'angle', 'angel', if no match, return an empty list [].

Any advice on performance improvement in terms of algorithm time complexity (not sure if Trie Tree is the best solution), code bugs or general advice on code style is highly appreciated.

from collections import defaultdict
class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.isEnd = False
    def insert(self, word):
        node = self
        for w in word:
            node = node.children[w]
        node.isEnd = True
    def search(self, word):
        node = self
        for w in word:
            if w in node.children:
                node = node.children[w]
            else:
                return []
        # prefix match
        # traverse currnt node to all leaf nodes
        result = []
        self.traverse(node, list(word), result)
        return [''.join(r) for r in result]

    def traverse(self, root, prefix, result):
        if root.isEnd:
            result.append(prefix[:])
        for c,n in root.children.items():
            prefix.append(c)
            self.traverse(n, prefix, result)
            prefix.pop(-1)
if __name__ == "__main__":
    words = ['a', 'apple', 'angle', 'angel', 'bat', 'bats']
    root = TrieNode()
    for w in words:
        root.insert(w)
    print root.search('a') # 'a', 'apple', 'angle', 'angel'
    print root.search('ang') # 'angle', 'angel'
    print root.search('angl') # 'angle'
    print root.search('z') # []


texts:
Sometimes you need to do things when a condition changes, here is a simple class to keep track of the state of the last call and execute callbacks when the state changes.

#include <functional>
#include <cassert>

/// latch is a class that contains of a test function and a couple of callbacks, when the return
/// value of the test function changes the approrpiate callback gets called, as long as the return
/// value of the test function stays the same no callbacks will be called. Callbacks may be nullptr
template<class...Args>
class Latch {
public:
    Latch(std::function<bool(Args ...)> shouldLatch, std::function<void(Args...)> onLatch = nullptr, std::function<void(Args...)> onUnlatch = nullptr) :
                m_shouldLatch(std::move(shouldLatch)),
                m_onLatch(std::move(onLatch)),
                m_onUnlatch(std::move(onUnlatch)) {}

    bool latched() const noexcept { return m_isLatched; }

    explicit operator bool() const noexcept { return m_isLatched; }

    void update(Args&& ... args)
    {
        if (m_shouldLatch && m_isLatched != m_shouldLatch(std::forward<Args>(args)... ))
        {
            m_isLatched = !m_isLatched;
            auto& call = (m_isLatched) ?  m_onLatch : m_onUnlatch;
            if (call) call(std::forward<Args>(args)...);
        }
    }

private:
    bool m_isLatched = false;
    std::function<bool(Args ...)> m_shouldLatch;
    std::function<void(Args ...)> m_onLatch;
    std::function<void(Args ...)> m_onUnlatch;
};

int main()
{
    int onLatch = 0;
    int onUnlatch = 0;
    int latchVal = 1;

    Latch<int> l1([&latchVal](auto val){return val == latchVal;},
                  [&onLatch](auto val){++onLatch;},
                  [&onUnlatch](auto val){++onUnlatch;});
    assert(!l1);
    l1.update(0);
    assert(!l1);
    assert(onLatch == 0 && onUnlatch == 0);
    l1.update(1);
    assert(l1.latched());
    assert(onLatch == 1 && onUnlatch == 0);
    l1.update(1);
    assert(onLatch == 1 && onUnlatch == 0);
    l1.update(0);
    assert(onLatch == 1 && onUnlatch == 1);

    Latch l2 = l1;
}

This is also at https://www.godbolt.org/z/z4b934
Thanks for the input


texts:
I am trying to add parallelism. The following function works.  For testing purposes, calculating chunckLength is fine. However, when I allocate more cores, it seems to slow down significantly which seems due to massive overhead. The visualisation shows the average core utilisation during execution. Each run, the function is iterated over 10 times with lists of 10000 elements.

I am fairly new to F# (as you can probably tell from the functions structure...), so any suggestions on how to optimise it so I can achieve some speed-up would help greatly.

let pmap_tpl_parforlb f (xs:list<_>) =
let xs_arr = xs.ToArray()
let chunkLength = xs.Length / numProc
Parallel.For(0,numProc,fun c ->
    let x = c * chunkLength
    let y = (c * chunkLength) + chunkLength
    for x in 0..y-1 do
        xs_arr.[x] <- f (xs_arr.[x])
) |> ignore


texts: Pulling substrings from a CSV string without knowing position

texts:
My task is to copy data from an Excel sheet into charts on PowerPoint slides. To minimize the interactions between the two, I have an Excel macro insert the data for each slide into that slide's Notes pane. Next I have a PowerPoint macro extract the data from each slide's Notes and insert it into the two charts on that slide.

The data in the Notes is a string with the values separated by commas. I use Split to convert the string to an array. I identify the fields by their position in the array; that's the part that embarrasses me.

This is an example of the data string:

Shawn-MPS/BSC/BP,1,,,
June Area Text,Flexible,Diplomatic,Stress Management,
June Area Numbers, 3.5,2.1,2.9

And the macro:

Sub openChartData()
'Dim ThisWB
Dim strSlideNoteText As String

'On each slide, this opens the charts in Item 4 and 13, and lets you edit the underlying data spreadsheet

For Each aSlide In ActivePresentation.Slides
    aSlide.Select                            'For debugging only
    strSlideNoteText = aSlide.NotesPage.Shapes(2).TextFrame.TextRange.Text
    If InStr(strSlideNoteText, "SAMPLE") > 0 Then GoTo skip 'Skip the Sample slide

    'Break the note text into an array of individual words
    Dim arrSlideNoteText As Variant          '
    arrSlideNoteText = Split(strSlideNoteText, ",")

     ' MPS/BSC/BP
    With aSlide.Shapes(13).Chart.ChartData
        .Activate
        With .Workbook.sheets(1)
            .Cells(2, 2).Value = arrSlideNoteText(1)
            .Cells(2, 3).Value = arrSlideNoteText(2)
            .Cells(2, 4).Value = arrSlideNoteText(3)
        End With
        .Workbook.Close
    End With

    ' First Harrison Score and "Area" names
    With aSlide.Shapes(4).Chart.ChartData
        .Activate
        With .Workbook.sheets(1)
            .Cells(1, 2).Value = Val(arrSlideNoteText(5))
            .Cells(1, 3).Value = Val(arrSlideNoteText(6))
            .Cells(1, 4).Value = Val(arrSlideNoteText(7))
            .Cells(2, 2).Value = Val(arrSlideNoteText(9))
            .Cells(2, 3).Value = Val(arrSlideNoteText(10))
            .Cells(2, 4).Value = Val(arrSlideNoteText(11))
        End With
        .Workbook.Close
    End With

skip:
    Next aSlide
    MsgBox "Done"
End Sub

Obviously, if I have to make a change to the order of the fields, I have to change 11 lines of code, and there's always a chance of error. Is there a better way to handle this?

(If fixing this code involves revising the format of the string sent by Excel, I'm willing to do that.)


texts:
Being my first time archiving data to the file system, I would like to have my code reviewed.  This simple test project works as expected, but I want to see if what I am doing is following best practices.  You open the app, put in text for the textfields, press button and strings are saved and displayed in labels.  When app reopens, the saved strings appear in labels.

Cars.h

@interface Car : NSObject <NSCoding>
@property (nonatomic, copy) NSString *year;
@property (nonatomic, copy) NSString *make;
@property (nonatomic, copy) NSString *model;
@end

Cars.m

NSString *const kYearKey = @"YearKey";
NSString *const kMakeKey = @"MakeKey";
NSString *const kModelKey = @"ModelKey";

@implementation Car

-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.year forKey:kYearKey];
[aCoder encodeObject:self.make forKey:kMakeKey];
[aCoder encodeObject:self.model forKey:kModelKey];
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self != nil) {
    _year = [aDecoder decodeObjectForKey:kYearKey];
    _make = [aDecoder decodeObjectForKey:kMakeKey];
    _model = [aDecoder decodeObjectForKey:kModelKey];
}
return  self;
}
@end

ViewController.m

@interface ViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *yearTextField;
@property (weak, nonatomic) IBOutlet UITextField *makeTextField;
@property (weak, nonatomic) IBOutlet UITextField *modelTextField;
@property (weak, nonatomic) IBOutlet UILabel *yearLabel;
@property (weak, nonatomic) IBOutlet UILabel *makeLabel;
@property (weak, nonatomic) IBOutlet UILabel *modelLabel;
@property (strong, nonatomic) NSString *yearString;
@property (strong, nonatomic) NSString *makeString;
@property (strong, nonatomic) NSString *modelString;

- (IBAction)doneButton:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[self loadCarInfo];
}

-(void)loadCarInfo {

NSString *path = [self archivePath];
Car *returnedCarInfo = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

NSString *year = [[NSString alloc] initWithFormat:@"%@", returnedCarInfo.year];
NSString *make = [[NSString alloc] initWithFormat:@"%@", returnedCarInfo.make];
NSString *model = [[NSString alloc] initWithFormat:@"%@", returnedCarInfo.model];

_yearLabel.text = year;
_makeLabel.text = make;
_modelLabel.text = model;
}

-(BOOL)saveCarInfo {

NSString *path = [self archivePath];

Car *myCar = [[Car alloc] init];
myCar.year = _yearString;
myCar.make = _makeString;
myCar.model = _modelString;

//archive the object to the file & return YES on success
return [NSKeyedArchiver archiveRootObject:myCar toFile:path];

}

- (IBAction)doneButton:(id)sender {

_yearString = [[NSString alloc] initWithString:_yearTextField.text];
_makeString = [[NSString alloc] initWithString:_makeTextField.text];
_modelString = [[NSString alloc] initWithString:_modelTextField.text];

BOOL success = [self saveCarInfo];
if (success) {
    [self loadCarInfo];
}
}

-(NSString *)archivePath {

NSArray *documentDirectories= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
//get the document directory from that list
NSString *documentDirectory = [documentDirectories firstObject];

return [documentDirectory stringByAppendingPathComponent:@"savedText.txt"];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {

[textField resignFirstResponder];

return YES;
}

@end


texts:
I've just written a simple caching / memoization python decorator. It's purpose is to cache what the function returns for all the arguments combinations it's been ever invoked with.

So, if, say, we had a function my_function(a, b=2, c=3) invoked once with my_function(1, 2, c=3), the results should be then cached whenever I call it with my_function(1, 2, 3) or my_function(1, c=3, b=2) or my_function(c=3, b=2, a=1).

Is what's below a good approach and could it be somehow improved?

import functools
import pickle

def memoize_all(func):
    """
    This is a caching decorator. It caches the function results for
    all the arguments combinations, so use it with care. It does not matter      whether the arguments
    are passed as keywords or not.
    """
    cache = {}

    @functools.wraps(func)
    def cached(*args, **kwargs):
        arg_names = func.func_code.co_varnames
        arg_dict = {}
        for i, arg in enumerate(args):
            arg_dict[arg_names[i]] = args[i]
        arg_dict.update(**kwargs)
        key = pickle.dumps(arg_dict)
        if key not in cache:
            cache[key] = func(*args, **kwargs)
        return cache[key]
    return cached


texts: Check if relations exists for a parent node before deleting it so that we don't have any orphan child node

texts:
Here I am trying to delete a parent node but only if it doesn't have any child node. Please review this code.

PostController.php

/**
 * Delete the given post.
 *
 * @param  int $post_id
 * @return void
 *
 * @throws \App\Exceptions\RelationExistsException
 */
public function deletePost($post_id)
{
    $relations = ['tags', 'comments'];

    $hasRelations = $this->postRepo->hasRelations($post_id, $relations);

    if ($hasRelations) {
        throw new RelationExistsException($relations);
    }

    $this->postRepo->delete($post_id);
}

RepositoryTrait.php

/**
 * Check if any relation exists.
 *
 * @param  int  $id
 * @param  array  $relations
 * @return bool
 */
public function hasRelations($id, array $relations)
{
    if (count($relations) == 0) {
        throw new \Exception('No relation is provided.');
    }

    $modelName = $this->model;

    $query = $modelName::where('id', $id);

    $query->where(function($q) use($relations) {
        foreach ($relations as $relation) {
            $q->orHas($relation);
        }
    });

    return $query->exists();
}

RelationExistsException.php

namespace App\Exceptions;

use Exception;

class RelationExistsException extends Exception
{
    /**
    * Create a new exception instance.
    *
    * @param array $relations
    * @return void
    */
    function __construct($relations)
    {
        parent::__construct(sprintf(
            'Cannot delete because there exists relations - %s.', implode(', ', $relations))
        );
    }
}

I have one more issue with the following code:

$modelName = $this->model; // contains '\App\Models\Post'

$query = $modelName::where('id', $id);

I have to save the $this->model in $modelName to use it with the where function. Is there a better solution for it. I have tried {}, () but nothing worked.

GitHub Gist for above code


texts:
Can someone please review this simple code for printing all paths in a matrix from bottom left to top right? If an element is 1, it is a "wall" and you cannot take it.

Possible steps: up and right

  // Prints possible paths from bottom left to top right
    public static void findPath(int n, int i , int j, int[][] mat,ArrayList<Integer> path)
    {
        if(i==0 && j==n-1)
        {
            System.out.println();
            for(Integer step: path)
            {
                System.out.print(","+step);
            }
        }

        if(isPossibleStep(i+1,j,n,mat))
        {
            path.add(i+1);
            findPath(n,i+1, j,mat, path);
        }
        else if(isPossibleStep(i,j-1,n,mat))
        {
            path.add(j-1);
            findPath(n,i, j-1,mat, path);
        }

    }

    // Tells if a given path is possible
    public static boolean isPossibleStep(int i, int j, int n,int[][] mat)
    {
        if(mat[i][j]==1)
            return false;

        if(i < n && j > 0)
            return true;
        else
            return false;
    }

Also, how do I print just 1 possible path and then exit? It seems like a simple change but I am not able to think of a graceful way of doing it.


texts:
I have a large file that I want to search for text as fast as possible. There is not a memory contraint, so I am loading the entire file into memory so that I can use the rayon parallelism crate in order to improve performance (so I don't get blocked by an IO thread). I have the following code (I've indented the benchmark lines to stand out from the functional code):

extern crate rayon;
use rayon::prelude::*;
use std::io;
use std::io::prelude::*;
use std::fs::File;
use std::time::Instant;

fn main() -> io::Result<()> {
    let now = Instant::now();

    let mut f = File::open("words_huge.txt")?;
        let time_to_open = now.elapsed().as_millis();

    let mut whole_file = String::new();

    let n = f.read_to_string(&mut whole_file)?;
        let time_to_read = now.elapsed().as_millis() - time_to_open;

    let mut lines = whole_file.par_lines(); // Split it into lines
        let time_to_line_split = now.elapsed().as_millis() - time_to_read;

    let mut results: Vec<&str> = lines.filter(|l| l.contains("test")).collect();
        let time_to_process = now.elapsed().as_millis() - time_to_line_split;

    for r in results
    {
        println!("{}", r);
    }

    let time_to_print = now.elapsed().as_millis() - time_to_process;
    println!("Time to open: {}", time_to_open);
    println!("Time to read: {}", time_to_read);
    println!("Time to line split: {}", time_to_line_split);
    println!("Time to process: {}", time_to_process);
    println!("Time to print: {}", time_to_print);
    println!("Total time elapsed: {}", now.elapsed().as_millis());
    Ok(())
}

Please provide feedback on how this could be further optimized. Could I be performing fewer memory operations in the name of speed? Is there too much overhead to threading here? Note that words_huge.txt is a text file with over 10 million lines of text from the English dictionary repeated over about 20 times.

Note: This is going to be machine and even run-dependent, but the current version above does execute quite fast... processing time takes 172-185ms on my machine... Pretty good for 10 million lines! But can we do better?


texts: Mongoose schema for products and social media posts

texts:
Here is my current schema:

Brand:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var BrandSchema = new mongoose.Schema({
  name: { type: String, lowercase: true , unique: true, required: true },
  photo: { type: String , trim: true},
  email: { type: String , lowercase: true},
  year: { type: Number},
  timestamp: { type : Date, default: Date.now },
  description: { type: String},
  location: { },
  social: {
    website: {type: String},
    facebook: {type: String },
    twitter: {type: String },
    instagram: {type: String }
  }
});

Style:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var StyleSchema = new mongoose.Schema({
  name: { type: String, lowercase: true , required: true},
});

Product:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProductSchema = new mongoose.Schema({
  name: { type: String, lowercase: true , required: true},
  brandId : {type: mongoose.Schema.ObjectId, ref: 'Brand'},
  styleId: {type: mongoose.Schema.ObjectId, ref: 'Style'},
  year: { type: Number },
  avgRating: {type: Number}
});

Post:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var PostSchema = new mongoose.Schema({
  rating: { type: number},
  brandId : {type: mongoose.Schema.ObjectId, ref: 'Brand'},
  comment: {type: String},
  productId: {type: mongoose.Schema.ObjectId, ref: 'Style'},
  styleId: {type: mongoose.Schema.ObjectId, ref: 'Style'},
  photo: {type: String}
});

I'm currently making use of the mongoose populate feature:

exports.productsByBrand = function(req, res){
  Product.find({product: req.params.id}).populate('style').exec(function(err, products){
    res.send({products:products});
  });
};

This works, however, I've started reading about performance issues with the mongoose populate, since it's really just adding an additional query.

For my post, it seems that could be taxing. The intent for the post is to be a live twitter / Instagram-like feed. It seems that could be a lot of queries, which could greatly slow my app down.

Also, I want to be able to search products / post / brand by fields at some point.

Should I consider nesting / embedding this data (products nested / embedded in brands)?

What's the most efficient schema design or would my setup be alright -- given what I've specified I want to use it for?

User story:

There will be an admin user.

The admin will be able to add the Brand with the specific fields in the Brand schema.

Brands will have associated Products, each Product*will have a Style / category.

Search:

Users will be able to search Brands by name and location (i'm looking into doing this with angular filtering / tags).

Users will be able to search Products by fields (name, style, etc).

Post:

Users will be able to Post into a feed. When making a Post, they will choose a Brand and a Product to associate the Post with. The Post will display the Brand name, Product name, and Style -- along with newly entered Post fields (photo, comment, and rating).

Other users can click on the Brand name to link to the Brand show page. They can click on the Product name to link to a Product show page.

Product show page:

Will show Product fields from the above Schema -- including associated Style name from Style schema. It will also display Post pertaining to the specific Product.

Brand show page:

Will simply show Brand fields.

My main worry is the Post, which will have to populate / query for the Brand, Product, and Style within a feed.

Again, I'm contemplating if I should embed the Products within the Brand. Would I then be able to associate the index of the Product with the Post for later queries? Or, possibly $lookup or other aggregate features.


texts: PHP - Deleting Directory Contents & SubDirectory Contents

texts:
I've set up some PHP to delete a directory, it's contents, and any subdirectory and its contents... I'm new to PHP so I'm most definitely doing something WRONG or am doing something in the most inefficient way.

Looking for some references or suggestion on how to do this better...

Using PHP 5.3.8.

First Draft

if ($handle = opendir($main_dir)) {
    while (false !== ($entry = readdir($handle))) {
        $absolute_path = $main_dir.'/'.$entry;
        if ($entry != "." && $entry != "..") {
            chmod($absolute_path, 0755);
            unlink($absolute_path);

            //check if any folders exist, then delete files within
            if (file_exists($absolute_path) && is_dir($absolute_path)) {
                if ($child_handle = opendir($absolute_path)) {
                    while (false !== ($child_entry = readdir($child_handle))) {
                    $child_absolute_path = $absolute_path.'/'.$child_entry;
                        if ($child_entry != "." && $child_entry != "..") {
                            unlink($child_absolute_path);
                        }
                    }
                    closedir($child_handle);
                }
            }
            rmdir($absolute_path);
        }
    }
    closedir($handle);
}
rmdir($main_dir);

how about something like this...

Second Draft

 $dir = "path/to/dir";
 chmod($dir, 0755);
 $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
 $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
 foreach ( $ri as $file ) {
     $file->isDir() ?  rmdir($file) : unlink($file);
 }
 rmdir($dir);

Any thoughts? Much appreciated!


texts:
I've had a bit of help but I'm still a bit unsure. I have an nginx webserver with SSH only required. I wrote this rule set based on information I found on the internet:

i=/sbin/iptables

# Flush all rules
$i -F
$i -X

# Setup default filter policy
$i -P INPUT DROP
$i -P OUTPUT DROP
$i -P FORWARD DROP

# DONT KNOW WHAT THESE DO
$i -A INPUT -i lo -j ACCEPT
$i -A INPUT -p icmp --icmp-type any -j ACCEPT

# Force SYN checks
$i -A INPUT -p tcp ! --syn -m state --state NEW -j DROP

# Drop all fragments
$i -A INPUT -f -j DROP

# Drop XMAS packets
$i -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

# Drop NULL packets
$i -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

# Allow established connections
$i -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow unlimited traffic on loopback
$i -A INPUT -i lo -j ACCEPT
$i -A OUTPUT -o lo -j ACCEPT

# Open nginx
$i -A INPUT -p tcp --dport 443 -j ACCEPT
$i -A INPUT -p tcp --dport 80 -j ACCEPT

# Open SSH
$i -A INPUT -p tcp --dport 22 -j ACCEPT

Can anyone please tell me if I am taking the right approach here, and if I can improve it in any way?


texts:
Consider the following:

If myString = "abc" Or myString = "def" [...] Or myString = "xyz" Then

In C# when myString == "abc" the rest of the conditions aren't evaluated. But because of how VB works, the entire expression needs to be evaluated, even if a match is found with the first comparison.

Even worse:

If InStr(1, myString, "foo") > 0 Or InStr(1, myString, "bar") > 0 [...] Then

I hate to see these things in code I work with. So I came up with these functions a while ago, been using them all over the place, was wondering if anything could be done to make them even better:

StringContains is used like If StringContains("this is a sample string", "string"):

Public Function StringContains(string_source, find_text, Optional ByVal caseSensitive As Boolean = False) As Boolean

    'String-typed local copies of passed parameter values:
    Dim find As String, src As String
    find = CStr(find_text)
    src = CStr(string_source)

    If caseSensitive Then
        StringContains = (InStr(1, src, find, vbBinaryCompare) <> 0)
    Else
        StringContains = (InStr(1, src, find, vbTextCompare) <> 0)
    End If

End Function

StringContainsAny works in a very similar way, but allows specifying any number of parameters so it's used like If StringContainsAny("this is a sample string", false, "foo", "bar", string"):

Public Function StringContainsAny(string_source, ByVal caseSensitive As Boolean, ParamArray find_strings()) As Boolean

    'String-typed local copies of passed parameter values:
    Dim find As String, src As String, i As Integer, found As Boolean
    src = CStr(string_source)

    For i = LBound(find_strings) To UBound(find_strings)
        find = CStr(find_strings(i))
        If caseSensitive Then
            found = (InStr(1, src, find, vbBinaryCompare) <> 0)
        Else
            found = (InStr(1, src, find, vbTextCompare) <> 0)
        End If
        If found Then Exit For
    Next

    StringContainsAny = found

End Function

StringMatchesAny will return True if any of the passed parameters exactly matches (case-sensitive) the string_source:

Public Function StringMatchesAny(string_source, ParamArray find_strings()) As Boolean

    'String-typed local copies of passed parameter values:
    Dim find As String, src As String, i As Integer, found As Boolean
    src = CStr(string_source)

    For i = LBound(find_strings) To UBound(find_strings)
        find = CStr(find_strings(i))
        found = (src = find)
        If found Then Exit For
    Next

    StringMatchesAny = found

End Function


texts: Estimating Pi with random darts on dartboard - high complexity issues

texts:
I've been trying to write nice snippet of code to simulate pi estimation by randomly throwing darts on a dartboard. While running the following code on high but reasonable numbers my mac doesn't plot.

When looking at it I don't find the source of such a high complexity.

I checked similar questions like
this but haven't been able to find straightforward answer.

My guess is that the line plotting real pi is computationally intense - but that's just a hunch.

I'd also appreciate any comment regarding style / efficiency.

import numpy as np
import random
import math
from matplotlib import pyplot as plt

def estimatePi(r,w,h,N):
    center = (w/2.0,h/2.0)
    in_circle = 0
    for i in range(N):
        x = random.uniform(0.0,w)
        y = random.uniform(0.0,h)
        distance = math.sqrt((x-center[0])**2+(y-center[1])**2)
        if distance <= r:
            in_circle += 1
    outOfCircle=N-in_circle
    ratio = float(in_circle)/N
    #ratio = ((r**2)*pi)/(w*h)  // *(w*h)
    #ratio*(w*h) = ((r**2)*pi) // : r**2
    pi = ratio*(w*h)/(r**2)
    return pi

#run, aggregate results:
PiEstimation=[]
num_darts=[]
loopcount = 1000001
i=10000

while i <loopcount:
    result=estimatePi(3,10,10,i)
    num_darts.append(i)
    PiEstimation.append(result)
    i += 15000

# plot:
plt.title('Estimating the Value of Pi - Dartboard Simulation')
plt.plot([0,100000000], [3.14,3.14], 'k-',color="red", linewidth=2.0)
plt.ylabel('Pi Estimation')
plt.xlabel('Number of Darts')
plt.errorbar(num_darts,PiEstimation, yerr=.0001,ecolor='magenta')
plt.show('hold')


texts: Java controller to farm out concurrent tasks

texts:
I've recently given a coding interview on a Java concurrency task and unfortunately didn't get the job.  The worst part is I've given my best but now I'm not even sure where went wrong.  Can anyone help give me some ideas about things I can improve on below code?

The question is pretty vague.  Given 4 generic interfaces which on a high level divides a task into small pieces, work on each piece and combine the partial result into final result. I'm asked to implement the central controller piece of the interface.  The only requirement is to use concurrency in the partial result processing and "code must be production quality".

My code is as below (the interfaces were given).  I did put in a lot of comment to explain my assumptions which are removed here.

// adding V,W in order to use in private fields types
public class ControllerImpl<T, U, V, W> implements Controller<T, U> {

    private static Logger logger = LoggerFactory.getLogger(ControllerImpl.class);

    private static int BATCH_SIZE = 100;

    private Preprocessor<T, V> preprocessor;
    private Processor<V, W> processor;
    private Postprocessor<U, W> postprocessor;

    public ControllerImpl() {
        this.preprocessor = new PreprocessorImpl<>();
        this.processor = new ProcessorImpl<>();
        this.postprocessor = new PostprocessorImpl<>();
    }

    public ControllerImpl(Preprocessor preprocessor, Processor processor, Postprocessor postprocessor) {
        this.preprocessor = preprocessor;
        this.processor = processor;
        this.postprocessor = postprocessor;
    }

    @Override
    public U process(T arg) {
        if (arg == null) return null;

        final V[] parts = preprocessor.split(arg);
        final W[] partResult = (W[]) new Object[parts.length];

        final int poolSize = Runtime.getRuntime().availableProcessors();
        final ExecutorService executor = getExecutor(poolSize);

        int i = 0;
        while (i < parts.length) {
            final List<Callable<W>> tasks = IntStream.range(i, i + BATCH_SIZE)
                .filter(e -> e < parts.length)
                .mapToObj(e -> (Callable<W>) () -> partResult[e] = processor.processPart(parts[e]))
                .collect(Collectors.toList());
            i += tasks.size();

            try {
                logger.info("invoking batch of {} tasks to workers", tasks.size());
                long start = System.currentTimeMillis();
                final List<Future<W>> futures = executor.invokeAll(tasks);
                long end = System.currentTimeMillis();
                logger.info("done batch processing took {} ms", end - start);
                for (Future future : futures) {
                    future.get();
                }
            } catch (InterruptedException e) {
                logger.error("{}", e);// have comments to explain better handling according to real business requirement
            } catch (ExecutionException e) {
                logger.error("error: ", e);
            }
        }

        MoreExecutors.shutdownAndAwaitTermination(executor, 60, TimeUnit.SECONDS);

        return postprocessor.aggregate(partResult);
    }

    private ExecutorService getExecutor(int poolSize) {
        final ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat("Processor-%d")
            .setDaemon(true)
            .build();
        return new ThreadPoolExecutor(poolSize, poolSize, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), threadFactory);
    }
}


texts:
I need to write a maximum function so that it finds that longest word in the Ternary Search Tree and prints it.
This is what I have done so far. I have words in the tree such as "canvas", "cats" "van" but it prints None any way.
def maximum(self):
    if self.root == None:
        return 0
    ptr = self.root
    self.maxLengthTST(ptr)

def maxLengthTST(self,ptr):
    if ptr.left == None:
        return
    if ptr.next == None:
        return
    if ptr.right == None:
        return
    return max(self.maxLengthTST(ptr.left),  self.maxLengthTST(ptr.next)+1, self.maxLengthTST(ptr.right));

def max( a, b, c):
    max = 0
    if a >= b and a >= c:
        max = a
    elif b >= a and b >= c:
        max = b
    else:
        max = c
    return max


texts:
I [believe that I] wrote foldl in terms of foldr:

myFoldl :: (a -> b -> a) -> a -> [b] -> a
myFoldl f base xs = foldr (flip f) base (reverse xs)

Is this an idiomatic implementation?


texts:
According to Wikipedia, here below is the definition of the algorithm:

  ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is a special case of the Caesar cipher, developed in ancient Rome.

  ROT47 is a derivative of ROT13 which, in addition to scrambling the basic letters, also treats numbers and common symbols. Instead of using the sequence A–Z as the alphabet, ROT47 uses a larger set of characters from the common character encoding known as ASCII. Specifically, the 7-bit printable characters, excluding space, from decimal 33 '!' through 126 '~', 94 in total, taken in the order of the numerical values of their ASCII codes, are rotated by 47 positions, without special consideration of case. For example, the character A is mapped to p, while a is mapped to 2.

I already implemented it in C++ but this time, I have implemented it in SQL Server. Here below is the user-defined function I wrote:

CREATE FUNCTION [dbo].[ROT47]
(
  @PLAIN_TEXT nvarchar(MAX)
)
RETURNS nvarchar(MAX)
AS
BEGIN
  DECLARE @ENCRYPTED_TEXT nvarchar(MAX) = N''
  DECLARE @LENGTH_TEXT int = 0
  DECLARE @c nvarchar = N''
  DECLARE @i int = 1

  SET @LENGTH_TEXT = LEN(@PLAIN_TEXT)

  WHILE (@i <= @LENGTH_TEXT)
  BEGIN
    SET @c = SUBSTRING(@PLAIN_TEXT, @i, 1)

    IF (ASCII(@c) BETWEEN ASCII(N'!') AND ASCII(N'~'))
    BEGIN
      SET @c = char(ASCII(N'!') + (ASCII(@c) - ASCII(N'!') + 47) % 94)
      SET @ENCRYPTED_TEXT = @ENCRYPTED_TEXT + @c
    END

    SET @i = @i + 1
  END

  RETURN @ENCRYPTED_TEXT
END

Below is the query I wrote to test my UDF:

DECLARE @PLAIN_TEXT nvarchar(MAX) = N'HelloWorld'
DECLARE @ENCRYPTED_TEXT nvarchar(MAX)
DECLARE @DECRYPTED_TEXT nvarchar(MAX)

SET @ENCRYPTED_TEXT = ( SELECT dbo.ROT47(@PLAIN_TEXT) )
SET @DECRYPTED_TEXT = ( SELECT dbo.ROT47(@ENCRYPTED_TEXT) )

SELECT @PLAIN_TEXT AS PLAIN_TEXT,
       @ENCRYPTED_TEXT AS ENCRYPTED_TEXT,
       @DECRYPTED_TEXT AS DECRYPTED_TEXT

As expected, the above query gives the following result:

+--------------+------------------+------------------+
|  PLAIN_TEXT  |  ENCRYPTED_TEXT  |  DECRYPTED_TEXT  |
+--------------+------------------+------------------+
|  HelloWorld  |    w6==@(@C=5    |    HelloWorld    |
+--------------+------------------+------------------+

What do you think about my implementation ? Is there a way to improve it ? I know loops are things you're trying to avoid in SQL Server but is there a way to avoid using a loop in my case ?


texts: Creating SwiftReachability Class in Swift 2.2

texts:
I am novice at creating independent classes for user. I have seen many Reachability library for Swift, but I need to create my own class for that. Here is my code:

class SwiftReachability: NSObject {

let REACHABILITY_NOTIFIER_KEY = "reachability_notifier_key"
var backgroundQueue: NSOperationQueue?
var isCancelled: Bool = false

//MARK: - Checking Internet Connecion
func isConnectedToNetwork() -> Bool{

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {

        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }

    var flags = SCNetworkReachabilityFlags(rawValue: 0)

    SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags)

    #if DEBUG
        print("Reachability flags = \(flags.rawValue) uint = \(UInt32(kSCNetworkFlagsReachable))")
    #endif

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection) ? true : false
}

func startNotifier(){

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SwiftReachability.networkConnectionObserver), name: REACHABILITY_NOTIFIER_KEY, object: nil)
    callingBackgroungThread()
}

func stopNotifier(){

    NSNotificationCenter.defaultCenter().removeObserver(self, name: REACHABILITY_NOTIFIER_KEY, object: nil)
    backgroundQueue?.cancelAllOperations()
    isCancelled = true
}

func callingBackgroungThread(){

    backgroundQueue = NSOperationQueue()

    let operation = NSBlockOperation {

        if self.isConnectedToNetwork(){

            NSNotificationCenter.defaultCenter().postNotificationName(self.REACHABILITY_NOTIFIER_KEY, object:nil)
        }
    }

    operation.completionBlock = {

        if !self.isCancelled{

            self.callingBackgroungThread()
        }
    }

    delay(5.0, closure: {

        if !self.isCancelled{

            self.backgroundQueue?.addOperation(operation)
        }
    })
}

func networkConnectionObserver(){

    print("Observer")
    showAlert("Network Identified")
}

//MARK: Dispatch Asyn Queue After
func delay(delay:Double, closure:()->()) {

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
}

func showAlert(message: String){

    let alertController = UIAlertController(title: "Bing", message: message, preferredStyle: UIAlertControllerStyle.Alert)

    let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) in

        self.stopNotifier()
    })

    alertController.addAction(okAction)

    dispatch_async(dispatch_get_main_queue(), {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.window?.rootViewController!.presentViewController(alertController, animated: true, completion: nil)
    })
}
}

Can anyone review it to make it better?


texts: Parsing data from XML using Ruby and Nokogiri

texts:
I have a method that parses XML into an array of hashes.

Here is the original XML:

<rowset name="skillqueue" key="queuePosition" columns="queuePosition,typeID,level,startSP,endSP,startTime,endTime">
  <row queuePosition="0" typeID="20495" level="3" startSP="2829" endSP="16000" startTime="2013-03-04 16:25:50" endTime="2013-03-05 01:02:20"/>
  <row queuePosition="1" typeID="19767" level="4" startSP="40000" endSP="226275" startTime="2013-03-05 01:02:20" endTime="2013-03-07 06:40:31"/>
</rowset>

Here is the final array of hashes:

[{:queuePosition=>"0", :typeID=>"20495", :level=>"3", :startSP=>"2829", :endSP=>"16000", :startTime=>"2013-03-04 16:25:50", :endTime=>"2013-03-05 01:02:20"}, {:queuePosition=>"1", :typeID=>"19767", :level=>"4", :startSP=>"40000", :endSP=>"226275", :startTime=>"2013-03-05 01:02:20", :endTime=>"2013-03-07 06:40:31"}]

Here is the method, which uses Nokogiri for parsing:

def get_training_queue(xml_data)
  queue = []
  xml_data.xpath("//row").each do |skill_in_queue|
    skill = {}
    skill_in_queue.attributes.each do |details|
      skill[details[0].to_s.to_sym] = details[1].to_s
    end
    queue << skill
  end
  queue
end

This works great, but it feels a bit inelegant.

I'm curious if there is a better way to create the hashes within the internal loop?
I am calling to_s because I couldn't figure out a way to pull out just the key/value without doing so, and it 'feels' like I'm missing some more elegant way of doing that.


texts: Sending templatized e-mail to a million contacts

texts:
This code runs fine without a bug, I need to optimize this code for following interview requirement.

Lets say i need to send it to 1 million contacts and emailBody is ~100Kb.

What code optimization do you recommend to make it faster ?
Write code or algorithm to explain the optimization you think will make this code faster, let's say 10x, 100x ?

public String sendEmail(String emailBody, Email email) {
      Hashtable<String, String> dataHash = new Hashtable<String, String>();

      dataHash.put("{{USER_EMAIL}}", email.getEmail());
      dataHash.put("{{USER_NAME}}", email.getName());
      dataHash.put("{{USER_PHONE}}", email.getPhone());
      dataHash.put("{{LOGIN_URL}}", email.getLoginUrl());

      Enumeration<String> tagList = dataHash.keys();

      while (tagList.hasMoreElements()) {
          String tag = tagList.nextElement();
          while (emailBody.indexOf(tag) != -1) {
              int indexOf = emailBody.toLowerCase()
                      .indexOf(tag.toLowerCase());

              String part1 = emailBody.substring(0, indexOf);
              String part2 = emailBody.substring(indexOf + tag.length(),
                      emailBody.length());

              emailBody = part1 + (String) dataHash.get(tag) + part2;
          }
      }
      return emailBody;
  }

My version is:

public String sendEmailUsingStringBuilder(String emailBody, Email email) {

        HashMap<String, String> dataHash = new HashMap<String, String>();
        dataHash.put("{{USER_EMAIL}}", email.getEmail());
        dataHash.put("{{USER_NAME}}", email.getName());
        dataHash.put("{{USER_PHONE}}", email.getPhone());
        dataHash.put("{{LOGIN_URL}}", email.getLoginUrl());

        StringBuilder strBuilder = new StringBuilder(emailBody);
        for ( String tag : dataHash.keySet() ) {
            int tagIndex;
            while ((tagIndex = strBuilder.indexOf(tag)) != -1) {
                strBuilder.replace(tagIndex, tagIndex + tag.length(),
                        (String) dataHash.get(tag));
                tagIndex = strBuilder.indexOf(tag);
            }
        }
        return strBuilder.toString();
    }


texts: Enforcing Paired Statements Using ScriptBlock

texts:
I really like c#'s Using statement as it allows you to pair Open statements with their corresponding Close/Dispose statements in an elegant way which matches C#'s syntax.
I realised that something similar can be achieved in PowerShell; e.g. Push-Location should be paired with a Pop-Location, and this can be enforced by creating a function which allows you to use a USING-like syntax.

e.g.

function PushDPopD {
    [CmdletBinding()]
    param (
        [string]$Path
        ,
        [scriptblock]$Code
    )
    process {
        if (Push-Location $Path -PassThru) { #only proceed with this function's logic if our pushd were successful
            try {
                $Code.Invoke()
            } finally { #ensure that whatever happens in user code, we always popd after our pushd
                Pop-Location
            }
        }
    }
}
function ShowCurrentLocation {
    ("You are in: {0}" -f (Get-Location).Path)
}

Clear-Host
[string]$localVariable = "We keep variables even in scriptblock context"

write-host "`n`n==Healthy Demo==`n`n" -ForegroundColor cyan
ShowCurrentLocation
PushDPopD 'c:\Users' {
    "hello"
    ShowCurrentLocation
    $localVariable
    "bye"
}
ShowCurrentLocation

write-host "`n`n==Exception Demo==`n`n" -ForegroundColor cyan
ShowCurrentLocation
PushDPopD 'c:\ThisPathDoesNotExist' {
    "hello"
    ShowCurrentLocation
    $localVariable
    "bye"
}
ShowCurrentLocation

To me this seems like a logical approach / looks neater than manually checking that all pushes are correctly paired with pops.
The only potential issue is if someone includes a popd in the scriptblock itself; but that's no worse than the original scenario, so isn't a big drawback.
This also gives us the advantage that code won't blindly run on thinking it's in a different directory to the one specified if the pushd fails.

As a concept does this seem logical / have I missed anything.

NB: I'm aware it's not currently following verb-noun convention; that's because it's just proof of concept code, so I've not yet put any thought into suitable naming (suggestions welcome though).


texts: Models in a Simple PyMongo-based Blogging Web App without ORM/ODM

texts:
I am currently using PyMongo + Flask for building a simple blogging application. I am not using any kind of ODM, instead I decided to use PyMongo directly. I need to know how to improve my code since learning is my main motivation for building this application.

This portion of code is implemented in a view controller called post.py and it is used to edit a post:

@posts.route('/<_id>/edit', methods=['GET', 'POST'])
def edit(_id):
    post = Post()
    post.get(_id)
    if request.method == 'POST':
        post.title = request.form.get('title')
        post.tags = [tag.strip() for tag in
                     request.form.get('tags').split(',')]
        post.body = request.form.get('body')
        post.update()
    return render_template('posts_edit.html', post=post)

The Post model looks something like this:

class Post:
    def __init__(self, _id=None, title=None, status=None, tags=None,
                 body=None, date=None, author=None):
        self._id = _id
        self.title = title
        self.status = status
        self.tags = tags
        self.body = body
        self.date = date
        self.author = author

    def save(self):
        mongo.db.posts.insert_one({
            "_id": ObjectId(),
            "title": self.title,
            "status": self.status,
            "tags": self.tags,
            "body": self.body,
            "date": datetime.utcnow(),
            "author": self.author
        })

    def update(self):
        mongo.db.posts.update({
            '_id': self._id
        },
            {
                "title": self.title,
                "status": self.status,
                "tags": self.tags,
                "body": self.body,
                "date": self.date,
                "author": self.author
        })

    def get(self, _id):
        post = mongo.db.posts.find_one({'_id': ObjectId(_id)})
        if post:
            self.__init__(**post)
            return self
        return None

    @classmethod
    def get_all(cls):
        return mongo.db.posts.find()

Is this the right direction?


texts: Increase performance in sub-line detection

texts:
I have an algorithm for checking whether one line is contained within another. The lines I have are made up of an ordered array of points, which are just data structures with values for x, y and z. The lines are no necessarily straight. The subline does not need to be going in the same direction as the main line.

The algorithm I have currently is:

public static bool IsSubline(Point[] subline, Point[] line)
{

    int prevIndex = int.MaxValue;
    bool contains = false;

    foreach (Point point in subline)
    {
        for (int i = 0; i < line.Length; i++)
        {
            if (Equal(point, line[i]))
            {
                if (prevIndex == int.MaxValue || System.Math.Abs(prevIndex - i) == 1)
                {
                    prevIndex = i;
                    contains = true;
                    break;
                }
            }

            contains = false;
        }

        if (!contains)
        {
            break;
        }
    }

    return contains;
}

Equal is:

internal static bool Equal(Point point1, Point point2, float epsilon = CoordinateEpsilon)
{
    return System.Math.Abs(point1.x - point2.x) < epsilon &&
        System.Math.Abs(point1.y - point2.y) < epsilon &&
        System.Math.Abs(point1.z - point2.z) < epsilon;
}

I feel like this could be done in a faster way, anyone have any suggestions?


texts: Is there a "code less" way to construct this JS loop?

texts:
I just know there's a simpler, better way to do this. Will eventually append <select> options with these values (e.g. 01:30, 02:45, 10:15, etc.)

var arrHours=[]
var i=0, j=0, k=0;
for (i=0;i<=23;i++)
{
    for(j=0;j<=45;j=j+15)
    {
        var m,n;
        m=i.toString();
        n=j.toString();
        if(m=="0")
        {
            m="00";
        }
        if(m.length<2)
        {
            m="0"+m;
        }
        if(n=="0")
        {
            n="00";
        }
        arrHours.push(m+":"+n);
    }
}
for(k in arrHours)
{
    $("#preview4").append(arrHours[k]+"<BR>");
}

ps. I prefer the semicolon. ;)


texts:
I'm currently learning about PDO, and trying to connect to the database and CRUD in OOP way, this is a simple code that I use.

index.php

include_once("connection.php");
include_once("model.php");

$con    = new Connection();
$model  = new Model();

$model->insert();
$con->closeConnection();

connection.php

class Connection {

    protected $host = "localhost";
    protected $dbname = "pdo";
    protected $user = "root";
    protected $pass = "";
    protected $DBH;

    function __construct() {

        try {

            $this->DBH = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->user, $this->pass);
        }
        catch (PDOException $e) {

            echo $e->getMessage();
        }
    }

    public function closeConnection() {

        $this->DBH = null;
    }
}

model.php

class Model extends Connection {

    public function insert() {

        $STH = $this->DBH->prepare("INSERT INTO people (name) VALUES ('Yeaaap')");
        $STH->execute();
    }
}

Am I doing it in the right way?


texts: Defining metaclass instance methods inside of the metaclass factory instead of the metaclass itself - flawed design?

texts:
I'm wondering if this is good design, or if the definition of the __init__, __call__, and __repr__ methods should be inside of mesh_class_meta itself instead of inside of the factory, mesh_class.

If it is better to for them to be defined inside of the metaclass definition, please explain specifically why? Or is there another even better way that I haven't thought of?

debugprint = print

##Metaclass for mesh data subclasses
##Receives a list of valid fields in a string (similar to namedtuple)
##Adds those fields to __slots__
class mesh_class_meta(type):
    def __new__(meta, name, bases, fields):
        if isinstance(fields, str): fields = fields.replace(',',' ').split()
        fields = tuple(fields)
        debugprint('\n-------------------------')
        debugprint('Allocating memory for new mesh_class', name)
        debugprint(meta)
        debugprint(bases)
        debugprint(fields)
        debugprint('\n')
        dctn = {}
        dctn['__slots__'] = list(fields)
        return super(mesh_class_meta, meta).__new__(meta, name, bases, dctn)

    def __init__(klass, name, bases, fields):
        debugprint('\n-------------------------')
        debugprint('Initializing class', name)
        debugprint(klass)
        debugprint(bases)
        debugprint(fields)
        debugprint('\n')
        super(mesh_class_meta, klass).__init__(name, bases, {})

##mesh_class_meta factory
##__init__, __call__, and __repr__ for the subclasses are defined here
##__call__ allows the values of slot fields to be changed by calling the class
##with a valid dictionary argument
def mesh_class(name, fields):
    new_class = mesh_class_meta(name, (object,), fields)
    def new_class__init__(self, *args, **kwargs):
        for slot, arg in enumerate(args):
            setattr(self, str(self.__slots__[slot]), arg)
        for k,v in kwargs.items():
            setattr(self, k, v)
        debugprint('\n-------------------------')
        debugprint('New', name, 'object created using', tuple(({attr: getattr(self, attr)} for attr in self.__slots__)))
        debugprint('\n')
        super(new_class, self).__init__() #Not sure if this is correct; seems to work
    new_class.__init__ = new_class__init__
    def new_class__call__(self, **kwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)
        debugprint('\n-------------------------')
        debugprint('Fields in', name, 'object edited:', tuple(({k: v} for k,v in kwargs.items())))
        debugprint('\n')
    new_class.__call__ = new_class__call__
    def new_class__repr__(self):
        return str(name) + str({attr: getattr(self, attr) for attr in self.__slots__})
    new_class.__repr__ = new_class__repr__
    return new_class

##mesh classes created
Point = mesh_class('Point', 'x y')
Elpoints = mesh_class('Elpoints','i j k l')
Boundpoint = mesh_class('Boundpoint','b')

##Testing procedures##

##Create some instances
Points = [Point(p,p) for p in range(0,4,1)]
e1 = Elpoints(*tuple(p for p in Points))
b1 = Boundpoint(Points[2])

##Do some tests
assert Points[3].x == 3
Points[3](x = 4)
assert e1.l.x == 4
e1.j(y = 5)
assert Points[1].y == 5
e1.k(x=7)
assert b1.b.x == 7
assert Points[2].x == 7
e1(i = Points[3])
b1(b = Points[3])
Points[3](x=-1,y=-1)
assert e1.i.x, e1.i.y == (-1 , -1)
assert b1.b.x, b1.b.y == (-1 , -1)


texts:
I am trying to write a simple program, from which the following can be achieved.

Button1_Click, the number on the Button is increased by 1.
The increased number is multiplied by the current value in TextBox
It does multiplication of the Button and TextBox
Display the result of Multiplication on the Label

Below is what I've done so far (added few lines for the above output).

static int i;
protected void Page_Load(object sender, EventArgs e)
{
    if(IsPostBack==false)
    {
        TextBox1.Text = "5";
        Label1.Text = "";
    }

}

protected void Button1_Click(object sender, EventArgs e)
{
    i++;
    Button1.Text = i.ToString();
    Label1.Text =Label1.Text+TextBox1.Text+" x "+Button1.Text+" = "+(Convert.ToInt32(TextBox1.Text) * Convert.ToInt32(Button1.Text)).ToString() + "
";
}

Output:

I didn't know until now that we can use HTML tags in ASP.NET. Therefore, using
 solved my issue.

My question is now, can I do this in more efficient way possible? What are other good practices I can learn?


texts: Rewriting to single pipeline by using data flow blocks

texts:
I have a number of messages with a payload as a list of items. My goal is to transform the message payload without losing the relation between the message and payloads.

Isn't it possible to rewrite the code to a single pipeline without creating an instance of a nested pipeline for each message?

using System.Threading.Tasks.Dataflow;

public class Message<T>
{
    public int Id { get; set; }

    public IList<T> Items { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var rnd = new Random();

        var input = new TransformBlock<Message<int>, Message<string>>(x => Transform(x));

        var action = new ActionBlock<Message<string>>(
            x =>
            {
                Console.WriteLine("MSG #{0}", x.Id);

                foreach (var item in x.Items)
                {
                    Console.WriteLine("\t {0}", item);
                }
            });

        input.LinkTo(action, new DataflowLinkOptions { PropagateCompletion = true });

        for (var idx = 1; idx <= 3; idx++)
        {
            var msg = new Message<int> { Id = idx, Items = Enumerable.Range(0, rnd.Next(0, 10)).ToList() };
            input.Post(msg);
        }

        input.Complete();
        action.Completion.Wait();

        Console.WriteLine("Done");
        Console.ReadKey();
    }

    private static async Task<Message<string>> Transform(Message<int> input)
    {
        var linkOpts = new DataflowLinkOptions { PropagateCompletion = true };

        var itr = new TransformManyBlock<IList<int>, int>(x => x);
        var multiply = new TransformBlock<int, int>(x => x * 10);
        var convert = new TransformBlock<int, string>(x => "STR-" + x);

        itr.LinkTo(multiply, linkOpts);
        multiply.LinkTo(convert, linkOpts);

        var pipeline = DataflowBlock.Encapsulate(itr, convert);

        pipeline.Post(input.Items);
        pipeline.Complete();

        var buffer = new BufferBlock<string>();
        pipeline.LinkTo(buffer);

        await pipeline.Completion;

        IList<string> items;
        if (!buffer.TryReceiveAll(out items))
        {
            items = new List<string>();
        }

        return new Message<string> { Id = input.Id, Items = items };
    }
}


texts: Dynamic module import in a class hierarchy

texts:
I have two python libraries, let's call them lib and extended_lib, that provide a very similar public API. To be more specific, extended_lib enriches the API of lib with new features and functionality; it also modifies the behavior of some functions that are also provided in lib (e.g. get_version()).

I have a pair of classes LibWrapper and ExtendedLibWrapper, the latter being a sub-class of the former, that dynamically load the corresponding module and save its reference within an instance variable (i.e. self._lib).

I have a class Base that inherits from LibWrapper and a class Derived that inherits from both Base and ExtendedLibWrapper. The class Base exposes the functionalities provided by lib. The class Derived inherits all these functions and exposes also the functionalities provided by extended_lib.

This setup is meant to allow Derived to inherit, without code duplication, the functionality provided by Base.

I designed the LibWrapper and ExtendedLibWrapper as an independent hierarchy of classes because there are multiple Base/Derived pairs.

Example:

#!/usr/bin/env python3

import importlib

class LibWrapper():
    def __init__(self, *args, **kwargs):
        self._lib = self.get_lib()

    def get_lib(self):
        return importlib.import_module("lib")

class ExtendedLibWrapper(LibWrapper):

    def __init__(self, *args, **kwargs):
        super(ExtendedLibWrapper, self).__init__(*args, **kwargs)

    def get_lib(self):
        return importlib.import_module("extended_lib")

class Base(LibWrapper):
    def __init__(self, *args, **kwargs):
        super(Base, self).__init__(*args, **kwargs)

    def get_version(self):
        return self._lib.get_version()

    def print_version(self):
        print("Base class:\n\t" + self.get_version())

class Derived(Base, ExtendedLibWrapper):

    def __init__(self, *args, **kwargs):
        super(Derived, self).__init__(*args, **kwargs)

    def print_version(self):
        print("Derived class:\n\t" + self.get_version())

if __name__ == '__main__':

    base = Base()
    base.print_version()

    derived = Derived()
    derived.print_version()

The output is:

~$ ./test.py
Base class:
    Lib Version
Derived class:
    Extended Lib Version

Question(s):

coming from a different software development experience (c++), I would like to ask: is this pythonic?
is there a better, more robust or easily extensible, setup?


texts: Loop to extract json from dataframe and storing in a new dataframe

texts:
I have a dataframe (obtained from a csv saved from mysql) with several columns, and one of them consist of a string which is the representation of a json. The data looks like:

id   email_id     provider  raw_data       ts
1    aa@gmail.com    A      {'a':'A',   2019-23-08 00:00:00
                             'b':'B',
                             'c':'C'}

And what my desired output is:

email_id      a   b   c
aa@gmail.com  A   B   C

What I have coded so far is the following:

import pandas as pd
import ast

df = pd.read_csv('data.csv')
df1 = pd.DataFrame()

for i in range(len(df)):
    dict_1 = ast.literal_eval(df['raw_content'][i])
    df1 = df1.append(pd.Series(dict_1),ignore_index=True)

pd.concat([df['email_id'],df1])

This works but it has a very big problem: it is extremely low (it takes hours for 100k rows). How could I make this operation faster?


texts: Using PHP's password_hash and password_verify for a login function

texts:
This is my first time using password_hash and password_verify in PHP. Would this be the correct usage of password_hash and password_verify to log the user into the site? Is there anything I could do to make this function more secure?

/**
 * Initiates User Login
 * @param  mixed $data Post data
 * @return mixed Checks if the user wants to be remembered and runs the corresponding function ('loginRemember', 'loginNoRemember')
 */
public function initiateLogin ($data) {
    //Database Connection
    $db = Database::getInstance();

    //Defining values for query
    $username = trim($data['login_username']);

    //Grab password from database based on username
    $query = $db->getConnection()->prepare("SELECT password FROM `users` WHERE username = :username");
    $query->execute(array(
        ':username' => $username
    ));

    //Query Results
    $queryResults = $query->fetch(PDO::FETCH_ASSOC);

    //Check if the password is correct
    if(password_verify($data['login_password'], $queryResults['password'])) {
        if (isset($data['login_remember_me'])) {
            $this->loginRemember($data);
        } else {
            $this->loginNoRemember($data);
        }
    } else {
        echo "Invalid password";
    }
}


texts:
I've created a function in C to reverse a singly-linked list in place:

typedef struct n {
    int key;
    struct n* next;
} node;

node* inplaceReverse(node* head, int index) {
    if(!head || !head->next) {
        /* Indication of last node (or empty list). This will be recursively returned to become the new head pointer of the reveresed list. */
        return head;
    }else {
        /* Reverse the list after head and store its return in tmp. */
        node* newhead = inplaceReverse(head->next,index+1);
        /* Make the next node's next point to head. */
        head->next->next = head;
        /* If head was the first node, make its next NULL. */
        if(!index) head->next = NULL;
        return newhead;
    }
}

It works but one thing that bothered me is that I needed to create an additional argument for the actual function (int index). This is to indicate the original head of the list so I know which one to set to NULL after the reverse. It feels like there's an obvious and better way to do this but I'm not sure.

Other suggestions for optimization and improvements are also welcomed.


texts:
Just looking for an initial steer on my AngularJS implementation.

Background

Started work on a clients new site which uses a popular CMS as the backend and AngularJS has been chosen as the client side framework.

Functionality

Build a simple control that will manage alerts generated from the CMS.

If the alert has been accepted already, remove the alert.
If not, leave there and attach to the 'alertToggle' to save the
cookie when it's clicked and remove the html.

Note

To keep a clean separation between backend and front-end I am avoiding logic in the HTML like ng-click="toggle" and instead using my custom alertToggle directive to achieve this. Same thing with not using ng-class for toggling alert--active.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

angular.module('alert', ['ngCookies'])
    .controller('alertController', function ($scope, $cookieStore) {
        $scope.is_active = true;
        $scope.cookie_key = null;
        $scope.cookie_expiry = new Date(new Date().setYear(new Date().getFullYear() + 2));
        $scope.initalizeFromCookie = function () {
            if ($scope.cookie_key !== null &&
                    $cookieStore.get($scope.cookie_key)) {
                $scope.is_active = false;
            }
        };
        $scope.toggle = function (override) {
            var is_active = typeof override === 'boolean' ? override : !$scope.is_active;
            if (!is_active) {
                $scope.saveCookie();
            }
            return ($scope.is_active = is_active);
        };
        $scope.saveCookie = function () {
            if ($scope.cookie_key !== null) {
                $cookieStore.put($scope.cookie_key, true, { expires: $scope.cookie_expiry });
            }
        };
    })
 .directive('alert', function () {
        return {
            scope: true,
            controller: 'alertController',
            restrict: 'A',
            link: function ($scope, $element, attrs) {
                if ('id' in attrs && $scope.cookie_key === null) {
                    $scope.cookie_key = 'synergy.alert.' + attrs.id;
                    $scope.initalizeFromCookie();
                }
                if ($element.hasClass('alert--active')) {
                    $scope.toggle(true);
                }
                $scope.$watch('is_active', function (is_active) {
                    $element.toggleClass('alert--active', is_active);
                });
            }
        };
    })
    .directive('cookieAlert', function () {
        return {
            scope: true,
            controller: 'alertController',
            restrict: 'A',
            link: function ($scope, $element, attrs) {
                $scope.cookie_key = 'synergy.alert.cookie-usage';
                $scope.initalizeFromCookie();
            }
        };
    })
    .directive('alertToggle', function () {
        return {
            restrict: 'A',
            link: function ($scope, $element, attrs) {
                $element.on('click touchend', function (e) {
                    e.preventDefault();
                    $scope.$apply(function () {
                        $scope.toggle();
                    });
                });
            }
        };
    });