texts:
When it come to security I try to be to better as possible but I don't have the knowledge.

According to what I read on-line my following code should be good but I could use some of your comment/critic/fixes

Here is a simple class just to example how I would do a login.  Does it look secure enough?

class UserClass
{
private $dbCon = null;
public $Error = '';
public function __construct(PDO $dbCon)
{
    $this->dbCon = $dbCon;
}
public function login($Email,$Password,$RegisterCustomerSession = FALSE)
{
    $GetSalt = $this->dbCon->prepare('SELECT id,salt,hashPass FROM `customer` WHERE `email` = :Email');
    $GetSalt -> bindValue(':Email',$Email);
    $GetSalt -> execute();
    if($GetSalt -> rowCount() == 0)
    {
        $this->Error = "No customer is registered with that email";
        return false;
    }
    elseif($GetSalt->rowCount()>0)
    {
        $CustomerInfo = $GetSalt->fetch(PDO::FETCH_ASSOC);
        if(sha1($Password.$CustomerInfo['salt'])==$CustomerInfo['hashPass'])
        {
            if($RegisterCustomerSession)
                self::RegisterAllCustomerSession($CustomerInfo['id']);
            return true;
        }
        else
        {
            $this->Error = "Invalid Password";
            return false;
        }
    }
}
public function SetPassword($CustomerId,$Password)
{
    $Salt = self::CreateSalt(16);
    $HashPass = sha1($Password.$Salt);

    $SetPasswordAndSalt = $this->dbCon->prepare('UPDATE `customer` SET `hashPass` = :HashPass,`salt` = :Salt WHERE `id` = :CustomerId;');
    $SetPasswordAndSalt -> bindValue(':CustomerId',$CustomerId);
    $SetPasswordAndSalt -> bindValue(':Salt',$Salt);
    $SetPasswordAndSalt -> bindValue(':HashPass',$HashPass);
    try{
        $SetPasswordAndSalt ->execute();
        return true;
    }catch(PDOException $e){echo $e->getMessage(); return false; }

}
private function CreateSalt($HowLong = 16)
{
    $CharStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-=+_<>';
    $ReturnStr = '';
    for($i = 0;$i<$HowLong;$i++)
    {
        $ReturnStr .= $CharStr{mt_rand(0,77)};
    }
    return $ReturnStr;
}
private function RegisterAllCustomerSession($CustomerId)
{
    // some code.
}
}


texts:
This checks the intersection between a Ray and a Plane and between a Ray and a Quad (in 3D):

import Linear

data Ray a   = Ray {rayPos :: V3 a, rayDir :: V3 a}
data Plane a = Plane {planePos :: V3 a, planeNorm :: V3 a}
type Quad a  = V4 (V3 a)

hitPlane :: (Num a, Fractional a) => Ray a -> Plane a -> V3 a
hitPlane (Ray rPos rDir) (Plane pPos pNorm) = rPos + dot (pPos - rPos) pNorm / dot rDir pNorm *^ rDir

hitQuad :: (Ord a, Epsilon a, Num a, Floating a) => Ray a -> Quad a -> Maybe (V3 a)
hitQuad ray (quad@(V4 a b c d)) = if hitInsideQuad then Just hitPoint else Nothing
    where hitInsideQuad = insideQuad hitPoint quad
          planeNormal   = cross (b - a) (d - a)
          hitPoint      = hitPlane ray (Plane a planeNormal)

insideQuad :: (Num a, Ord a) => V3 a -> Quad a -> Bool
insideQuad pos (V4 a b c d) = all inside borders where
    borders      = [(a,b),(b,c),(c,d),(d,a)]
    inside (a,b) = dot (b - a) (pos - a) > 0

Please, analyze if:

(Most importantly) I'm using instances correctly (I'm suspect something is wrong with the amount of instances on the types).
My design of types is correct and linguistic.
My code is comprehensible.
If I did something stupid in general.


texts:
This is a class to hold an animation and be able to refer to different animations by titles, but it seems like calling draw(Graphics2D g) and update every frame, would, with this implementation, cause a big slowdown with all the list.get(Object obj) calls. Is this a big deal, and if so how should I change the implementation? Other comments on the code are very welcome.

package core.graphics;

import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AnimationSet {

    private int currentAnimation;

    private Map<String, Integer> namesToAnimation;
    private List<Animation> animations;

    public AnimationSet() {
        currentAnimation = 0;
        namesToAnimation = new HashMap<String, Integer>();
        animations = new ArrayList<Animation>();
    }
    public void addAnimation(String title, Animation animation){
        animations.add(animation);
        namesToAnimation.put(title, animations.size()-1);
    }
    public void goToAnimation(String title){
        currentAnimation = namesToAnimation.get(title);
    }
    public void removeAnimation(String title){
        animations.remove(namesToAnimation.get(title));
        namesToAnimation.remove(title);
    }
    public void draw(Graphics2D g, int x, int y){
        g.drawImage(animations.get(currentAnimation).getImage(), x, y, null);
    }
    public void update(){
        animations.get(currentAnimation).update();;
    }
}


texts:
I'm learning Python. I'm making a random animal generator, from 5 txt files. Each file is a list of words for respectively the specie of the animal, an adjective, an origin, and a bodypart with a color. Not all may appear in the description. I also wanted it to be arithmogrammatic. Here is my code, I know it can be improved, but how ?

import time
import random
z=5
nom=[line.strip() for line in open("ani_nom.txt").readlines()]
adj=[line.strip() for line in open("ani_adj.txt").readlines()]
ori=[line.strip() for line in open("ani_ori.txt").readlines()]
cor=[line.strip() for line in open("ani_cor.txt").readlines()]
cou=[line.strip() for line in open("ani_cou.txt").readlines()]

for w in range (120):
    z=random.randint(1,100)
    Inom=[x for x in nom if len (x) == z ]
    Iadj=[x for x in adj if len (x) == z ]
    Iori=[x for x in ori if len (x) == z ]
    Icor=[x for x in cor if len (x) == z-2 ]
    Icou=[x for x in cou if len (x) == z ]
    try:
            name = random.choice(Inom)
            adje = random.choice(Iadj)
            orig = random.choice(Iori)
            corp = random.choice(Icor)
            coul = random.choice(Icou)
    except IndexError :
        continue
    r = random.randint(1,5)
    print ""
    if r == 0:
        print name
    elif r == 1:
        print name
        print orig
    elif r == 2:
        print name
        print "a " + corp
        print coul
    elif r == 3:
        print name
        print adje
        print "a " + corp
        print coul
    elif r == 4:
        print name
        print orig
        print "a " + corp
        print coul
    elif r == 5:
        print name
        print adje
        print orig
        print "a " + corp
        print coul

The quite chaotic results look like this :

gecko
d'ete

merles
musque
d'Iran
a tete
Prasin

moucheron
d'Espagne

foulque
pelerin
d'hiver
a duvet
Abricot

crocodile
du Canada
a griffes
Malachite

sphecides
de bassan
a remiges
Framboise

okapi
a pic
Safre

gasteruption
constricteur
d'Angleterre
a couverture
Vert poireau

chardonneret
garde-boeufs
a couverture
Cafe au lait

vireos
a tete
Tomate

calligraphe
du Pakistan
a mandibule
Bleu marine

enrouleuses
de Finlande
a mandibule
Bleu canard

puceron
d'arbre
a joues
obscure

hemipteres
a criniere
Anthracite

perroquet
des tours
a remiges
Amethyste

roadrunner
porte-musc
a poitrine
Vert gazon

mamba
a pic
blanc

chaus
huppe
a pic
brune

serpent
de Bali
a duvet
Abricot

loriot
d'Inde

etoiledemer
flamboyante
de Brewster
a mandibule
Vert meleze

bronze
maçon
de mer
a aile
Soufre

hesperie
d'egypte

grande
d'Irak
a lore
Brique

belette
a duvet
Abricot

cochond'inde
d'Angleterre
a scapulaire
Vert prairie

moucheron
atricille
de Russie
a collier
Amethyste

salamandre
parenthese
a poitrine
Heliotrope

dendrocygne
de Birmanie
a mandibule
Bleu Persan

tephritides
a mandibule
Tourterelle

trichopteres
a scapulaire
Jaune canari

etc...

Feel free to comment, any help is appreciated !


texts: Deciding whether a list of sum types is homogeneous

texts:
I ran into a problem recently where I had to decide whether a set of sum types was homogeneous (all the same). In itself, this is a pretty simple problem. However, there were a few complicating factors:

There exists a type within the types (call it Id) that is ignored in the comparisons.
There exists a type (call it Mix) that immediately makes the set non-homogeneous, even if all the types are Mix.

The extension of this problem was, given a list of types, is there a single type that can be removed that will make the rest of the types homogeneous (excepting, of course, the Mix type).

For example, if we define our type as:

data Foo = Bar | Baz | Quux | Id | Mix deriving (Eq, Ord, Show)

then [Bar, Bar, Bar] is homogeneous, [Bar, Bar, Baz] would be homogeneous if Baz were removed. Further, [Bar, Bar, Id] is homogeneous, and [Mix, Mix, Mix] is not. Finally, [Bar, Bar, Mix] contains a Mix type, and hence would not be homogeneous even if this type were removed.

import Data.List as List
import Data.Map as Map

data Foo = Bar | Baz | Quux | Id | Mix deriving (Eq, Ord, Show)

-- Is a list of the above sum types homogeneous?
-- Note that Id is ignored in the comparisons, and Mix immediately
-- makes this False.
homogeneous :: [Foo] -> Bool
homogeneous [] = True
homogeneous [x] = if x == Mix then False else True
homogeneous (x:xs) = all isEqNotMix xs
    where isEqNotMix y = ((y == x || y == Id) && y /= Mix)

-- Find a type that would make the set homogeneous if it were removed.
-- Note that if we have an already homogeneous set, then removing the
-- single homoogeneous type from the list will leave it being homogenoeous.
-- The final part of the tuple returns whether it was a homogeneous list or not.
-- Note that in the case of no such type existing, the result is
-- (Mixed, Mixed, False).
homogeneousButOne :: [Foo] -> (Foo, Foo, Bool)
homogeneousButOne xs = case xs of
    [] -> (Id, Id, True)
    [x] -> (x, x, homogeneous [x])
    xs@(x:_) -> if homogeneous xs then (x, x, True)
                else (fst mixed, snd mixed, False)
        where mixed = mixedCase $ List.filter (/= Id) xs

-- Deal with the case where the list is not homogeneous in homogeneousButOne.
mixedCase :: [Foo] -> (Foo, Foo)
mixedCase xs
    | Mix `elem` keys        = (Mix, Mix)
    | Map.size fooMap == 2   = decideTwo fooMap
    | otherwise              = (Mix, Mix)
        where fooMap = List.foldl (\acc x -> Map.insertWith (+) x 1 acc) Map.empty xs
              keys = Map.keys fooMap
              single = Map.filter (== 1) fooMap
              multiple = Map.filter (> 1) fooMap
              firstKey = head . Map.keys
              secondKey = head . tail . Map.keys
               -- Only case where we may not have (Mix, Mix) is if there were
               -- only two types found, and neither of them was `Mix`.
              decideTwo mp = case Map.size single of
                               -- Both types exist > 1 times
                               0 -> (Mix, Mix)
                               -- One type exists once, it is the type that can be removed
                               1 -> (firstKey multiple , firstKey single)
                               -- Both types only exist once (e.g. [Bar, Baz])
                               2 -> (firstKey single, secondKey single)

Any improvements to this code are welcome (excepting the names of the sum types: I realise Foo, Bar, Baz and Quux aren't great, but in the original problem, the names were no more descriptive).


texts: Processing files retrieved through FTP in parallel

texts:
I am busy creating a file processor that needs to get some files from an Ftp client download the file and save the data into the database. I have a two part question.

How can i refactor the code to look a bit cleaner? Feels like the
    method ProcessFiles is doing a bit much. I can extract some of the
    methods but then i am just sitting with a lot of small methods and
    not really gaining anything.
What will be the best way the handle exceptions? I need to be able
to capture the file that caused an error.

Code Sample

public void Run()
        {
            var ftpFileManager = new FtpFileManager("ftp.someurl.net", "username", "password");
            var files = ftpFileManager.GetDirectory("somepath");

            try
            {
                ProcessFiles(files, ftpFileManager);
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.InnerExceptions)
                {
                    if (ex is ArgumentException)
                        Console.WriteLine(ex.Message);
                    else
                        throw ex;
                }
            }
        }

private void ProcessFiles(IEnumerable<FtpListItem> files, IFtpFileManager ftpFileManager)
        {
            var exceptions = new ConcurrentQueue<Exception>();
            files.AsParallel().ForAll(async _ =>
            {
                try
                {
                    var dataFileService = _container.GetExportedValue<IDataFileHandler>();
                    var progress = new ProgressReporter(_container.GetExportedValue<IDataFileHandler>());

                var attr = FtpFileAttributes.Parse(_.Name);
                attr.DateOfFile = _.Modified;
                var dataFileId = await dataFileService.AddAsync(attr);

                await progress.Report(Status.Started, dataFileId);

                var file = ftpFileManager.DownloadFile(_.FullName);
                var fileHandler = FileHandlerFactory.Create(attr.FileType, attr);
                var list = fileHandler.ProcessFile(file);

                var handler = CreateHandler(attr.FileType);
                await handler.AddAsync(list, dataFileId);

                var dataFile = await dataFileService.GetAsync(dataFileId);
                dataFile.EndDate = DateTime.Now;
                dataFile.TotalRecords = list.Count();
                await dataFileService.UpdateAsync(dataFile);

                await progress.Report(Status.Completed, dataFileId);
            }
            catch (Exception e)
            {
                exceptions.Enqueue(e);
            }
        });

        if (exceptions.Count > 0)
            throw new AggregateException(exceptions);
    }


texts: Define the scope of negation with the Dependency Parser of spaCy

texts:
Sentiment words behave very differently when under the semantic scope of negation. I want to use a slightly modified version of Das and Chen (2001) They detect words such as no, not, and never and then append a "neg"-suffix to every word appearing between a negation and a clause-level punctuation mark. This method is very static and I want to create something a little bit more dynamic with the help of dependency parsing from spaCy.

This is an example of a tweet that I will process:

RT @trader $AAPL 2012 is ooopen to Talk about patents with GOOG definitely not the treatment Samsung got heh someURL

See here the visualized dependency parser in action on my string.
I am able to identify not as negation modifier of got with the following:

negation_tokens = [tok for tok in doc if tok.dep_ == 'neg']

Next, I want define the scope of the negation:

negation_head_tokens = [token.head for token in negation_tokens]
for token in negation_head_tokens:
    end = token.i
    start = token.head.i + 1
    negated_tokens = doc[start:end]
    print(negated_tokens)
    #  ooopen to Talk about patents with GOOG definitely not the treatment Samsung

Now I have defined the scope, I want to add "not" to certain words conditional on their POS-tag:

list = ['ADJ', 'ADV', 'AUX', 'VERB']
for token in negated_tokens:
    for i in list:
        if token.pos_ == i:
           print('not'+token.text)
           # notooopen, notTalk, notdefinitely, notnot

Logically, I want to exclude notnot from the string.

Full script

import spacy

nlp = spacy.load("en_core_web_sm")

doc = nlp(u'RT @trader $AAPL 2012 is ooopen to Talk about patents with GOOG definitely not the treatment Samsung got heh someURL', disable=['ner'])
pos_list = ['ADJ', 'ADV', 'AUX', 'VERB']

def negation(doc):
    negation_tokens = [tok for tok in doc if tok.dep_ == 'neg']
    negation_cue = [token.text for token in negation_tokens]

    if not negation_tokens:   # no negation token(s) present in the string
        return doc
    else:
        negation_head_tokens = [token.head for token in negation_tokens]
        new_doc = []

        for token in negation_head_tokens:
            end = token.i
            start = token.head.i + 1
            negated_tokens = doc[start:end]
        for token in doc:
           if token.text not in negation_cue:
               if token in negated_tokens:
                  if token.pos_ in pos_list:
                     new_doc.append('not'+token.text)
                     continue
                  else:
                     pass
               new_doc.append(token.text)
        return new_doc

negated_doc = negation(doc)
print(negated_doc)

Output:

['RT', '@trader', '$', 'AAPL', '2012', 'is', 'notooopen', 'to', 'notTalk', 'about', 'patents', 'with', 'GOOG', 'notdefinitely', 'the', 'treatment', 'Samsung', 'got', 'heh', 'someURL']

Questions

Q1: Is it possible to use a direct route instead of the creating a list with

negation_cue = [token.text for token in negation_tokens]

and then check

if token.text not in negation_cue:

Q2: Is it maybe faster to remove the negation_cue token at the end of the script from the returned doc?

Q3 / Most important question: Do you see any speed-improvements in my script


texts: WordPress plugin for obfuscating a file URL

texts:
I'm making a WordPress plugin that obfuscates the real file URL and forces the download of one of this 3 types of URL:

Local: http://example.com/wp-content/custom/filename.zip
Dropbox: https://www.dropbox.com/s/DBOX-KEY/filename.zip?dl=1
Google Drive: https://docs.google.com/uc?export=download&id=GDOCS-KEY

The final URL that's provided to the user has a code which is checked against the database (http://example.com/private/?download_file=SITE-KEY). If correct, there are other checks in place and at the end the file is served through the script below with a read_file to the real URL:

$download_url = "LOCAL-GOOGLE-DROPBOX-URL";

@ob_end_clean(); //turn off output buffering to decrease cpu usage

// required for IE, otherwise Content-Disposition may be ignored
if ( ini_get( 'zlib.output_compression' ) ) ini_set( 'zlib.output_compression', 'Off' );

header( 'Content-Type: ' . $mime);
header( "Content-Disposition: attachment; filename=\"".$final_name."\";" );
header( "Content-Transfer-Encoding: binary" );
header( 'Accept-Ranges: bytes' );
header( "Cache-control: private" );
header( 'Pragma: private' );
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );

flush();
readfile( $download_url );

I'm inspecting the headers and response and there's no trace of the real URL.

Doubts:

Is this really a "secure" method?
Can the real URL be sniffed by other means?

For completeness, here are the inspection results for a Google Drive file:

Request URL:http://example.com/private/?download_file=1310819c43
Request Method:GET
Status Code:200 OK

Request Headers
  Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
  Accept-Encoding:gzip,deflate,sdch
  Accept-Language:en-US,en;q=0.8
  Connection:keep-alive
  Host:example.com
  User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1366.0

  Safari/537.22 FirePHP/4Chrome
        X-FirePHP-Version:0.0.6

Query String Parameters
  pvdn_file:1310819c43

Response Headers
  Accept-Ranges:bytes
  Access-Control-Allow-Origin:http://example.com
  Cache-control:private
  Connection:Keep-Alive
  Content-Disposition:attachment; filename="Test File";
  Content-Transfer-Encoding:binary
  Content-Type:image/png
  Date:Sun, 19 May 2013 17:50:00 GMT
  Expires:Mon, 26 Jul 1997 05:00:00 GMT
  Keep-Alive:timeout=5, max=100
  Pragma:private
  Server:Apache
  Transfer-Encoding:chunked
  X-Pingback:http://example.com/xmlrpc.php
  X-Powered-By:PHP/5.3.6


texts:
def merge_arrays(list1, list2):
  len_list1 = len(list1); len_list2 = len(list2)
  merge_len = len_list1 + len_list2
  merge_list = []

  l1_ptr = 0
  l2_ptr = 0
  # import pdb; pdb.set_trace()
  while(l1_ptr <= len_list1-1 and l2_ptr <= len_list2-1):

    if (list1[l1_ptr] <= list2[l2_ptr]):
      merge_list.append(list1[l1_ptr])
      l1_ptr += 1

    elif (list1[l1_ptr] > list2[l2_ptr]):
      merge_list.append(list2[l2_ptr])
      l2_ptr += 1

  if l1_ptr > len_list1-1: #list1 exhausted
    for item in list2[l2_ptr:]:
      merge_list.append(item)
  else:
    for item in list1[l1_ptr:]:
      merge_list.append(item)

  return merge_list

I am trying to merge sorted arrays in python. How can I improve this? Honestly it looks like I've written this in C and not in Python


texts: SpringBoot application to send notification via phone numbers on SMS

texts:
I'm using Spring boot - 2.3.3.RELEASE and gradle.
Note- I'm using Factory and Strategy pattern. This project is going to be used as a Library for other projects to import and use the methods exposed by Service layer.
Here is the folder structure: https://imgur.com/a/jYr7wyP
I would appreciate if the community can review this code and give suggestions to make it better.
Demo.class
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@SpringBootApplication
public class Demo {
    public static void main(String[] args) {
        SpringApplication.run(Demo.class, args);
    }
}

Init.java
@Component
public class InitClass implements ApplicationRunner {

    @Autowired
    PhoneService phoneService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String title="Title";
        String message="message";
        List<String> phoneNumbers = new ArrayList<>();
        phoneNumbers.add("333-222-1111");
        phoneService.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
    }
}

PhoneService.java
@Service
public class PhoneService {

    @Autowired
    PhoneServiceImpl notificationServiceImpl;

    public void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers) {
        notificationServiceImpl.sendNotificationByPhoneNumbers(title, message, phoneNumbers);
    }
}

PhoneServiceImpl.java
@Slf4j
@Component
public class PhoneServiceImpl {

    @Value("${notificationService.url}")
    String url;

    public void sendNotificationByPhoneNumbers(String title, String message, List<String> phoneNumbers) {
        PhoneContext phoneContext = new PhoneContext(new SendPhoneByPhoneNumbers(url));
        phoneContext.notify(title, message, phoneNumbers);
    }
}

PhoneContext.java
public class PhoneContext {

    private PhoneStrategy phoneStrategy;

    public PhoneContext(PhoneStrategy phoneStrategy){
        this.phoneStrategy = phoneStrategy;
    }

    public void notify(String title, String message, List<String> employees){
        phoneStrategy.sendNotification(title, message, employees);
    }
}

PhoneStrategy.java
public interface PhoneStrategy {

   public void sendNotification(String title, String message, List<String> listOfEmployeeIdGroupNamePhoneNumbers);
}

SendPhoneByPhoneNumbers.java
@Slf4j
public class SendPhoneByPhoneNumbers implements PhoneStrategy {

    RestTemplate restTemplate;
    String notificationServiceURL;
    BuildHttpRequest buildHttpRequest;

    public SendPhoneByPhoneNumbers(String notificationServiceURL) {
        this.notificationServiceURL = notificationServiceURL;
        this.restTemplate = new RestTemplate();
        this.buildHttpRequest = new BuildHttpRequest();
    }

    @Async
    public void sendNotification(String title, String message, List<String> listOfEmployeeIdGroupNamePhoneNumbers) {
        SmsMessage smsMessage= new SmsMessage(title, message, listOfEmployeeIdGroupNamePhoneNumbers, Collections.emptyList(), Collections.emptyList());

        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("idToken", buildHttpRequest.getNewToken());

            HttpEntity<SmsMessage> newRequest = new HttpEntity<>(smsMessage, headers);
            restTemplate.postForObject(notificationServiceURL + "/sms/custom", newRequest, String.class);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}


texts: Removes course objects from the course list

texts:
I have implemented those two methods described as in 1 and 2.
I appreciate any kind of review to improve my method implementation.

  Implement the method toString.
  toString returns a string representation of the list
  Implement the method remove .
  remove removes a given course from the list.
  If the course is not in the list, the list is not updated.

  When the code is executed, the following printout is generated:

  <10, Algebra>

  <20, Algorithms>

  <30, Electronics>

  <40, Physics>

  <50, Programming>

  After the implemented methods call.

  <10, Algebra>

  <20, Algorithms>

  <50, Programming>

public class CourseList {

    private static final int CAPACITY = 5;
    // courses
    private Course[] courses;
    // the number of courses
    private int courseCount;

    public CourseList() {
        courses = new Course[CAPACITY];
        courseCount = 0;
    }

    // add adds a course to the list
    public void add(Course course) {
        courses[courseCount] = course;
        courseCount++;
    }
    public void remove (Course course) {
        int courseIndex = -1;
        for (int i = 1; i < courseCount; i++)
            if (courses[i].equals(course)) {
                courseIndex = i;
                break;
            }
        if (courseIndex != -1) {
            for (int i = courseIndex; i < courseCount - 1; i++)
                courses[i] = courses[i + 1];
            courses[courseCount - 1] = null;
        }
    }

    public String toString(){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i< courses.length; i++){
            sb.append(courses[i]);
            sb.append("\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        CourseList list = new CourseList();
        list.add(new Course(10, "Algebra"));
        list.add(new Course(20, "Algorithms"));
        list.add(new Course(30, "Electronics"));
        list.add(new Course(40, "Physics"));
        list.add(new Course(50, "Programming"));
        System.out.println(list);
        list.remove(new Course(40, "Physics"));
        list.remove(new Course(30, "Electronics"));
        System.out.println(list);

    }
}


texts: Public property, backing up by a private field, with caching and null checking inside

texts:
I have a private field called individualProfile (camelCase) and I've created a public property called IndividualProfile (PascalCase) on it:

private Profile individualProfile;
public Profile IndividualProfile
{
    get
    {
        if (individualProfile == null)
        {
            individualProfile = ProfileFacade.Instance.GetMainProfileByType
                                (
                                    PortalContext.CurrentUserId,
                                    ProfileType.IrnicIndividual
                                );
            if (individualProfile == null)
            {
                individualProfile = new Profile()
                {
                    FirstName = string.Empty,
                    Family = string.Empty,
                    Details = new IrnicIndividual()
                    {
                        NationalCode = string.Empty
                    }
                };
            }
        }
        return individualProfile;
    }
}

I have to use this public property in almost 10 places, so I first check the private member to see if it's null and load it only once, so that I load it only once and I cache it and use it 10 times. Also, since GetMainProfileByType can return null value, I check another time to see if the private member is null or not. If it's null, I simply set it to an empty object, so that I won't bother checking null values when I bind this object to my view.

Is this code efficient and maintainable? Is there anything I've overlooked?


texts:
As part of an exercise I've written some code to generate multiple HTML files based on information stored in a couple of XML files. I'm not really sure how much code you'd need to evaluate my function so this is most of the relevant code regarding the actual HTML from XML generation:

  # search taxonomy.xml for nodes with the attribute 'atlas_node_id'
  # to get a NodeSet of all the destinations
  destinations = tax_file.css('[atlas_node_id]')

  # cd to directory you want to create the files in
  FileUtils.cd(directory)

  destinations.each do |destination|
    # temp variable to make code easier to read later on
    id = destination.attribute('atlas_node_id').value

    html = Nokogiri::HTML::Builder.new do |doc|
      doc.html{
        doc.head{
          doc.title destination.children[1].content
          doc.link(rel: 'stylesheet', href: "all.css")
        }

        doc.body{
          doc.h1{
            doc.text destination.children[1].content
          }

          # check if there is a destination higher in the taxonomy and display
          # the relevant link if so.
          if !(destination.parent.attribute('atlas_node_id').nil?)
            file = destination.parent.children[1].content + ".html"
            doc.a(:href => file){
              doc.text destination.parent.children[1].content
            }
          end

          # I chose to show the overview content since this exists for every
          # destination
          doc.p{
            node = dest_file.xpath("//destination[@atlas_id = #{id}]").first
            doc.text node.xpath(".//introductory/introduction/overview").text unless
            node.nil?
          }
        }
      }
    end

    # write file using destination name as filename
    filename = destination.children[1].content + ".html"
    directory << File.open(filename,'w').write(html.to_html)
  end

At the moment the XML files in questions are small (there are only 24 destinations in total) so everything works without problems. How can I refactor this to make if more performant for situations where there are many thousands of destinations?


texts: Thread-safe arraylist with get, put, add, remove functions

texts:
I am preparing for multithreading interview questions and I don't have much experience with multithreading. I referred some online article to come up with a solution. Is this solution appropriate?

public class ThreadSafeArrayList<E> {
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final Lock readLock = readWriteLock.readLock();
    private final Lock writeLock = readWriteLock.writeLock();
    private final List<E> list = new ArrayList<>();
    public void set(E o) {
        writeLock.lock();
        try {
            list.add(o);
        } finally {
            writeLock.unlock();
        }
    }

    public E get(int i) {
        readLock.lock();
        try {
            return list.get(i);
        } finally {
            readLock.unlock();
        }
    }

    public void add(E num) {
        List<E> sync = Collections.synchronizedList(list);
        sync.add(num);
    }

    public E remove(int i) {
        List<E> sync = Collections.synchronizedList(list);
        if (sync.isEmpty()) return null;
        return sync.remove(i);
    }
}


texts:
I created a function that filters data and I want to know if it's fully secure to filter user input data.

function user_input_data($data,$options) {
    $output = null;
    $error_msg = "";
    $check_length = false;
    $options_fetch = array(
    @$length_max = $options["length_max"],
    @$length_min = $options["length_min"],
    $data_type = $options["data_type"],
    );

    if($length_min && $length_max) {
        $check_length = true;
    }

    if($data_type == "only_letters") {

        if (preg_match('/^[\p{Arabic}a-zA-Z]+\h?[\p{Arabic}a-zA-Z]*$/u', $data)) {
             $output = $data;
        }else{
            $output = false;
        }
    }

    if($data_type == "only_letters_numbers") {

        if (preg_match('/^[\p{Arabic}a-zA-Z0-9]+\h?[\p{Arabic}a-zA-Z0-9]*$/u', $data)) {
            $output = $data;
        }else{
            $output = false;
        }
    }

    if($data_type == "string") {
        $output = htmlspecialchars($data,ENT_QUOTES,"UTF-8",true);
    }
    if($data_type == "text") {
        $output = strip_tags($data);
    }
    if($data_type == "integer") {
        if(filter_var($data,FILTER_VALIDATE_INT)) {
            $output = $data;
        }
    }
    if($data_type == "float") {
        if(filter_var($data,FILTER_VALIDATE_FLOAT)) {
            $output = $data;
        }
    }
    if($data_type == "boolean") {
        if(filter_var($data,FILTER_VALIDATE_BOOLEAN)) {
            $output = $data;
        }
    }
    if($data_type == "email") {
        if(filter_var($data,FILTER_VALIDATE_EMAIL)) {
            $output = $data;
        }
    }
    if($data_type == "url") {
        if(filter_var($data,FILTER_VALIDATE_URL)) {
            $output = $data;
        }
    }
    if($data_type == "ip") {
        if(filter_var($data,FILTER_VALIDATE_IP)) {
            $output = $data;
        }
    }
    if($data_type == "array") {
        if(is_array($data)) {
            $data = array_map("htmlspecialchars",$data);
            $output = $data;
        }
    }
    if($data_type == "file_directory") {
        if(file_exists($data)) {
            $output = basename($data);
        }
    }
    if($output) {

    if($check_length) {

        if( ( ( mb_strlen($output) >= $length_min ) && ( mb_strlen($output) <= $length_max ) ) === false) {
            $output = false;
        }
    }
    return $output;

    }
}

// call function
$password = user_input_data(
    $_POST["password"],
    array(
        "length_min" => 8, "length_max" => 24 ,"data_type" => "string"
    )
);


texts:
Below is a pretty simple Python script to ingest some data, massage it as necessary, append a column, sort it, and then write it back to another file.  Still learning all the Python best practices and APIs, so as always, any tips and tricks are appreciated!  Feel free to be brutal with me if it's horrible.  It's my first time trying any kind of object-orientation with the language as well, so I have no idea if I'm massacring that or not.

from collections import OrderedDict
import sys

class SkuSequence:
    def __init__(self, iln, ili, sn, psn, ssd, ssc, idc):
        self.inv_loc_nm = iln.strip()
        self.inv_loc_id = ili
        self.sku_nbr = sn
        self.prt_seq_nbr = psn
        self.sign_sz_desc = ssd
        self.sign_sz_cd = ssc
        self.inv_disp_cd = idc.strip()
        self.mod_seq_nbr = "null"

    def get_str_attrs(self):
        attrs = []
        attrs.append(str(self.inv_loc_nm))
        attrs.append(str(self.inv_loc_id))
        attrs.append(str(self.sku_nbr))
        attrs.append(str(self.prt_seq_nbr))
        attrs.append(str(self.sign_sz_desc))
        attrs.append(str(self.sign_sz_cd))
        attrs.append(str(self.inv_disp_cd))
        attrs.append(str(self.mod_seq_nbr))
        return attrs

def sort_sequence(sequence):
    dict = {}
    for sku in sequence:
        if sku.inv_loc_id not in dict:
            dict[sku.inv_loc_id] = {}
        dict[sku.inv_loc_id][sku.prt_seq_nbr] = sku
    for bay in dict:
        dict[bay] = OrderedDict(sorted(dict[bay].items()))
    return OrderedDict(sorted(dict.items()))

def convert_to_csv(header, data):
    rows = []
    if header is not None:
        rows.append(",".join(header.get_str_attrs()))
    for bay, sequence_data in data.items():
        seq_nbr = 0
        for sku in sequence_data.values():
            if int(sku.inv_disp_cd) == 5:
                sku.mod_seq_nbr = "null"
            else:
                seq_nbr += 1
                sku.mod_seq_nbr = seq_nbr
            rows.append(",".join(sku.get_str_attrs()))
    return rows

def consume_data(filename):
    lines = []
    skus = []
    with open(filename) as csv:
        lines = csv.readlines()
    for line in lines:
        attrs = line.split(",")
        skus.append(SkuSequence(attrs[0], attrs[1], attrs[2], attrs[3], attrs[4], attrs[5], attrs[6]))
    return skus

def write_file(lines):
    filename = sys.argv[1]
    file_parts = filename.split(".")
    file_parts[0] += "_resequence"
    filename = ".".join(file_parts)
    with open(filename, "a") as file:
        for line in lines:
            file.write(line + "\n")

def main():
    if len(sys.argv) < 2:
        print("You must provide an input filename as an argument.")
        sys.exit(128)
    data = consume_data(sys.argv[1])
    header = data.pop(0)
    header.mod_seq_nbr = "mod_seq_nbr"
    sorted = sort_sequence(data)
    write_file(convert_to_csv(header, sorted))

if __name__ == "__main__":
    main()


texts: Finding the difference between two different arrays using JS and FP

texts:
I'm trying to practice functional programing using JavaScript. These pure functions just work together to find the difference between two arrays. I know that this might be an impractical example of functional programing, but could you let me know where I can improve or maybe where I've misunderstood an FP technique?

"use strict";

let find = (arr1) => (arr2) => {
  let diff1 = findDiff(arr1)(arr2);
  let diff2 = findDiff(arr2)(arr1);

  return concat(diff1)(diff2);
};

let concat = (arr1) => (arr2) => arr1.concat(arr2);
let findDiff = (arr1) => (arr2) => arr1.filter( (elem) => arr2.indexOf(elem) < 0 );

let sweet = find( [1,2,3,4,5] )( [1,2,3,5,6] );
console.log(sweet);


texts: Asp.net web API Nlog implementation with UnhandledExceptionHandler

texts:
I have an asp.net web api. I would like to log errors into a file. So I decided to use NLog. I already have UnhandledExceptionHandler so I added NLog as follows. I removed all the try/catch in order to log from a single point, just inside the handler.

Would you please have a look at my code? Is it good enough?

using System;
namespace Game.Handlers
{
    public class UnhandledExceptionLogger : ExceptionLogger
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public override void Log(ExceptionLoggerContext context)
        {
            var ex = context.Exception;

            string strLogText = FormatException(ex);

            var requestedURi = (string)context.Request.RequestUri.AbsoluteUri;
            var requestMethod = context.Request.Method.ToString();
            var timeUtc = DateTime.Now;

            SqlErrorLogging sqlErrorLogging = new SqlErrorLogging();
            ApiError apiError = new ApiError()
            {
                Message = strLogText,
                RequestUri = requestedURi,
                RequestMethod = requestMethod,
                TimeUtc = DateTime.Now
            };
            //sqlErrorLogging.InsertErrorLog(apiError);
            //NLOG
            logger.Error(strLogText + Environment.NewLine + DateTime.Now);
        }

        private string FormatException(Exception ex, int depth = 0)
        {
            var indent = "";
            if (depth > 0)
                indent.PadRight(depth * 4);

            var sb = new StringBuilder();
            IndentLine($"Source --- {ex.Source}");
            IndentLine($"StackTrace --- {ex.StackTrace}");
            IndentLine($"TargetSite --- {ex.TargetSite}");

            if (ex.InnerException != null)
            {
                IndentLine("--- Inner Exception ---");
                sb.Append(FormatException(ex.InnerException, depth + 1));
                IndentLine("--- End Inner Exception ---");
            }
            if (ex.Message != null)
            {
                IndentLine($"Message --- {ex.Message}");
            }
            return sb.ToString();

            void IndentLine(string s)
            {
                sb.Append(indent);
                sb.AppendLine(s);
            }
        }

    }
}

Here is the sample NLog config:

<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" />
      <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" GamePIN Api Services" />
      <target name="database" type="Database" connectionString="Data Source=(localdb)\MSSQLLocalDB;Database=Game; Initial Catalog=GameAPI;MultipleActiveResultSets=True;">
        <commandText> insert into ExceptionLog ([TimeStamp],[Level],Logger, [Message], UserId, Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message, case when len(@UserID) = 0 then null else @UserId end, @Exception, @StackTrace); </commandText>
        <parameter name="@TimeStamp" layout="${date}" />
        <parameter name="@Level" layout="${level}" />
        <parameter name="@Logger" layout="${logger}" />
        <parameter name="@Message" layout="${message}" />
        <parameter name="@UserId" layout="${mdc:user_id}" />
        <parameter name="@Exception" layout="${exception}" />
        <parameter name="@StackTrace" layout="${stacktrace}" />
        <dbProvider>System.Data.SqlClient</dbProvider>
      </target>
    </targets>
    <rules>
      <!-- I am adding my 3 logging rules here -->
      <logger name="*" minlevel="Error" writeTo="database" />
      <logger name="*" minlevel="Error" writeTo="logfile" />
      <logger name="*" minlevel="Error" writeTo="eventlog" />
    </rules>
  </nlog>


texts:
This is more to get clarity on an implementation that I did. I am working on a React, Node, and Electron application that essentially has a form that a user inputs values that will update some content files.

The application has to scale for a lot of different scenarios so I found that I kept writing switch statements to incorporate all of these scenarios. So for the sake of time I wrote a class that:

Takes in two arrays, An array of keys and array of functions that correspond to those keys.
The constructor function creates a table for the values
Then there is a method on the class that allows you to look up that value and returns it

here is the code

Array.prototype.createObjectFromKeysandValues = function(array) {
    let table = {}
    for(let pointer=0;pointer<this.length;pointer++){
        let key = this[pointer]
        let value = array[pointer]
        table[key]=value
    }
    return table
}

  module.exports = class KeyFunctionMappingTable {
      constructor(keys, values){
        this.lookUpTable = Object.assign({},
         keys.createObjectFromKeysandValues(values),
         { default: () =>  new Error("Value Not Found")})
         }

     findHandlerFunction(value){
        return this.lookUpTable[value]|| this.lookUpTable.default
     }
   }

So when the code is implemented it looks like this ( this scenario is for React Components) :

const factory = new KeyFunctionMappingTable(['select', 'input'], [
    (options, labelText) => ( <Select options={options} labelText={labelText} />),
    (options, labelText) => ( <Input labelText={labelText} />)])

I am finding that I have about three of these "mappings" throughout the code.

What I want to know is if this seems like a readable implementation and does this make sense to strangers. If you dont think so please let me know your suggestion.


texts: How to optimize code to only pull separate table rows that are necessary

texts:
I have a Company Class, and separate normalized Address Class. I did this because the Address table will hold more than just Company Addresses, so I don't want "CompanyAddress", "EmployeeAddress", "MiscAddress" tables. The Address table will also hold historical addresses, which would only need to be seen on the Edit and Detail Views.

I am able to return my Company Address along with the Company View by calling "ToList()" on the _context.Address table, but that will load all addresses, most of which are not necessary for this View.

This code works, and will display correctly in the View - however note that it is calling "ToList" on the entire Address table.

//This returns the address
public async Task<IActionResult> Index()
{
    var x = await _context.Address.ToListAsync();
    return View(await _context.CompanyViewModel.ToListAsync());
}

The below examples do not work. The Address returns null.

public async Task<IActionResult> Index()
{
    return View(await _context.CompanyViewModel.ToListAsync());
}

and

var y = from c in _context.CompanyViewModel
        join a in _context.Address on c.CurrentAddress.ID equals a.ID
        select c;

The classes are fairly standard. I have left out a lot of the "meat" to make the code review as simple as possible - the other properties do not impact the review, as this issue is only with the Address property.

Classes:

public class CompanyViewModel
{
    public int ID { get; set; }
    public string CompanyName { get; set; }
    public Address CurrentAddress { get; set; }
}

public class Address
{
    public int ID { get; set; }
    public string Address1 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

Calling ToList on the entire Address table does work, but is very inefficient. The View displays properly, but every time the page is loaded, it will materialize the entire Address table, which is much more work than is required for the Index View.

What is the right way with EF/MVC to only materialize the addresses that exist for the current context?

This is the best solution I can come up with right now. I have no idea if this is a best practice, but this seems to do the trick. Again though, I'm throwing darts blindfolded here. If someone knows a better way, my eyes and ears are open.

var companies = await _context.CompanyViewModel.ToListAsync();
var ret = from c in companies
          join a in _context.Address on c.CurrentAddress.ID equals a.ID
          select c;
return View(ret);


texts: Detecting a certain amount of violet in an image

texts:
I need to be able to detect if an image has the colour Violet in it. (Follow-up)

The problem that I'm facing is that there are quite a number of shades of violet that it seems almost impossible it add every single one.

 private void ProcessImage(PictureBox picture)
    {
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            List<Color> ColoursToDetect = new List<Color>()
            {
                Color.FromArgb(202,156,254),
                Color.FromArgb(143,125,151),
                Color.FromArgb(100,76,136),
                Color.FromArgb(232,175,254)
            };
            Boolean colour_Found = false;
            Bitmap SelectedImage = new Bitmap(picture.Image);
            Color selected_Pixel;

            for (int x = 0; x != SelectedImage.Width; x++)
            {
                for (int y = 0; y != SelectedImage.Height; y++)
                {
                    selected_Pixel = SelectedImage.GetPixel(x, y);
                    foreach (Color c in ColoursToDetect)
                    {
                        if (c == selected_Pixel)
                        {
                            colour_Found = true;
                            MessageBox.Show("Found");
                            colour_Found = true;
                        }
                    }
                    if (colour_Found)
                    {
                        break;
                    }
                }
            }
        }
    }

The above code is working (So to speak) However I'm worried that one day an image will have a certain violet that i have no added and in hindsight will make the code useless.I did look at the .Net library AForge http://www.aforgenet.com/projects/iplab/, However I couldn't find any information about detecting a range of a certain colour.


texts: Displaying information about an order when selection changes

texts:
I feel like just because the below works doesn't mean it is correct, I want to improve it but I can't really figure out how. Besides the fact it is down right ugly I feel the performance could be increased a lot also.
Am I even using the Entity Framework and/or LINQ the way it is supposed to be used?
So I have these classes:
[Table("OrderInfo")]
public class OrderInfo
{
    public long ID {get; set;}
    public long OrderID {get; set;}
    public virtual Order Order { get; set; }
    public long ItemID {get; set;}
    public double Qty { get; set; }
    public virtual Item Item { get; set; }
}

[Table("Items")]
public class Item
{

    public Item()
    {
        this.Orders = new List<OrderInfo>();
    }
    #region Strings
    public string Color { get; set; }
    public string FullName { get; set; }
    [Column(@"Sheet/Roll")]
    public string Type { get; set; }
    public string PrimaryMachine { get; set; }
    public string Alias { get; set; }
    public string Brand { get; set; }

    #endregion

    #region Long
    public long ID { get; set; }
    public long? Weight { get; set; }
    #endregion

    #region Doubles
    public double? Size1 { get; set; }
    public double? Size2 { get; set; }
    public double? Size3 { get; set; }
    #endregion.

    public virtual ICollection<OrderInfo> Orders { get; set; }
}

below is the code calling the data:
    private void dgvOrders_SelectionChanged(object sender, EventArgs e)
    {
        DataGridView dgv = (DataGridView)sender;

        if (dgv.SelectedRows.Count > 0)
        {
            if (dgvOrderItems.DataSource != null)
                dgvOrderItems.DataSource = null;

            int ID = Convert.ToInt32(dgv["ID", dgv.SelectedRows[0].Index].Value);
            List<OrderInfo> OrderInfo = new List<OrderInfo>();
            OrderInfo = c.OrderInfo.Include("Item").Where(x => x.OrderID == ID).ToList();

             if(OrderInfo.Count <= 0)
             {
                MessageBox.Show("No Info Found For This Order!");
                ClearForm();
                return;
             }

            lblPO.Text = "P.O. # " + OrderInfo[0].ID.ToString();
            lblRequestedBy.Text = "Requested By: " + OrderInfo[0].Order.RequestedBy;
            lblOrderDate.Text = "Ordered On: " + OrderInfo[0].Order.Date.ToShortDateString();

            dgvOrderItems.DataSource = OrderInfo.Select(x => new { x.ItemID, x.Qty, x.Item.FullName, x.Item.Brand, x.Item.Color }).ToList();
        }
    }


texts: Process list of e-mail addresses in PHP 5.3

texts:
Part of an application that I am building in CakePHP 2.1 needs to send out an e-mail based on a template from a database. The end user is able to set the from, reply to, to, cc, and bcc addresses. Because the user could enter just about anything, I need to process those addresses into a usable array that I can pass to CakeEmail. To this end, I wrote the following code and I want to make sure that it is efficient before I put it into production use (and possibly write a tutorial about it).

<?php
$parseAddress = function(&$address) {
    preg_match_all('/"(.*?)"\s*\<(.*?)\>/', $address, $matches); // Check if $address is in the format ""Test Address" <test@example.com>". TODO: Make the quotes optional.

    if (!is_array($matches) || !isset($matches[1]) || empty($matches[1]) || !isset($matches[2]) || empty($matches[2]) || is_null(array_filter($matches))) {
        return $address; // Return the plain e-mail address if name is not provided
    }

    $parsedAddress = array();

    for ($i = 0; $i < count($matches[0]); $i++) {
        $parsedAddress[$matches[2][$i]] = $matches[1][$i]; // Add e-mail address to array as "email => name"
    }

    $addressCSV = str_getcsv($address); // Split e-mail addresses into array - seems to automatically strip anything between "<" and ">" characters
    foreach($addressCSV as $key => $val) {
        if (!filter_var($val, FILTER_VALIDATE_EMAIL)) { // Take advantage of afformentioned stripping by filtering out everything that is not an e-mail address
            unset($addressCSV[$key]); // Remove the array value that is not an e-mail address
        }
    }

    return array_merge($addressCSV, $parsedAddress); // Join the parsed e-mail addresses with the filtered addresses and return the resulting array
};

echo $parseAddress('test@address.tld'); // returns (string) "test@address.tld"
echo $parseAddress('"Test Address" <test@example.com>, test@address.tld, "Smith, John"<jsmith@example.com>'); // returns (array) [0 => "test@address.tld", "test@example.com" => "Test Address", "jsmith@example.com" => "Smith, John"]


texts:
I'm given a hexadecimal number in string form with a leading "0x" that may contain 1-8 digits, but I need to pad the number with zeros so that it always has 8 digits (10 characters including the "0x").

For example:

"0x123" should become "0x00000123".
"0xABCD12" should become "0x00ABCD12".
"0x12345678" should be unchanged.

I am guaranteed to never see more than 8 digits, so this case does not need to be handled.

Right now, I have this coded as:

padded = '0x' + '0' * (10 - len(mystring)) + mystring[2:]

It works, but feels ugly and unpythonic.  Any suggestions for a cleaner method?


texts: Read a txt file and split into 2 csvs based on regex

texts:
So I have been told that my code is not good and needs refactoring. I'm struggling to see what I need to do. How do I specify the success and failure conditions for lambda? Also don't get what the method process_lines should contain. Any help is greatly appreciated!
These are the comments I was given:

Let's create a function (process _lines) that accepts 2 lambda functions (success, failure). The success will accept the function pointer that will write to good csv file, while failure to the bad csv file.
Something like:
def process_lines(success, failure):
...
def write_to_csv(csv_file):
...
process_lines(lambda: write_to_csv(good_csv), lambda: write_to_csv(bad_csv))

Currently this is my code:
import re
import csv

pattern = re.compile("([0-9]+) +([0-9\.-]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+) +([0-9\.\-+Ee]+)")

good_csv = []
bad_csv = []
fname = "track_param_hist.txt"
good_csv_fname = "good_hist_csv.csv"
bad_csv_fname = "bad_hist_csv.csv"

class ConvertTxtToCsvs:
  def process(self):
    print("Script for splitting text file into two separate csvs...")
    # read in the text file and store the lines as a list
    with open(fname) as f:
      lines = f.readlines()

    # split the lines into good and bad
    for line in lines:
      good_csv.append(line) if pattern.match(line) else bad_csv.append(line)

    # create the csv for bad data
    with open(bad_csv_fname, 'w') as myfile:
      wr = csv.writer(myfile)
      for line in bad_csv:
        row = (' '.join(line.split())).split(' ')
        wr.writerow(row)
    print("Csv for the bad data has been created successfully")

    # create the csv for good data
    with open(good_csv_fname, 'w') as myfile:
      wr = csv.writer(myfile)
      for line in good_csv:
        row = (' '.join(line.split())).split(' ')
        wr.writerow(row)
    print("Csv for the good data has been created successfully")

# This can also be run as regular python script
if __name__ == "__main__":
  ConvertTxtToCsvs().process()


texts: Database abstraction class in C# (version 2)

texts:
Below is my revised version of this code after I acted on the suggestions:

Database abstraction class in C#

class DatabaseAccess : IDisposable
{
    private SqlConnection connection;
    private SqlCommand alreadyDownloadedCommand;
    private SqlCommand markedDownloadedCommand;
    // *FieldSize variables match the size of the field in the database.
    private const int FileNameFieldSize = 80;
    private const int AppTypeFieldSize = 2;
    private const int UserNameFieldSize = 8;

    public DatabaseAccess(string dbconnectionstring)
    {
        connection = new SqlConnection(dbconnectionstring);

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

    public void Dispose()
    {
        alreadyDownloadedCommand.Dispose();
        markedDownloadedCommand.Dispose();
        connection.Dispose();
    }
    private void ValidateFieldSize(string fielddata, int fieldsize)
    {
        if (fielddata.Length > fieldsize)
        {
            throw new ArgumentOutOfRangeException("Parameter size too large");
        }
    }
    private SqlCommand getMarkedDownloadedCommand(SqlConnection connection)
    {
        const string sql =
        @"insert into dbo.InspectionsDownloaded(FileName)
          values (@FileName)
        ";
        SqlCommand command = new SqlCommand(sql, connection);
        command.Parameters.Add(new SqlParameter("@FileName", System.Data.SqlDbType.VarChar, FileNameFieldSize));
        command.Prepare();
        return command;
    }

    private SqlCommand getAlreadyDownloadedCommand(SqlConnection connection)
    {
        const string sql =
        @"select count(*) as numDownloaded
            from dbo.InspectionsDownloaded id
           where id.FileName = @FileName
        ";
        SqlCommand command = new SqlCommand(sql, connection);
        command.Parameters.Add(new SqlParameter("@FileName", System.Data.SqlDbType.VarChar, FileNameFieldSize));
        command.Prepare();
        return command;
    }
    public bool IsAlreadyDownloaded(string filename)
    {
        int rowCount;
        ValidateFieldSize(filename, FileNameFieldSize);
        alreadyDownloadedCommand.Parameters[0].Value = filename;
        rowCount = (Int32)alreadyDownloadedCommand.ExecuteScalar();
        return (rowCount != 0);
    }
    public int MarkDownloaded(string filename)
    {
        ValidateFieldSize(filename, FileNameFieldSize);
        markedDownloadedCommand.Parameters[0].Value = filename;
        return(markedDownloadedCommand.ExecuteNonQuery());
    }
}


texts: Comparing and pasting ranges of spreadsheet cells

texts:
I have a moderate size sub-procedure where I am calling multiple functions to feed values into other functions. I feel there may be a better or more concise way to present and run this module, but have refactored the code as far as I can see.

Public Sub CompareArrays()

    Dim matchCell As Range
    Set matchCell = ThisWorkbook.Sheet1.Range("A1")
    Dim matchArray As Variant
    matchArray = RangeToLastRow(matchCell)

    Dim compareCell As Range
    Set compareCell = matchCell.Parent.Range("B1")
    Dim compareArray As Variant
    compareArray = RangeToLastRow(compareCell)

    Dim arrayToPaste As Variant
    arrayToPaste = MatchArrays(matchArray, compareArray)

    RangeToLastRow(matchCell.Parent.Range("C1")) = arrayToPaste

End Sub


texts: Retrieving values from Entity Framework DbContext to render in a ListBox

texts:
I need to pass a ViewModel to a strongly typed View which will display a multiple-select box using Html.ListBoxFor. My ViewModel has a List<int> for the selected values and an IEnumerable<SelectListItem> for the options.

Is there a better way I could be enumerating the list of options?

private MyDbContext db = new MyDbContext();

public List<int> SelectedPhysicians { get; set; } = new List<int>(1) { 1 };

public IEnumerable<SelectListItem> AllPhysicians
{
    get
    {
        List<SelectListItem> temp = new List<SelectListItem>();
        foreach (PhysicianModel p in db.Physicians)
        {
            temp.Add(new SelectListItem { Value = p.Id.ToString(), Text = p.Name });
        }
        return temp;
    }
}

Also, can you see any long-term reasons I would even need a List<int> rather than an int[]? I tend to go with List because I almost always end up needing more than basic array operations. In this case, however, I'm just retrieving and storing sets of values in the database.
It's occurred to me that all of my models are using Lists for no tangible reason, but I want to be sure before refactoring.


texts: Casting an Enumeration with Descriptions into a Dictionary

texts:
The Enumeration in question is based on int, so the following Extension returns a Dictionary<int, string> of the Enum's Value and Description.

Is there a cleaner way of implementing this?

public enum TeamDepartments
{
    [Description("Geschäftsleitung")] Management = 1,
    [Description("Verkaufsleitung")] Sales = 2
}

public static class UtilityExtensions
{
    public static Dictionary<int, string> ToDictionary(this Type EnumerationType)
    {
        Dictionary<int, string> RetVal = new Dictionary<int,string>();
        var AllItems = Enum.GetValues(EnumerationType);
        foreach (var CurrentItem in AllItems)
        {
            DescriptionAttribute[] DescAttribute = (DescriptionAttribute[])EnumerationType.GetField(CurrentItem.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
            string Description = DescAttribute.Length > 0 ? DescAttribute[0].Description : CurrentItem.ToString();
            RetVal.Add((int)CurrentItem, Description);
        }
        return RetVal;
    }
}


texts: Showing the header and sub-caption in a listbox

texts:
I am trying to write this code in a reusable way so I can use it in other places if needed. The code is about the listbox where there is a ListHeader and it can contain any items like caption with price or without price, sub-caption with price or without, etc.

The sample might be something like this:

Header1 $100

sub-caption1 $20

Edit button

Header2

sub-caption2 $100

sub-caption3 $200

For this I have written the following code which works but there x-main and x-sub block is repeated and the code looks too long if there is more header and sub-header in the items.

How should I organize such code?

const
  DetailListing = () =>
  <x-listbox class={styles.listbox}>
    <Row>
      <Header border>
        <x-main>
          <x-caption>Listing Side</x-caption>
        </x-main>
        <x-sub>
          <x-subcaption>SubCaption</x-subcaption>
        </x-sub>
        <x-edit>
          <Button
            caption="Edit"
            appearance="transparent-gray"
            className={classNames(styles.editBtn)}
           />
        </x-edit>
      </Header>
    </Row>
    <Row>
      <Header>
        <x-main>
          <x-caption>Caption</x-caption>
          <x-price>$12,000.00</x-price>
        </x-main>
      </Header>
      <Header>
        <x-main>
          <x-caption>SubCaption</x-caption>
        </x-main>
        <x-sub>
          <x-subcaption>Another SubCaption</x-subcaption>
          <x-subprice>$12,000.00</x-subprice>
        </x-sub>
      </Header>
      <Header>
        <x-main>
          <x-caption>Caption</x-caption>
        </x-main>
        <x-sub>
            <x-subcaption>SubCaption</x-subcaption>
            <x-subprice>$12,000.00</x-subprice>
        </x-sub>
        <x-sub>
          <x-subcaption>Another SubCaption</x-subcaption>
          <x-subprice>$12,000.00</x-subprice>
        </x-sub>
      </Header>
      <Header>
        <x-main>
          <x-caption>Caption</x-caption>
        </x-main>
        <x-sub>
          <x-subcaption>SubCaption</x-subcaption>
          <x-subprice>$1,155.00</x-subprice>
        </x-sub>
      </Header>
      <Header>
        <x-sub class={classNames(styles.shadedCaption, styles.coloredText)}>
          <x-subcaption>Net Details</x-subcaption>
          <x-subprice>$2,750.78</x-subprice>
        </x-sub>
      </Header>
    </Row>
  </x-listbox>;

const
    Header = ({children, ...props}) =>
        <x-header class={classNames(styles.header, {active: props.active, border: props.border})}>
            {children}
        </x-header>;

const
    Row = ({children}) => <x-row>{children}</x-row>;


texts:
In Java, I use a LoadingCache which offers weakKeys
and I need something similar in Typescript, so I wrote the following:

function loadingWeakCache<K extends object, V>(loader: (k: K) => V) : ((k: K) => V) {
    const cache = new WeakMap<K, V>();
    return function(k: K) : V {
        let v = cache.get(k);
        if (v !== undefined) return v;
        v = loader(k);
        cache.set(k, v);
        return v;
    };
}

It seems to work and I'd like it to be reviewed*

Unfortunately, I need to cache a two-argument function. My first attempt was

function pairLoadingWeakCache<K1 extends object, K2 extends object, V>(loader: (k1: K1, k2: K2) => V) : (k1: K1, k2: K2) => V {
    const cache = new WeakMap<K1, (k2: K2) => V>();
    return function(k1: K1, k2: K2) : V {
        let second = cache.get(k1);
        if (second !== undefined) return second(k2);
        const v = loader(k1, k2);
        second = loadingWeakCache(k => loader(k1, k));
        cache.set(k1, second);
        return second(k2);
    };
}

which was wrong as it prevented collecting the second key because of it being referenced from the closure. I'm only presenting it here as it's a smart but broken idea someone could propose. I rewrote it as

function pairLoadingWeakCache<K1 extends object, K2 extends object, V>(loader: (k1: K1, k2: K2) => V) : (k1: K1, k2: K2) => V {
    const cache = new WeakMap<K1, WeakMap<K2, V>>();
    return function(k1: K1, k2: K2) : V {
        let second = cache.get(k1);
        if (second === undefined) {
            second = new WeakMap();
            cache.set(k1, second);
        } else {
            const v = second.get(k2);
            if (v !== undefined) return v;
        }
        const v = loader(k1, k2);
        second.set(k2, v);
        return v;
    };
}

and I'd like it to be reviewed* as well.

* Just please ignore my single-line conditionals as it's my strongly preferred way.


texts: Importing modules for private use in Python

texts:
There's something I completely dislike when importing a module in an interactive Python shell, typing the name of the module, hitting tab and getting the automatic completion cluttered with other modules that the module itself had imported (but are internal implementation details that are not really useful for me).

Example:

a.py

import os
import datetime

def foo():
    now = datetime.datetime.now()
    print os.path.join(map(str, (now.year, now.month, now.day)))

shell

$ ipython
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
Type "copyright", "credits" or "license" for more information.

IPython 5.5.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import a

In [2]: a.
           a.datetime a.py
           a.foo      a.pyc
           a.os

I don't care that module a depends on datetime and os, that is distracting me from what the module provides (foo).

So I have started to make my imports private, like this:

a.py

import os as _os
import datetime as _datetime

def foo():
    now = _datetime.datetime.now()
    print _os.path.join(map(str, (now.year, now.month, now.day)))

shell

$ ipython
iPython 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
Type "copyright", "credits" or "license" for more information.

IPython 5.5.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import a

In [2]: a.
           a.foo
           a.py
           a.pyc

Is this considered pythonic at all? I feel like it's a little bit too verbose, but I think simplifying the end user's experience should be above saving some extra tokens per import.


texts: Return row count from mysqli prepared statement

texts:
I want to know if it is okay/safe to use a prepared statement and mysqli_num_rows like this:
public function getUnreadNumber() {
    $userLoggedIn = $this->user_obj->getUsername();

    // get_result for * and bind for select columns
    // bind_result Doesn't work with SQL query that use *
    $query = $this->con->prepare('SELECT * FROM notifications WHERE viewed="0" AND user_to = ? ');
    $query->bind_param("s", $userLoggedIn);
    $query->execute();
    $query_result = $query->get_result();

    return mysqli_num_rows($query_result);
}

Or should I do this?
$query = $this->con->prepare('SELECT * FROM notifications WHERE viewed="0" AND user_to = ? ');
$query->bind_param("s", $userLoggedIn);
$query->execute();
$query_result = $query->get_result();
$numRows = $query_result->num_rows;

return $numRows;


texts: Generating a sequential number for app-wide use

texts:
I have to generate a sequential number for groovy-grails app wide use and came up with the following.  However, is there a better way to do this?

Domain classes:

class RoastIdCounter {
    int counter =0
    static constraints = {
    }
}

This one has no views or controller associated with it.  It's purely for db interaction in a service class.

class RoastId {
    Family family
    Integer nextId
    long timeCreated = new Date().time

    static constraints = {
        family()
        nextId()
    }
    static belongsTo = [ Family ]
}

class Family  extends {

    String farmId;
    String welcome;
    String familyName;
    String ourFarm;
    String howMuchDoWeGetPaid;

    SortedSet pictureAlbums;
    SortedSet pictures;

    Integer pictureAlbumsCount = 0;
    Integer picturesCount = 0;

    Date dateCreated = new Date()
    Date lastUpdated = new Date()

    static hasMany = [ roastIds : RoastId, pictureAlbums : PictureAlbum, pictures : Picture ]

    static constraints = {
        farmId()
        familyName( )
        welcome( widget:'textarea' )
        ourFarm( widget:'textarea' )
        howMuchDoWeGetPaid( widget:'textarea' )

        dateCreated()
        lastUpdated()
}

    String toString() { "$farmId - $familyName" }

} // Family

Service class for dealing with the number generation:

class RoastIdCounterService {

    static transactional = true

    def getNextRoastId() {

        def ric = RoastIdCounter.list()[-1]

        if( ric != null ){
            ric.lock()
            ric.counter = ric.counter + 1
            ric.save()
            return ric.counter
        } else {
            return -1
        }
    }
}

Controller:

Here I'm just sending the object all pre-populated:

def create = {
    def roastIdInstance = new RoastId()
    roastIdInstance.properties = params
    roastIdInstance.nextId = roastIdCounterService.getNextRoastId()
    return [roastIdInstance: roastIdInstance]
}

Environment: Grails 1.3.7, PostgreSql 8.4

Would there be a better way to do this? What potential problems am I overlooking?


texts:
I made a WPF Application, called Palindrome Checker, which checks if what you input is a palindrome.

Any and all tips on how to make this code better in all capacities are wanted and appreciated.

public class Check {

    /// <summary>
    /// Method for checking if the word/text is a palindrome.
    /// </summary>
    public static bool IsPalindrome(string text) {

        int min = 0;
        int max = text.Length - 1;

        while (true) {
            if (min > max) {
                return true;
            }

            char a = text[min];
            char b = text[max];

            if (a != b) {
                return false;
            }

            min++;
            max--;
        }
    }
}

public partial class MainWindow : Window {

    public MainWindow() {

        InitializeComponent();

        lblInput.Foreground = Brushes.ForestGreen;
        lblResult.Foreground = Brushes.ForestGreen;
        lblTitel.Foreground = Brushes.ForestGreen;

    }

    /// <summary>
    /// User input and checking the input if the word a palindrome is.
    /// </summary>
    private void InputText_TextChanged(object sender, TextChangedEventArgs e) {

        string text = InputText.Text;

        bool isPalindrome = Check.IsPalindrome(text);

        OutputText.Text = text + (isPalindrome ? " is a palindrome" : " is NOT a palindrome");

        if(InputText.Text == string.Empty)
            OutputText.Clear();
    }
}


texts: How to simply express a desire to run a function when two properties are true?

texts:
require([
    'jquery',
    'underscore',
    'backbone'
], function ($, _, Backbone) {
    'use strict';

    //  TODO: Would like to access through define module, but not sure how..
    var player = chrome.extension.getBackgroundPage().YouTubePlayer;
    var user = chrome.extension.getBackgroundPage().User;

    //  If the foreground is opened before the background has had a chance to load, wait for the background.
    //  This is easier than having every control on the foreground guard against the background not existing.
    if (user.get('loaded')) {
        loadForeground();
    } else {
        user.on('change:loaded', function (model, loaded) {
            if (loaded) {
                loadForeground();
            } else {
                //  Show refreshing message?
            }
        });
    }

    function loadForeground() {

        if (player.get('ready')) {
            //  Load foreground when the background indicates it has loaded.
            require(['foreground']);
        } else {

            player.once('change:ready', function () {

                //  Load foreground when the background indicates it has loaded.
                require(['foreground']);
            });
        }

    }
});

My goal is to call require(['foreground']) once the user object is loaded and the player is ready. This code works fine, but seems really unclear / overly verbose.

Am I missing an easy simplification in trying to express this need?


texts: Showing form on btn click - preventDefault of submit btn, then remove listener

texts:
I've built out a section on a page that contains multiple instances (why I'm using querySelectorAll()) of this Request Brochure form. They are using Campaign Monitor so much of the form code has been removed for this post.

Operation

On page load an event handler that calls preventDefault on click  events is added to elements with class download to prevent the submit action.
A class of .is-open is added to the .download container.
This triggers a keyframe animation that transitions the height, then the opacity of the forms
The event listener is removed to allow the button to perform it's submit action

I did try using the method of setting the button to disabled initially, then removing this attribute onclick but found this meant the hover states would not work.

I'm looking to see if this is the most efficient way of adding, then removing preventDefault once it is no longer required.

const packageCMCont = document.querySelectorAll('.download');

packageCMCont.forEach(function(item) {

  function handleClick(e) {
    e.preventDefault()
    var btn = item.querySelector('.btn');

    item.classList.add('is-open');

    btn.classList.remove('is-style-outline');
    btn.classList.add('is-style-default');

    item.removeEventListener('click', handleClick);
  }

  item.addEventListener('click', handleClick);

})
.download {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
 }
.download.is-open .inputs {
    display: flex;
    height: 100px;
    animation: showForms 3s forwards;
}
.inputs {
  opacity: 0;
  display: none;
  flex-direction: column;
  height: 0;
  overflow: hidden;
}
input {
  height: 50px;
}
button {
  height: 50px;
  width: 100%;
  background-color: green;
  color: white;
}
button:hover {
  background-color: white;
  color: green;
}

@keyframes showForms {
  0% {
    height: 0;
  }
  50% {
    height: 100px;
    opacity: 0;
  }
  100% {
    height: 100px;
    opacity: 1;
  }
}

  <form>

      <input aria-label="Name" id="fieldName" maxlength="200" name="cm-name" placeholder="Name">
      <input autocomplete="Email" aria-label="Email" id="fieldEmail" maxlength="200" required="" type="email" placeholder="Email">

      <button class="btn" type="submit">Request Brochure</button>

  </form>


texts:
The script is fully working, but I ask is there a better way I can do this rather than name all of the query variables, $q, $q1 etc, and then use if else statements to execute the code.

<?php
// open the mysql connection

require_once('mysqli.php');

// successful login variables

$q = $dbc -> prepare("SELECT * FROM accounts WHERE email = ? && password = ? && logcount != ''");
$q -> bind_param('ss', ($_POST['email']), ($_POST['password']));
$q -> execute();
$q -> store_result();

// wrong password variables

$q1 = $dbc -> prepare("SELECT * FROM accounts WHERE email = ? && password != ? && logcount != ''");
$q1 -> bind_param('ss', ($_POST['email']), ($_POST['password']));
$q1 -> execute();
$q1 -> store_result();

// not active variables

$q2 = $dbc -> prepare("SELECT * FROM accounts WHERE email = ? && logcount = ''");
$q2 -> bind_param('s', ($_POST['email']));
$q2 -> execute();
$q2 -> store_result();

// successful login query

if ($q -> num_rows == 1) {
    $q = $dbc -> prepare("UPDATE accounts SET logcount = logcount+1 WHERE email = ?");
    $q -> bind_param('s', ($_POST['email']));
    $q -> execute();
    $dbc -> close();
    header('location: shack');
    exit();
}

// wrong password query

elseif ($q1 -> num_rows == 1) {
    echo '
Your password is incorrect.
';
}

// not activated query

elseif ($q2 -> num_rows == 1) {
    echo '
Your account is not activated.
';
}

// blank email form entry

elseif (empty($_POST['email'])) {
    echo '
You did not fill in an email on the login form.
';
}

// account not found

else {
    echo '
An account could not be found.
';
}

// close the mysql connection

$dbc -> close();

?>


texts: Divide and Conquer algorithm for counting inversions

texts:
I've written a program that counts the number of inversions using a Divide and Conquer algorithm, written in C++11.

#include <iostream>
#include <tuple>
#include <vector>

using IntVec = std::vector<int>;

std::tuple<IntVec, long long> count_inv(IntVec xs);
std::tuple<IntVec, long long> count_split_inv(IntVec xs, IntVec ys);

std::tuple<IntVec, long long> count_inv(IntVec xs) {
    int n = xs.size();

    if (n < 2) return std::make_tuple(xs, 0);

    IntVec::iterator middle = xs.begin() + (n / 2);
    IntVec left(xs.begin(), middle);
    IntVec right(middle, xs.end());

    long long left_inv, right_inv, split_inv;
    IntVec as, bs, cs;
    std::tie(as, left_inv) = count_inv(left);
    std::tie(bs, right_inv) = count_inv(right);
    std::tie(cs, split_inv) = count_split_inv(as, bs);
    return std::make_tuple(cs, left_inv + right_inv + split_inv);
}

std::tuple<IntVec, long long> count_split_inv(IntVec xs, IntVec ys) {
    int n = xs.size() + ys.size();
    IntVec zs(n);
    long long split_inv = 0;

    int i = 0, j = 0, k = 0;
    for (; k < n && i < xs.size() && j < ys.size(); ++k) {
        if (xs[i] <= ys[j]) {
            zs[k] = xs[i];
            ++i;
        } else {
            zs[k] = ys[j];
            ++j;
            split_inv += xs.size() - i;
        }
    }

    for (; i < xs.size(); ++k, ++i)
        zs[k] = xs[i];

    for (; j < ys.size(); ++k, ++j)
        zs[k] = ys[j];

    return std::make_tuple(zs, split_inv);
}

int main() {
    std::vector<int> xs;
    int x;
    while (std::cin >> x) {
        xs.push_back(x);
    }

    IntVec ys;
    long long inv;
    std::tie(ys, inv) = count_inv(xs);
    std::cout << inv << std::endl;
    return 0;
}

I find that the code is very verbose in some areas, such as specifying the type of the tuple. Also, parts of it are confusing. How could I rewrite this code such that it is more concise and clearer?


texts:
I am currently working on my own implementation of the Buddhabrot. So far I am using the std::thread-class from C++11 to concurrently work through the following iteration:

void iterate(float *res){
    //generate starting point
    std::default_random_engine generator;
    std::uniform_real_distribution<double> distribution(-1.5,1.5);

    double ReC,ImC;
    double ReS,ImS,ReS_;
    unsigned int steps;

    unsigned int visitedPos[maxCalcIter];

    unsigned int succSamples(0);

    //iterate over it
    while(succSamples < samplesPerThread){
        steps = 0;
        ReC = distribution(generator)-0.4;
        ImC = distribution(generator);
        double p(sqrt((ReC-0.25)*(ReC-0.25) + ImC*ImC));
        while (( ((ReC+1)*(ReC+1) + ImC*ImC) < 0.0625) || (ReC < p - 2*p*p + 0.25)){
            ReC = distribution(generator)-0.4;
            ImC = distribution(generator);
            p = sqrt((ReC-0.25)*(ReC-0.25) + ImC*ImC);
        }
        ReS = ReC;
        ImS = ImC;
        for (unsigned int j = maxCalcIter; (ReS*ReS + ImS*ImS < 4)&&(j--); ){
            ReS_ = ReS;
            ReS *= ReS;
            ReS += ReC - ImS*ImS;
            ImS *= 2*ReS_;
            ImS += ImC;
            if ((ReS+0.5)*(ReS+0.5) + ImS*ImS < 4){
                visitedPos[steps] = int((ReS+2.5)*0.25*outputSize)*outputSize + int((ImS+2)*0.25*outputSize);

            }
            steps++;

        }
        if ((steps > minCalcIter)&&(ReS*ReS + ImS*ImS > 4)){
            succSamples++;
            for (int j = steps; j--;){
                //std::cout << visitedPos[j] << std::endl;
                res[visitedPos[j]]++;
            }
        }
    }
}

These are my declarations and main():

#include <iostream>
#include <string>
#include <thread>
#include <random>
#include <vector>

#define outputSize 20000

#define samplesPerThread 5000
#define numThreads 16

#define maxCalcIter 60000
#define minCalcIter 40000

//iterate function

int main(){
    float *outImg = new float[outputSize*outputSize];

    std::vector<std::thread> threads;
    for (int i = numThreads; i--; ){
        threads.push_back(std::thread(iterate,outImg));
    }
    for (auto& t : threads){
        t.join();
    }

    return 0;
}

I am basically working in every thread so long that I generated enough trajectories of sufficient length which in expectation takes the same time in every thread.

But I really have the feeling that this function might me very unoptimized since its code is so very readable. Can anybody come up with some fancy optimizations? When it comes to compiling I just use:

  g++ -O4 -std=c++11 -I/usr/include/OpenEXR/ -L/usr/lib64/ -lHalf -lIlmImf -lm buddha_cpu.cpp -o buddha_cpu

Any hints on crunching some more numbers/sec would be really appreciated. Also, any links to further literature are totally welcome.


texts: Google's Python exercise about lists very different from the given solution

texts:
I found some Python exercises that were made by Google in their Python classes and decided to spend some time with them.
Given the following description:

E. Given two lists sorted in increasing order, create and return a merged
ist of all the elements in sorted order. You may modify the passed in lists.
deally, the solution should work in "linear" time, making a single
pass of both lists.

So, knowing that comparing two characters is \$O(1)\$, Python's sorted() function in this situation is \$O(n \log{n})\$ and thinking that merging two lists into a new one is \$O(k)\$ where \$k\$ the number of elements in list1 + list2, which is quite "linear" in the sense of what was asked, I did...
def linear_merge(list1, list2):
  return sorted(list1 + list2)

However, when looking at the problem's solution, I found it to be somewhat different:
def linear_merge(list1, list2):
  result = []
  # Look at the two lists so long as both are non-empty.
  # Take whichever element [0] is smaller.
  while len(list1) and len(list2):
    if list1[0] < list2[0]:
      result.append(list1.pop(0))
    else:
      result.append(list2.pop(0))

  # Now tack on what's left
  result.extend(list1)
  result.extend(list2)
  return result

which is followed by the following comment:

Note: the solution above is kind of cute, but unforunately list.pop(0)
is not constant time with the standard Python list implementation, so
the above is not strictly linear time.
An alternate approach uses pop(-1) to remove the endmost elements
from each list, building a solution list which is backwards.
Then use reversed() to put the result back in the correct order. That
solution works in linear time, but is more ugly.

This confused me a little bit, since my solution looks... better in general (code and complexity, given the last comment paragraph).
Are any of my assumptions about my version of the code wrong?
Keep in mind that I wrote this version using Python3, when instead google's python classes uses Python2. I'm not really sure, but this may have something to do with it.
Here is the rest of the related source to give a full example:
def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = '  X '
  print('{} got: {} expected: {}'.format(prefix, repr(got), repr(expected)))

# Calls the above functions with interesting inputs.
def main():
  print('linear_merge')
  test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']),
       ['aa', 'bb', 'cc', 'xx', 'zz'])
  test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
       ['aa', 'bb', 'cc', 'xx', 'zz'])
  test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
       ['aa', 'aa', 'aa', 'bb', 'bb'])

if __name__ == '__main__':
  main()


texts:
I have an object that represents a PDF file. In the constructor, I pull out various information about the file name and make it available via properties:

public class Invoice
{
    //public properties
    public string FullPath {get { return this.fullPath;} }
    public string FileNameWithoutExtension { get { return this.fileNameWithoutExtension;} }
    public string FileName { get { return this.fileName; } }
    public string BatchSequenceNumber { get { return this.batchSequenceNumber; } }

    //private fields
    private string fullPath;
    private string fileNameWithoutExtension;
    private string fileName;
    private string batchSequenceNumber;

    //Default construtor
    public Invoice(string filePath)
    {
        this.fullPath = filePath;
        this.fileName = Path.GetFileName(filePath);
        this.fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
        this.batchSequenceNumber = Path.GetFileNameWithoutExtension(filePath).Split('_').LastOrDefault();
    }
}

One of the attributes I would like to get is the number of pages in the PDF.
I am using iTextSharp and I have a PageCount method in the above Invoice class that looks like this:

public int PageCount()
    {
        PdfReader reader = null;
        int pageCount;

        try
        {
            reader = new PdfReader(this.FullPath);
            pageCount = reader.NumberOfPages;
        }
        catch (Exception ex)
        {
            throw new Exception("Error reading pdf! " + ex.Message);
        }
        finally
        {
            if (reader != null) { reader.Close(); }
        }

        return pageCount;
    }

This works fine, except now I need to get the count of pages at several times during the object lifetime. I do not want to keep opening the PDF each time to get the count so these are my ideas:

Rename method PageCount to CountPages and store the result in field/property PageCount.
Count the pages in the constructor and store the result in a field/propertry PageCount and don't expose a CountPages method.

Number 1 seems preferable to me, but what if someone tries to read PageCount before running method CountPages? How best to handle this situation, set PageCount to 0 in the constructor?

Number 2 seems bad because it feels wrong to open the PDF file in the constructor, is it? (I have been reading this)


texts:
I have a list of boxes, and wish to group them into unconnected sets of overlapping boxes. (Note that two boxes A and B may not overlap each other, but if they are both overlapped by a box C, they will still be grouped together).

The following works ok, but I feel like it could be made a lot more concise with LINQ, or possibly made faster.

private List<List<Box>> FindUnconnectedSets(List<Box> boxes)
{
    List<List<Box>> unconnectedSets = new List<List<Box>>();

    while (boxes.Count() != 0)
    {
        List<Box> set = new List<Box>();

        bool found = true;
        while (found)
        {
            found = false;

            foreach (Box newBox in boxes)
            {
                if (set.Count != 0)
                {
                    foreach (Box setBox in set)
                    {
                        if (newBox.Overlaps(setBox))
                        {
                            set.Add(newBox);
                            boxes.Remove(newBox);
                            found = true;
                            break;
                        }
                    }
                }
                else
                {
                    set.Add(newBox);
                    boxes.Remove(newBox);
                    found = true;
                }

                if (found)
                    break;
            }
        }

        unconnectedSets.Add(set);
    }

    return unconnectedSets;
}

Edit: added the Box class. It's not all that interesting really.

private class Box
{
    public Box(int xOrigin, int yOrigin, int size)
    {
        XOrigin = xOrigin;
        YOrigin = yOrigin;

        Size = size;
    }

    public int XOrigin;
    public int YOrigin;

    public int Size;

    public override string ToString()
    {
        string s = "Box: "
            + "(" + XOrigin.ToString() + ", " + YOrigin.ToString() + ")"
            + " " + Size.ToString();
        return s;
    }

    public bool Overlaps(Box b2)
    {
        if (XOrigin >= b2.XOrigin + b2.Size)
            return false;
        if (b2.XOrigin >= XOrigin + Size)
            return false;
        if (YOrigin >= b2.YOrigin + b2.Size)
            return false;
        if (b2.YOrigin >= YOrigin + Size)
            return false;

        return true;
    }
}

Comments welcome, both on the LINQifying side, and algorithm suggestions if you think I'm going about this the wrong way, as well as any other feedback. :)


texts:
I have  created a custom scatterplot in Qt and am wondering if there is a more efficient way to do it. Here is a sketch of the problem:

The layout of the plotting area consists of a rectangular structure starting at [0,0] in the top left corner and expands by 250 pixels to the bottom right corner [250,250]. So the y-coordinate grows downwards and the x-coordinate to the right.

The task consists of mapping two vectors (A[i],B[i]) holding numerical data onto this rectangular structure such that the lowest x,y coordinates are in the bottom left corner and the highest x,y coordinates are in the top right corner.

To solve this problem I choose the following approach (pseudo code):

calculate the min and max for (A and B);
calculate the spread (max - min) for (A and B);
transform A and B by:

 foreach (i in A) {
     (i - min(A) / spread(a))* 250
 }
 foreach(j in B) {
     (250 - ((j - min(B) / spread(B))*250
 }

and the implementation:

.h file

#include <QDialog>
#include <QtGui>
#include <QtCore>
#include <QGraphicsScene>
#include <cstdlib>
#include <cmath>
#include <QVector>
#include <QRectF>

namespace Ui {
class paintEr;
}

class paintEr : public QDialog
{
    Q_OBJECT

public:
    explicit paintEr(QWidget *parent = 0);
    ~paintEr();
private slots:
    void addPoint();

private:
    Ui::paintEr *ui;
    QGraphicsScene *scatter;

protected:
    void paintEvent(QPaintEvent *event);

};

.cpp

#include "painter.h"
#include "ui_painter.h"

paintEr::paintEr(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::paintEr)
{
    ui->setupUi(this);
}

void paintEr::paintEvent(QPaintEvent *event){

    scatter = new QGraphicsScene(this);
    ui->graphicsView->setSceneRect(0,0,250,250);
    ui->graphicsView->setScene(scatter);

}
void paintEr::addPoint(){
    QPen greenPen(Qt::green);
    QBrush greenBrush(Qt::green);

    QVector<double> a,b,c,d;
    a << 2 << 5 << 7;
    b << 22 << 34 << 75;
    double min_a = *std::min_element(a.begin(), a.end());
    double max_a = *std::max_element(a.begin(), a.end());
    double min_b = *std::min_element(b.begin(), b.end());
    double max_b = *std::max_element(b.begin(), b.end());
    double spread_a = max_a - min_a;
    double spread_b = max_b - min_b;

    for(int i = 0; i < a.length(); ++i){
        c.push_back(((a[i]-min_a)/spread_a)*250);
        d.push_back(250-((b[i]-min_b)/spread_b)*250);
        scatter->addEllipse(c[i], d[i], 5, 5, greenPen, greenBrush);
    }
}
paintEr::~paintEr()
{
    delete ui;
}

main.cpp

#include "painter.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    paintEr w;
    w.show();

    return a.exec();
}


texts: A better way to convert an SQLObject instance into a dict

texts:
I've got this function which returns an SQLObject instance as a dict (taking into account inherited classes, properties, etc).  It doesn't work right now on SQLObject classes which inherit from another class but add new attributes, so that's a work in progress, but I feel like this could be done smarter/better in Python.

What do you think?

PS the purpose of this is to allow a generic presentation of an object as a JSON document.  It returns a dict which can be then given to json.dumps.  If you've got a different way to convert an SQLObject to a JSON doc, that would be cool as well

def sqlobject_to_dict(obj):
    obj_dict = {}
    cls_name = type(obj)
    has_props = False
    for attr in vars(cls_name):
        attr_parent = type(getattr(obj, attr)).__bases__[0]
        if isinstance(getattr(cls_name, attr), property):
            has_props = True
            if isinstance(getattr(obj, attr), Decimal):
                obj_dict[attr] = float(getattr(obj, attr))
            elif isinstance(getattr(obj, attr), list):
                dict_list = []
                for list_item in getattr(obj, attr):
                    dict_list.append(sqlobject_to_dict(list_item))
                obj_dict[attr] = dict_list
            elif isinstance(getattr(obj, attr), dict):
                dict_dict = {}
                for key, val in getattr(obj, attr):
                    dict_dict[key] = sqlobject_to_dict(val)
                obj_dict[attr] = dict_dict
            elif attr_parent == SQLObject:
                obj_dict[attr] = sqlobject_to_dict(getattr(obj, attr))
            else:
                obj_dict[attr] = getattr(obj, attr)
        elif not has_props and attr_parent != SQLObject:
            if "_get_" in attr:
                attr_name = '_'.join(attr.split('_', 3)[3:])
                if hasattr(obj, attr_name):
                    obj_dict[attr_name] = getattr(obj, attr_name)
    return obj_dict


texts:
Does the following code look okay? Want to see if anyone can spot any mistakes I may have made. This will be pulling from a pre-formatted Excel document - I have already specified all needed Cell locations.

Things I want clarified:

How many times can you invoke SetInfo and did I use it more than needed? I was under the impression that a SetInfo would be needed before a SetPassword can be used, but I could be very wrong.
Does this line look okay? Was I correct to separate multiple cells using a comma in order to put all the info together? I know it worked with an Echo command:

Set objUser = objOU.Create _
("User", "cn=" & objExcel.Cells(intRow, 3).Value, objExcel.Cells(intRow, 2).Value, objExcel.Cells(intRow, 19).Value)

Is this the correct code for setting a password to never expire?

objUser.Put "userAccountControl", intUAC XOR _
ADS_UF_DONT_EXPIRE_PASSWD

Full code below, I'd appreciate any feedback on anything else that is found.

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open _
    ("C:\Book1.xls")
intRow = 2
Do Until objExcel.Cells(intRow,1).Value = ""
    Set objOU = GetObject _
    ("ou=" & objExcel.Cells(intRow, 13).Value & _
        ", dc=satdc, dc=com")
    Set objUser = objOU.Create _
        ("User", "cn=" & objExcel.Cells(intRow, 3).Value, objExcel.Cells(intRow, 2).Value, objExcel.Cells(intRow, 19).Value)
    objUser.sAMAccountName = objExcel.Cells(intRow, 19).Value & ".sat"
    objUser.GivenName = objExcel.Cells(intRow, 3).Value
    objUser.SN = objExcel.Cells(intRow, 2).Value
    objUser.SetInfo
    objUser.AccountDisabled = False
    objUser.AccountExpirationDate = Date + 365
    objUser.SetPassword objExcel.Cells(intRow, 9).Value
    objUser.SetInfo
    objUser.Put "userAccountControl", intUAC XOR _
        ADS_UF_DONT_EXPIRE_PASSWD
    objUser.HomeDirectory = "\\satdc" & "\" & "Users" & "\" & _
        objUser.Get("sAMAccountName")
    objUser.homeDrive = "U:"
    objUser.SetInfo
    intRow = intRow + 1
Loop
objExcel.Quit