texts: How could I make this PHP $_POST more secure? -Or is it secure already?

texts:
On most my $_post data inputted on my site I use the following php:

$example = $_POST['textfield'];
$example = strip_tags($example);
$example = mysql_real_escape_string($example);

And then I would interact with the MySQL database...

Is this 'secure' / 'safe'?

Any major exploits to the above code?

-How could I make it secure?

Thanks alot.


texts: Exception handling for timing CouchBase fetch

texts:
override def get(key: String): Option[Any]  = {
  val timer = couchbaseMetricsTimer.time()
  try { // Any way (is it more elegant?) to avoid the try/catch/finally?
    Option(couchBaseClient.get(key))
  } catch {
    case e: Exception => couchbaseFailureMetricCounter.inc(); throw e
  } finally {
    timer.stop()
  }
}

Note the clients of this code are expecting exceptions in case of failures.


texts:
Here the task (in Indonesian).

I think my binary search algorithm is correct.

Ideone

 #include<bits/stdc++.h>
using namespace std;
vector<pair<string, string>> v;
int awal1 = 1;
string check(string s, int awal, int akhir){
    int tengah = (awal+akhir)/2;
    bool temukan = false;
    if(v[tengah].first == s){
        return v[tengah].second;
        temukan = true;
    }
    else if(v[tengah].first > s){
        return check(s, awal, tengah-1);
    }
    else if(v[tengah].first < s){
        return check(s, tengah+1, akhir);
    }
    if(temukan == false) return "NIHIL";
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
     string s, s1, s2; vector<string> h;
    int n, p;
    cin >> n >> p;
    for(int i=1;i<=n;i++){
        cin >> s >> s1;
        v.push_back(make_pair(s, s1));
    }
    for(int j=1;j<=p;j++){
        cin >> s2;
        h.push_back(s2);
    }
    for(int i=1;i<=h.size();i++){
        cout << check(h[i], 1, v.size()) << "\n";
    }
    /*for(int i=0;i<v.size();i++){
        cout << v[i].first << " " << v[i].second << "\n";
    } */
}


texts: Converting regular text phrase to Pig Latin in Groovy

texts:
Am I using the best conventions or are there better ways?

    static void makePigLatin(String text){

    String[] textArray = text.split(" ")
    String buffer, translated

    for (int i = 0; i < textArray.length; i++) {

        buffer = ""
        translated = ""

        for (int j = 0; j < textArray[i].length(); j++){

            if (textArray[i][j].find { a -> vowels.any {a.contains(it)}}) {

                translated = textArray[i].substring(j)
                break

            } else {

                buffer = "$buffer${textArray[i][j]}"
            }
        }

        if (textArray[i][textArray[i].length() - 1].find { a -> punctuation.any {a.contains(it)}}) {

            print "${translated.substring(0, translated.length() - 2)}$buffer" + "ay" + "${textArray[i][textArray[i].length() - 1]}" + " "
        } else {

            print "$translated$buffer" + "ay "
        }
    }

    println ""
}

The vowels and punctuation variables are global:

static def vowels = ["a", "e", "i", "o", "u", "y"]
static def punctuation = [",", ".", "?", "!", ":"]


texts: Submiting form and transform model to match backend

texts:
I have different model in frontend and backend. When I submit form in frontend I need to transform that object to match backend model. Is there a better way than this one:

submit(confirmed: boolean) {
    this.transformCreditCardModel(confirmed);
    this.dialogRef.close({
      success: confirmed,
      productAdjustment: confirmed === true ? this.exposuresForm.value : null
    });
  }

  private transformCreditCardModel(confirmed: boolean) {
    const product = this.exposuresForm.value;
    if (confirmed && product.hasOwnProperty(ExposuresFieldNamesEnum.creditCardProductIdentification)) {
      const prefix = product.creditCardProductIdentification.accountPrefix;
      const number = product.creditCardProductIdentification.accountNumber;
      delete product.creditCardProductIdentification.accountNumber;
      delete product.creditCardProductIdentification.accountPrefix;
      product.creditCardProductIdentification.cardNumber = prefix + this.CREDIT_CARD_MASK + number;
    }
  }

I don't like the part where I am asking whether the object contain some property if yes then creating new one and deleting old one. Is there a nicer way to do this ?


texts: Reading a config file outside of the publicly visible root directory

texts:
To enable my PHP scripts to access my MySQL database, I have a configuration file containing the name of the MySQL database, usernames, etc.

In order to keep that information secure, I'm storing it outside of the web root on the server. I WAS setting an environment variable in httpd.conf to the file path of the .ini file so that PHP could access it and then parse the config file.

However, for the purposes of demonstration I'm deploying this database and front end on a shared server which will not give me access to httpd.conf. This is the alternative I worked out:

<?php
  if(!isset($GLOBALS['config'])){
    $nonPublic = explode("/",$_SERVER['DOCUMENT_ROOT']);
    array_pop($nonPublic);
    $nonPublic = implode("/",$nonPublic);
    $GLOBALS['config'] = parse_ini_file($nonPublic."/configs/JCDBconfig.ini");
  }
?>

The theory is that I make sure the 'configs' folder is just above DOCUMENT_ROOT, grab all but the last part of the DOCUMENT_ROOT path, and the PHP script should be able to find the config file stored there.

My question is: Is this a good idea, or sloppy? Is $_SERVER['DOCUMENT_ROOT'] reliable enough that, should I deploy this on a dedicated server in the future, it will still work?


texts: What would be proper way to store data from file and validate data from file

texts:
what is proper way to save all lines from text file to objects. I have .txt file something like this

0001Marcus Aurelius          20021122160   21311
0002William  Shakespeare     19940822332   11092
0003Albert Camus             20010715180   01232

From this file I know position of each data that is written in file, and all data are formatted.

Line number is from 0 to 3
Book author is from 4 to 30
Publish date is from 31 to 37
Page num. is from 38 to 43
Book code is from 44 to 49

I made class Data which holds information about start, end position, value, error.

Then I made class Line that holds list of type Data, and list that holds all error founded from some line. After load data from line to object Data I loop through lineError and add errors from all line to list, because I need to save errors from each line to database.

My question is this proper way to save data from file to object and after processing same data saving to database, advice for some better approach?
Is better approach to create custum attribute which holds position of every record?
For this I can't use third party library.

public class Data
{
    public int startPosition = 0;
    public int endPosition = 0;
    public object value = null;
    public string fieldName = "";
    public Error error = null;

    public Data(int start, int end, string name)
    {
        this.startPosition = start;
        this.endPosition = end;
        this.fieldName = name;
    }

    public void SetValueFromLine(string line)
    {
        string valueFromLine = line.Substring(this.startPosition,
                               this.endPosition - this.startPosition);
        // if else statment that checks validity of data (lenght, empty
         value)
         this.value = valueFromLine;
     }

 }

 public class Line
 {
     public List<Data> lineData = new List<Data>();
     public List<Error> lineError = new List<Error>();

     public Line()
     {
         AddObjectDataToList();
     }

     public void AddObjectDataToList()
     {
         lineData.Add(new Data(0, 3, "lineNumber"));
         lineData.Add(new Data(4, 30, "bookAuthor"));
         lineData.Add(new Data(31, 37, "publishData"));
         lineData.Add(new Data(38, 43, "pageNumber"));
         lineData.Add(new Data(44, 49, "bookCode"));
     }

     public void LoadLineDataToObjects(string line)
     {
         foreach(Data s in lineData)
         {
             s.SetValueFromLine(line);
         }
      }

      public void GetAllErrorFromData()
      {
           foreach (Data s in lineData)
           {
               if(s.error != null)
               {
                    lineError.Add(s.error);
               }

           }
      }

   }

   public class File
   {
     public string fileName;
     public List<Line> lines = new List<Line>();
   }


texts: Printing all the permutations of a string in alphabetical order-ver1.1

texts:
I adapted most of the suggestions from answers for my previous question Printing all the permutations of a string in alphabetical order to rewrote my solution again. Please let me know any more changes required or any more suggestions.

#include <iostream>
#include<fstream>
#include<algorithm>
#include<string>

void create_permute(  std::string& record )
{
    std::sort( record.begin(), record.end() );
    std::cout<<record;

    while( std::next_permutation( record.begin(), record.end() ) )
    {
        std::cout<<","<<record;
    }
    std::cout << "\n";
}
void readInputFile( std::string filename )
{
    std::ifstream infile(filename);
    std::string record;
    while( std::getline( infile,record ) )
    {
       create_permute( record );
    }
    infile.close();
}

int main( int argc, char* argv[] )
{
    if( argc < 2 )
    {
        std::cout << "usage: filesize filename" << "\n";
        exit( 0 );
    }
    std::ios_base::sync_with_stdio( false );
    readInputFile( argv[ 1 ] );

    return 0;
}


texts: Mean of integers, ignoring the largest and smallest values

texts:
The code returns the mean of a list of integers, except ignoring the largest and smallest values in the list. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value.  Assume that the list is length 3 or more.

For this problem, as part of my learning, I’ve defined my own functions. Please comment on my variable names, docstrings, readability of code etc. and let me know how you would do it.

from typing import Sequence

def find_length(seq: Sequence) -> int:
    """ Return the number of elements in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_length(numbers)
    6
    """

    count = 0
    for _ in seq:
        count += 1

    return count

def find_min(numbers: Sequence) -> int:
    """ Return the smallest number in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_min(numbers)
    -10
    """

    min_number = numbers[0]

    for number in numbers:
        if number < min_number:
            min_number = number

    return min_number

def find_max(numbers: Sequence) -> int:
    """ Return the biggest number in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_max(numbers)
    0
    """

    max_number = numbers[0]

    for number in numbers:
        if number > max_number:
            max_number = number

    return max_number

def find_sum(numbers: Sequence) -> int:
    """ Return sum of the numbers in a sequence.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_sum(numbers)
    -22
    """

    total = 0

    for number in numbers:
        total += number

    return total

def find_centered_average(numbers: Sequence) -> int:
    """ Return the centered average of a list of numbers.

    >>> numbers = [-10, -4, -2, -4, -2, 0]
    >>> find_centered_average(numbers)
    -3
    """

    max_number = find_max(numbers)
    min_number = find_min(numbers)
    total = find_sum(numbers) - max_number - min_number
    centered_average = total // (find_length(numbers) - 2)

    return centered_average

All of that can be accomplished with either:

(sum(numbers) - max(numbers) - min(numbers)) // (len(numbers) - 2)

Or,

centered_numbers = sorted(numbers)[1:-1]
sum(centered_numbers) // len(centered_numbers))

There must be a number of other ways to do it.


texts: Find allele frequencies at each site for each iteration for each population from FASTA file

texts:
The script takes a FASTA format file in input and outputs the frequencies of each amino acid (A, C, T and G) at each site per population per iteration. The name of each sequence looks like >it0pop1ind0locus0. In this example, this indicates that the sequence that follows is the DNA sequence for the zeroth iteration (it), the first population (pop), the zeroth individual (ind) at the zeroth locus (locus).

My goal (just to restate it) is to get the frequencies of each amino acid (A, C, T and G) at each site per population per iteration.

from __future__ import division
import os
from Bio import SeqIO
import itertools
import re
import sys
os.chdir("/path/to/directory/")

#### ReFormat the data ####

maxit = 1
maxpop = 1
maxind = 1
maxlocus = 1
for pos, i in enumerate(SeqIO.parse("0.0.1.fasta", "fasta")):
    if pos == 0:
        maxsite = len(i.seq)
    v1 = re.findall(r'\d+', i.id)
    v = []
    for val in v1:
        v.append(int(val))
    maxit = max(v[0]+1, maxit)
    maxpop = max(v[1]+1, maxpop)
    maxind = max(v[2]+1, maxind)
    maxlocus = max(v[3]+1, maxlocus)

all = [[[[ "x" * maxsite for locus in xrange(maxlocus)] for ind in xrange(maxind)] for pop in xrange(maxpop)] for it in xrange(maxit)]

for i in SeqIO.parse("0.0.1.fasta", "fasta"):
    v1 = re.findall(r'\d+', i.id)
    v = []
    for val in v1:
        v.append(int(val))
    it = v[0]
    pop = v[1]
    ind = v[2]
    locus = v[3]
    all[it][pop][ind][locus] = str(i.seq)

#### Calculate the frequencies ####

pA = [[[2 for it in xrange(maxsite)] for pop in xrange(maxpop)] for site in xrange(maxit)]
pC = [[[2 for it in xrange(maxsite)] for pop in xrange(maxpop)] for site in xrange(maxit)]
pG = [[[2 for it in xrange(maxsite)] for pop in xrange(maxpop)] for site in xrange(maxit)]
pT = [[[2 for it in xrange(maxsite)] for pop in xrange(maxpop)] for site in xrange(maxit)]

for it in xrange(maxit):
    for pop in xrange(maxpop):
        for locus in xrange(maxlocus):
            for site in xrange(maxsite):
                x = []
                for ind in xrange(maxind):
                    x.append(all[it][pop][ind][locus][site])
                pA[it][pop][site] = x.count("A")/maxind
                pT[it][pop][site] = x.count("T")/maxind
                pC[it][pop][site] = x.count("C")/maxind
                pG[it][pop][site] = x.count("G")/maxind

Here are the values I get:

>>> pA
[[[0.16666666666666666, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.6666666666666666, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0]]]
>>> pC
[[[0.8333333333333334, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 0.6666666666666666, 0.0, 0.0, 0.0, 0.0, 1.0]]]
>>> pG
[[[0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.3333333333333333, 0.0, 1.0, 0.0, 0.0, 0.0]]]
>>> pT
[[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3333333333333333, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]]

Here is the data for the example (FASTA). In this example, we have only 1 iteration (it), 2 populations (pop), 5 individuals (ind), 1 locus (locus) and 9 sites (length of the sequence).

>it0pop0ind0locus0
CGGCAGAAC
>it0pop0ind1locus0
CGGCAGATC
>it0pop0ind2locus0
CGGCAGAAC
>it0pop0ind3locus0
CGGCAGAAC
>it0pop0ind4locus0
CGGCAGATC
>it0pop0ind5locus0
AGGCAGAAC
>it0pop1ind0locus0
CGGCAGAAC
>it0pop1ind1locus0
CGGCAGAAC
>it0pop1ind2locus0
CGGGAGAAC
>it0pop1ind3locus0
CGGCAGAAC
>it0pop1ind4locus0
CGGGAGAAC
>it0pop1ind5locus0
CGGCAGAAC


texts:
My query is this:

UPDATE `phrases`
SET `phrases`.`count`=(SELECT COUNT(*) FROM `strings` WHERE `string` LIKE CONCAT('%', `phrases`.`phrase`, '%'))

My tables look like this:

CREATE TABLE `phrases` (
    `hash` varchar(32) NOT NULL,
    `count` int DEFAULT 0,
    `phrase` text NOT NULL,
     PRIMARY KEY (`hash`),
     KEY(`count`)
)

And

CREATE TABLE `strings` (
    `string` text NOT NULL,
)

phrases has 18,000 rows and strings has 1500 rows.


texts: Refreshing cell values in visible rows of a VirtualMode DataGridView

texts:
I have a DataGridView whose Virtual Mode property is set to True.  When values of the underlying list are updated, those updates are not occurring in the UI unless I scroll vertically.

So I have created a timer which, every 1 second, calls DataGridView.Refresh().  Feels ineffective and overkill.  Is there a better way, taking into consideration the current design of my application?

public partial class ProxyTesterView : UserControl
{
    public List<Proxy> Proxies = new List<Proxy>();
    public List<ProxyJudge> Judges = new List<ProxyJudge>();
    public List<ProxyTest> Tests = new List<ProxyTest>();

    private PauseOrCancelTokenSource pcts = new PauseOrCancelTokenSource();

    public ProxyTesterView()
    {
        InitializeComponent();

        //Fill lists with testing data for debugging purposes.
        for (int i = 0; i < 10000; i++)
        {
            Proxies.Add(new Proxy("127.0.0." + RandomUtility.GetRandomInt(1, 5), 8888));
        }
        ProxiesDataGridView.RowCount = Proxies.Count;

        Judges.Add(new ProxyJudge("http://azenv.net"));
    }

    private void ValidateProxiesButton_Click(object sender, EventArgs e)
    {
        ValidateProxiesMenu.Show(ValidateProxiesButton, new Point(0, ValidateProxiesButton.Height));
    }

    private void AddProxiesButton_Click(object sender, EventArgs e)
    {
        AddProxiesMenu.Show(AddProxiesButton, new Point(0, AddProxiesButton.Height));
    }

    private void RemoveProxiesButton_Click(object sender, EventArgs e)
    {
        RemoveProxiesMenu.Show(RemoveProxiesButton, new Point(0, RemoveProxiesButton.Height));
    }

    private void StartValidatingProxiesMenuItem_Click(object sender, EventArgs e)
    {
        UpdateProxyDGVTimer.Start();
        Task.Run(async () =>
        {
            await ProxyTester.Start(Proxies, Judges, Tests, pcts.Token, 1);
        });
    }

    private void PauseValidatingProxiesMenuItem_Click(object sender, EventArgs e)
    {
        pcts.Pause();
    }

    private void ResumeValidatingProxiesMenuItem_Click(object sender, EventArgs e)
    {
        pcts.Resume();
    }

    private void StopValidatingProxiesMenuItem_Click(object sender, EventArgs e)
    {
        pcts.Cancel();
    }

    private void ProxiesDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
    {
        var proxy = Proxies[e.RowIndex];
        switch (e.ColumnIndex)
        {
            case 0:
                e.Value = proxy.IP;
                break;
            case 1:
                e.Value = proxy.Port;
                break;
            case 2:
                e.Value = proxy.IsValid;
                break;
            default:
                break;
        }
    }

    private void UpdateProxyDGVTimer_Tick(object sender, EventArgs e)
    {
        Console.WriteLine("Timer");
        ProxiesDataGridView.Refresh();
    }
}


texts:
I have been looking at a couple of different approaches on how I can notify the UI about messages coming from the ViewModel, and wanted to see if this seemed appropriate or if it is too coupled. (We already have a static class that deals with notifications that I am trying to wrap for now, and maybe remove at a later time?)

INotifier
{
  void Notify(Notification notification);
}

ConcreteNotifier()
{
  void Notify(Notification notification)
  {
    Notification.ShowMessage(notification.Title, notification.Message, notification.MessageLevel);
  }
}

Main will create ConcreteNotifier and pass it into each View, which will pass it into each VM

ViewModel(INotifier notifier)
{
  _notifier = notifier;
}

DoStuff()
{
  try
  {
  }
  catch(Exception ex)
  {
    _notifier.Notify(new Notification{Title="DoStuff Error", Message=ex.Message, MessageLevel=Error});
  }
}

This seems ok to me, however there is coupling due to the Notification class. This is really just encapsulating parameters, so it is probably ok, but I wanted to run it past some people who are more familiar with MVVM and UI interaction. I only need to talk one way, so the Messenger pattern seems like overkill as I do not need to talk to other VM's, and this seemed like a simplistic way of dealing with this issue.  Can anybody verify that this approach is ok, or if it has some issues with it?


texts: Toggling the background color of a page using JavaScript closures

texts:
This question is to see if I can get some input on the "design pattern" I tried to implement here. I'm just learning about closure in JavaScript and I think I'm starting to get it. I'm wondering if the way I wrote this code is or is not terrible stylistically.

The code in question is attempting to answer a challenge given in the JavaScript: The Hard Parts (by Will Sentance) on Frontend Masters. Based on the challenge, it seems I went above and beyond as the solution provided, when run, doesn't work properly.

The challenge:

  Write a function changeColor that when invoked will first check if the
  current page background color is "rgb(221, 238, 255)". If it is, it
  changes the color to "rgb(255, 238, 221)". If it isn't, it sets the
  color to "rgb(221, 238, 255)".

  Add a click event listener to button #1 above (it has an id of "activate"). On click, the button should log to the console "clicked
  1". It should also set up a click event listener on button #2 (id of
  "color"). That listener should log to console "clicked 2" and then
  call the changeColor function you just created.

  Clear the console and hit the 'Run with JS' button. Look at what code has run by analyzing the console. Then try to change the
  background color by clicking button #2. What needs to happen for the
  button to work?

Based on the wording of the challenge it seemed like the solution that was hinted at was (in pseudo-ish code):

// Provided solution to the question above
// Assume all necessary HTML is in place

activationButton.addEventListener("click", () => {
  console.log("clicked activation button")
  colorChangerButton.addEventListener("click", () => {
    console.log("clicked color changer button")
    changeTheColor()
  })
})

The obvious problem with the code above is that a new event listener will be added to the colorChangerButton every time you click the activationButton. This was where I started thinking about trying to use a closure to keep track of a state variable so that I could make sure that the event listener only gets added to the second button once. Also, this is the solution provided in the solution set for the challenge.

To that end, this is what I came up with (please assume that the correct HTML is there, etc):

(function () {

  let clickCount = 0

  function changeColor() {
    if (document.body.style.backgroundColor === "rgb(221, 238, 255)") {
      document.body.style.backgroundColor = "rgb(255, 238, 221)"
    } else {
      document.body.style.backgroundColor = "rgb(221, 238, 255)"
    }
  }

  function activateButton2() {
    const btn2 = document.querySelector('#color') // Appropriate to grab button here?
    btn2.addEventListener("click", () => {
      console.log("clicked #2")
      changeColor()
    })
  }

  const btn1 = document.querySelector('#activate') // Appropriate to have variable declaration here?
  btn1.addEventListener("click", () => {
    clickCount++
    if (clickCount === 1) {
      activateButton2()
    }
    console.log("clicked #1")
    return
  })
  // Initially had an un-necessary return statement here
})()

The code above - that I wrote - is working how I'd expect it to - the color change functionality and the console logs are firing as I would expect.

One question I had about my implementation was about containing the button variables inside the IIFE. I feel like I see a lot of front-end scripts putting all the query selectors at the top of the script - is there a reason to do that vs. including them within a function like this? If I understand closure correctly, once the event handlers are created there is a persistent reference to everything in the IIFE, so I can fire this function and the buttons and their handlers persist and behave as expected.

It also seems like I could probably use a boolean to track the "clicked" status of the first button, and a switch statement for checking the background color of the page.

Any other pointers anyone wants to offer?


texts:
This is a student module marks calculator that I was asked to write for a uni revision session in year 2.

Is this a good example of modern C++ code? Is there anything I can improve on or need to change to become a better programmer?

#include <iostream>
#include <cstdlib>

float student_results[5][2];

unsigned int input_student_result(unsigned int);

float input_student_weighting(unsigned int);

unsigned int input_exam_result();

float calculate_exam_weighting();

float calculate_module_mark();

int main() {

    // Coursework 1

    for (unsigned int i = 0; i < 4; ++i) {

        student_results[i][0] = input_student_result(i);

        student_results[i][1] = input_student_weighting(i);

    }

    student_results[4][0] = input_exam_result();

    student_results[4][1] = calculate_exam_weighting();

    std::cout << "Module mark = " << calculate_module_mark() << '\n';
    std::cout << '\n';

    system("pause");

    return 0;

}

unsigned int input_student_result(unsigned int n) {

    unsigned int input_validation = 0;

    do {

        std::cout << "Enter coursework " << (n + 1) << " result <0 - 100> = ";
        std::cin >> input_validation;

    } while (!(input_validation >= 1 && input_validation <= 100));

    return input_validation;

}

float input_student_weighting(unsigned int n) {

    float input_validation = 0;

    do {

        std::cout << "Enter coursework " << (n + 1) << " weighting 0.1 or 0.2 = ";
        std::cin >> input_validation;

    } while (!(input_validation == 0.1f || input_validation == 0.2f));

    return input_validation;

}

unsigned int input_exam_result() {

    unsigned int input_validation = 0;

    do {

        std::cout << "Enter exam result <0-100> = ";
        std::cin >> input_validation;

    } while (!(input_validation >= 1 && input_validation <= 100));

    return input_validation;

}

float calculate_exam_weighting() {

    float exam_weighting = (1 - (student_results[0][1] + student_results[1][1] + student_results[2][1] + student_results[3][1]));

    std::cout << "Exam weighting = " << exam_weighting << '\n';

    return exam_weighting;

}

float calculate_module_mark() {

    float module_mark{
            (student_results[0][0] * student_results[0][1]) +
            (student_results[1][0] * student_results[1][1]) +
            (student_results[2][0] * student_results[2][1]) +
            (student_results[3][0] * student_results[3][1]) +
            (student_results[4][0] * student_results[4][1])
    };

    return module_mark;

}


texts: Select items between two dates that are available

texts:
I wrote this MySQL query, but I feel it could be better. I had to get all clients between today and 14 days' time, that have at least one day "free". I have a SQL Fiddle, and there you can see how my schema looks, how my query looks and what it returns.

SELECT cl.id as clientId, a.id as attendantId, ca.id as caringId,
ca.startDate, ca.endDate, a.name as attendantName,
IFNULL(
  SUM(eca.effectiveDays),
  0
) AS `sumDays`
FROM client cl
LEFT JOIN
(
  SELECT ca.id,
  GREATEST(ca.startDate, CURDATE()) as `effectiveStartDate`,
  LEAST(ca.endDate, DATE_ADD(CURDATE(), INTERVAL 14 DAY)) as `effectiveEndDate`,
    DATEDIFF(
      DATE_ADD(LEAST(ca.endDate, DATE_ADD(CURDATE(), INTERVAL 14 DAY)), INTERVAL 1 DAY),
      GREATEST(ca.startDate, CURDATE())
  ) as `effectiveDays`,
  ca.clientId
  FROM caring ca
  WHERE ca.startDate <= DATE_ADD(CURDATE(), INTERVAL 14 DAY)
  AND ca.endDate >= CURDATE()
) eca
ON eca.clientId = cl.id
LEFT JOIN caring ca ON ca.clientId = cl.id
LEFT JOIN attendant a ON a.id = ca.attendantId
GROUP BY cl.id HAVING sumDays < DATEDIFF(DATE_ADD(DATE_ADD(CURDATE(), INTERVAL 14 DAY), INTERVAL 1 DAY), CURDATE())

Here you can see an example of my data:

In the marked period, I have to return John Doe and Steve Smith, because  John Doe has 3 days free in that time span, and Steve Smith has all days free.

How could I improve this query, or is there any better way of getting desired data?


texts: Generic function for loading a function from a DLL library

texts:
I am trying to write a generic function for loading a function from a DLL library. I am in no way an expert on DLLs, that is why I ask.

We have discussed it first in my Stack Overflow question to discover the most obvious errors, and there were some crucial ones.

Current version of my code follows:

function LoadFunctionFromLibrary(const LibraryName, FunctionName: string; out FunctionPointer: Pointer): Boolean;

var
  LibraryHandle: THandle;

begin
  Result := False;
  FunctionPointer := nil;

  LibraryHandle := Winapi.Windows.LoadLibrary(PChar(LibraryName));
  if LibraryHandle = 0 then Exit;

  FunctionPointer := Winapi.Windows.GetProcAddress(LibraryHandle, PChar(FunctionName));

  if Assigned(FunctionPointer) then
    Result := True;
end;

This version of the function has been successfully tested on my EnableInput function:

function EnableInput(const Enable: Boolean): Boolean;

var
  BlockInput: function(Block: BOOL): BOOL; stdcall;

begin
  Result := LoadFunctionFromLibrary('User32.dll', 'BlockInput', @BlockInput) and
            BlockInput(not Enable);
end;


texts:
I created the following program that transforms a numerical month into the corresponding textual month. I initially calculated the starPoint and endPoint in the class constructor; then I changed that calculation to the getName method. Which is a better option? Calculating in the class constructor, or in a separate method like shown in the code?

/**
 * Created by Robert Holland on 25/11/2016.
 *
 * A class that accepts a number and calculates
 * the corresponding month. Once the month has
 * been calculated it will then be returned.
 *
 */

public class Month
{
    public static final String MONTHS = "January   " + "February  " + "March     " +
                                        "April     " + "May       " + "June      " +
                                        "July      " + "August    " + "September " +
                                        "October   " + "November  " + "December  ";
    private int monthNumber;

    //Construct a month class that has a value equal to the numerical month
    //@param uMonthNumber the number of the month to find the correspondance.
    public Month(int uMonthNumber)
    {
        monthNumber = uMonthNumber;
    }

    //Determine the name that corresponds to the month number.
    //@return month the name of the corresponding month.
    public String getName()
    {
        String month;
        int startPoint;
        int endPoint;

        endPoint = monthNumber * 10;
        startPoint = endPoint - 10;
        month = MONTHS.substring(startPoint, endPoint);

        return month;
    }
}


texts:
This script extracts all urls from a specific HTML div block (with BeautifulSoup 4) :

raw_data = dl("http://somewhere")
links = []
soup = BeautifulSoup(raw_data)
data = str(soup.find_all('div', attrs={'class' : "results"}))
for link in BeautifulSoup(data, parse_only = SoupStrainer('a')):
    links.append(urllib.parse.unquote_plus(link['href']))
return links

Is there a more efficient and clean way to do it ?


texts: Sieve of Eratosthenes JavaScript implementation - performance very slow over a certain number

texts:
I've been playing around with the code challenges on projecteuler.net. A few of them involve prime numbers, so I've created a function to find them based on the sieve of Eratosthenes.

It works fine, and is reasonably quick for small numbers, but much slower for the challenges that involve the larger numbers, like 2million. So to try to improve my function I tested it to see how the performance changes and discovered that the time it takes to run shoots up dramatically at a specific number, not gradually as you might expect.

I'm running this on the chrome dev tools. It consistently takes about 1.5 seconds for 354,957 and 15 seconds for 354,958. I found this very odd and was wondering if anyone had experienced similar or new why this might be?

Below is my code. I know it's not perfect and there a much (much) quicker implementations out there.

function getPrimesUnder(number) {
  var start = new Date().getTime();

  var numbers = [2];
  var sqNum = Math.sqrt(number);
  var i, x;
  for (i = 3; i < number; i = i + 2) {
    numbers.push(i);
  }
  for (x = 0; numbers[x] < sqNum; x++) {
    for (i = 0; i < numbers.length ; i++){
       if (numbers[i] > numbers[x]) {
        if(numbers[i] % numbers[x] === 0){
          numbers.splice(i, 1)
        }
      }
    }
  }
  var end = new Date().getTime();
  var time = end - start;
  alert('Execution time: ' + time/1000 + ' seconds');
  return numbers;

}


texts:
I know there is a lot of libraries with this built in $.get() etc... but as for writing this in pure JavaScript how does this look?

var get_request;

ajaxRequest(function() {
    var activexmodes, i, _i, _len, _ref, _results;
    activexmodes = ['Msxm12.XMLHTTP', 'Microsoft.XMLHTTP'];
    if (window.ActiveXObject) {

        _ref = activexmodes.length;
        _results = [];

        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            i = _ref[_i];
            try {
                _results.push(new ActiveXObject(activexmodes[i]));
            } catch (_error) {}
        }
        return _results;
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return false;
    }
});

get_request = new ajaxRequest();


texts: Count the accumulated rainfall in a 2D mountain range

texts:
Challenge:

  Count how much rain will be collected in the valleys between the peaks
  of a mountain range in a 2D world.

  The mountain range is defined by a single array of positive ints,
  where each element defines the height a peak. IE the array [1,2,1,2]
  would create the 2D slice:

 . m . m
 m m m m

m = mountain
. = open space

  As the rain falls, it will fill up to the height of its surrounding
  peaks, then overflow. If the rain reaches the edge of the grid, it
  disappears. In this case the amount of water collected will be 1:

 . m r m
 m m m m
 r = rain

  More examples:

  Input: [2, 4, 2, 2, 5, 1, 2, 2, 1, 3]

  Output: 10

  2D visualization:

. . . . m . . . . .
. m r r m . . . . .
. m r r m r r r r m
m m m m m r m m r m
m m m m m m m m m m

  Input: [1, 2, 3, 2, 1]

  Output: 0

  2D visualization:

. . m . .
. m m m .
m m m m m

Constraints:

The input array will have size at least 1
Each element of the array will be greater than or equal to 1
Must be in Java 7

My Code:

//Time Complexity: worst case O(n^2)?
//Space Complexity: O(1)
public class Solution
    public static int solution(int[] heights) {
       int fillCount = 0, minHeight = heights[0];

       for(int i = 1; i<heights.length; i++){
           if(heights[i] < minHeight){
               minHeight = heights[i];
           }
           else{
               minHeight=heights[i];
               int fillHeight = findFillHeight(heights, i);
               if(fillHeight == -1) continue;
               fillCount+= fillIn(heights, fillHeight, i);
           }
       }

       return fillCount;
    }

    static int findFillHeight(int[] heights, int rightEdgePosition){
        int maxHeight = -1, j=0;

        for(int i=rightEdgePosition-1; i-1 >=0 && heights[i] < heights[rightEdgePosition]; i--, j=i){
            if(heights[i] >= heights[rightEdgePosition]){
                return heights[rightEdgePosition];
            }
            if(heights[i] > maxHeight){
                maxHeight = heights[i];
            }
        }

        if(heights[j] >= heights[rightEdgePosition]){
            maxHeight = heights[rightEdgePosition];
        }

        return maxHeight;
    }

    static int fillIn(int[] heights, int fillInHeight, int startHeightPosition){
        int fillCount = 0;
        for(int i=startHeightPosition-1; heights[i] < fillInHeight; i--){
            fillCount+= fillInHeight-heights[i];
            heights[i]=fillInHeight;
        }
        return fillCount;
    }
}

The idea is to search the array from left to right, looking for rises in elevation. When we find one, we backtrack looking for how high up we can fill the valley, and then redo the backtrack, this time actually filling it (this prevents "double filling" in future elevation rises).

The worst case arises when we get a large elevation on element 1 and elements 2 through n are rising from 1 to the value of element 1. IE [10, 1, 2, 3.... 10]. In this case we do the maximum number of backtracks. If I have my math right, our time complexity would be

$$n + \sum_{i=0}^{n} {i}\ = n+\frac{1}{2}n(n+1) \implies O(n^2)$$

So quadratic time obviously a red flag, but I'm not sure I can avoid it since I'm dealing with 2D arrays. Other than that, the big ugly part is the j variable in findFillHeight(). The point of it is to check that the left edge we end the loop on is properly checked. The last notable issue is that much of this code would be very risky if run on its own because the assumption is that all inputs are valid. This was due to time constraints though, so I don't consider it an issue.


texts:
I have a MongoRepository:
@Repository
public interface GooglePlayGameRepository extends MongoRepository<GooglePlayGame, String> {

    Optional<GooglePlayGame> findByTitle(String title);

    List<GooglePlayGame> findByTitleContainsIgnoreCase(String title);

    @Aggregation("{$sample: {size: ?0} }")
    List<GooglePlayGame> findRandomGames(Long number);

}

And service:
@Service
public class GooglePlayGameService {

    private final GooglePlayGameRepository googlePlayGameRepository;

    public GooglePlayGameService(GooglePlayGameRepository googlePlayGameRepository) {
        this.googlePlayGameRepository = googlePlayGameRepository;
    }

    public void saveToLibrary(GooglePlayGame googlePlayGame) {
        googlePlayGameRepository.save(googlePlayGame);
    }

    public GooglePlayGame getGameByTitle(String title) throws NoSuchGooglePlayGameFoundException {
        Optional<GooglePlayGame> googlePlayGame = googlePlayGameRepository.findByTitle(title);
        return googlePlayGame.orElseThrow(
                () -> new NoSuchGooglePlayGameFoundException("Game was not found: " + title)
        );
    }

    public List<GooglePlayGame> findByTitle(String title) {
        List<GooglePlayGame> googlePlayGames = googlePlayGameRepository.findByTitleContainsIgnoreCase(title);
        return googlePlayGames.isEmpty()
                ? Collections.emptyList()
                : googlePlayGames;
    }

    public Long getLibrarySize() {
        return googlePlayGameRepository.count();
    }

    public List<GooglePlayGame> getRandomGames(Long number) {
        return googlePlayGameRepository.findRandomGames(number);
    }

}

What do you think about methods getGameByTitle (returns exact match) and findByTitle (looking for similar matches by title)? Is it good practice to handle Optional in Service layer and just throws Exception? Or should I use Optional as a return type in Service layer too and handle it in other places which will use this service?
About findByTitle: is it necessary to use this construction?
googlePlayGames.isEmpty()
          ? Collections.emptyList()
          : googlePlayGames;

Maybe I should just check it in code like this (not in the service):
if (googlePlayGames.isEmpty()){
   log.error("Game {} doesn't exist in library", title);
}

I have another variant for these methods:
public GooglePlayGame getGameByTitle(String title) throws NoSuchGooglePlayGameFoundException {
    return findByTitle(title).stream()
             .findFirst()
             .orElseThrow(NoSuchGooglePlayGameFoundException::new);
 }

public List<GooglePlayGame> findByTitle(String title) {
     List<GooglePlayGame> games = googlePlayGameRepository.findByTitleContainsIgnoreCase(title);
     if (!games.isEmpty()) {
         return games;
     }
     return Collections.emptyList();
 }

Which one is better?


texts:
This seems to work for me, but I want to make it more secure. I want to see how far I can go without pre-built packages/bundles, so please don't suggest any.

How secure is this? What are some steps I can take to improve it?

In a controller:

public function loginUser($request, $response) {
    if (Security::isUser()) { return $this->redirect('home'); }
    $username = $request->getParam('username');
    $password = $request->getParam('password');
    $user = Security::authenticate($username, $password);
    if ($user) {
        Security::login($user->id);
        return $this->redirect('home');
    } else {
        $this->flash->addMessage('error', 'Invalid username and/or password.');
        return $this->redirect('login');
    }
}

Here is part of the Security class:

public static function hash($string) {
    return password_hash($string, PASSWORD_DEFAULT);
}

public static function authenticate($username, $password) {
    $user = User::where('username', $username)->orWhere('email', $username)->first();
    if (password_verify($password, $user->password) && $user->banned === 0) { return $user; }
    else { return false; }
}

public static function getUser() {
    if (isset($_SESSION['uid'])) {
        $user =  User::where('id', $_SESSION['uid'])->first();
        if ($user->banned === 1) { return false; }
        else { return $user; }
    } else { return false; }
}

public static function isUser() {
    if (!self::getUser()) { return false; } else { return true; }
}

public static function isAdmin() {
    $user = self::getUser();
    if (!$user) { return false; }
    else if ($user->role === 'admin') { return true; }
    else { return false; }
}

public static function login($uid) {
    session_regenerate_id();
    $_SESSION['uid'] = $uid;
}

public static function logout() {
    session_unset();
    session_destroy();
}

Then, to secure something:

public function loginUser($request, $response) {
    if (!Security::isUser()) { // or use ::isAdmin()
        // deny access
    }
    // allow access
}

Csrf tokens are checked by Slim's Guard. This is all over https.


texts:
I have this method in my rails app:

def find_or_create_session(fbid)
    @sessions = Session.all
    if @sessions.find_by facebook_id: fbid
      @session = @sessions.find_by facebook_id: fbid
      if ((Time.now - @session.last_exchange).fdiv(60)).to_i > 5
        @session = Session.create(facebook_id: fbid, context: {})
      end
    else
       @session = Session.create(facebook_id: fbid, context: {})
    end
    @session
end

It retrieves all the Sessions, and tries to find one with a given facebook_id. If there is one, it checks if it's a recent one (last_exchange was less than 5 minutes ago). If it's not, it creates a new one.

If it can't find a session for this facebook_id, it will create one.

This is pretty easy, but it seems to be a lot of if/else for such a straightforward thing.


texts: Generate random string to match the goal string with minimum iteration and control statements

texts:
The following is my python code to find the number of iterations needed to generate random string iteratively to match the input string.
Here I have repeated a similar kind of for loop in both the functions getRandomString() and getMatchString(). I tried to avoid it but couldn't. I want this to be combined together into a single generateString() function with minimum iteration statements. Any suggestions to make it so or any other possible way to make the code better without complicating much?
The input is any string statements like "Hello, World! How Are Y@u doiNG?" and the output is the number of iterations needed to match the input string e.g 408. Your suggestions to improve the code will be helpful.
import random

goalString = input()
stringLen = len(goalString)

alphanum = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–[{}]:;‘,'?/*1234567890'''
alphaLen = len(alphanum)

def getRandomString():
    randomString = ''
    for i in range(stringLen):
        randomString = randomString + alphanum[random.randrange(alphaLen)]

    return randomString

def getMatchString():
    betterString = getRandomString()
    newString = ''
    iteration = 1 #included the iteration of generating randomString
    while betterString != goalString:
        charIndex = [i for i in range(stringLen) if betterString[i] == goalString[i]]
        for i in range(stringLen):
            if i in charIndex:
                newString = newString + betterString[i]
            else:
                newString = newString + alphanum[random.randrange(alphaLen)]

        betterString = newString
        newString = ''
        iteration = iteration + 1

    return iteration

print(getMatchString())

Sample Input: "Hello, World! How Are Y@u doiNG?"
Sample Output: 408   ##May change depending on the random iteration##


texts: Validating user credentials and logging into a Symfony site

texts:
I have the following code in a Symfony site that validates a user's credentials and logs them in via the Session class:

/**
 * Validates an Affiliate
 */
public function validateUser($username, $password, $session, $securityContext)
{
    $repo = $this->em->getRepository('JCMainBundle:Affiliate');
    $user = $repo->findOneBy(["username" => $username]);

    if (!is_object($user)) return false;

    $passwordValidated = password_verify($password, $user->getPassword());

    if (!$passwordValidated) return false;

    // Create token for user
    $token = new UsernamePasswordToken($user, null, "affiliate_dashbaord", ['ROLE_AFFILIATE']);
    $securityContext->setToken($token);
    $session->set('_security_affiliate_dashboard', serialize($token));

    return true;
}

As you can see, the function has very simple return values--just booleans. The function that calls this function looks at the return value of this function and determines whether or not to redirect the user to the affiliate dashboard.

How can I handle the return values better? I have two possible paths than can return false, but the calling function will have no idea what caused "false" to be returned.

In the past I've done something like this:

$response = ["success" => false, "message" => "error message here"];

I return the response with the success and a message. Using this design, I can return false AND return what made it return false. However, this seems a bit unorthodox for use on the backend and seems to fit more in a REST API.

I could use an exception, but the role of the function is to validate, so it wouldn't make sense to throw an exception if the user credentials are incorrect.


texts:
My history of C/ASM locks here in codereview:

Simple spinlock for C using ASM
Simple spinlock for C using ASM, revision #1 (basis for this approach. If this one fails, then so will the one below.)

Once you have gotten taste of assembly, there is no turning back. I don't care if I
am not ready/worthy, I going to step things up a bit and be a little bit more adventures.
So I went ahead and made a lock that I hope is able to handle recursions.
I will without a doubt fail very painfully and the mistake is also going to be hard to spot.
No, I am not pessimistic. Just like gravity works to put things down, so does my reasoning skills to me.
It is up to you to give me tough love and spot my faulty reasoning and throw bananas at me!

The code in question.

// "gate_" is the namespace marker for higher level languages that might import this code... as if...
#define gate_Gate volatile int
#define gate_Pass volatile int

extern inline void
gate_Enter
(gate_Gate *gate, gate_Pass *pass)
{
    asm volatile (
        "jmp gate_Enter_check\n"     // Skip the line.
        "gate_Enter_wait:\n"         // Wait in line.
        "pause\n"                    // Wait a long time.
        "gate_Enter_check:\n"        // Now we are at the gate.
        "cmp %[lock], %[checkin]\n"  // See if our pass is any good.
        "jge gate_Enter_skip\n"      // Skip if pass >= lock.
        "mov %[lock], %%eax\n"       // eax = 1.
        "lock xchg %%eax, %[gate]\n" // Attempt to validate our pass and connect it to the gate.
        "test %%eax, %%eax\n"        // Hope for the best.
        "jnz gate_Enter_wait\n"      // There is no hope, go back in line.
        "gate_Enter_skip:\n"         // We are VIP!
        "add %[lock], %[checkin]\n"  // Checkin pass like pro!
        : [gate] "=m" (*gate), [checkin] "=m" (*pass)
        : [lock] "r" (1)
        : "eax"
    );
}

extern inline void
gate_Leave
(gate_Gate *gate, gate_Pass *pass)
{
    asm volatile (
        "cmp %[pass], %[isLast]\n"   // Have I checked in only once?
        "jg gate_Leave_skip\n"       // Skip next step if I have checked in more then once.
        "mov %[unlock], %[gate]\n"   // Close the gate because I am the last one to leave.
        "gate_Leave_skip:\n"         // Comment!
        "add %[checkout], %[pass]\n" // Checkout. This may or may not be the last time.
        : [gate] "=m" (*gate), [pass] "=m" (*pass)
        : [unlock] "r" (0), [checkout] "r" (-1), [isLast] "r" (1)
    );
}

// Example use
gate_Gate gate = 0;
gate_Pass exampleUsePass = 0;
void exampleUse(int count)
{
    printf("pass=%d\n", exampleUsePass);
    gate_Enter(&gate, &exampleUsePass);
    if (count == 3) {
        // exampleUsePass = 0; // force deadlock.
    }
    if (count < 5) {
        printf("Count = %d\n", count);
        exampleUse(++count);
    }
    gate_Leave(&gate, &exampleUsePass);
    printf("pass=%d\n", exampleUsePass);
}

exampleUse(0);

The question

The intent of this code is a lock that allows recursion.
Will this lock make exampleUse both threadsafe and reentrant if we allow our self to assume the pass, exampleUsePass is only used for that function?

If not? what is wrong?
If yes, it is still wrong; isn't it?... Give me a good rant about what to consider, what is missing or about better approach. If you want to suggest libraries, please restrict your self to C. I am not experienced enough to bind C++ stuff to other languages, so I often can't use the good stuff over there :'(


texts:
I'm making an app that creates pdfs of images layed out in a grid. I know the size of each grid element and how many fit on a page, it works out to a 5x6 grid.
The syntax is not the real focus, but the logic for how I determine when to start a new row or page.

const pageconstants = {
 grid:{
   x: 5,
   y: 4,
 }
}

const griditems = []//an array containing 35 elements

const doc = new PDFDocument(
    {
        layout : 'portrait',
        width: 612,
        height: 792,
        autoFirstPage: false
    }
);

let gridx = 0;
let gridy = 0;
let pagenum = 1;

createNewPage(doc);//create new page and elements like header and footer

griditems.forEach((item) => {
    var x = 100 * gridx;//The actual equation has more parts, I'm simplifying here
    var y = 100 * gridy;

    addGridItem(doc, { x: x, y: y }, item)//places the image on the grid

    if( gridx == pageconstants.grid.x ){
      gridx = 0;

      if( gridy == pageconstants.grid.y ){
        subjecty = 0;
        pagenum++;
        createNewPage(doc)
      }
      else{
        subjecty++;
      }
    }
    else{
      subjectx++;
    }
})

So basically, it checks if the current gridx has reached the max of 5 (6 because it starts at zero), and if so, resets gridx, and increments gridy to start the next row.

If gridy reaches it's maximum, gridx and gridy are reset and a new page is created again, so it can go again until there are no items left.
This all works, but it feels really word, I really hate having nested if's like this, and incrementing all these numbers. Is there a more elegant way to achieve this?


texts: Multithreaded non-blocking tiny echo server

texts:
I wrote this code to make a non-blocking server without using select(), my main concern is to catch as many exceptions as possible for worst case scenarios (so I would appreciate some feedback on cases I missed), and to let each client to be handled separately by its own thread.

Any feedback on style/performance/good or bad coding practice is welcome.

import socket
import logging
import threading
import sys

class EchoServer:
    BUFFER_SIZE = 1024

    # size limit in bytes for the client message to be received
    MAX_MSG_SIZE = 1024 * 5

    # this maps connected clients socket objects returned from accept() to their address tuple
    connected_clients = {}

    def __init__(self, port):
        self.hostname = 'localhost'
        self.port = port

        try:
            self.sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sockfd.bind((self.hostname, self.port))
            self.sockfd.listen(10)
            self.sockfd.setblocking(False)

        except socket.error as e:
            logging.critical(e)
            logging.critical('Could not start up server. Exiting.')
            sys.exit(-1)

    def look_for_connections(self):
        while True:
            try:
                client_connfd, client_addr = self.sockfd.accept()
                logging.info('Connection from client {!r}'.format(client_addr))
                self.connected_clients[client_connfd] = client_addr

                client_handling_thread = threading.Thread(target=self.handle_client, args=(client_connfd,))
                client_handling_thread.start()

            except BlockingIOError:
                # no active clients trying to connect, nothing to do
                continue

    def handle_client(self, connfd: socket.socket):
        msg = self.get_client_msg(connfd)
        logging.info('Client: {} sent {} bytes.'.format(self.connected_clients[connfd], len(msg)))

        sent_bytes_size = self.send_client_msg(connfd, msg)
        logging.info('Server sent {} bytes to client: {!r}'.format(sent_bytes_size, self.connected_clients[connfd]))

        del self.connected_clients[connfd]
        connfd.close()

    def startup_server_loop(self):
        # this starts the main event loop (accepting connections from client)
        # each client get handled by its own thread
        server_thread = threading.Thread(target= self.look_for_connections)
        server_thread.start()

    def get_client_msg(self, connfd: socket.socket):
        data = b''

        while True:
            try:
                buffer = connfd.recv(self.BUFFER_SIZE)
                if len(buffer) == 0 or len(data) >= self.MAX_MSG_SIZE:
                    break
                else:
                    data += buffer
            except BlockingIOError:
                break
        return data

    def send_client_msg(self, connfd: socket.socket, msg: str):
        sent_bytes = 0
        total_bytes = len(msg)
        total_sent = 0

        if len(msg) == 0:
            return total_sent

        while True:
            try:
                sent_bytes = connfd.send(msg[sent_bytes: total_bytes])
                total_sent += sent_bytes

                if sent_bytes == 0:
                    return total_sent
            except BlockingIOError:
                return total_sent

            # in case client disconnected before sending the echo
            except ConnectionResetError:
                logging.info('Client {!r} disconnected before sending echo.'.format(self.connected_clients[connfd]))
                return total_sent

    def __del__(self):
        for client in self.connected_clients.keys():
            del self.connected_clients[client]
        self.sockfd.close()

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    my_server = EchoServer(50000)
    my_server.startup_server_loop()


texts:
I want to go more in depth, but this is the 'boilerplate'.

Is there any way I can optimize this or use more idiomatic Python code?

#Luhn algorithm - distinguish valid numbers from mistyped or incorrect numbers.
def checkNumber(cc_number=''):
    sum_ = 0
    parity = len(cc_number) % 2
    for i, digit in enumerate([int(x) for x in cc_number]):
        if i % 2 == parity:
            digit *= 2
            if digit > 9:
                digit -= 9
        sum_ += digit
    return sum_ % 10 == 0

def main():
    number = input('Input credit card number: ')

    if 12 < len(number) < 17:
        first_two = number[0:2]
        first_four = number[0:4]

        vendor = None
        if number[0] == 4:
            vendor = 'Visa'
        elif number[0] == '5' and '0' < number[1] < '6':
            vendor = 'Mastercard'
        elif number[0] == '6' or first_four == '6011':
            vendor = 'Discover'
        elif first_two in ('36', '38'):
            vendor = "Diners Club"
        elif first_two in ('34', '37'):
            vendor = 'American Express'

        if vendor is not None:
            if checkNumber(number):
                print(f'This is a valid {vendor} credit card!')
            else:
                print(f'This is not a valid {vendor} credit card.')
        else:
            print('Unknown vendor.')
    else:
        print('Sorry, this is not a valid credit card number!')

print(checkNumber('12345'))


texts: Tracking when a column was last modified using a trigger (in SQL Server)

texts:
How can I improve the following code to track when an Azure SQL Database column value was last modified?

IF UPDATE([UserId]) AND EXISTS (SELECT [UserId] FROM inserted EXCEPT SELECT [UserId] FROM deleted)
BEGIN
    UPDATE [MyTable] SET [UserIdModified] = SYSUTCDATETIME() FROM [inserted] WHERE [MyTable].[Id] = [inserted].[Id]
END

Does it make sense (from clarity, readability or performance point-of-view in your opinion) to include the (extra) UPDATE([UserId]) in the beginning of the IF clause, as opposed to only using EXISTS?

IF EXISTS (...)
BEGIN
...
END

UPDATE could clarify things out for a reader (e.g. the script will run only when [UserId] is included) but on the other hand it is redundant (perhaps without real benefits).

I built upon David Coster's answer from here.

Testing things out:

DROP TABLE IF EXISTS [MyTable]
GO
CREATE TABLE [MyTable] ([Id] INT IDENTITY NOT NULL PRIMARY KEY, [UserId] INT, [UserIdModified] DATETIME2)
GO
CREATE TRIGGER [trgMyTableUserIdModified]
ON [MyTable]
AFTER INSERT, UPDATE
AS
BEGIN
    IF UPDATE([UserId]) AND EXISTS (SELECT [UserId] FROM inserted EXCEPT SELECT [UserId] FROM deleted)
    BEGIN
        UPDATE [MyTable] SET [UserIdModified] = SYSUTCDATETIME() FROM [inserted] WHERE [MyTable].[Id] = [inserted].[Id]
    END
END
GO
INSERT INTO [MyTable] ([UserId]) VALUES (1)
SELECT * FROM [MyTable]

WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = 2
SELECT *, 'Updated.' [Time should be] FROM [MyTable]

WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = 2
SELECT *, 'Same as above.' [Time should be] FROM [MyTable]

WAITFOR DELAY '00:00:00.010'
UPDATE[MyTable] SET [UserId] = NULL
SELECT *, 'Updated.' [Time should be] FROM [MyTable]

WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = NULL
SELECT *, 'Same as above.' [Time should be] FROM [MyTable]

WAITFOR DELAY '00:00:00.010'
INSERT INTO [MyTable] ([UserId]) VALUES (1)
SELECT *, 'Same as above for 1st element.' [Time should be] FROM [MyTable]

WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = 2 WHERE [Id] = 2
SELECT *, 'Updated only for the 2nd element.' [Test] FROM [MyTable]

The above test code prints out:


texts: Ruby install script; packages+installs as a .deb or .rpm from source

texts:
Is this bad practice?  Also, how can it be improved?

#!/usr/bin/env bash

RUBY_VERSION=2.1.0
printf "Installing Ruby $RUBY_VERSION\\n"

if [ -d ruby_build ]; then
    rm -Rf ruby_build
fi

if [[ `command -v ruby` && `ruby --version | colrm 11` == "ruby $RUBY_VERSION" ]] ; then
    echo "You already have this version of Ruby: $RUBY_VERSION"
    exit 113
fi

sudo apt-get build-dep -y ruby1.9.1

mkdir ruby_build && cd ruby_build
curl -O "http://ftp.ruby-lang.org/pub/ruby/2.1/ruby-$RUBY_VERSION.tar.gz"
tar xf "ruby-$RUBY_VERSION.tar.gz"
cd "ruby-$RUBY_VERSION"

./configure
make

sudo checkinstall -y --pkgversion "$RUBY_VERSION" --provides "ruby-interpreter" --replaces="ruby-1.9.2"
cd ../.. && rm -Rf ruby_build


texts:
Please tell me ways I can improve this code to be more efficient.

#Moving Character in 2D Plane
'''
Made by a beginner
'''
arena = [] # This is a map file

def make_board(place): #Generates map terrain
    for i in range(5):
        place.append(["O"] * 5)

def list_to_string(alist): #Makes map easier to read
    for i in alist:
        print(" ".join(i))

make_board(arena) #Calling the function

prev_char_y = 2 # Keeping track of player's last movement
prev_char_x = 2 #Keeping track of player's last movement
char_y = 2 #Keeping track of player's current movements
char_x = 2 #Keeping track of player's current movements
arena[char_x][char_y] = "X" #What is used to show player pos.
list_to_string(arena) #Shows map with player
go = True # Loop :)
while True:
    try:
        while go:
            print("You are: \nX") #Remind player where he or she is (\n means new line)
            control = input("Move left, right, up, down, or stop?") #Ask what player wants to do
            control = control.lower() #Converts player input to lowercase
            if control == "left": #If left
                char_x = char_x - 1
            elif control == "right":# If right
                char_x = char_x + 1
            elif control == "up": #If up
                char_y = char_y - 1
            elif control == "down": #If down
                char_y = char_y + 1
            elif control == "stop": #If player wants to stop
                go = False
            elif control is not "left" or control is not "right" or control is not "down" or control is not "up":
                print("Please enter a proper direction") #If it's not one of those commands
            arena[prev_char_y][prev_char_x] = "O" #Removes previous player position marker
            arena[char_y][char_x] = "X" #Adds current player position marker (Y, X) instead of (X, Y)
            prev_char_y = char_y #Sets the previous y to the current y
            prev_char_x = char_x #Sets the previous x to current x
            list_to_string(arena) #Prints map
    except IndexError:
        print("That's out of range, please pick somewhere else to move")
        char_y = prev_char_y
        char_x = prev_char_x
        arena[char_y][char_x] = "X"
        list_to_string(arena)


texts: How to parse a collection of objects in Backbone?

texts:
In my Backbone.Collection I need to parse the response before to render it in Backbone.View.  The following code works, but it will be great to have some suggestions:

// response is array of object
// [{id:1, prop: null },{id:2, prop: "bar" }]

// the output parsed_response can be
//[{id:1, prop: null, isProp: true },
// {id:2, prop: "bar", isProp: false }]

parse: function(response)
{
    var parsed_response;

    parsed_response = _(response).clone();

    var parsed_response = _.map(parsed_response, function (obj) {
        return function (_obj) {
            if (_obj.prop === "" || typeof _obj.prop === "null" ) {
                _obj.isProp = false;
            }
            else {
                _obj.isProp = true;
            }
            return _obj;
        }(obj)
    });

    return parsed_response;
}

My questions are:

Is there a way to improve the code?  Also renaming the name of variables to make it more clear.
Since this code should be reused from other collections, what is the best way to generalise it?


texts:
I'm trying to protect the password login for a website against automated guessing. After too many failed attempts from an IP address, it presents a mandatory CAPTCHA test to the user.

The class is supposed to not forgive the source completely after a successful login attempt, and the more failed attempts the more penalties.

Are there any logic or lock fails here?

public class BruteforceProtector
{
    const int max_log_per_source = 20;
    private ConcurrentDictionary<string, LinkedList<DateTimeOffset>> requests;

    public BruteforceProtector()
    {
        requests = new ConcurrentDictionary<string, LinkedList<DateTimeOffset>>();
    }

    public bool isBlocked(string source, int limit)
    {
        LinkedList<DateTimeOffset> list;
        var haslist = requests.TryGetValue(source, out list);

        if (!haslist)
            return false;

        lock (list)
        {
            removeOld(list);

            return list.Count > limit;
        }
    }

    public void ForgiveSource(string source)
    {
        LinkedList<DateTimeOffset> list;
        if (!requests.TryGetValue(source, out list))
            return;

        lock (list)
        {
            if (list.Count > 0)
                list.RemoveLast();
        }
    }

    public void HandleRequest(string source, int limit, out bool blocked)
    {
        blocked = true;
        bool haslist = true;

        var list = requests.GetOrAdd(source, (x) =>
        {
            var newlist = new LinkedList<DateTimeOffset>();
            newlist.AddLast(DateTimeOffset.Now);
            haslist = false;
            return newlist;
        });

        if (!haslist)
        {
            blocked = false;
            return;
        }
        else
        {
            lock (list)
            {
                list.AddLast(DateTimeOffset.Now);

                removeOld(list);

                if (list.Count > max_log_per_source)
                    list.RemoveFirst();

                blocked = list.Count > limit;
            }
        }
    }

    private void removeOld(LinkedList<DateTimeOffset> list)
    {
        if (list.Count < 1)
            return;

        var oldest = list.First.Value;
        while (oldest.AddHours(list.Count) < DateTimeOffset.Now)
        {
            list.RemoveFirst();

            if (list.Count > 0)
                oldest = list.First.Value;
            else
                break;
        }
    }
}


texts: Random temp folder implementation for unit testing

texts:
I faced a series of problems when unit testing a tool of mine that generates files. They were caused by me putting the files in the same temporary folder and the tests running in parrallel.

Here is an exemple of the unit tests (for @shanif)

public class OutputWriterTests
{
    [Fact]
    public async Task WriteToDirectoryAsync()
    {
        using var tempFolder = new TempFolder();
        var fileWriter = new OutputWriter(tempFolder.Folder);
        var fileCount = tempFolder.Folder.GetFiles().Length;

        await fileWriter.WriteAsync("toto").ConfigureAwait(false);

        Assert.Equal(fileCount + 1, tempFolder.Folder.GetFiles().Length);
    }

    [Fact]
    public async Task AppendToFileAsync()
    {
        using var tempFolder = new TempFolder();
        var testFile = new FileInfo(Path.Combine(tempFolder.Folder.FullName, "test"));
        var fileWriter = new OutputWriter(testFile);

        await fileWriter.WriteAsync("toto").ConfigureAwait(false);

        var text = File.ReadAllText(testFile.FullName);
        Assert.Equal("toto\r\n", text);
    }
}

As a result I created this simplistic class that handles the creation and deletion of a temporary folder. As it implements IDisposable it's meant to be used inside a using block, or manually disposed.

public class TempFolder : IDisposable
{
    public DirectoryInfo Folder;

    public TempFolder(string prefix = "TempFolder")
    {
        var folderName = prefix + new Random().Next(1000000000);
        Folder = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), folderName));
    }

    public void Dispose()
    {
        Directory.Delete(Folder.FullName, true);
    }
}


texts: Accurately calculating gravity for large systems

texts:
I'm in the middle of a program to simulate gravity between particles for > 50000 particles. It works so far, but the way I calculate gravity seems to be a tad askew. Generally, it works. It fails when particles get too close (distance between them approaching 0, gravitational force approaching infinity). I believe this is because of how the implementation chunks up time. It can only calculate the gravity between frames, and I can shorten the time between frames but the problem still exists.

Here's the implementation:

//The time between frames
static final double planc = 0.002;

//Calculates distance^2 between two particles
public double d2(Particle p) {

    return (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y);

}

//Gets Vector from on particle pointing to the next
public Vector getVec(Particle p) {

    return new Vector(p.x - x, p.y - y);

}

//The function that actually (independently) moves the particles according
//to the forces acting on them
public void move() {

    //v is a Vector that represents the force (not acceleration)
    //acting on the particle
    x += v.dx * planc / m;
    y += v.dy * planc / m;

}

//Actually calculates gravity
public boolean grav(Particle p) {

    double d2 = d2(p);

    //Happens once because of how the function is used (unimportant)
    if (d2 == 0)
        return false;

    //-1000 is the G value
    double f = -1000 * m * p.m / d2;

    //Creates acceleration-vectors
    Vector v = getVec(p);
    v.normTo(f * planc, Math.sqrt(d2));//sets v's magnitude to f * planc. 2nd parameter saves a calculation
    //Basically formats a vector which represents gravitational acceleration

    //"adds" force-vector to both particles
    this.v.sub(v);
    p.v.add(v);

    return false;

}

This is fast but sacrifices accuracy. Is there a better way to calculate gravity for large n-body systems (that doesn't screw over performance)?


texts: Given an index return item from opposite end of list

texts:
Given the following code:

namespace AtBash
{
  class Program
 {
    static List<string> letters = new List<string> {
        "Aleph", "Beis", "Gimmel", "Daled", "Hei", "Vav", "Zayin", "Chies", "Teis",
        "Yud", "Chof", "Lamed", "Mem", "Nun", "Samech", "Ayin", "Pei", "Tzadik",
        "Kuf", "Reish", "Shin", "Taf"
    };
    static string AtBash(int index) => letters[Math.Abs((index + 1) - letters.Count)];

    static void Main(string[] args)
    {
        foreach (var item in letters)
        {
            Console.WriteLine(letters.IndexOf(item));
            Console.WriteLine($"{item} -> {AtBash(letters.IndexOf(item))}");
        }
    }
  }
}

Where the purpose is:

  Given an index (say 0) return the corresponding item from the other end of the array (for our example 22).

This is the part of the code that actually does anything:

static string AtBash(int index) => letters[Math.Abs((index + 1) - letters.Count)];

The code works but I am interested in knowing if it can be made faster/more efficient. I would also like to know if there is an official term for this kind of algorithm.


texts:
I have this problem:
Given a String of any length, return a new String where the last 2 chars, if present, are swapped. My question is, is there a more delicate way to do this than this way:

public String lastTwo(String str) {
   if(str.length() < 2 || str.equals("")){
      return str;
   }
   String lastTwo = str.substring(str.length() - 2);
   StringBuilder sb = new StringBuilder(lastTwo);
   String lastTwoReversed = sb.reverse().toString();
   return str.substring(0, str.length() - 2) + lastTwoReversed;
}


texts:
I wrote some string-extensions:

public static class RegexStringExtensions
{
    public static string PatternReplace(
        this string seed, string pattern,
        Func<string, string> outPattern)
    {
        return Regex.Replace(seed, pattern, s => outPattern(s.Groups[1].Value));
    }

    public static string PatternReplace(
        this string seed, string pattern,
        Func<string, string, string> outPattern)
    {
        return Regex.Replace(seed, pattern, s => outPattern(s.Groups[1].Value, s.Groups[2].Value));
    }
    public static string PatternReplace(
        this string seed, string pattern,
        Func<string, string, string, string> outPattern)
    {
        return Regex.Replace(seed, pattern, s => outPattern(s.Groups[1].Value, s.Groups[2].Value, s.Groups[3].Value));
    }
    public static string PatternReplace(
        this string seed, string pattern,
        Func<string, string, string, string, string> outPattern)
    {
        return Regex.Replace(seed, pattern, s => outPattern(s.Groups[1].Value, s.Groups[2].Value, s.Groups[3].Value, s.Groups[4].Value));
    }
}

with those, I could handle a replacement for regex-pattern and work with the groups more in C#-way like (just an easy example):

string val =
    "abcdef".PatternReplace(@"(ab)(cd)(ef)", (s,t,u) => u + string.Concat(s.Reverse()));
// result is "efba"

I think it's not that nice, to have so many overloads since I could have like 10 groups or something.
Any idea how I could make this a bit nicer?
For now, it'd work with up to 4 parameters, but with also 4 overloads.


texts:
I saw this problem in C++ on here and decided to try it in Python, which was much simpler. I've used the same problem blurb as in the link above, so they are consistent. I'm sure my code can be improved.
You are given 3 strings: text, pre_text and post_text. Let L be a substring of text. For each substring L of text, we define pattern_score as follows:
pre_text_pattern_score = highest n, such that first n characters of L are equal to the last n characters of pre_text and occur in the same exact order.
post_text_pattern_score = highest n such that last n characters of L are equal to the first n characters of post_text and occur in the same exact order.
pattern_score = pre_text_pattern_score + post_text_pattern_score. For example, if L = "nothing", pre_text = "bruno", and post_text = "ingenious", then
pre_text_pattern_score of L is 2 because the substring "no" is matched, and
post_text_pattern_score is 3 because the substring "ing" is matched.
pattern_score is 5 = 2 + 3 Your program should find a non-empty substring of text that maximizes pattern_score.
If there is a tie, return the substring with the maximal pre_text_pattern_score.
If multiple answers still have a tied score, return the answer that comes first lexicographically. Complete the definition of function string calculateScore(string text, string prefix,string suffix)
Constraints:

text, pre_text, and post_text contain only lowercase letters ('a' -
'z')
1 <= |text| <= 50
1 <= |pre-text| <= 50
1 <= |post-text| <= 50 (where |S| denotes the number of characters in string S)

Sample case #1 text: "nothing" prefix: "bruno" suffix: "ingenious" Returns: "nothing"
this is "no" from "bruno" and "ing" from "ingenious", so "nothing" is returned.
Sample case #2 text: "ab" prefix: "b" suffix: "a" Returns: "a"
def calculateScore(text, prefixString, suffixString):
    result = {}
    lenText = len(text)

    while lenText > 0:
        for i in range(len(text) + 1 - lenText):
            substring = text[i:i + lenText]

            # calc the pre_text_pattern_score
            pre_text_pattern_score = min(len(prefixString), len(substring))

            while pre_text_pattern_score > 0 and substring[:pre_text_pattern_score] != prefixString[-pre_text_pattern_score:]:
                pre_text_pattern_score -= 1

            # calc the post_text_pattern_score
            post_text_pattern_score = min(len(suffixString), len(substring))

            while post_text_pattern_score > 0 and substring[-post_text_pattern_score:] != suffixString[:post_text_pattern_score]:
                post_text_pattern_score-= 1

            # calculate the pattern_score
            pattern_score = pre_text_pattern_score + post_text_pattern_score

            if not pattern_score in result:
                # resets the dictionary key
                result[pattern_score] = []

            result[pattern_score].append(substring)

        lenText -= 1 # reduce lenText by 1

    # store the highest key, so we can sort the right item to return
    maximum_pattern_score = max(result.keys())

    # make sure to sort the lexicographically lowest string of the highest key
    result[maximum_pattern_score].sort()

    # return the lexicographically highest key
    return result[maximum_pattern_score][0]


texts: Assigning browser cookies for A-B testing

texts:
The following code creates a cookie on the client browser such that 25% of the browsers will have a value 0, and 75% a value of 1. Can anyone review the following code and point out any problems in it?

// AB testing code starts;
$abTestValues = array(1,1,0,1);
$abTestValue = 0;
$abTestCurrentValue = $abTestValues[$abTestValue];
$cookieName = 'ab-ranking-20160301';
$cookieLifeTime = time() + (86400 * 30);
$cookiePath = "/";
$abTestCookieValue = $_COOKIE[$cookieName];
if(trim($abTestCookieValue) != '' && $abTestCookieValue != null){
$abTestCurrentValue = $abTestCookieValue;
}else{
$abTestFile = 'abranking.txt';
if(is_file($abTestFile)){
$abTestLastValue = file_get_contents($abTestFile);
if( ($abTestLastValue + 1) == sizeof($abTestValues) ){
$abTestValue = 0;
}else{
$abTestValue = $abTestLastValue+1;
}
$abTestCurrentValue = $abTestValues[$abTestValue];
}
file_put_contents($abTestFile , $abTestValue);
$ranking_cookieval = $abTestCurrentValue;

setcookie($cookieName,$abTestCurrentValue,$cookieLifeTime,$cookiePath); //cookie set for 30 day
}
// AB testing code ends;


texts: Filtering Gantt chart data involving hierarchical DTOs

texts:
I have a bunch of code that deals with modifying a large nested set of IEnumerable<DTO's>

Basically, this is the structure of the DTO's

public class ProductLineDto
{
    ...
    public IEnumerable<ProjectTypeDto> ProjectType { get; set; }
}
public class ProjectTypeDto
{
    ...
    public IEnumerable<ProjectDto> Projects { get; set; }
}
public class ProjectDto
{
    ...
    public IEnumerable<SubProjectsDto> SubProjects { get; set; }
}

public class SubProjectDto
{
    ...
    public IEnumerable<SubProjectDto> Children { get; set; }
    public IEnumerable<ActivityDto> Activities { get; set; }
}

Here is what the code that uses them looks like.

I was wondering if there was a way to clean up the code. I don't like to have to make a copy of every nested IEnumerable to modify the ganttData variable. I was thinking of maybe making an extension method take care of that for me, that way I wouldn't have to throw those two lines of code in for every IEnuemerable
Are there any performance enhancements I can make? For instance, would it be faster to use Select() or Where() instead of RemoveAll()?

public IEnumerable<ProductLineDto> FilterGanttChartData(IEnumerable<ProductLineDto> ganttData, GanttFilterDto ganttFilterDataModel)
{
    ...

    ganttData = GetDataByEndDate(ganttData.ToList(), ganttFilterDataModel);

    return ganttData;
}

    private IEnumerable<ProductLineDto> GetDataByEndDate(List<ProductLineDto> ganttData, GanttFilterDto ganttFilterDataModel)
    {
        if (ganttFilterDataModel.EndDateFrom == null && ganttFilterDataModel.EndDateTo == null)
            return ganttData;

        var gdata = new List<ProductLineDto>();
        gdata.AddRange(ganttData);

        for (var i = 0; i < gdata.Count; i++)
        {
            var pType = new List<ProjectTypeDto>();
            pType.AddRange(gdata[i].ProjectType);

            for (var j = 0; j < pType.Count; j++)
            {
                var projects = new List<ProjectDto>();
                projects.AddRange(pType[j].Projects);

                for (var a = 0; a < projects.Count; a++)
                {
                    var subProjects = new List<SubProjectDto>();
                    subProjects.AddRange(projects[a].Children);
                    subProjects = GetActivitiesByEndDateRange(subProjects, ganttFilterDataModel.EndDateFrom, ganttFilterDataModel.EndDateTo).ToList();
                    projects[a].Children = subProjects;
                }
                pType[j].Projects = projects;
            }

            gdata[i].ProjectType = pType;
        }

        ganttData = gdata;
        return ganttData;
    }

Then the recursive function follows the same logic

    private IEnumerable<SubProjectDto> GetActivitiesByEndDateRange(List<SubProjectDto> children, DateTime? endDateFrom, DateTime? endDateTo)
    {
        var subProjects = new List<SubProjectDto>();
        subProjects.AddRange(children);

        for (var i = 0; i < subProjects.Count; i++)
        {
            var acts = new List<ActivityDto>();
            acts.AddRange(subProjects[i].Activities);

            if (endDateFrom != null)
                acts.RemoveAll(activity => activity.EndDate < endDateFrom);
            if (endDateTo != null)
                acts.RemoveAll(activity => activity.EndDate > endDateTo);
            subProjects[i].Activities = acts;

            if (subProjects[i].Children.Any())
                subProjects[i].Children = GetActivitiesByEndDateRange(subProjects[i].Children.ToList(), endDateFrom, endDateTo);
        }

        children = subProjects;
        return children;
    }


texts: Network programming - asynchronous, single-threaded, nickname-only chat server

texts:
I am starting to learn network programming. I have implemented a very simple chat server based upon TCP, where the users only need to provide username.
The assumption is that the server makes use of no additional threads and the sockets are not blocking. The code:

import sys
import time
import socket
import select

class User:
    def __init__(self, name, sock):
        self.name = name
        self.sock = sock

class Server:
    def __init__(self, host, port):
        self.users = []

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((host, port))

    def accept_usr(self):
        usock, _ = self.sock.accept()
        usock.send(b"Please, choose your username: ")
        uname = usock.recv(1024)
        self.users.append(User(uname, usock))
        _, writes, _ = select.select([], self._usocks(), [])
        for w in writes:
            w.send(bytes(f"{uname} has joined us!", encoding="ascii"))

    def handlerr(self, errs):
        for s in errs:
            s.close()

    def update(self):
        reads, writes, errs = select.select([*self._usocks(), self.sock], self._usocks(), self._usocks())
        for r in reads:
            if r is self.sock:
                self.accept_usr()
            else:
                uname = [u for u in self.users if u.sock is u.sock][0].name
                msg = r.recv(1024)
                for w in writes:
                    w.send(bytes(f"{uname}: {msg}", encoding="ascii"))
        self.handlerr(errs)

    def run(self):
        self.sock.listen(5)
        while 1:
            self.update()
            time.sleep(0.1)

    def _usocks(self):
        return [u.sock for u in self.users]

if __name__ == "__main__":
    s = Server("localhost", int(sys.argv[1]))
    s.run()

I would be grateful for any hints and comments.

EDIT:
An obvious improvement that comes to my mind is to store the mapping of socket->User in a dict so that I'll be able to quickly determine the author of the message being sent.


texts: Basic declarative style to rotate and crop an image array

texts:
I wrote a couple of basic Clojure functions (practicing a declarative style) and I was looking to get some feedback on them. You can see all the code here. Is there anything I could improve on to write more functional style code? How could I improve my tests? (Code can be run with lein test if you have Leiningen installed.)

Here are the main parts:

core_test.clj

(ns image-array-util.core-test
  (:require [clojure.test :refer :all]
            [image-array-util.core :refer :all]))

(deftest rotate-image-test
  (testing "Rotate an image"
    (is (= (rotate-image [[1]] :90) [[1]]))
    (is (= (rotate-image [[[0 0 0]]] :90) [[[0 0 0]]]))
    (is (= (rotate-image [[1 2]] :90) [[2][1]]))
    (is (= (rotate-image [[[1 1 1][2 2 2]]] :90) [[[2 2 2]][[1 1 1]]]))
    (is (= (rotate-image [[1 2]] :180) [[2 1]]))
    (is (= (rotate-image [[[1 1 1][2 2 2]]] :180) [[[2 2 2][1 1 1]]]))
    (is (= (rotate-image [[[1 1 1][2 2 2][3 3 3]][[4 4 4][5 5 5][6 6 6]]] :270) [[ [4 4 4] [1 1 1]][[5 5 5][2 2 2]][[6 6 6][3 3 3]]]))
    (is (thrown-with-msg? Exception #"Can't do that bucco. Argument 'deg' \(curently ':1'\) must be one of :90 :180 :270." (rotate-image [[1]] :1)))))

(deftest crop-image-test
  (testing "Cropping an image"
    (is (= (crop-image [[1]] [0 1] [0 1]) [[1]]))
    (is (= (crop-image [[1 2 3][4 5 6][7 8 9]] [0 1] [0 3]) [[1 2 3]]))
    (is (= (crop-image [[1 2 3][4 5 6][7 8 9]] [0 3] [0 1]) [[1][4][7]]))
    (is (= (crop-image [[1 2 3][4 5 6][7 8 9]] [1 2] [1 2]) [[5]]))
    (is (= (crop-image [[ [1 1 1] [2 2 2] [3 3 3]]
                        [ [4 4 4] [5 5 5] [6 6 6]]
                        [ [7 7 7] [8 8 8] [9 9 9]]] [1 2] [1 2]) [[[5 5 5]]]))))

core.clj

(ns image-array-util.core)

(defn rotate-image [image deg]
  (case deg
    :90 (let [new-height (count (nth image 0)) new-width (count image)]
          (->>
            (map reverse image)
            (apply interleave)
            (partition new-width)))
    :180 (reverse (map reverse image))
    :270 (rotate-image (rotate-image image :90) :180)
    (throw (IllegalArgumentException. (str "Can't do that bucco. Argument 'deg' (curently '" deg "') must be one of :90 :180 :270.")))))

(defn crop-image [image [vertical-s vertical-e] [horizontal-s horizontal-e]]
  (map #(subvec % horizontal-s horizontal-e) (subvec image vertical-s vertical-e)))


texts: Making empty cells in Underscore template

texts:
From the back-end, I am receiving 8 data. The client requires showing that the row per data is 7, so I have 1 data in balance. I have created empty data and made the empty cells, which works fine. But is it a correct approach to using Underscore templates?

Here is the live demo

Template:

JavaScript:

var obj = {
"schemeCodeDetails": [
    { "schemeCode": "AFN"},{"schemeCode": "BBT"},{"schemeCode": "BCH*"},
    {"schemeCode": "BCY*"},{"schemeCode": "BDP"},{"schemeCode": "BDQ"},{"schemeCode": "BDV"}, {"schemeCode": "BDW" } ]
}
for(i=0;i<  obj.schemeCodeDetails.length % 7; i++){
    obj.schemeCodeDetails.push({"schemeCode": ""});
}

    var temp = _.template($('#scheme').html());

    $('body').append(temp(obj));


texts:
I just found a whole bunch of plane tickets that only have a start and destination on them. I also know the route started in a certain city. I would like to recover the (alphabetically) first possible route a person took using these tickets. I added some examples in the doctests.

from collections import OrderedDict, defaultdict

class OrderedDefaultDict(OrderedDict):
    def __missing__(self, key):
        self[key] = value = 0
        return value

class FlightStorage():
    amount = 0

    def __init__(self):
        self.storage = defaultdict(OrderedDefaultDict)

    def add(self, start, destination):
        self.storage[start][destination] += 1
        self.amount += 1

    def list(self, start):
        return (destination for destination, amount in self.storage[start].items() if amount > 0)

    def remove(self, start, destination):
        self.storage[start][destination] -= 1
        self.amount -= 1

    def __len__(self):
        return self.amount

def reassemble_flights(start, flights):
    '''Reassembles a series of flights.

    >>> reassemble_flights('YUL', [('YUL', 'SFO'), ('SFO', 'HKO')])
    ['YUL', 'SFO', 'HKO']
    >>> reassemble_flights('YUL', [('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')])
    ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD']

    Returns the first (alphabetically sorted) route:
    >>> reassemble_flights('A', [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')])
    ['A', 'B', 'C', 'A', 'C']

    If no solution is available, returns None:
    >>> reassemble_flights('COM', [('SFO', 'COM'), ('COM', 'YYZ')]) is None
    True
    '''
    storage = FlightStorage()
    for flight in sorted(flights):
        storage.add(*flight)
    return backtrack_flights(start, storage)

def backtrack_flights(start, storage):
    if len(storage) == 0:
        return [start]
    if not any(storage.list(start)):
        return
    for destination in storage.list(start):
        storage.remove(start, destination)
        result = backtrack_flights(destination, storage)
        if result is not None:
            return [start] + result
        storage.add(start, destination)


texts: A JavaScript graph plotter for schoolchildren using paper.js

texts:
I have begun coding a simple graph plotter for my schoolchildren using JavaScript. I have used the paper.js library as I would like to be able to export the graphs as svg files.
I am only a beginner to all this (just a humble maths teacher) so I would hugely welcome any thoughts you may have. The code does not run particularly quickly so I would be particularly interested in any improvements to performance.
Many thanks and best wishes.
HTML:

<input type="number" id="input_xWidth" value=14>

<input type="number" id="input_yWidth" value=4>

<input type="text" id="eqn" value='sin(x)'>

<button onclick="drawGrid()">draw grid</button>
<button onclick="exportSVG()">export</button>

<canvas id="canvas_1"></canvas>

JavaScript:
var graphScope = new paper.PaperScope();
var canvas_1 = document.getElementById('canvas_1');
graphScope.setup(canvas_1);
graphScope.activate();

const scale = 10;

function drawGrid() {

  var xWidth = document.getElementById("input_xWidth").value;
  var yWidth = document.getElementById("input_yWidth").value;

  var z;
  var zz;

  //clear the canvas
  graphScope.project.activeLayer.removeChildren()

  //draw minor gridlines
  for (z = 0; z < xWidth; z++) {
    for (zz = 1; zz < 5; zz++) {
      var myPath = new graphScope.Path();
      myPath.strokeColor = new graphScope.Color(0.9, 0.9, 0.9);
      myPath.add(new graphScope.Point(z * scale + (scale / 5) * zz, -(0)));
      myPath.add(new graphScope.Point(z * scale + (scale / 5) * zz, -(yWidth * scale)));
    }
  }

  for (z = 0; z < yWidth; z++) {
    for (zz = 1; zz < 5; zz++) {
      var myPath = new graphScope.Path();
      myPath.strokeColor = new graphScope.Color(0.9, 0.9, 0.9);
      myPath.add(new graphScope.Point(0, -(z * scale + (scale / 5) * zz)));
      myPath.add(new graphScope.Point(xWidth * scale, -(z * scale + (scale / 5) * zz)));
    }
  }

  //draw major gridlines
  for (z = 0; z <= xWidth; z++) {
    var myPath = new graphScope.Path();
    myPath.strokeColor = new graphScope.Color(0.5, 0.5, 0.5);
    myPath.add(new graphScope.Point(z * scale, -(0)));
    myPath.add(new graphScope.Point(z * scale, -(yWidth * scale)));
  }

  for (z = 0; z <= yWidth; z++) {
    var myPath = new graphScope.Path();
    myPath.strokeColor = new graphScope.Color(0.5, 0.5, 0.5);
    myPath.add(new graphScope.Point(0, -(z * scale)));
    myPath.add(new graphScope.Point(xWidth * scale, -(z * scale)));
  }

  // parse equation from input box
  const node2 = math.parse(document.getElementById("eqn").value)
  const code2 = node2.compile()
  let scope = {
    x: 3,
  }

  // trim graph to grid
  var rectangle = new graphScope.Rectangle(new graphScope.Point(0, 0), new graphScope.Point(xWidth * scale, -yWidth * scale));
  var GraphBoundary = new graphScope.Path.Rectangle(rectangle);
  var graphPath = new graphScope.Path();
  for (z = 0; z < xWidth; z += 0.001) {
    scope.x = z
    graphPath.add(new graphScope.Point(z * scale, -(20 + scale * code2.evaluate(scope))));
  }
  var NewPath = graphPath.intersect(GraphBoundary, {
    trace: false
  })
  NewPath.strokeColor = new graphScope.Color(0.1, 0.1, 0.1);
  graphPath.remove();

  //fit page to canvas bounds
  graphScope.project.activeLayer.fitBounds(graphScope.view.bounds);
}

function exportSVG() {
  var fileName = "custom.svg"
  var url = "data:image/svg+xml;utf8," + encodeURIComponent(graphScope.project.exportSVG({
    asString: true
  }));
  var link = document.createElement("a");
  link.download = fileName;
  link.href = url;
  link.click();
}


texts: TikZ: Arrow pointing to circle from inside through two points

texts:
Originally posted here; this comment suggested that I ask this question on this site instead.

The code at the bottom produces the correct drawing, shown below.  The issue is that I don't think I drew it in the best way possible; in particular, I really don't like having to construct (X) or (Y) (I would rather specify that the radius is 2 and that the ray should go in the direction of (p)).

Can someone show me a better way?

\begin{tikzpicture}
\node [fill=black, shape=circle, inner sep=1pt, label=below:$O$] (O) at (0,0) {};
\node [fill=black, shape=circle, inner sep=1pt, label=below:$p$] (p) at (0.6,1.2) {};
\node [fill=black, shape=circle, inner sep=1pt, label=below:$f(p)$] (fp) at
(-1.2,0.7) {};
\coordinate (X) at (2,0);
\coordinate (Y) at (2.4, 1.7);
\node (C) [name path=C, draw, circle through=(X)] at (O) {};
\path [name path=fp--Y] (fp)--(Y);
\path [name intersections={of=fp--Y and C, by=F}];
\node [fill=black, shape=circle, inner sep=1pt, label=right:$r(p)$] (rp) at (F) {};
\draw [->] (fp)--(rp);
\end{tikzpicture}


texts: Making a .bat batch command-line interface

texts:
Recently I am working on batch to make a very simple command line interface.

The code looks like this:

@echo off
echo Simple command-line interface
echo.
:input.get
set /p input="COMMAND\>"
set input5=%input:~0,5%
if "%input%"=="something" goto something
if "%input5%"=="echo " goto echo

:echo
set content=%input:~5%
echo.%content%
goto input.get

:something
::do something
goto input.get

Is this really a good way to do it? I have posted a question about "How to check whether labels exist" in stack overflow, but if i input "echo hi" then it will be nearly impossible to check the tag.

Is it good to use both ways? (check whether label exist -> if not exist -> do "if" check)


texts:
here is my LinkedList Queue Implementation , seems like its almost like the linkedlist implementation with little differences mainly in the poll() method, i think that the offer() method is same like the linkedlist method add() , the point is that in the offer() method we are adding the elements to the tail, than we are moving them to the left, but their next is same like the add() method, where we are adding in the head and moving the elements to the right... Is i'm right? I'm glad to hear any suggestations...

import java.util.NoSuchElementException;

public class DynamicQueue {

private class Node {
    private Object item;
    private Node next;

    Node(Object item){
        this.item = item;
        this.next = null;
    }

    Node(Object item, Node prevNode){
        this.item = item;
        prevNode.next = this;
    }
}

private Node head;
private Node tail;
private int count;

public DynamicQueue() {
    this.head = null;
    this.tail = null;
    this.count = 0;
}

public int size() {
    return count;
}

public void offer(Object item) {
    if(tail == null) {
        tail = new Node(item);
        head = tail;
    }else {
        Node newNode = new Node(item,tail);
        tail = newNode;
    }
    count++;
}

public void clear() {
    head = null;
}

public Object peek() {
    if(head == null) {
        throw new NoSuchElementException("Overflow Exception");
    }else {
        return head.item;
    }
}

public void poll() {
    if(head == null) {
        throw new NoSuchElementException("Overflow Exception");
    }
    Node currentNode = head.next;
    head.next = null;
    head = currentNode;
    count--;

}

public static void main(String[] args) {
    DynamicQueue queue = new DynamicQueue();
    queue.offer("First");
    queue.offer("Second");
    queue.offer("Third");
    queue.offer("Fourth");
    queue.poll();
    System.out.println(queue.peek());
    queue.poll();
    System.out.println(queue.peek());
    queue.poll();
    System.out.println(queue.peek());

}

}


texts:
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?

This code works with NodeJS. It is also using ES6 features.
So no SpiderMonkey nonsense now.
$ node -v
v0.12.7
$ node --harmony p55.js
249

Any and all feedback is appreciated.
// Like Python's range.
function* range(start, stop, step){
    if (arguments.length == 0){
        start = 0;
        stop = null;
    }
    if (arguments.length == 1){
       stop = start;
       start = 0;
    }
    if (arguments.length < 3)
        step = 1;

    start = parseInt(start);
    if (Number.isNaN(start))
        start = 0;
    stop = parseInt(stop);
    if (Number.isNaN(stop))
        stop = null;
    step = parseInt(step);
    if (Number.isNaN(step))
        step = 1;

    if (stop === null){
        while (true){
            yield start;
            start += step;
        }
    }else if (step == 0){
        while (true){
            yield start;
        }
    }else{
        if (step > 0){
            for (var number = start; number < stop; number += step){
                yield number;
            }
        }else{
            for (var number = start - 1; number >= stop; number += step){
                yield number;
            }
        }
    }
}

function is_palindrome(string){
    var str_len = string.length - 1;
    for (var index of range(string.length / 2)){
        if (string[index] != string[str_len - index]){
            return false;
        }
    }
    return true;
}

function reverse(string){
    var new_string = '';
    for (var index of range(string.length, 0, -1)){
        new_string += string[index];
    }
    return new_string;
}

function is_lychrel(number, recursions){
    if (recursions == 0)
        return false;
    if (arguments.length == 1)
        recursions = 50;
    number += parseInt(reverse(number.toString()));
    if (is_palindrome(number.toString()))
        return true;
    return is_lychrel(number, recursions - 1);
}

function main(){
    var total = 0;
    for (var number of range(10000)){
        if (! is_lychrel(number)){
            total += 1;
        }
    }
    return total;
}

console.log(main());