texts:
I have the following method that I am trying to optimize. Currently, the method works great, however, it takes a little over 3 hours to complete. I feel like, using some nifty LINQ joins, it should be able to run in minutes. Here is the method:
    public async Task UpdateEmailTable(IEnumerable<StudentEmail> students)
    {
        Console.WriteLine("Updating Email table");
        var studentEmails = students.ToList();
        int totalStudents = studentEmails.Count;
        int currentCount = 0;
        float lastPercentage = -1;

        foreach (var student in studentEmails)
        {
            var isIn = await _context.BarcDemoGraphicEmail.AnyAsync(z => z.Sridentifier == student.StudentId);

            if (!isIn)
            {
                var ar = await _context.Barcaccount.FirstOrDefaultAsync(z => z.SrIdentifier == student.StudentId);

                await _context.BarcDemoGraphicEmail.AddAsync(new BarcDemoGraphicEmail
                {
                    Sridentifier = student.StudentId,
                    Email = student.EmailAddress,
                    Updatedate = DateTime.Now,
                    Aridentifier = ar == null ? "" : ar.ArIdentifier
                });
            }
            else
            {
                var rec = await _context.BarcDemoGraphicEmail.Where(z => z.Sridentifier == student.StudentId)
                    .FirstAsync();
                rec.Email = student.EmailAddress;
                rec.Updatedate = DateTime.Now;
            }

            await _context.SaveChangesAsync();

            int percentage = (int)Math.Round((float)currentCount / totalStudents * 100);
            if (lastPercentage != percentage) Console.Write("\r" + percentage + "%");
            lastPercentage = percentage;
            currentCount++;
        }
    }

So this method is called with a list of student ids and emails. This list does not come from the database. This list comes from a web call and must be passed into the method. It then iterates through the list, one at a time. It takes the student's id and checks to see if it exists in the BarcDemoGraphicEmail table, there by setting the isIn flag.
If the student ID is NOT in the BarcDemoGraphicEmail table, it pulls the account information from another table called BarcAccount. It then inserts this student's email into the BarcDemoGraphicEmail using the information from the BarcAccount table and the email from the students current iteration.
If the student ID IS in the BarcDemoGraphicEmail table, it simply pulls that record and updates the UpdateDate field and the Email field from the current iteration.
As I said earlier, this method currently works fine, however it takes way too long. How can I optimize my code (or possibly optimize the database) so this executes faster?
This is a console .NET Core 3.1 C# application using Entity Framework Core 3.1. The database is a SQL Server database.


texts:
When writing an answer for questions here or on Stack Overflow, it is a good idea to write some basic unit tests to make sure that the rewritten code performs as expected. To make this easier, I created a tiny test runner with the following goals.

Short - This is meant to be included in snippets, so it can't take up too much space.
Readable - Readability should not be sacrificed to make it a bit shorter.
Simple change to support objects, supports primitive values by default.

Here's a basic example of the usage:

const test = ({ func, tests, equal = (a, b) => a === b, format = t => t }) => {
  let [passed, failed] = [0, 0]
  for (const { args, expected } of tests) {
    const result = func(...args)
    if (equal(result, expected)) {
      passed++
    } else {
      failed++
      console.log(`Expected ${func.name}(...${JSON.stringify(args)}) to equal ${format(expected)} but got ${format(result)}`)
    }
  }
  console.log(`${func.name} - Passed: ${passed} Failed: ${failed}`)
}

let tests = [
  { args: [1], expected: 2 },
  { args: [3], expected: 4 },
  { args: [-1], expected: 0 },
]

function badAddOne(n) { return n + "1" }
function goodAddOne(n) { return n + 1 }

test({ func: badAddOne, tests })
test({ func: goodAddOne, tests })

// Testing with a custom equals function
function createDate(epoch) {
  return new Date(parseInt(epoch, 10) * 1000)
}

test({
  tests: [
    { args: [ 1509220283 ], expected: new Date(1509220283000) },
    { args: [ 0 ], expected: new Date(0) },
    // Show the custom format function
    { args: [ 0 ], expected: new Date(1) }
  ],
  equal: (a, b) => a.getTime() === b.getTime(),
  format: d => d.toISOString(),
  func: createDate
})

What I'm looking for in a review:

Can this function be improved to make usage simpler? Would the signature test(func, tests, { equal, format } = {}) make more sense?
Am I missing something a test runner designed for Stack Snippets should have that this function doesn't?

Edit:

This code uses the JavaScript Standard Style.
Support for non modern (read obsolete) browsers is not important. I don't know any developers who use IE as a browser of choice and thus this code only needs to run on recent Firefox / Chrome versions.


texts:
I've already reduced it and have tried making the main code is_divisible=, followed directly by the (2...).each... code, but that didn't work.

Any suggestions on reducing the size of this code? I have tests for other methods that use the code (so I know if changes are working) but not unit tests for this method yet.

  def self.divisible?(n)
    is_divisible= false
    (2...n).each do |divisor|
      division=n/divisor
      if n== divisor*division
        is_divisible= true
      end
    end
    is_divisible
  end


texts: Enumerating AWS instances in Rails, with error handling

texts:
I have created a method, which is raising the same exception in case of any error:

def fetch_aws_instances
  region_name = 'us-west-2'
  ec2 = Aws::EC2::Client.new(region: region_name)
  describe_regions_result = ec2.describe_region
  ...
  ...
rescue Seahorse::Client::NetworkingError, Aws::Errors::MissingCredentialsError, Aws::EC2::Errors::UnauthorizedOperation => error
  raise error
end

Now, I am calling this method like this:

begin
  fetch_aws_instances
rescue Seahorse::Client::NetworkingError
  Rails.logger.error 'Network Error: Please check whether the application instance is allowed outbound access to the Internet.'
rescue Aws::Errors::MissingCredentialsError, Aws::EC2::Errors::UnauthorizedOperation
  Rails.logger.error 'Authorization Error: Please ensure IAM role is attached to the application instance.'
end

Am I calling the method in correct way, do I need to rescue all the errors or is there some better way to do it?


texts: Is this an acceptable way of writing PHP code(in scriptlets)

texts:
Is this the way PHP developers write PHP or is echoing the html the preferred method?

<?php

require_once 'db_connect.php';
session_start();

$result = mysql_query("SELECT * FROM products");
?>

    Product ID

    Name

    Description

    Price

    Image

    Action

<?php
while($row = mysql_fetch_array($result))
{
    ?>

            <?php
                echo $row['p_id'];
            ?>

            <?php
                echo $row['p_name'];
            ?>

            <?php
                echo $row['p_description'];
            ?>

            <?php
                echo $row['p_price'];
            ?>

            <?php
                echo $row['p_image_path'];
            ?>

            edit

            delete

<?php
}
?>


texts: Solve binomial coefficient without lookup

texts:
I want to solve for n in the expression (binomial coefficient):
\$y=\frac{n^2+n}2\$
let y = (Math.pow(n, 2) + n) / 2;

I know the \$y\$ value, but I want to compute \$n\$.

Here is what I have so far, but I would want to know if there was a way to compute the value rather than look it up. In this example, I have to lookup the max value in a reversed array that is constrained by a length of 10.
Edit: Here is another avenue I took (still not an expression):
// Iterative
const toBase = n => {
  if (n < 1) return 0;
  let value = n, delta = 0;
  while (value > 0) value -= delta++;
  return delta - 1;
};

// Recursive
const toBase = (n, delta = 0) =>
  n === 0 && delta === 0
    ? 0
    : n < 1
      ? delta - 1
      : toBase(n - delta, delta + 1);

const MAX_BASES = 10;
const range = n => new Array(MAX_BASES).fill(0);
const binomialCoefficient = n => (Math.pow(n, 2) + n) / 2;
const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i));
const toBase = n => baseMax.indexOf([...baseMax].reverse().find(max => n > max)) + 1;

const main = () => {
  const inputs = getInputs().trim().split(/\n/)
    .map(l => l.trim().split(/\s+/g).map(v => parseInt(v.trim(), 10)))
    .filter(([v]) => !isNaN(v));
  inputs.forEach(input => validate(...input));
};

const validate = (n, expected) => {
  const actual = toBase(n);
  if (actual !== expected) {
    throw new Error(`${actual} !== ${expected} for n=${n}`);
  }
  console.log(`${n}: ${expected} === ${actual} | valid!`);
};

const getInputs = () => `
 0 0

 1 1

 2 2
 3 2

 4 3
 5 3
 6 3

 7 4
 8 4
 9 4
10 4

11 5
12 5
13 5
14 5
15 5

16 6
17 6
18 6
19 6
20 6
21 6

22 7
23 7
24 7
25 7
26 7
27 7
28 7

29 8
30 8
31 8
32 8
33 8
34 8
35 8
36 8
`;

main();
.as-console-wrapper { top: 0; max-height: 100% !important; }
14

14 - 1 =  13
13 - 2 =  11
11 - 3 =   8
 8 - 4 =   4
 4 - 5 =  -1

Background: I noticed a pattern which looked very similar to a factorial expression, but with addition rather than multiplication. After some research, I stumbled upon the following question which lead me in the right direction:

"Factorial, but with addition" - Mathematics Stack Exchange


texts:
In my application i use SignalR to push messages to connected clients.
The messages pushed to a client is dependent on the group the client is in.
For this I have a MessagesHub which implements an interface IMessagesHub

[HubName("ApplicationName")]
public class MessagesHub: Hub<IMessagesHub>
{
    public static MessagesHub MessagesHubStatic = new MessagesHub();

    private const string _groupName = "group_{0}";

    public static string SubscriptionGroupName(string groupId)
    {
        return String.Format(_groupName, groupId);
    }

    public override Task OnConnected()
    {
        return Clients.Client(Context.ConnectionId).SetConnectionId(Content.ConnectionId);
    }

    public async Task Subscribe(string groupId)
    {
        await Groups.Add(Context.ConnectionId, this.SubscriptionGroupName(groupId));
    }

    public async Task Unsubscribe (string groupId)
    {
        await Groups.Remove(Context.ConnectionId, this.SubscriptionGroupName(groupId));
    }
}
public interface IMessagesHub
{
    Task SetConnectionId(string connectionId);

    Task SendMessage(MessageDTO message);
}

The Controller MessagesController that pushes messages to the client inherits from MessagesHubController<MessagesHub>.

public abstract class MessagesHubController<T> : BaseController
    where T : Hub
{
    private readonly IHubContext _hub;

    public IHubConnectionContext<dynamic> Clients { get; private set; }

    public IGroupManager Groups { get; private set; }
    protected MessagesHubController(IConnectionManager signalRConnectionManager)
    {
        var _hub = signalRConnectionManager.GetHubContext<T>();
        Clients = _hub.Clients;
        Groups = _hub.Groups;
    }
}

So in my controller I do the following to push the message to the clients:

public class MessagesController : MessageHubController<MessagesHub>
{
    public async Task<IActionResult> Post([FromBody] MessageDTO postedMessage)
    {
        //save message code
    if(MessagesHub.MessagesHubStatic == null)
    {
        MessagesHub.MessagesHubStatic = new MessagesHub();
    }

    string groupname = MessagesHub.SubscriptionGroupName(this.GroupId);
        this.Client.Group(groupName).SendMessage(postedMessage);
    }
}

This all works fine. But now I also want to add code to push other updates to the clients like when a message is deleted or pinned.
I have already implemented this functionality but I have some duplicate code (in Send, Update and Delete) and I am wondering what would be the best way to avoid this duplication of code.
The following piece of code is duplicate:

        if(MessagesHub.MessagesHubStatic == null)
        {
            MessagesHub.MessagesHubStatic = new MessagesHub();
        }

        string groupname = MessagesHub.SubscriptionGroupName(this.GroupId);

I guess the best place for this piece of code is the MessagesHubController:

public abstract class MessagesHubController<T> : BaseController
{
    public string HubGroupName
    {
        get
        {
            return String.Format("group_{0}", GroupId);
        }
    }

    protected MessagesHubController(IConnectManager signalRConnectionManager)
    {
        MessagesHub.MessagesHubStatic = new MessagesHub();
    }
}

Would this be a good way to restructure my code?


texts:
Recently I was studying about the benefits and uses of std::optional in C++17 (Bartek's Blog) and there I saw a line that said "std::optional can be used for Lazy Loading of Resources" . Upon digging a little bit, I saw that C++ does not have native support for Lazy evaluation. So I just gave it a try and wrote the following code for lazy evaluation in C++.

Lazy.ixx - Visual Studio(Experimental :Modules)

To compile this (VS2019):

cl /experimental:module /EHsc /TP /MD /std:c++latest Lazy.ixx /module:interface /module:output Lazy.pcm /Fo: Lazy.obj /c

#include<optional>
#include<functional>
export module Lazy;

export namespace gstd
{
template<typename T>
class Lazy
{
   std::optional<T> m_resource;
   std::function<T()>m_ctor_func;
public:
   Lazy(std::function<T()>ctor_func)
   {
       m_ctor_func=ctor_func;
   }
   std::optional<T> operator ->()
   {
     //If resource is not initialized(i.e Ctor not invoked/ first time use)
    if(!m_resource)
    {
        m_resource=m_ctor_func();
    }
     return m_resource;
   }
};
}

Now sorry for using modules! (I just love them). To use this class it's pretty simple:

//main.cpp
#include<iostream>
import Lazy;

// A simple class called Resource
class Resource
{
  public:
  Resource()
  {
    std::cout<<"Welcome to new C++\n";
  }
  Resource(int a, int b)
  {
    std::cout<<"This also works : "<<a<<" "<<b<<"\n";
  }
  void func()
  {
    std::cout<<"Resource::func()\n";
  }

};

int main()
{
   gstd::Lazy<Resource>resx([](){ return Resource(4,5); });
   std::cout<<"Before construction\n";

   //Some code before using the resource

   resx->func();
   std::cin.get();
   return 0;
}

To compile this:

cl /experimental:module /module:reference Lazy.pcm /std:c++latest /TP /MD /EHsc /c /Fo: main.obj main.cpp

Get the executable by linking those two files:

cl main.obj Lazy.obj

I am pretty much new to programming so please bear me with the silly mistakes. One problem that can be seen at the first glance is this class (Lazy) is not thread-safe. Implementing that would be easy with mutexes. But, other than that, how can I improve my code?


texts: Print how many times a sequence of characters appears in a string

texts:
Given a string, count how many times a sequence of characters (in this code, the sequence is "ei") appears until the user types '#', then print the amount. I would like to know how to improve the code.

#include <stdio.h>
#include <inttypes.h>

int main(void)
{
    char ch, cur_ch, last_ch;
    cur_ch = '\0';
    uint16_t count = 0;

    puts("Enter a string (# to finish):");
    while ((ch = getchar()) != '#')
    {
        last_ch = cur_ch;
        cur_ch = ch;

        if (last_ch == 'e' && cur_ch == 'i')
            count++;
    }

    printf("There %s %" PRIu16 " %s.\n", count == 1 ? "is" : "are", count,
    count == 1 ? "ei" : "ei's");

    return 0;
}


texts: Longest Common Substring solution for a string and a list

texts:
Recently I have discovered one thing, which makes me feel frustrated. The Perl is lack of syntax sugar for strings, to do the same things, those are applicable to lists. The implementation I posted here would require to be rewritten to work for lists.

Thus, I had to re-write the code to Python to work for list as efficient as it does for strings:

def _contains(subseq, inseq):
    return any(inseq[pos:pos + len(subseq)] == subseq for pos in range(0, len(inseq) - len(subseq) + 1))

def lcss(s1, s2, threshold=3):

    all_of = []

    def is_inner_seq(i, j):
        return any(k < i < j <= l or k <= i < j < l for k, l in all_of)

    for i in range(0, len(s1)):
        for j in range(i + threshold, len(s1) + 1):

            if _contains(subseq=s1[i:j], inseq=s2):
                all_of.append((i, j))  # add a tuple to work OK when s1, s2 are lists

    only_outer_seq = filter(lambda tup: not is_inner_seq(tup[0], tup[1]),
                            all_of)

    return [s1[i:j] for i, j in only_outer_seq]

Here I implemented one minor improvement - filtering out inner substrings from the resultset, which aims to display more laconic result.

To not to frighten anyone with long sheets of code, here I am attaching a link to units tests, I used to tune up this solution: https://gist.github.com/anonymous/aa7540cc7db2ca446e2b

Your comments are welcomed! Especially on function '_contains', which does not look like a simple way of doing a simple task. I have started studying the Python just a few weeks ago.


texts:
I am testing the WIFEXITED to see if a child process exited abnormally or normally. According to documentation, it should return a non-zero status for a child process that terminated normally.

#include <wait.h>
#include <unistd.h>
#include <iostream>
#include <sys/types.h>

int main(int argc, const char* const* argv) {
    int *pointer=NULL;
    int status;
    pid_t pid=fork();
    if (pid==0) {
        std::cout << "Child is: " << getpid() << std::endl;
        if (argc>1) {
            std::cout << getpid() << "Going to crash myself" << std::endl;
            *pointer=1; //Segmentation fault as of null pointer dereference
        }
        else
            pointer=NULL; //Safe code
    }
    else {
        std::cout << "Parent is: " << getpid() << std::endl;
        pid_t terminated=waitpid(-1, &status, 0);
        std::cout << "Child " << terminated << " exited ";
        if (WIFEXITED(status)) std::cout << "GOOD";
        else {
             std::cout << "BAD";
             // Is it worth here to also check for WIFSIGNALED or is it redundant?
        }
        std::cout << std::endl;
    }
    std::cout << getpid() << " exiting normally" << std::endl;
    return 0;
}

To test a normal exit, call it without arguments, and an abnormal exit with segmentation fault, call it with some parameters.

Furthermore, if I use WIFSIGNALED it detects correctly the bad status, then, what's the use for WIFEXITED?

Is it advisable to use only WIFEXITED, or do you advise also to use WIFSIGNALED for further checks? Is this combination useful or redundant?


texts: Periodically comparing the play count of two Last.FM users

texts:
There is some little program (using a Last.FM API wrapper) which gets the play count of 2 specific users every 5 minutes and appends the difference between these 2 numbers to log file.

Can you review that part of the code?
I think that using the <- operator so many times decreases the readability and simplicity of the code.

main = forever $ do
  diff <- user1 `subtractCounts` user2
  timestamp <- formatTime defaultTimeLocale dateFormat <$> getZonedTime
  let logMessage = printf "%s %d\n" timestamp diff :: String
  homeDir <- getHomeDirectory
  let logFilePath = homeDir </> logFile
  appendFile logFilePath logMessage
  threadDelay $ 10^6 * 60 * timeDelay -- in microseconds
    where
      subtractCounts = liftM2 ((-) `on` fromMaybe 0) `on` getPlayCount
      dateFormat = "[%s] %D %H:%M"


texts: Is there a better way to output a javascript array from ASP.net?

texts:
I often run into the problem of producing a javascript array on an ASP.net page from an IEnumerable and I was wondering if there was an easier or clearer way to do it than

<% bool firstItem = true;
   foreach(var item in items){
      if(firstItem)
      {
         firstItem = false;
      }
      else
      {%>
        ,
      <%}%>
     '<%:item%>'
  %>

The whole thing is made much more verbose because of IE's inability to handle a hanging comma in an array or object.


texts: Verifying that all form fields are filled in

texts:
I grabbed the form from some random site because I'm only interested writing the javascript at the moment.

I am trying to check that a user has selected or entered text for all fields. I've made it a long if if-else but that can't be the best/most elegant/easiest solution.

Leaving aside the radio button validation for now, what's the better way to check that the text fields, drop down, and checkboxes all have a value/input?

I'm teaching myself javascript so I'm open to being told the proper way and I'll research it and do it on my own, or updating my fiddle would be fine too. (Be gentle with me. I'm sure this code is janky.)

Any thoughts on this would be appreciated.

Fiddle: https://jsfiddle.net/kiddigit/g0rur21a/

document.getElementById("newForm").addEventListener("submit", enterForm);

function enterForm(event) {
    event.preventDefault();

    var dropdown = document.getElementById('dropDown');

    if (document.getElementById('fname').value === ''){
            document.getElementById('fname').focus();
            alert('Enter text.');
        } else if (document.getElementById('eMail').value === ''){
            document.getElementById('eMail').focus();
            alert('Enter text.');
            } else if  (document.getElementById('textArea').value === '') {
                document.getElementById('textArea').focus();
                alert('Enter text.');
                } else if (!dropDown.value) {
                    document.getElementById('dropDown').focus();
                    alert('Choose an option.');
                    } else if ( ( newForm.checkbox[0].checked == false ) && ( newForm.checkbox[1].checked == false ) )
                        { alert ( "Please choose a checkbox" );
                            return false;
                            }

    var radios = document.getElementsByName("radio");
    var formValid = false;
    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
            i++;
        }

        if (!formValid) alert("Please check a radio button.");
        return formValid;

        return false;
};


texts:
I use the following code to import multiple worksheets from another workbook and do some processing. The importing time is too long. Can anyone suggest a more efficient way to import? Should I be looking into more information in the source files for copy? Can anyone please suggest a way to speed up the import function?

I am not a professional developer, so I might have left out some key points to note. Please let me know if I need to look into something else, as well.

Sub SKR_Import()
On Error GoTo errorhandler
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim wb1 As Workbook
Dim wb2 As Workbook
Dim Sht As Worksheet
Set wb1 = ActiveWorkbook
Dim fd As FileDialog
Dim filechosen As Integer
Dim filename As String
Dim i As Long
Set fd = Application.FileDialog(msoFileDialogOpen)
fd.AllowMultiSelect = True
fd.Title = "Select Excel workbooks to import all sheets"
filechosen = fd.Show
If filechosen = -1 Then
    For i = 1 To fd.SelectedItems.Count
        Set wb2 = Workbooks.Open(fd.SelectedItems(i))
        For Each Sht In wb2.Sheets
            Sht.Activate
            ActiveSheet.Copy after:=wb1.Sheets(wb1.Sheets.Count)
        Next Sht
        wb2.Close SaveChanges:=False
    Next i
End If
wb1.Activate
Application.ScreenUpdating = True
Exit Sub
errorhandler:
msgBox Error, vbCritical, "Error"
wb2.Close SaveChanges:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub


texts:
This is a little program I put together to help people learn the phonetic alphabet. Feel free to query the code.

import random

phonetic = {    'a' : 'alpha',    'b' : 'bravo',    'c' : 'charlie',    'd' : 'delta',    'e' : 'echo',    'f' : 'foxtrot',    'g' : 'golf',    'h' : 'hotel',    'i' : 'india',    'j' : 'juilett',    'k' : 'kilo',    'l' : 'lima',    'm' : 'mike',    'n' : 'november',    'o' : 'oscar',    'p' : 'papa',    'q' : 'quebec',    'r' : 'romeo',    's' : 'sierra',    't' : 'tango',    'u' : 'uniform',    'v' : 'victor',    'w' : 'whiskey',    'x' : 'x-ray',    'y' : 'yankee',    'z' : 'zulu'    }

print('Welcome to the IkeaFish Phonetic Trainer. \n Answer no or n to stop the program.')

again = 'yes'
while again != 'no' or 'n':

    #Picks either 0 or 1. If equal to 1 tests the letters, If equal to 0, tests the words.
    if random.randint(0,1) == 1:

        question = random.choice(list(phonetic.keys()))
        answer = input('What does this letter {} stand for: '.format(question))

        if answer == phonetic[question]:
            print('Correct')
        else:
            print('Wrong answer', question, 'stands for', phonetic[question])

    else:
        letter = random.choice(list(phonetic.keys()))
        #Grabbing a random key
        question = phonetic[letter]
        answer = input('What does this word {} stand for: '.format(question))

        if answer == letter:
            print('Correct')
        else:
            print('Wrong answer', question, 'stands for', phonetic[letter])


texts:
I wanted to get some feedback concerning the program. It's console based and in C#. If I should try to add constraints like making sure only the 4 questions shown are able to be typed in and nothing else or uses a number system to retrieve and set answers and if to add a randomization. If I am to add randomization how am I to do so with string and methods? Was thinking of loading it from an external file where questions and answers would be read, randomized and printed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Trivia_Game
{
class Questions
{
    public void Question1()
    {
        List<string> Q1 = new List<string>();
        Q1.Add("Paris");
        Q1.Add("Spain");
        Q1.Add("England");
        Q1.Add("Portugal");

        string Answer1="";

        string TrueAnswer = "Paris";

            for (int i = 0; i < Q1.Count; i++)
            {

                Console.Write(Q1[i] + ", ");

            }

            Console.WriteLine();

        while (Answer1 != TrueAnswer)
        {
            Console.WriteLine("What is the Capital of France?");
            Answer1 = Console.ReadLine();
            Console.WriteLine();

            if (Answer1 != TrueAnswer)
            {
                Console.WriteLine("Wrong answer");
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("Correct");
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Questions questions = new Questions();

        questions.Question1();

        Console.ReadKey();
    }
}
}


texts:
I need to review my code. I used prepared statements to select data from the database. Is there more sanitization needed or any other problem in the code? Rate it, please. Thanks.

<?php
session_start();
require_once './db_con.php';
require_once './funcs.php';
if ( $_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim(filter_input(INPUT_POST, 'email'));
    $password = trim(filter_input(INPUT_POST, 'password'));
    $errs = array();
    if ( empty($email) ) {
        $errs[] = "Please enter your E-mail.";
    } elseif ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
        $errs[] = "Please enter a valid E-mail.";
    }
    if ( empty($password) ) {
        $errs[] = "Please enter your password.";
    } elseif (strlen($password) < 6) {
        $errs[] = "Your password must have  at least 6 characters.";
    }
    if ( !empty( $errs ) )  {
        foreach ($errs as $err) {
            echo $err.'
';
        }
    } else {
        $stmt = $connection->prepare("SELECT `password` FROM `users` WHERE `email` = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();
        $rows_count = $result->num_rows;
        if ( $rows_count === 1 ) {
            $row = $result->fetch_row();
            $hash = $row[0];
            if ( password_verify($password, $hash) ) {
                $_SESSION['email'] = $email;
                header('Location: index.php');
            } else {
                echo "Password is wrong.";
            }
        } else {
            echo "register.";
        }
        $stmt->close();
        }
}
?>

<!DOCTYPE html>

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

            <form action="#" method="POST">

Enter Your E-mail: <input type="text"
                name="email" value="" />

Enter Your Password: <input

    type="password"                   name="password" value="" />

<input type="submit" value="Log now" />

            </form>


texts:
I built a web scraper to pull a list of jobs on Facebook and other websites but want to break up the code into functions that I can reuse for other websites. This structure is working but I think it can be more efficient with functions. I'm getting stuck on how to structure the functions. It's only pulling two pages for testing.

from time import time
from requests import get
from time import sleep
from random import randint
from IPython.core.display import clear_output
from warnings import warn
from bs4 import BeautifulSoup
import csv

# Range of only 2 pages
pages = [str(i) for i in range(1, 3)]
cities = ["Menlo%20Park%2C%20CA",
          "Fremont%2C%20CA",
          "Los%20Angeles%2C%20CA",
          "Mountain%20View%2C%20CA",
          "Northridge%2CCA",
          "Redmond%2C%20WA",
          "San%20Francisco%2C%20CA",
          "Santa%20Clara%2C%20CA",
          "Seattle%2C%20WA",
          "Woodland%20Hills%2C%20CA"]

# Preparing the monitoring of the loop
start_time = time()
requests = 0

with open('facebook_job_list.csv', 'w', newline='') as f:
    header = csv.writer(f)
    header.writerow(["Website", "Title", "Location", "Job URL"])

for page in pages:
    for c in cities:
        # Requests the html page
        response = get("https://www.facebook.com/careers/jobs/?page=" + page +
                       "&results_per_page=100&locations[0]=" + c)

        # Pauses the loop between 8 and 15 seconds
        sleep(randint(8, 15))

        # Monitor the frequency of requests
        requests += 1
        elapsed_time = time() - start_time
        print("Request:{}; Frequency: {} request/s".format(requests, requests/elapsed_time))
        clear_output(wait=True)

        # Throw a warning for non-200 status codes
        if response.status_code != 200:
            warn("Request: {}; Status code: {}".format(requests, response.status_code))

        # Break the loop if number of requests is greater than expected
        if requests > 2:
            warn("Number of requests was greater than expected.")
            break

        # Parse the content of the request with BeautifulSoup
        page_soup = BeautifulSoup(response.text, 'html.parser')
        job_containers = page_soup.find_all("a", "_69jm")

        # Select all 100 jobs containers from a single page
        for container in job_containers:
            site = page_soup.find("title").text
            title = container.find("div", "_69jo").text
            location = container.find("div", "_1n-z _6hy- _21-h").text
            link = container.get("href")
            job_link = "https://www.facebook.com" + link

            with open('facebook_job_list.csv', 'a', newline='') as f:
                rows = csv.writer(f)
                rows.writerow([site, title, location, job_link])


texts:
I need to round numeric values for properties of a given object.
The following code works fine, but I am concerned if there is a way to make it faster.

I am targeting latest Chrome and Firefox.

http://jsbin.com/bahedegoni/edit?html,output

window.app = {
            start: function () {
                var cmd = {
                    a: 11.12,
                    b: 0.29,
                    c: 'x',
                    d: 'y'
                };
                Object.keys(cmd).forEach(function (prop) {
                    if (typeof cmd[prop] === 'number') {
                        cmd[prop] = Math.round(cmd[prop]);
                    }

                }.bind(this));
                console.log(cmd);
            }
        };


texts:
This program is supposed to find and slice any cell within a CSV file which contains more than a defined number of characters.

The files can be pretty large, so being a beginner I would like to know if it is written correctly, and if I could make it more efficient. One of the lines is also more than 80 characters long, which bothers me.

import configparser, csv, sys

if len(sys.argv) < 3 :
        usage = """Usage: %s [inputfile][output file]\nThis program requires 2 \
arguments to function properly.\n[input file] is the file to clean\n[output fil\
e] is the name of the file that will be created as a result of this program\n"""
        print(usage % (sys.argv[0]))
else :
        #reads the config file
        config = configparser.ConfigParser()
        config.read('csv_cleaner.ini')
        config = config['CONFIG']
        encoding = config['character_encoding']
        size = int(config['truncation_size'])
        #opens target file and creates the receiving one
        with open(sys.argv[1], 'r', newline='', encoding=encoding)as csv_file, \
             open(sys.argv[2],'x', newline='', encoding=encoding)as output_file:
                #helps with parsing
                if config['detect_dialect'] :
                        dialect = csv.Sniffer().sniff(csv_file.read(2048))
                        dialect.escapechar = '\\'
                        #return to beginning of file
                        csv_file.seek(0)
                        #creates reader and writer
                        reader = csv.reader(csv_file, dialect)
                        dialect.delimiter = config['delimiter_in_output']
                        writer = csv.writer(output_file, dialect)
                        #loops through file's lines
                        for row in reader :
                                #slices cells and loops through line's columns
                                row=[col[:(size-2)]+(col[(size-2):]and'..')for col in row]
                                #writes in new file
                                writer.writerow(row)

This program uses a config file :

[CONFIG]
character_encoding = UTF-8
delimiter_in_output = ;
#set this option to False if the file is not recognized
detect_dialect = True
truncation_size = 255


texts: Timed series of events. Logic for organizing events based on time?

texts:
I would like to execute a series of events at the time at which they occur.

The events are stored in a list and always sorted by time of execution.

volatileEvents.Sort(SortScriptEventAscending.Comparer);

I would like to have my update method execute the following points.

The list should be checked to see if it contains any events (if not then don't continue)
The events should be executed and remain in the list until the next event is executed
Once the current event is executed the previous event should be removed
Events should always be checked to see if they have either expired or are yet to occur

I have the basic conditions implemented but the algorithm doesn't work as intended.

        float currentTime = game.ScriptTimer.CurrentTime;

        int numEvents = volatileEvents.Count;

        // Check for no events
        if (numEvents == 0)
        {
            return;
        }

        // Check for expired events
        while (volatileEvents[0].Time < currentTime)
        {
            volatileEvents.RemoveAt(0);
        }

        // Check if the current event has yet to occur
        if (volatileEvents[0].Time > currentTime)
        {
            return;
        }

        // Protect against index range error
        int next = numEvents == 1 ? 0 : 1;

        ScriptEvent currentEvent = volatileEvents[0];
        ScriptEvent nextEvent = volatileEvents[next];

        // Update the current value based on the script and event parameters
        float value = currentEvent.Interpolate ?
            MathTools.Lerp2D(currentEvent.Value, nextEvent.Value, currentEvent.Time, currentTime, nextEvent.Time) :
            currentEvent.Value;

I would like some help to achieve the four bullet points as the basic conditions are there but the method's order of execution is incorrect.


texts: OpenCV 3: Using k-Nearest Neighbors to analyse RGB image

texts:
I'm new to computer vision and numpy.

I wrote a simple script to seperate red, green and blue colors from the original image by using the kNN algorithm.
After reading through some numpy tutorials, I'm under the impression that the performance of my script can be improved heavily.
So here are my questions:

Is there a way to avoid the call to np_pixel = np.asarray(...) for each of the pixels? I can't find a format for the trainData that would allow me that.
Is there a way to feed the whole image into the findNearest method?
This would make it possible to avoid the slow python loop.
Do you see any other ways to improve the performance or length of this script?

import cv2
import numpy as np

trainData = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]], dtype=np.float32)
# Labels each one of the BGR channels as numbers 0, 1, 2 respectively
responses = np.array([[0], [1], [2]], dtype=np.float32)

imgPath = "../Images/RGB.png"
img = cv2.imread(imgPath)
if img is None:
    raise FileNotFoundError("'{0}' could not be opened!".format(imgPath))

knn = cv2.ml.KNearest_create()
knn.train(trainData, cv2.ml.ROW_SAMPLE, responses)

height, width, depth = img.shape
colorLayers = dict()
colorLayers[0] = np.zeros((height, width, 3), dtype=np.float32)
colorLayers[1] = np.zeros((height, width, 3), dtype=np.float32)
colorLayers[2] = np.zeros((height, width, 3), dtype=np.float32)

for row in range(height):
    for col in range(width):
        np_pixel = np.asarray([img[row, col]], dtype=np.float32)
        ret, results, neighbours, dist = knn.findNearest(np_pixel, 1)
        int_result = int(results)

        if int_result == 0:
            color = np.asarray([255, 0, 0]).astype(np.float32)
        elif int_result == 1:
            color = np.asarray([0, 255, 0]).astype(np.float32)
        else:
            color = np.asarray([0, 0, 255]).astype(np.float32)

        colorLayers[int_result][row, col] = color

cv2.imshow('Original', img)
cv2.imshow('Blue', colorLayers[0])
cv2.imshow('Green', colorLayers[1])
cv2.imshow('Red', colorLayers[2])
cv2.waitKey(0)


texts: Will this test to check if an element has an attribute work?

texts:
Here is my code:

hasAttr = new function(tag, attrName) {
    return (tag.attrName)
}

Will this code work? I can't test it now because I cannot acces jsfiddle and jsbin but Down For Everyone or Just Me? says something else.

jsFiddle Down For Everyone or Just Me
jsBin Down For Everyone or Just Me

Example usage:

JavaScript:

alert(hasAttr("div", "id"))

HTML:

Expected:

(In alert box)
    true
                OK

Can someone test it for me?

If it doesn't work, how should I code it?

I want hasAttr to return true or false.

I will be open to code optimization, cleaner code etc.

Thanks in advance!


texts:
The following code I devised to compute a determinant:

module MatrixOps where

determinant :: (Num a, Fractional a) => [[a]] -> a
determinant [[x]] = x
determinant mat =
 sum [s*x*(determinant (getRest i mat)) | i <- [0..n-1], let x = (head mat) !! i
                                                             s = (-1)^i]
 where n = length $ head mat

getRest :: (Num a, Fractional a) => Int -> [[a]] -> [[a]]
getRest i mat = removeCols i (tail mat)

removeCols :: (Num a, Fractional a) => Int -> [[a]] -> [[a]]
removeCols _ [] = []
removeCols i (r:rs) = [r !! j | j <- [0..n-1], j /= i] : removeCols i rs
 where n = length r

I have a few general questions about the style of my code and practices:

Is a very "Haskell" solution? I come from an OOP background and I am still learning functional programming.
Is there a better way to space this out? I feel like some of the code is not very readable (this may just be because I am new), especially the definition of determinant mat = ...
Is this code considerably "clean?"


texts:
We have an exercise to design a simple library, which can calculate some length with different unit, e.g.

2m*2 + 20cm/2 - 5mm

and the result can be any of:

4.095m
409.5cm
4095mm

I want to design it in Object-oriented, and have a solution like this:

public class Length {

    private final double value;
    private final Unit unit;

    public Length(double value, Unit unit) {
        this.value = value;
        this.unit = unit;
    }

    @Override
    public boolean equals(Object obj) {
        Length length = (Length) obj;
        return this.unit.toMM(this.value) == length.unit.toMM(length.value);
    }

    public Length add(Length added) {
        return new Length(this.unit.toMM(this.value) + added.unit.toMM(added.value), Unit.mm);
    }

    public Length subtract(Length another) {
        return new Length(this.unit.toMM(this.value) - another.unit.toMM(another.value), Unit.mm);
    }

}

enum Unit {
    m(1000), cm(10), mm(1);
    private final int rate;

    Unit(int rate) {
        this.rate = rate;
    }

    public double toMM(double value) {
        return rate * value;
    }
}

It works, but I have several questions:

Is there anything wrong from the OO point of view?
Unit has a method toMM which is bind to a concrete type of unit mm(millimeter), I don't feel good about it, is there any way to improve it? Or it's just acceptable since we have to choose one?
Length has chosen mm for all kinds of unit, is it good? I'm looking for a way to avoid it, but not found

These questions are mostly based on this possible requirement change: don't want to support mm anymore. Most of the code has to be modified in this case.

Update: from this article, seems it's not a good idea to use enum here for different units?


texts: Finding the majority element in a sequence of integers in \$O(n \log n)\$

texts:
I wrote this piece of code as solution to a problem set that required finding the majority element in a list using divide and conquer in \$ O(n \log n)\$. The majority element is defined as the element with number of repetitions more than half the length of the input list.

The stated solution for that problem was to find the majority element in the two sub-lists which will be the majority element of the entire list.

I don't know how this is supposed to work if the input list is \$ [1,1,1,5,5] \$ where the two sub-lists would be \$ [1,1,1] \$ and \$ [1,5,5] \$ yielding two different majority elements, so I came up with another solution.

The recurrence relation for the Divide and Conquer part is $$ T(n) = 2 T\left(\dfrac{n}{2}\right)+O(n) $$ which is \$ O(n \log n) \$ and an extra \$ O(n) \$ for iterating on the resulting list of tuples after the divide and conquer terminates.

What do you guys think about the performance and efficiency of this algorithm, I know I could have sorted at first in \$ O(n \log n)\$ and then do this same iteration in \$ O(n) \$, but I wanted to come up with new way of solving it.

What do you also think about the supposedly correct answer for the problem of finding the majority element in each sub-list, is it possible, and how can you code it if yes ?!

def element_repetitions(lst):
    """
    This function is used to determine the number of repetitions of each element in the input list
    :param lst: A list of positive integers.
    :return: A sorted list of tuples, each tuple representing an element in the
    input lst and the number of repetitions of this element.
    """
    n = len(lst)
    if n == 1:
        return [(lst[0], 1)]
    first_half = element_repetitions(lst[:n // 2])
    second_half = element_repetitions(lst[n // 2:])
    return merge_the_tuples(first_half, second_half)

def merge_the_tuples(lst1, lst2):
    """
    This function sorts and merges the two input list of tuples.
    It iterates on both of the input lists with a technique similar to that used in
    the merging function of the merge sort, but if both of the elements are equal, only one instance
    of the element is added as the first element of the tuple, and the sum of their repetitions is added as the
    second element of the tuple.

    :param lst1: A sorted list of tuples, each tuple has a unique element, and the number of repetitions of
    this element.
    :param lst2: The other sorted list of tuples.
    :return: A merged list of tuples.
    """
    list_of_tuples = []
    i, j = 0, 0
    while i < len(lst1) and j < len(lst2):
        if lst1[i][0] < lst2[j][0]:
            list_of_tuples.append(lst1[i])
            i += 1
        elif lst1[i][0] > lst2[j][0]:
            list_of_tuples.append(lst2[j])
            j += 1
        elif lst1[i][0] == lst2[j][0]:
            list_of_tuples.append((lst1[i][0], lst1[i][1] + lst2[j][1]))
            i += 1
            j += 1
    return list_of_tuples + lst1[i:] + lst2[j:]

def majority_element(lst):
    """
    Iterates over the resulting list of tuples from element_repetitions(), returning the element with repetitions
    more than half the length of the input list.
    :param lst: A list of integers > 0
    :return: The majority element if present, else 0
    """
    element_repetition_list = element_repetitions(lst)
    for element_repetition in element_repetition_list:
        if element_repetition[1] >= len(lst) // 2 + 1:
            return element_repetition[0]
    return 0

print(majority_element([1, 1, 1, 5, 5])) outputs 1

print(majority_element([1, 3, 4, 1, 2, 6, 2, 1, 1, 1])) outputs 0


texts: Gin framework project with an endpoint to return a list of users based on their score

texts:
My relevant work experience is with Java (mostly web development with Dropwizard/Spring) so I can not avoid using the same practices as I do in a Java project. The project is there but I am going to copy it here:

Project

A very simple project with Gin framework with an endpoint to return a list of users based on their score.

Structure

liveops-tool
-- user
---- model
------ user.go
---- service
------ userService.go
------ userDirectory.go (mock the db)
-- main.go

main.go

r.GET("/competition/users", func(c *gin.Context) {
        numUsers, err := strconv.Atoi(c.DefaultQuery("numusers", "6"))
        minScore, err := strconv.Atoi(c.DefaultQuery("minscore", "0"))
        maxScore, err := strconv.Atoi(c.DefaultQuery("maxscore", "2000"))
        fmt.Printf("numUsers: %d , minScore: %d , maxScore: %d \n", numUsers, minScore, maxScore)

        if err == nil {
            var res = userService.GenerateUserListByScore(numUsers, minScore, maxScore)
            c.JSON(http.StatusOK, gin.H{"users": res})
        } else {
            c.JSON(http.StatusBadRequest, gin.H{"users": "no valid"})
        }

    })

user.go

package user

type User struct {
    ID         string `json:"id"`
    Name       string `json:"name"`
    Country    string `json:"country"`
    TotalScore int    `json:"totalScore"`
}

userService.go

package user

import (
    user "liveops-tool/user/model"
)

// GenerateUserListByScore returns a list of users for a tournament
func GenerateUserListByScore(numUsers, minScore, maxScore int) []user.User {
    return searchUsers(numUsers, minScore, maxScore)
}

userDirectory.go

package user

import (
    "fmt"
    userModel "liveops-tool/user/model"
)

var users = []userModel.User{}

func init() {
    initUsers()
}

func searchUsers(numUsers, minScore, maxScore int) []userModel.User {
    return filterUsersByScore(numUsers, minScore, maxScore)
}

func filterUsersByScore(numUsers, minScore, maxScore int) []userModel.User {
    var filteredUsers = []userModel.User{}
    var countUsers = 0
    if len(users) < numUsers {
        numUsers = len(users)
    }
    for i := range users {
        if users[i].TotalScore >= minScore && users[i].TotalScore <= maxScore {
            filteredUsers = append(filteredUsers, users[i])
            countUsers++
        }

        if countUsers >= numUsers {
            break
        }
    }
    return filteredUsers
}

func initUsers() {
    user1 := userModel.User{ID: "1", Name: "John", Country: "UK", TotalScore: 500}
    user2 := userModel.User{ID: "2", Name: "Frank", Country: "ES", TotalScore: 1500}
    user3 := userModel.User{ID: "3", Name: "Bob", Country: "UK", TotalScore: 2000}
    user4 := userModel.User{ID: "4", Name: "Anna", Country: "FR", TotalScore: 3000}
    users = append(users, user1)
    users = append(users, user2)
    users = append(users, user3)
    users = append(users, user4)
    fmt.Printf("users: %+v\n", users)
}

Questions

I am mocking the user list and I would like the method initUsers would not be accesible from userService. Golang doesn't have public and private methods because the visibility depends on the package. The same for the function filterUsersByScore. How can I improve it?
User (model): I need to put the attributes with the first letter in uppercase to make it exportable when I return the JSON. Is it possible to have the attributes as private to access them through getters and setters and also return them in the JSON response?

Any other advice about the code is well received.


texts:
This program is one of the exercises I solved in my book. Can anyone suggest any improvements to it?

import java.util.Random;
import java.util.Scanner;

public class GuessMyNumber {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Random random = new Random();

    System.out.println("I'm thinking of a number between 1 and 100 (including both).\nCan you guess what it is?");
    System.out.print("Type a number : ");
    int guessNum = in.nextInt();
    System.out.printf("Your guess is : %d\n", guessNum);
    int randomNum = random.nextInt(100) + 1;
    System.out.printf("The number I was thinking of is : %d\n", randomNum);
    System.out.print("You were off by : ");

    int diff = guessNum - randomNum;
    if (guessNum >= randomNum) {
      System.out.println(diff);
    } else { System.out.println(randomNum - guessNum); }
  }
}


texts:
This code finds a common ancestor. If one of the input does not exist in the tree then throws an exception. This does not use extra storage. It does not even traverse more than what it should be. It would also account for duplicate node values in binary tree.

I want you to pick my code apart and give me some feedback on how I could make it better or more simple.

public class LeastCommonAncestor {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        TreeNode (TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void createBinaryTree (Integer[] arr) {
        if (arr == null)  {
            throw new NullPointerException("The input array is null.");
        }

        root = new TreeNode(null, null, arr[0]);

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = arr.length / 2;

        for (int i = 0; i < half; i++) {
            if (arr[i] != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (arr[left] != null) {
                    current.left = new TreeNode(null, null, arr[left]);
                    queue.add(current.left);
                }
                if (right < arr.length && arr[right] != null) {
                    current.right = new TreeNode(null, null, arr[right]);
                    queue.add(current.right);
                }
            }
        }
    }

    private static class LCAData {
        TreeNode lca;
        int count;

        public LCAData(TreeNode parent, int count) {
            this.lca = parent;
            this.count = count;
        }
    }

    public int leastCommonAncestor(int n1, int n2) {
        if (root == null) {
            throw new NoSuchElementException("The tree is empty.");
        }

        LCAData lcaData = new LCAData(null, 0);

        foundMatchAndDuplicate (root, lcaData, n1,  n2, new HashSet<Integer>());

        if (lcaData.lca != null) {
            return lcaData.lca.item;
        } else {

            throw new IllegalArgumentException("The tree does not contain either one or more of input data. ");
        }
    }

    private boolean foundMatchAndDuplicate (TreeNode node, LCAData lcaData, int n1, int n2, Set<Integer> set) {
        if (node == null) {
            return false;
        }

        // when both were found
        if (lcaData.count == 2) {
            return false;
        }

        // when only one of them is found
        if ((node.item == n1 || node.item == n2) && lcaData.count == 1) {
            if (!set.contains(node.item)) {
                lcaData.count++;
                return true;
            }
        }

        boolean foundInCurrent = false;
        // when nothing was found (count == 0), or a duplicate was found (count == 1)
        if (node.item == n1 || node.item == n2) {
            if (!set.contains(node.item)) {
                set.add(node.item);
                lcaData.count++;
            }
            foundInCurrent = true;
        }

        boolean foundInLeft = foundMatchAndDuplicate(node.left, lcaData, n1, n2, set);
        boolean foundInRight = foundMatchAndDuplicate(node.right, lcaData, n1, n2, set);

        if (((foundInLeft && foundInRight) ||
                (foundInCurrent && foundInRight) ||
                    (foundInCurrent && foundInLeft)) &&
                        lcaData.lca == null) {
            lcaData.lca = node;
            return true;
        }
        return foundInCurrent || (foundInLeft || foundInRight);
    }

}


texts:
Preface

At some point I was tired of writing & supporting __repr__ methods, so I've decided to write it once and reuse everywhere in my classes.

Since I'm trying to write classes as simple as possible, most of them ends in something like

class MyClass:
     def __init__(self, param, other_param, ...):
         self.param = param
         self.other_param = other_param
         ...

i.e. initializer parameters names corresponds to fields names, so we can get initializer arguments by simply getattr'ing corresponding fields.

Main ideas are:

I want to have informative string which includes parameters involved in instance creation. For simple cases it should be possible to copy string & paste in some place (e.g. REPL session) and have similar object definition with as less work as possible. This helps a lot during debugging sessions, logging, especially in failed test cases with randomly generated data.

Great examples are Counter & OrderedDict from collections standard library:

>>> from collections import Counter
>>> Counter(range(2))
Counter({0: 1, 1: 1})
>>> Counter(range(2)) == Counter({0: 1, 1: 1})
True
>>> from collections import OrderedDict
>>> OrderedDict.fromkeys(range(2))
OrderedDict([(0, None), (1, None)])
>>> OrderedDict.fromkeys(range(2)) == OrderedDict([(0, None), (1, None)])
True

Once signature change, __repr__ should handle this automatically for simple cases like renaming/removing/changing order of parameters.

Attempt

Note: following code requires Python3.5+ due to yield from statement

import inspect
from collections import (OrderedDict,
                         abc)
from typing import (Any,
                    Callable,
                    Iterable,
                    TypeVar,
                    Union)

Domain = TypeVar('Domain')
Range = TypeVar('Range')
Map = Callable[[Domain], Range]

Constructor = Callable[..., Domain]
Initializer = Callable[..., None]

def generate_repr(constructor_or_initializer: Union[Constructor, Initializer],
                  *,
                  field_seeker: Callable[[Domain, str], Any] = getattr
                  ) -> Map[Domain, str]:
    signature = inspect.signature(constructor_or_initializer)
    parameters = OrderedDict(signature.parameters)
    # remove `self`
    parameters.popitem(0)
    to_positional_argument_string = repr
    to_keyword_argument_string = '{}={!r}'.format

    def __repr__(self: Domain) -> str:
        return (type(self).__qualname__
                + '(' + ', '.join(to_arguments_strings(self)) + ')')

    def to_arguments_strings(object_: Domain) -> Iterable[str]:
        for parameter_name, parameter in parameters.items():
            field = field_seeker(object_, parameter_name)
            if parameter.kind == inspect._VAR_POSITIONAL:
                if isinstance(field, abc.Iterator):
                    yield '...'
                else:
                    yield from map(to_positional_argument_string, field)
            elif parameter.kind == inspect._VAR_KEYWORD:
                yield from map(to_keyword_argument_string,
                               field.keys(), field.values())
            elif parameter.kind in {inspect._POSITIONAL_ONLY,
                                    inspect._POSITIONAL_OR_KEYWORD}:
                yield to_positional_argument_string(field)
            else:
                yield to_keyword_argument_string(parameter_name, field)

    return __repr__

Test

Let's define our class like

class A:
    def __init__(self, positional, *variadic_positional, keyword_only,
                 **variadic_keyword):
        self.positional = positional
        self.variadic_positional = variadic_positional
        self.keyword_only = keyword_only
        self.variadic_keyword = variadic_keyword

    __repr__ = generate_repr(__init__)

After that

>>> A(1, 2, 3, keyword_only='some', a={'sample': 42}, b={1, 2})
A(1, 2, 3, keyword_only='some', b={1, 2}, a={'sample': 42})


texts: Computing a mathematical function in MIPS assembly

texts:
This code computes the function (3x^2-4x+16) / (5x^2+2x-4). I ran the program and it works, but I am fairly new to assembly language and am not quite sure how to make the most efficient use of the registers.  Does this look ok or is there a better way to do it?

.text
.globl  main

main:
ori      $8, $0, 3         #put x into $8
ori      $9, $0, 3         #puts 3 into $9
ori      $10, $0,  4       #puts 4 into $10
ori      $11, $0, 16       #puts 16 into $11

mult     $8, $8            #Squares x
mflo     $13               #$13 = x^2
mult     $9, $13           #Computes 3x^2
mflo     $14               # $14 = 3x^2
mult     $10, $8           # lo = 4x
mflo     $15               # $9 = 4x
sub      $16, $14,  $15    # $16 = 3x^2 -4x
add      $17, $16,  $11    #$17 = 3x^2 - 4x + 16

ori      $8, $0, 1         #put x into $8
ori      $9, $0, 5         #puts 5 into $9
ori      $10, $0,  2       # put 2 into $10
ori      $11, $0, 4        # puts 4 into $11

mult     $8, $8            #Squares x
mflo     $13               #$13 = x^2
mult     $9, $13           #Computes 5x^2
mflo     $14               # $14 = 5x^2
mult     $10, $8           # lo = 2x
mflo     $15               # $9 = 2x
add      $16, $14,  $15    # $16 = 5x^2 +4x
sub      $18, $16,  $11    #$17 = 5x^2 + 2x - 4

div      $17, $18          #divides 2 functions
mflo     $8                #quotient
mfhi     $9                #remainder
## End of file


texts:
The things I'm interested the most from the review are:

The performance of the code
Overall review of the code structure, styling rules and naming conventions.

  What is the largest prime factor of the number 600851475143 ?

import math
#----------------------------------------------------------------------------------
def prime_factorization(num_to_factor):
    """Calculates the prime factors of the input number based on
    Pollard's rho algorithm for integer factorization.

    Arguments:
        type:<int> - An number to factor.
    Return:
        type:<arr> - An array holding the prime factors of input number.
    """

    #------------------------------------------------------------------------------
    def calc_factor(num_to_factor):

        x,x_fixed = 2,2
        cycles = 2
        factor = 1

        while factor == 1:
            for counter in range(cycles):
                if factor > 1: break

                x = (x * x - 1) % num_to_factor
                factor = math.gcd(x - x_fixed, num_to_factor)

            x_fixed = x
            cycles *= 2
        return factor

    factors = []
    while num_to_factor > 1:

        # Gets the smallest factor of (num_to_factor) and appends it to the array.
        # Divides the (num_to_factor) with it, and starts searching for the next factor.
        factor = calc_factor(num_to_factor)
        factors.append(factor)
        num_to_factor //= factor

    return factors

#----------------------------------------------------------------------------------
def main():
    n = 600851475143
    print(' Prime factorization of {} is: {}'.format(n, prime_factorization(n)))
#----------------------------------------------------------------------------------
if __name__ == "__main__":
    main()


texts:
My requirement is to design a part of a solution in such matter that specific placeholders are replaces dynamically with a defined logic and new rules can be easily added.

Simple example:

  Today is {today}. The year is {year}. Last year was {year-1}.

Should output something like:

  Today is 26 Jan 2018. The year is 2018. Last year was 2017.

There are several more business and context specific placeholders and new rules can follow frequently.

As such I came up with this class:

public class PlaceholderDefinition
{
    public string Name { get; }
    public string Pattern { get; }
    private readonly Func<Match, string> _logic;

    public PlaceholderDefinition(string name, string pattern, Func<Match, string> logic)
    {
        Name = name;
        Pattern = pattern;
        _logic = logic;
    }

    public string Apply(Match match) => _logic.Invoke(match);
}

To fulfill the above example, I register the following PlaceholderDefinitions in the service configuration:

RegisteredPlaceholders.Add(
    new PlaceholderDefinition(
        "Today",
        @"{[tT][oO][dD][aA][yY]}",
        (_) => DateTime.Today.ToShortDateString()
    ));

RegisteredPlaceholders.Add(
    new PlaceholderDefinition(
        "Year",
        @"{[yY][eE][aA][rR]}",
        (_) => DateTime.Today.Year.ToString()
    ));

RegisteredPlaceholders.Add(
    new PlaceholderDefinition(
        "YearAddition",
        @"(?:{[yY][eE][aA][rR])([+-])(\d+)}",
        (m) =>
        {
            var operation = m.Groups[1].Value;
            int.TryParse(m.Groups[2].Value, out int value);
            return (operation == "+" ? DateTime.Today.Year + value : DateTime.Today.Year - value).ToString();
        }
    ));

The RegisteredPlaceholders is an enumerable of PlaceholderDefinition held in the container.

The logic of these patterns/placeholders is applied like this:

foreach (var placeholder in RegisteredPlaceholders)
 {
     var match = new Regex(placeholder.Pattern).Match(content);
     while (match.Success)
     {
         content = content.Remove(match.Index, match.Length).Insert(match.Index, placeholder.Apply(match));
         match = match.NextMatch();
     }
 }

I decided to take this approach instead of using Regex.Replace() to not reveal the content or text to the class defining the pattern logic. Maybe there is a more elegant solution, that I didn't come up with.

Every critique, improvement proposal, code smells are welcome.


texts: Finding added keys, removed keys, and unchanged keys in ordereddict

texts:
I'm comparing two OrderedDict objects and I need to find added keys, removed keys, and keys that are present in both (the intersection).  Sets are designed for exactly that sort of thing, so my initial attempt involved getting the keys, converting to sets and then comparing/intersecting appropriately.  The trouble I ran into is that I need the order of the original keys to be preserved all the way through the process (hence the use of OrderedDict) and sets don't seem to do that.  I did some googling about ordered sets in python3, but there don't appear to be any native solutions, and I don't really want to bring in another class/library for this one small computation.  Instead, I came up with these lines of code:

def differences(a, b):
    added = []
    removed = []
    overlap = []
    for key in a.keys():
        if key in b:
            overlap.append(key)
        else:
            removed.append(key)

    for key in b.keys():
        if not key in a:
            added.append(key)

    return (added, removed, overlap)

I'm especially interested in hearing suggestions on different ways of tackling this problem, but I'm happy to hear any general suggestions.


texts:
Notes:

I know \ are against PEP8; they are for readibility
I created this working through a tutorial
I forgot to add blank lines, so it may be a little squished

''' Tic-Tac-Toe Minimax Program by Peter'''

#Tutorial found at: http://giocc.com/concise-implementation-of-minimax-through-higher-order-functions.html'''
class GameState:
    def __init__(self,board):
        self.board = board
        self.winning_combos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
    def is_gameover(self):
        '''returns if a game_state has been won or filled up'''
        if self.board.count('X') + self.board.count('O') == 9:
            return True
        for combo in self.winning_combos:
            if (self.board[combo[0]] == 'X' and self.board[combo[1]] == 'X' and self.board[combo[2]] == 'X') or \
            (self.board[combo[0]] == 'O' and self.board[combo[1]] == 'O' and self.board[combo[2]] == 'O'):
                return True
        return False
    def get_possible_moves(self):
        '''returns all possible squares to place a character'''
        squares = []
        for index, square in enumerate(self.board):
            if square != 'X' and square != 'O':
                squares.append(index)
        return squares
    def get_next_state(self, move, our_turn):
        '''returns the gamestate with the move filled in'''
        copy = self.board[:]
        if our_turn:
            copy[move] = 'X'
        else:
            copy[move] = 'O'
        return GameState(copy)
'''Named evals instead of eval to respect the eval function. http://stackoverflow.com/questions/9383740/what-does-pythons-eval-do'''
def evals(game_state):
    '''score a game_state from the computers point of view, 1 = win, 0 = tie, -1 = lose'''
    for combo in game_state.winning_combos:
        if game_state.board[combo[0]] == 'X' and game_state.board[combo[1]] == 'X' and game_state.board[combo[2]] == 'X':
            return 1
        elif game_state.board[combo[0]] == 'O' and game_state.board[combo[1]] == 'O' and game_state.board[combo[2]] == 'O':
            return -1
    else:
        return 0

'''max and min will call on each other recusively, until a terminal state'''
def max_play(game_state):
    '''if the game is over returns score, otherwise calls min_play on it's childen (possible moves from the state) and returns the maximum'''
    if game_state.is_gameover():
        return evals(game_state)
    return max(map(lambda move: min_play(game_state.get_next_state(move, True)), game_state.get_possible_moves()))
def min_play(game_state):
    '''if the game is over returns score, otherwise calls max_play on it's childen (possible moves from the state) and returns the minimum'''
    if game_state.is_gameover():
        return evals(game_state)
    return min(map(lambda move: max_play(game_state.get_next_state(move, False)), game_state.get_possible_moves()))

def minimax(game_state):
    '''returns the max of mapping the (move, score) tuple to the possible move using [1] of the tuple the (score)'''
    return max(map(lambda move: (move, min_play(game_state.get_next_state(move, True))), game_state.get_possible_moves()), key = lambda x: x[1])

def pretty_print(board):
    '''prints a list by 3 chars, joined by spaces'''
    print(' '.join(board[:3]))
    print(' '.join(board[3:6]))
    print(' '.join(board[6:9]))

'''starting board, assuming it is X's turn.'''
start_board = '_ _ _ ' + '_ O _ ' + '_ _ _'

'''Interpreting and printing start board'''
start_game_state = GameState(start_board.split(' '))
pretty_print(start_game_state.board)
'''Finding best possible move and score'''
move, score = minimax(start_game_state)
'''Displaying move and outcome'''
if score == 0:
    word = 'TIE'
elif score == 1:
    word = 'WIN'
else:
    word = 'LOSS, who rigged the board?!?'
print('X should go at index #',move, 'Which will always result in a ' + word)
start_game_state.board[move] = 'X'
pretty_print(start_game_state.board)


texts: Combining two 32-bit integers into one 64-bit integer

texts:
long long combine(unsigned int high, unsigned int low) {
    return ((unsigned long long) high) << 32 || low;
}

Is there a better name for the operation?
Is the implicit cast from unsigned long long to long long a reinterpret_cast, or what happens if the unsigned number is too large for the signed data type?


texts:
I currently have a utility that will display details about a list of specified users. In its current state I don't use any functions, which I've noticed make it a little more repetitive than I would like.
I'm specifically interested in how to make this more functional, but I'd be interested in any suggestions for how to make this better.
Details.py
class userdetails:

    def __init__(self, Userdetails, Education, Work_history, Bank_history,
    Credit_history):

        self.Userdetails = Userdetails
        self.Education = Education
        self.Work_history = Work_history
        self.Bank_history = Bank_history

My other file
from Details import userdetails

pin_no = ('1111', '2222', '3333')

while True:

   pin_no = input("Input the no : ")

   if pin_no == '1111' or pin_no == '2222' or pin_no == '3333':

       print ("\n Hello and welcome to my program.  Please choose from one of the following
options:")

       break

else:

    print ("please try again ")

Tom_Watts = userdetails ('Tom Watts \n' , '\nSidney Stringer School \n\n' 'GCSE English: Grade A \n'
'GCSE Maths:   Grade B \n' 'GCSE Physics: Grade A \n', 'GSA LTD', 'Barclays Bank', 'Good')

Bill_Gates = userdetails ('Bill Gates \n ', '\nBinley Woods School \n\n' 'GCSE Maths: Grade A \n',
'MI6', 'Bank of England', 'Good' )

Steve_McQueen = userdetails ('Steve McQueen \n', '\nArizona High School \n\n' 'GCSE English: Grade A
\n' 'GCSE Maths:   Grade A \n', 'GSA LTD', 'Lloyds Bank ', 'Average')

dict = {

    '1111': Tom_Watts,
    '2222': Bill_Gates,
    '3333': Steve_McQueen,

}

user =  input("\n\n 1. Userdetails \n 2. Education \n 3. Work History \n 4. Bank History \n" ' 5.
Credit History \n\n  '  )

a = '1'
b = '2'
c = '3'
d = '4'
e = '5'

if user == a:

    print (dict[pin_no].Userdetails)

elif user == b:

    print (dict[pin_no].Education)

elif user == c:

    print (dict[pin_no].Work_history)

elif user == d:

    print (dict[pin_no].Bank_history)

elif user == e:

    print (dict[pin_no].Credit_history)


texts: Requesting product data from an eBay webform

texts:
The code takes in a hash that comes from a webform and also works with product data from the database. It then uses an eBay gem I built that connects with the eBay API and then returns a response object that you can call #extract on to return desired data. #extract takes an optional argument that will return data other than the default.

I've been working with this code for quite some time, trying to figure out how I can break it up. It feels very clunky and unorganized.

require 'ebay'

class ListingForm
  include ActiveModel::Model

  attr_accessor :title, :price, :subtitle, :product_id, :duration

  def initialize(form={})
    @title = form[:title]
    @price = form[:price]
    @subtitle = form[:subtitle]
    @product_id = form[:product_id]
    @duration = form[:duration]
    @product = set_product if @product_id
  end

  def post
    yield self if block_given?
    ebay_response = api.add_item(item: item)
    item_id = ebay_response.extract
    if valid_listing?(item_id)
      Listing.new(product_id: @product.id,
                  item_number: item_id).save
    else
      raise "invalid item number"
    end
    ebay_response
  end

  def valid_listing?(item_id)
    item_id.to_i != 0
  end

  def item_specifics
    item_specifics = []
    @product.properties.each do |k,v|
      name = k.to_s.for_humans
      value = "#{v}#{PROPERTY_FORMATTER[k.to_sym]}"
      if value == "1"
          value = "included"
      elsif value == "0"
        next
      end
      item_specifics << Ebay::Types::NameValueList.new({name: name, value: value})
    end
    item_specifics
  end

  def remote_images
    remote_images = []
    @product.images.each do |i|
      url = "http://www.howmuchcomputer.com" + i
      remote_url = @api.upload_site_hosted_pictures({:external_picture_url => url})
      remote_images << remote_url.extract(ignore_errors: true)
    end
    remote_images.reverse!
  end

  def template(path)
    ERB.new(File.open(path, "r").read).result(binding).to_s
  end

  def item
    Ebay::Types::Item.new({
      :start_price => price.to_s || @product.price.to_s,
      :description => template("lib/ebay_templates/description.html.erb"),
      :condition_description => template("lib/ebay_templates/condition_description"),
      :listing_duration => "Days_#{duration}",
      :item_specifics => item_specifics,
      :listing_type => "FixedPriceItem",
      :title => title || @product.ebay_title,
      :currency => "USD",
      :country => "US",
      :postal_code => "21030",
      :global_shipping => "true",
      :payment_methods => ["PayPal", "VisaMC", "Discover"],
      :auto_pay => "true",
      :condition_id => @product.condition.to_s,
      :paypal_email_address => "info@EMAIL.com",
      :dispatch_time_max => 1,
      :picture_details => remote_images
    })
  end

  def set_product
    @product = Product.find(@product_id)
  end

  def api
    @api ||= Ebay::Api.new
  end
end


texts:
Background:
This is supposed to be the sole worker thread to carry out long-lasting jobs in a GUI application. The GUI thread should be able to schedule tasks in a non-blocking manner and the tasks should que-up until the thread gets around executing them. I tried my best to make it exception safe.
Code:
#include <condition_variable>
#include <functional>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>

class WorkerThread final {
 public:
  using Task = std::function<void(void)>;

 private:
  /* this mutex must be locked before
   * modifying state of this class */
  std::mutex _mutex;

  /* list of tasks to be executed */
  std::queue<Task> _toDo;

  /* The thread waits for this signal when
   * there are no tasks to be executed.
   * `notify_one` should be called to
   * wake up the thread and have it go
   * through the tasks. */
  std::condition_variable _signal;

  /* This flag is checked by the thread
   * before going to sleep. If it's set,
   * thread exits the event loop and terminates. */
  bool _stop = false;

  /* the thread is constructed at the
   * end so everything is ready by
   * the time it executes. */
  std::thread _thread;

 private:
  /* entry point for the thread */
  void ThreadMain() noexcept {
    /* Main event loop. */
    while (true) {
      /* not locked yet */
      std::unique_lock lock{_mutex, std::defer_lock_t{}};  // noexcept

      /* Consume all tasks */
      while (true) {
        /* locked while we see if
         * there are any tasks left */
        lock.lock();  // won't throw

        if (_toDo.empty()) {  // noexcept
          // Finished tasks. Mutex stays locked
          break;
        }

        // Pop the front task
        // move shouldn't throw
        auto const task = std::move(_toDo.front());
        _toDo.pop();

        // Allow other tasks to
        // be added while we're executing one
        lock.unlock();  // won't throw

        try {
          // execute task
          task();  // May throw. Will be caught.
        } catch (...) {
          // log if throws
        }
      }

      // queue is empty (and mutex is still locked)

      /* if `_stop` is set, unlock
       * mutex (in lock destructor)
       * and stop the thread */
      if (_stop) return;

      // wait for further notice (and unlock the mutex)
      _signal.wait(lock);  // won't throw
    }
  }

 public:
  template <class Func>
  void Schedule(Func&& func) {
    // lock the mutex so we can add a new task
    std::lock_guard<std::mutex> guard{_mutex};

    // push the task
    // May throw. RAII lock will be unlocked. State is valid
    _toDo.push(std::forward<Func>(func));

    // notify the worker thread in case it's sleeping
    _signal.notify_one();
  }

  WorkerThread() : _thread(&WorkerThread::ThreadMain, this) {}

  ~WorkerThread() {
    std::unique_lock lock{_mutex};  // won't throw
    // tell the thread to finish up
    _stop = true;

    // wake up the thread in case it's sleeping
    _signal.notify_one();  // noexcept

    lock.unlock();  // won't throw

    // wait for the thread to finish up
    _thread.join();  // won't throw since ThreadMain is noexcept
  }

  WorkerThread(WorkerThread const&) = delete;
  WorkerThread& operator=(WorkerThread const&) = delete;
  WorkerThread(WorkerThread&&) = delete;
  WorkerThread& operator=(WorkerThread&&) = delete;
};

// Example driver code

#include <chrono>
#include <iostream>

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

  int constexpr sz = 100;

  int vars[sz];

  {
    WorkerThread thread;
    for (int i = 0; i < sz; ++i) {
      thread.Schedule([&vars, i] {
        std::this_thread::sleep_for(1ms);
        vars[i] = i;
      });
    }
  }

  for (auto const var : vars) std::cout << var << '\n';
}

The parts marked with // won't throw are parts I believe won't possibly throw even though aren't marked with noexcept.


texts: Observer pattern implementation in JavaScript

texts:
I'm working on redeveloping a running project, and the main goal is to enhance the JS code as much as possible.

I'm using the observer pattern to watch the window events like scroll, and resize

The following is my implementation:

module.exports = {

    // Watch window scrolling/resizing, then fire a set of watchers
    watchWindow: {
        watchers: {
            scroll: {},
            resize: {}
        },
        initialized: false,
        init: function () {
            this.initialized = true;
            var watchers = this.watchers;
            $window.on('scroll resize', function (e) {
                for(var id in watchers[e.type]) {
                    if(watchers[e.type].hasOwnProperty(id)) {
                        if (typeof watchers[e.type][id] === 'function') {
                            watchers[e.type][id](e.type === 'scroll' ? $window.scrollTop() : $window.width());
                        }
                    }
                }
            });
        },
        addWatcher: function (settings) {
            var id = Date.now();
            this.watchers[settings.event][id] = settings.callback;
            !this.initialized && this.init();
            return id;
        },
        removeWatcher: function(settings) {
            delete this.watchers[settings.event][settings.id];
        }
    }
}

Then that's how I'm using it:

// Watch window resizing
utilities.watchWindow.addWatcher({
    event: 'resize',
    callback: function (windowWidth) {
        mobileMenuEnabled = windowWidth < sideMenuBreakpoint;
    }
});


texts:
I was wondering if this code can be coded better in terms of semantics or design. Should I return the LOS as numbers? should I have the constants be read from the db in case the user or I want to change them in the future?

def get_LOS(headway = None, frequency = None, veh_per_hr = None):
  if frequency != None and headway = veh_per_hr == None:
    headway = 1 / frequency

  if headway!= None or veh_per_hr != None:
    if headway 10 < or veh_per_hr > 6:
      return 'A'
    elif 10 <= headway < 15 or 5 < veh_per_hr <= 6:
      return 'B'
    elif 15 <= headway < 20 or 3 < veh_per_hr <= 5:
      return 'C'
    elif 20 <= headway < 31 or 2 < veh_per_hr <= 3:
      return 'D'
    elif 31 <= headway < 60 or 1 <= veh_per_hr < 2:
      return 'E'
    elif headway >= 60 or veh_per_hr < 1:
      return 'F'
    else:
      return 'Error'


texts: Daily coding problem 18: Maximums of k-sized windows

texts:
The challenge

Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.

For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since:

10 = max(10, 5, 2)
7 = max(5, 2, 7)
8 = max(2, 7, 8)
8 = max(7, 8, 7)

Do this in O(n) time and O(k) space. You can modify the input array in-place and you do not need to store the results. You can simply print them out as you compute them.

My question

This was posed as a hard coding challenge. My confusion is that I solved the problem in 5 lines of code. Either the code doesn't achieve the correct time complexity (which I think it does), or this challenge has been incorrectly categorised. Please can someone review my code to see if it is correct.

array = [10,5,2,7,8,7,9]
k = 4

for index in range (len(array)-(k-1)):
    print(max(array[index:index+k]))


texts: Test 2 time ranges to see if they overlap

texts:
I am doing a project for school and had to create a function to check if 2 time ranges overlap. I searched the net a bit but failed to find a simple function to do that. I played around a bit with my code and I think I created a working one.

Note: it works for 24 hour times only & don't forget the 0 in front of AM time e.g "08:15"

If anyone has a better function to do this or finds some bugs in the code below - please post below.

Here is the code you can test directly on.

$start_time1 = "10:15";
$end_time1 = "12:20";

$start_time2 = "13:15";
$end_time2 = "14:25";

function testRange($start_time1,$end_time1,$start_time2,$end_time2)
{
    $timeCheck;

    if(($end_time1 < $start_time2))
    {
        $timeCheck = true;
        return $timeCheck;
    }
    else if(($start_time1 > $start_time2) && ($start_time1 > $end_time2))
    {
        $timeCheck = true;
        return $timeCheck;
    }
    else
    {
        $timeCheck = false;
        return $timeCheck;
    }

}

if(testRange($start_time1,$end_time1,$start_time2,$end_time2))
{
    echo "Not In Range";
}
else
{
    echo "In Range";
}


texts:
My disgusting list comprehension in the return statement is quite a headful.

"""Hopefully this function will save you the trip to oocalc/excel.

"""

def rangeth(start, stop=None, skip=1):
    """rangeth([start,] stop[, skip])

returns a list of strings as places in a list (1st, 2nd, etc)

>>> rangeth(4)
['0th', '1st', '2nd', '3rd']

    """

    if stop is None:
        stop, start = start, 0

    places = {'1':'st', '2':'nd', '3':'rd'}

    return ["{}{}".format(i, places.get(i[-1], 'th')) \
            if i[-2:] not in ['11', '12', '13'] else "{}{}".format(i, 'th') \
            for i in map(str, range(start, stop, skip))]

Also, can someone explain to me how range accepts it's parameters? I have my ugly little boilerplate here that I wish didn't exist. I can't find the source for range, as I gave up after thinking it's probably some header file in include.


texts:
My goal is to read from standard input, break up the input into words (Unicode letters and apostrophes), case-insensitively, and produce a report to standard output, where each line is a word followed by a space followed by its count. The output should be sorted by words.

This is my code:

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

class TraditionalWordCountApp
{
    public static void Main(string[] args)
    {
        SortedDictionary<string, int> counts = new SortedDictionary<string, int>();
        Regex wordRegex = new Regex(@"[\p{L}']+");
        string line;
        while ((line = Console.ReadLine()) != null)
        {
            line = line.ToLower();
            foreach (Match m in wordRegex.Matches(line))
            {
                String word = m.Value;
                int count;
                counts.TryGetValue(word, out count);
                counts[word] = ++count;
            }
        }
        foreach (KeyValuePair<string, int> pair in counts)
        {
            Console.WriteLine("{0} {1}", pair.Key, pair.Value);
        }
    }
}

My concerns:

Should things be wrapped in a namespace?
Should either the class or the main function or both be public?
Is there a nicer way to declare the sorted dictionary? Java has <>, does C#?
I used the C-style idiom of assigning to a variable and then checking for null, all inside the while-condition! Surely there is a nicer way to do this in C#. Is there? I like neither the embedded assignment nor the billion-dollar-mistake null. :)
I searched StackOverflow a bit for a nicer way to update a word frequency dictionary. Most languages seem to have a built-in get-with-default method on dictionaries, but the answers I saw said no, and they recommended TryGetValue. These answers are old, though. Is there something nicer in the most modern C#?
Any nicer way to do the last loop?
Would a LINQ-based solution be nicer? More idiomatic? What would it look like? I think (though I am brand new to C#) I could whip something up, but should I? FWIW I do know how to do the LINQ-y stuff in Java but wonder if this is the right way to go in C#.


texts: Reading a line from a text file and splitting its contents

texts:
I have this kind of file structure

MALE:FooBar:32
FEMALE:BarFoo:23

Where I would want to identify the gender and age of person, <Gender>:<Name>:<age>

try{
    BufferedReader in = new BufferedReader(new FileReader("people.ser"));
    String s;

    while((s = in.readLine()) != null){

        String[] var = s.split(":");
             //var[0]=MALE etc etc
        addGender.add(var[0]);
    }

}catch(Exception e){
    e.printStackTrace();
}

Is using a delimiter (like a : in this case) to split string considered a bad practice?
What about using the array from the splitted string to store it in some place?
Are there any alternatives and better file structure?


texts: Feedback Request on Title Capitalization Function Converted From JavaScript to PHP

texts:
I have a function in JavaScript that converts a string value to title case using APA style:

function titleCase(str, options) {
  const stopwords = 'a an and at but by for in nor of on or so the to up yet'
  const defaults = stopwords.split(' ')

  const opts = options || {}

  if (!str) return ''

  const stop = opts.stopwords || defaults
  const keep = opts.keepSpaces
  const splitter = /(\s+|[-‑–—])/

  return str
    .split(splitter)
    .map((word, index, all) => {
      if (word.match(/\s+/)) return keep ? word : ' '
      if (word.match(splitter)) return word

      if (
        index !== 0 &&
        index !== all.length - 1 &&
        stop.includes(word.toLowerCase())
      ) {
        return word.toLowerCase()
      }

      return capitalize(word)
    })
    .join('')
}

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

Credits of above JS functions

I converted the above to PHP:

function APATitle($title, $keepSpaces = false, $stopWords = array())
{
    if (!is_string($title)) {
        return false;
    }

    if (!is_array($stopWords) || count($stopWords) < 1) {
        $stopWords = array('a', 'an', 'and', 'at', 'but', 'by', 'for', 'in', 'nor', 'of', 'on', 'or', 'so', 'the', 'to', 'up', 'yet'); //Must all be lowercase!
    }

    $regexWordSplit = '/(\s+|[-‑–—])/';
    $words = preg_split($regexWordSplit, $title, -1, PREG_SPLIT_DELIM_CAPTURE);

    foreach ($words as $i => $currWord) {
        if (preg_match('/\s+/', $currWord) === 1) {
            if (!$keepSpaces) {
                $words[$i] = ' ';
            }
            continue;
        }

        if (preg_match($regexWordSplit, $currWord) === 1) {
            continue;
        }

        $currWordLower = strtolower($currWord);
        if ($i != 0 && $i != count($words) - 1 && in_array($currWordLower, $stopWords)) {
            $words[$i] = $currWordLower;
            continue;
        }

        if (strlen($currWord) > 0) {
            $currWord[0] = strtoupper($currWord[0]);
            $words[$i] = $currWord;
        }
    }

    return implode('', $words);
}

Everything works well (as far as I can tell). I'm looking for feedback on the above conversion and also general feedback on the PHP code (which it's maybe too much of a JS translation).

Some el cheapo testing for the PHP code:

$tests = array(
    array('in' => '', 'out' => '', 'keepSpaces' => false),
    array('in' => 'this is a test', 'out' => 'This Is a Test', 'keepSpaces' => false),
    array('in' => 'why sunless tanning is A hot trend', 'out' => 'Why Sunless Tanning Is a Hot Trend', 'keepSpaces' => false),
    array('in' => 'Satin Sheets are a Luxury you Can Afford', 'out' => 'Satin Sheets Are a Luxury You Can Afford', 'keepSpaces' => false),
    array('in' => 'the Dangers Of Hiking Without Proper Shoes', 'out' => 'The Dangers of Hiking Without Proper Shoes', 'keepSpaces' => false),
    array('in' => 'an hour or so', 'out' => 'An Hour or So', 'keepSpaces' => false),
    array('in' => 'Of the meaning Of Of', 'out' => 'Of the Meaning of Of', 'keepSpaces' => false),
    array('in' => 'Thing With     Extra Spaces', 'out' => 'Thing With Extra Spaces', 'keepSpaces' => false),
    array('in' => 'Thing with     extra spaces', 'out' => 'Thing With     Extra Spaces', 'keepSpaces' => true),
    array('in' => 'Observations of isolated pulsars and disk-fed X-ray binaries.', 'out' => 'Observations of Isolated Pulsars and Disk-Fed X-Ray Binaries.', 'keepSpaces' => false)
);

$ok = 0;
foreach ($tests as $currTest) {
    $currRes = APATitle($currTest['in'], $currTest['keepSpaces']);
    if ($currRes === $currTest['out']) {
        ++$ok;
    }
}
echo $ok == count($tests) ? 'All tests OK' : 'Test bad';


texts: Handling success and failure when retrieving product information

texts:
I've got an Angular controller where I have two functions that are repeated inside two functions:

(function () {

    'use strict';

    angular
        .module( 'app.purchases.products' )
        .controller( 'ReadProductController', ReadProductController );

    ReadProductController.$inject = [ '$scope', 'ReadProductFactory' ];

    function ReadProductController( $scope, ReadProductFactory ) {

        /* jshint validthis: true */
        var vm = this;

        vm.products          = {};
        vm.product           = {};
        vm.getProductsList   = getProductsList;
        vm.getProductDetails = getProductDetails;

        function getProductsList( columnOrder, sortOrder ) {

            var data = {
                columnOrder: columnOrder,
                sortOrder: sortOrder
            };

            ReadProductFactory.listProducts( data, success, fail );

            //The following are the callbacks funcs but they repeat
            //for the getProductDetails func too, should i set them global?
            function success( products ) {
                vm.products = products;
            }

            function fail( error ) {
                console.log( error );
            }
        }

        function getProductDetails( id ) {

            var data = {
                id: id
            };

            ReadProductFactory.detailProduct( data, success, fail );

            function success( product ) {
                vm.product = product;
            }

            function fail( error ) {
                console.log( error );
            }

        }

    }

})();

The above is the controller of a Product Listing view, i've tried to take rest logic to a factory, what i feel is that my code is not completely DRY because of the callback functions, maybe you'll understand better what i've tried to do with the factory code, here it is:

(function () {

    'use strict';

    angular
        .module( 'app.purchases.products' )
        .factory( 'ReadProductFactory', ReadProductFactory );

    ReadProductFactory.$inject = [ 'Restangular' ];

    function ReadProductFactory( Restangular ) {

        return {
            detailProduct: detailProduct,
            listProducts: listProducts
        };

        function detailProduct( data, success, fail ) {

            Restangular
                .one( '/purchases/products/', data.id )
                .all( '/detail' )
                .getList()
                .then( success, fail );

        }

        function listProducts( data, success, fail ) {

            Restangular
                .all( '/purchases/products/list' )
                .getList()
                .then( success, fail );

        }

    }

})();

Somes have told me to use promises instead of callback, how could i do that?
Also, is it good practice to declare empty arrays as I've done?


texts: Django controller method to list the top characters, guilds, and killers

texts:
I've been reading the Chapter 8 of this book.

Here's the view I'm currently coding. It list all characters/guilds according to the type of URL.

/ranking -> List Top 50 Characters

/ranking/guild -> List top guilds

/ranking/pvp -> list top killers

def ranking(request, type):
    if type=='':
        queryset_list = Character.objects.annotate(num_resets=Count('resets')).order_by('-resets').select_related('account')[:50]
        paginator = Paginator(queryset_list, 10)

        page = request.GET.get('page')
        try:
            queryset = paginator.page(page)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)
            context = {'object_list' : queryset, 'states':STATES, 'class_type':CLASS_TYPE}
        template = 'ranking_character.html'
    elif type=='guild':
        queryset_list = Guild.objects.all()
        paginator = Paginator(queryset_list, 10)

        page = request.GET.get('page')
        try:
            queryset = paginator.page(page)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)

        context = {'object_list' : queryset}
        template = 'ranking_guild.html'

    elif type=='pvp':
        queryset_list = Character.objects.filter(pk_count__gt=0).annotate(total=Count('pk_count')).order_by('-pk_count')[:50]
        paginator = Paginator(queryset_list, 10)

        page = request.GET.get('page')
        try:
            queryset = paginator.page(page)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)
            context = {'object_list' : queryset, 'class_type':CLASS_TYPE}
        template = 'ranking_pvp.html'

    return render(request,template,context)

It's possible to make it more "generic"? How can I abstract this different queryset?


texts: Keeping object consistence at its creation

texts:
Let's assume I have 2 objects Product and Volume. 1 Product must have at least 1 Volume which means: Product ----> 1...* Volume.

I want to keep the consistence of Product at its creation, in other words, I want to block the user to create products without any volumes.

I have a ready working code, but nonetheless I want to know your opinions guys.

Here is the running code: https://3v4l.org/t7JqO#v700

Here is my code:

<?php
declare(strict_types = 1);

namespace App
{
    class Product
    {
        private $id;
        private $name;
        private $volumes;

        /**
         * Product constructor.
         * @param int $id
         * @param string $name
         * @param array $volumes
         * @throws \InvalidArgumentException
         */
        public function __construct(int $id, string $name, array $volumes)
        {
            $this->id = $id;
            $this->name = $name;

            if (count($volumes) === 0) {
                throw new \InvalidArgumentException('Your product must have 1 product at least.');
            }

            $this->volumes = $this->prepareVolumes($volumes);
        }

        private function prepareVolumes(array $volumes)
        {
            foreach ($volumes as $volume) {
                $volume->setProduct($this);
            }
            return $volumes;
        }
    }

    class Volume
    {
        protected $id;
        protected $product;
        protected $description;

        public function __construct(string $description)
        {
            $this->description = $description;
        }

        public function setProduct(Product $product)
        {
            $this->product = $product;
        }
    }

    class ProductTest
    {
        public function __construct()
        {
            $volume1 = new Volume('part-1');
            $volume2 = new Volume('part-2');
            $volume3 = new Volume('part-3');

            $product = new Product(1, 'BED', [$volume1, $volume2, $volume3]);
            $invalidProduct = new Product(2, 'Table', []);
        }
    }

    return new ProductTest();
}


texts:
Here is the function I have come up with. Any improvements possible?

E.g LeetCode -> rotate by 2 -> deLeetCo

public static String rotateAntiClockWise(String s, int offset){
    int i = offset%s.length();
    StringBuffer prefix = new StringBuffer();
    for(int j=0;j<i;j++){
        prefix.append(s.charAt(s.length()-1-j));
    }
    return prefix.append(s.substring(0, s.length()-i)).toString();
}