texts:
The idea here is that rather than placing objects directly into the scene, these building objects are instantiated at run time and placed in the correct locations.  This gives me full control over where and how to place the buildings.

The workflow is still a little involved. I have to import the model and texture image, drag it out into the scene, scale it, add a Mesh collider to it, and then add all of that to a prefab object that I also need to create. Then I need to add the name of that prefab to the script below. This must be done for each model that I want to use in the game.  This approach is still a whole lot better than having to manually place and position each object in the Unity scene though.

GameModelScript.cs

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class GameModelScript : MonoBehaviour {

    public int worldSize;

    private System.Random random = new System.Random();

    void Start () {
        List<string> names = new List<string> ();
        names.Add ("arco01_2_prefab");
        names.Add ("arco03_prefab");
        names.Add ("arco04_prefab");
        names.Add ("arco05_prefab");
        names.Add ("ballTower01_prefab");
        names.Add ("bank01_prefab");
        names.Add ("barn01_prefab");
        names.Add ("bigApartments05_prefab");
        names.Add ("bigFactory06_prefab");
        names.Add ("bigMatterCube01_prefab");
        names.Add ("busDepot01_prefab");
        names.Add ("casino01_prefab");

        for (int y = 0; y < worldSize; y+=30) {
            for (int x = 0; x < worldSize; x+=30) {
                int randomNumber = random.Next(0, names.Count);
                GameObject tileObject = (GameObject)GameObject.Instantiate (Resources.Load (names[randomNumber]));
                tileObject.transform.position = new Vector3(x, 10, y);
            }
        }
    }

    void Update () {
    }
}

My plan is to use this foundation to build some kind of superhero city exploration game.  Here is a link to a very early playable version: Super Voxel

And here is a little screenshot from up high:


texts:
I wrote the following function that takes a string and returns a new string with each word capitalized: first letter uppercase, following letters lower-cased.

It works, but I would be interested in seeing how a more sophisticated Haskell programmer would do this (if there is already a built-in, great, but still interested in an example implementation).

ghci> let capWord word = [toUpper $ head word] ++ (map toLower $ tail word)
ghci> let capitalize sentence = unwords $ map capWord $ words sentence
ghci> capitalize "the quick brown fox jUMPS OVER thE LaZY DOG"
"The Quick Brown Fox Jumps Over The Lazy Dog"


texts: Testing an implementation of ports-and-adaptors for tkinter

texts:
I'm trying to test my implementation of ports-and-adaptors for tkinter.

Assume I have a tkinter Entry declared like so:

entry = tk.Entry(container)
entry.value = tk.StringVar()
entry.configure(textvariable=entry.value)

In module ports.py I have a simple function to set the value:

def set_widget_value(widget, value):
    widget.value.set(value)

In module adaptors.py I have a class that provides domain specific method to set the value:

from myapp.gui.ports import set_widget_value

class EntryAdaptor(object):
    """Wraps a Tkinter Entry widget."""

    def __init__(self, entry):
        self._entry = entry

    def set_value(self, value):
        set_widget_value(self._entry, value)

To test my adaptor layer I have come up with two options.

Option A

import unittest
import unittest.mock as mock

from myapp.gui.adaptors import EntryAdaptor

class EntryAdaptorTests(unittest.TestCase):

    def test_should_set_value_of_entry(self):
        entry = mock.Mock()
        adaptor = EntryAdaptor(entry)

        text = 'some user-typed text'
        adaptor.set_value(text)
        entry.value.set.\
            assert_called_once_with(text)

Option B

import unittest
import unittest.mock as mock

class EntryAdaptorTests(unittest.TestCase):

    def test_should_set_value_of_entry(self):
        entry = mock.Mock()
        with mock.patch('myapp.gui.ports.set_widget_value') as set_widget_value:
            from myapp.gui.adaptors import EntryAdaptor
            adaptor = EntryAdaptor(entry)

            text = 'some user-typed text'
            adaptor.set_value(text)

            set_widget_value.assert_called_once_with(entry, text)

In Option A, I'm looking at the mocked tkinter.Entry object and checking if it was called as expected; this has the disadvantage of mocking the external tkinter API.

In Option B, I mock my set_widget_value() function and check if it was called as expected; this has the disadvantage of performing the import of EntryAdaptor within the test_should_set_value_of_entry() method because of the dependency of adaptors.py to ports.py.

Which is the best way to perform the test: A, B or something completely different?


texts: Python code to continue if a certain type is seen, otherwise try again to get valid input

texts:
I am very very new to programming, and this is my first day using Python.

I want to check to see if an input is of type 'int' and to proceed with my program if the user has entered an 'int', otherwise to print some error message, followed by a prompt to the user to try again.

What I have:

user_in = input('Input an integer value')
if type(user_in) == int:
    a = user_in
else:

I'm really not sure what to do here, or if its even possible to achieve this way, hence the blank line after 'else:'! I tried it with a while loop with try and excepts such as this:

while True:
    try:
        user_in = int(input('Enter an integer value'))
        a = user_in
    except:
        print('Invalid input, please try again')

Which works good for the exception case (because of the while True essentially acting infinitely), but of course, does not move on to the next part of the code in the case where an integer has successfully been inputted.


texts:
I am summing the total .outerHeight() of multiple divs like this:

var h = $('#div1').outerHeight() + $('#div2').outerHeight() + $('#div3').outerHeight() + $('#div4').outerHeight();

Is there any way to do this more efficiently?

I was considering something like this (but it doesn't work):

$('#div1, #div2, #div3').outerHeight();


texts:
I've got this transform method with a triple-nested loop. The Generate methods do their own caching so they are fast. K will have a worst-case value of 150. N will have a worst-case value of about 20000. It's that 200002 that's killing me. It looks to me like the innermost loop could be moved out, but would you store every possible sum?

    public static void Transform(IList<float> x, int offset, int sampleRate, int binsPerOctave,
        double minFrequency, double maxFrequency, out double[] magnitudes, out double maxMagnitude)
    {
        var Q = 1.0 / (Math.Pow(2.0, 1.0 / binsPerOctave) - 1.0);
        var K = (int)Math.Ceiling(Math.Log(maxFrequency / minFrequency, 2.0) * binsPerOctave);

        magnitudes = new double[K];
        var maxN = (int)Math.Round(Q * sampleRate / minFrequency);
        var halfN = -maxN / 2;
        double[] wcs = GenerateWindowConstants(maxN);
        maxMagnitude = double.NegativeInfinity;

        for(int k = 0; k < K; k++)
        {
            var N = (int)Math.Round(Q * sampleRate / (minFrequency * Math.Pow(2.0, (double)k / binsPerOctave)));
            Complex[] piqs = GeneratePiQConstants(N, Q);

            var maxMag = double.NegativeInfinity;
            for(int i = 0; i < N; i++)
            {
                Complex sum = new Complex();
                for(int n = 0; n < maxN; n++)
                {
                    var index = n + offset + halfN;
                    index = Math.Min(x.Count - 1, index);
                    index = Math.Max(0, index);
                    sum += (wcs[n] * x[index]) * piqs[(n + i) % N];
                }
                sum /= maxN;
                maxMag = Math.Max(maxMag, sum.Magnitude);
            }
            magnitudes[k] = maxMag;
            maxMagnitude = Math.Max(maxMagnitude, maxMag);
        }
    }


texts:
I wrote this function to map value to a color

I am looking for some general feedback on how I can improve the efficiency of the function. and if there is better way to do it.

function getColor($value, $values_range, $opacity = '0.7') {

       $deltaS = ($values_range['max'] - $values_range['min']) / 2;
       $ds = ($value - $values_range['min']) / $deltaS;
       $nearest_color_index = floor($ds);
       $alpha = $ds - $nearest_color_index;

      $r = $g = $b = -1;
      $colors = [['r'=>255,'g' => 60,'b' => 40],
                 ['r' => 255,'g' => 247,'b' =>40],
                 ['r' => 12,'g' => 197,'b' => 17]];

      if ($nearest_color_index != 2) {
             $r = round($colors[$nearest_color_index]['r'] + $alpha * ($colors[$nearest_color_index + 1]['r'] - $colors[$nearest_color_index]['r']));
             $g = round($colors[$nearest_color_index]['g'] + ($alpha * ($colors[$nearest_color_index + 1]['g'] - $colors[$nearest_color_index]['g'])));
             $b = round($colors[$nearest_color_index]['b'] + $alpha * ($colors[$nearest_color_index + 1]['b'] - $colors[$nearest_color_index]['b']));

             return "rgba($r,$g,$b,$opacity)";

     } else {
          $r = round($colors[$nearest_color_index]['r']);
          $g = round($colors[$nearest_color_index]['g']);
          $b = round($colors[$nearest_color_index]['b']);
          return "rgba($r,$g,$b,$opacity)";
  }

 }


texts: ASP.NET account login system implemented via Masterpage and Panels

texts:
I have been tasked with implementing a secure account login system for a website's content management system. I have built a solution around an access masterpage that handles all account access functions. Here is the Page_Load

Protected Sub Page_Load() Handles Me.Load
    If Not Request.IsSecureConnection Then
        Response.Redirect(Request.Url.ToString.Replace("http://", "https://"))
    End If
    UpdateSecurity()
End Sub

And the definition of UpdateSecurity()

Private Sub UpdateSecurity()
    PageContentPanel.Visible = Session("access")
    PleaseLogInPanel.Visible = Not Session("access")
End Sub

As you can probably infer from the snippet, having "access" set in the Session makes an asp:Panel containing the content of whatever child page the user requested visible, otherwise, the PageContentPanel is hidden, and the PleaseLogInPanel with a username and password prompt is made visible. In the handler for the login button (also on the login Panel), the posted credentials are verified and if correct, Session values are added.

I was wondering if this implementation is fundamentally sound or not. Page requests from not logged in users still execute (I think), but the results are hidden inside an invisible asp:Panel. I'm not familiar enough with the ASP.NET security model to know if this poses risks or not from wayward POSTs. If a child page utilizes this masterpage, what access do not logged in users have to resources on the page?


texts:
This is an alternative edition of a game I modified the code for. See:

Guess My Number, Classic Edition

I seek advice on best practice. Tips, tricks, and suggestions, all welcome:

# Alex Grattan
# 9/10/14

# This is an alternative version of the "Guess My Number Game".
# The Computer now has the role of guessing a number chosen by the player.
# The Computer emulates the expected behaviour of a player -
# The Computer will not choose a number higher or lower than one already chosen.

import random

BOUNDS = (1, 100)
THE_NUMBER = int(input("\t\tPick a number between %r and %r:\n " % BOUNDS))
TRIES_ALLOWED = 7
PREVIOUS_GUESSES = {'Min': BOUNDS[0], 'Max': BOUNDS[1]}
TRIES = 0

print("""\n\t\tThe Computer will now attempt to guess your number in a minimum of attempts:\n
\t\tO.K. Computer, you have %d gusses. Proceed!\n""") % TRIES_ALLOWED

for x in range(TRIES_ALLOWED):

    GUESS = random.randint(PREVIOUS_GUESSES.get('Min'), PREVIOUS_GUESSES.get('Max'))
    print ("\t\t\t %d\n") % GUESS
    TRIES += 1

    if GUESS > THE_NUMBER:
        print("\t\tSorry Computer. Your guess of %d was too high.\n\t\tTake a lower guess:\n") % GUESS
        PREVIOUS_GUESSES['Max'] = GUESS - 1

    elif GUESS < THE_NUMBER:
        print("\t\tSorry Computer. Your guess of %d was too low.\n\t\tTake a higher guess:\n") % GUESS
        PREVIOUS_GUESSES['Min'] = GUESS + 1

    else:
        GUESS == THE_NUMBER
        print("""\tCongratulations Computer, you guessed it! The number was %d
        \t\tAnd it only took you %d tries!\n""") % (THE_NUMBER, TRIES)
        break
else:
    print("""Sorry Computer; you failed to guess the number!
    The number I chose was %d""") % THE_NUMBER


texts: SQL trigger to log when employee records are updated

texts:
I am learning TSQL (SQL in general for that matter), and I wrote this trigger that inserts logs about updated employees into the tblEmployeeAudit table.

When I was looking at the end result my eyes hurt.
The trigger was super simple, yet super long (for something which is so simple), it seemed as if a 10-year-old rascal wrote it. Does anyone know if I can make this any better/shorter, and/or How to avoid repeating same line of code 100 times? Here's the code.

Alter TRIGGER tr_tblEmployee_ForUpdate
ON tblEmployee
FOR UPDATE

AS
declare @id int
declare @Name nvarchar(50)
declare @GenderID int
declare @Salary int
declare @City nvarchar(50)
declare @DepartmentID int
declare @ManagerID int
declare @DateOfBirth datetime

declare @Nameol nvarchar(50)
declare @GenderIDol int
declare @Salaryol int
declare @Cityol nvarchar(50)
declare @DepartmentIDol int
declare @ManagerIDol int
declare @DateOfBirthol datetime

BEGIN
    Select @id = employeeid from inserted

    Select @Name = Name
          ,@GenderID = GenderID
          ,@Salary = Salary
          ,@City = City
          ,@DepartmentID = DepartmentID
          ,@ManagerID = ManagerID
          ,@DateOfBirth = DateOfBirth
    From Inserted

    Select @Nameol = Name
          ,@GenderIDol = GenderID
          ,@Salaryol = Salary
          ,@Cityol = City
          ,@DepartmentIDol = DepartmentID
          ,@ManagerIDol = ManagerID
          ,@DateOfBirthol = DateOfBirth
    From deleted

    Select * from deleted
    Select * from inserted
    Insert into tblEmployeeAudit2 values(
    'Employee with ID ='
    + str(@id)
    + ' changed Name from ' + cast(@Nameol as nvarchar(50)) + ' to ' + cast(@Name as nvarchar(50) )
    + 'Gender from ' +cast(@GenderIDol as nvarchar(5)) +' to ' +cast(@GenderID as nvarchar(5))
    + 'Salary from ' +cast(@SalaryOl as nvarchar(5)) +' to ' +cast(@Salary as nvarchar(5))
    + 'City from ' +cast(@Cityol as nvarchar(50)) +' to ' +cast(@City as nvarchar(50))
    + 'Department from ' +cast(@DepartmentIDol as nvarchar(5)) +' to ' +cast(@DepartmentID as nvarchar(5))
    + 'ManagerID from ' +cast(@ManagerIDol as nvarchar(5)) + ' to ' +cast(@ManagerID as nvarchar(5))
    )

END;


texts:
An entry for the August 2016 Community Challenge

I slightly modified the input and output to suit the snippet tool, and also because I really like the mapped output with the basins.

I have been golfing a lot recently, which always impacts my coding style. You will find a number of possibly too smart one-liners. I am looking for more gracious alternatives.

//1 liner helper functions
const $ = id => { return document.getElementById(id); },
      trim = s => { return s.trim(); },
      splitNumbersOnSpace = s => { return s.split(' ').map(Number); },
      join = a => { return a.join('') };

//DOM elements
const input = $('input'),
      output = $('output'),
      output2 = $('output2'),
      go = $('go');

go.addEventListener('click', () => {

  const depths = input.value.split('\n').map(trim).map(splitNumbersOnSpace),
        basins = Array(depths.length).fill().map(()=>{return [];}),
        basinDepths = new Map();
  let nextBasin = 1;

  //compare a spot with the lowest neighbour thus far
  function compareNeighbour( lowestSpotSoFar, attemptRow, attemptCol ){
    try {
      if( depths[attemptRow][attemptCol] < lowestSpotSoFar.value ){
        lowestSpotSoFar.row = attemptRow;
        lowestSpotSoFar.col = attemptCol;
        lowestSpotSoFar.value = depths[attemptRow][attemptCol];
      }
    } catch (e) {
      //This is bound to happen due to out of bounds access requests
    }
  }

  //For a given spot, try and find a lower neighbour
  function lowestNeighbour(spot){
    //Assume we are in a sink
    const lowest = {
      row: spot.row,
      col: spot.col,
      value: depths[spot.row][spot.col]
    }
    //Test the assumption
    compareNeighbour( lowest, spot.row + 1, spot.col );
    compareNeighbour( lowest, spot.row - 1, spot.col );
    compareNeighbour( lowest, spot.row, spot.col + 1 );
    compareNeighbour( lowest, spot.row, spot.col - 1 );
    return lowest;
  }

  //Mark a whole path as belong to a basin
  function markPath( path , basin ){
    basinDepths.set( basin , ( basinDepths.get( basin ) || 0 ) + path.length );
    while(path.length){
      let spot  = path.shift();
      basins[spot.row][spot.col] = basin;
    }
  }

  //Recursively wander on the map towards a sink
  function wander( path ){
    const spot = lowestNeighbour( path[0] );
    //We are on a sink
    if( spot.row == path[0].row && spot.col == path[0].col ){
      markPath( path , nextBasin++ );
    //We hit a known path to a sink
    }else if ( basins[spot.row][spot.col] ){
      markPath( path , basins[spot.row][spot.col] );
    //Any other case, keep wandering
    }else {
      path.unshift(spot);
      wander(path);
    }
  }

  //Analyze the depth map
  for( let row = 0 ; row < depths.length ; row++ ){
    for( let col = 0 ; col < depths[row].length ; col++ ){
      //We already know know the basin this spot belongs to
      if( basins[row][col] )
        continue;
      //We will now wander on a path to a sink
      wander( [{row,col}] );
    }
  }

  //Spit it out
  output.innerHTML = basins.map( join ).join( '
' );
  output2.innerHTML = 'Sizes: ' + Array.from( basinDepths.values() ).sort().join(' ');
});
#output, #input {
  font-family: monospace;
}
<textarea id="input" rows="7">
    1 0 2 5 8
    2 3 4 7 9
    3 5 7 8 9
    1 2 5 4 3
    3 3 5 2 1</textarea>

  <button id="go">Analyze</button>

Output


texts: Algorithm to generate this alignment pattern locations table for QR codes

texts:
I'm looking for a way to generate the following the series of numbers given the version number on the left. For example, given "2", generate [6, 18]. The series of numbers is from the alignment pattern locations for different versions of QR codes.

 V2  6  18
 V3  6  22
 V4  6  26
 V5  6  30
 V6  6  34
 V7  6  22  38
 V8  6  24  42
 V9  6  26  46
V10  6  28  50
V11  6  30  54
V12  6  32  58
V13  6  34  62
V14  6  26  46  66
V15  6  26  48  70
V16  6  26  50  74
V17  6  30  54  78
V18  6  30  56  82
V19  6  30  58  86
V20  6  34  62  90
V21  6  28  50  72   94
V22  6  26  50  74   98
V23  6  30  54  78  102
V24  6  28  54  80  106
V25  6  32  58  84  110
V26  6  30  58  86  114
V27  6  34  62  90  118
V28  6  26  50  74   98  122
V29  6  30  54  78  102  126
V30  6  26  52  78  104  130
V31  6  30  56  82  108  134
V32  6  34  60  86  112  138
V33  6  30  58  86  114  142
V34  6  34  62  90  118  146
V35  6  30  54  78  102  126  150
V36  6  24  50  76  102  128  154
V37  6  28  54  80  106  132  158
V38  6  32  58  84  110  136  162
V39  6  26  54  82  110  138  166
V40  6  30  58  86  114  142  170

I've come up with the following Python code which generates the correct sequences, but contains an "exceptional" condition for V32, expressed in the if statement.

import math

def pattern(ver):
    w = 21 + ((ver - 1) * 4)       # Width
    h = 6                          # First item
    t = (w - 1) - 6                # Last item
    r = t - h                      # Distance between first and last
    n = math.ceil(r/28)            # Number of items in list - 1

    if (w == 145):
        intervals = 26             # Anomaly
    else:
        intervals = math.ceil(r/n) # Ceiling to nearest multiple of 2
        intervals = intervals + (intervals % 2)

    xs = [t]
    for m in (n-1) * [intervals]: xs.append(xs[-1] - m)
    xs.append(h)
    return list(reversed(xs))

for n in range(2, 41):
    print("Version {:2d}: {}".format(n, pattern(n)))

I'm looking for an algorithm where the magic branch & value is not needed The algorithm might not exist, but I'm hopeful.


texts: Update SQL database with using statement and SqlParameters

texts:
I'm just starting out to learn all about sql databases. For now based on previous suggestions that was given to me online, I've incorporated a using statement to avoid problems in sql connection and then I applied parameterized queries to avoid sql injection. I was also been given an advice to use sqlparameter arrays to supplement the parameterized queries that i implemented. I just want to know if there are other techniques that you would recommend to improve my code, which i will indicate below. Feel free to suggest better solutions.

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["brandsConnection"].ToString())) {
    string query = "UPDATE [guitarBrands] SET type = @type, name = @name, image = @image WHERE id = @id";
    SqlParameter[] p = new SqlParameter[4];
    p[0] = new SqlParameter("@type", newType.Text);
    p[1] = new SqlParameter("@name", newName.Text);
    p[2] = new SqlParameter("@image", newImage.Text);
    p[3] = new SqlParameter("@id", id);

    connection.Open();
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        GetExample(command, p);
        command.ExecuteNonQuery();
        connection.Close();
        command.Parameters.Clear();
    }
}

public void GetExample(SqlCommand command, params SqlParameter[] p)
{
  if (p != null && p.Any()){
        command.Parameters.AddRange(p);
   }

}


texts: More efficient jQuery scripting when manipulating multiple elements with multiple CSS attributes

texts:
I'm relatively new to JavaScript and jQuery so go easy on me. I'm creating a website where upon jQuery document.ready a set of basic animations are performed on different divs on the HTML markup. All divs have separate IDs and I am storing all divs with same CSS property change in the same variable. Using these variables I run the function after. This code works fine but what would be a more effective manner of writing it?

<script src="jquery-1.8.3.js" type="text/javascript" ></script>

<script type="text/javascript">
    $(document).ready(function() {
        function fader(){
            var logofade = $('#portlogo, #toolslogo, #contactlogo, #portfoliolblw, #toolslblw, #contactlblw'),
                homefade = $('#homelogo'),
                homeline = $('#hline'),
                uline = $('#upline'),
                acrossline = $('#acrossline'),
                glow = $('#logoglow');

            logofade.fadeOut(0)
            homefade.fadeOut(0).delay(300).fadeIn(100)
            homeline.delay(100).animate({'width': '150px'}, 100)
            uline.delay(200).animate({'height': '41px', 'top':'-30px'}, 100)
            acrossline.delay(300).animate({'width': '825px'}, 100)
            glow.fadeOut(0).delay(600).fadeIn(600);
        }

        fader()
    });

    function logochange() { $('#homelogo').delay(300).fadeIn(100);}
    function logochange1() { $('#portlogo, #toolslogo, #contactlogo').fadeOut(100);}

    function logochange2() { $('#portlogo').delay(300).fadeIn(100);}
    function logochange3() { $('#toolslogo, #homelogo,  #contactlogo').fadeOut(100);}

    function logochange4() { $('#toolslogo').delay(300).fadeIn(100);}
    function logochange5() { $('#portlogo, #homelogo, #contactlogo').fadeOut(100);}

    function logochange6() { $('#contactlogo').delay(300).fadeIn(100);}
    function logochange7() { $('#portlogo, #homelogo, #toolslogo').fadeOut(100);}

    function homebtn() { $('#homelblw').fadeIn(0);}
    function homebtn1() { $('#homelblw').fadeOut(0);}

    function portbtn() { $('#portfoliolblw').fadeIn(0);}
    function portbtn1() { $('#portfoliolblw').fadeOut(0);}

    function toolsbtn() { $('#toolslblw').fadeIn(0);}
    function toolsbtn1() { $('#toolslblw').fadeOut(0);}

    function contactbtn() { $('#contactlblw').fadeIn(0);}
    function contactbtn1() { $('#contactlblw').fadeOut(0);}

    function hline1() {$('#hline').animate({'width': '150px'}, 100);}
    function hline2() {$('#hline').animate({'width': '0px'}, 100);}

    function pline1() {$('#pline').animate({'width': '150px'}, 100);}
    function pline2() {$('#pline').animate({'width': '0px'}, 100);}

    function tline1() {$('#tline').animate({'width': '150px'}, 100);}
    function tline2() {$('#tline').animate({'width': '0px'}, 100);}

    function cline1() {$('#cline').animate({'width': '150px'}, 100);}
    function cline2() {$('#cline').animate({'width': '0px'}, 100);}

    function upline1() {
        $('#upline').animate({
            'height': '-41px', 'top':'0px'
        }, 0).delay(100).animate({
            'height': '41px', 'top':'-30px'
        }, 100);
    }

    function acrossline1() {
        $('#acrossline').animate({
            'width': '0px'
        }, 0).delay(200).animate({
            'width': '825px'
        }, 100);
    }
</script>


texts:
The statement is as follows :

  The sequence of triangle numbers is generated by adding the natural numbers.
     So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.

  The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have over five divisors.

  What is the value of the first triangle number to have over five hundred divisors?

My implementation :

import java.util.ArrayList;
import java.util.HashMap;
public class Euler_12{

    // This function finds the prime factorization
    // of a given number
    public static int getDivisors(int number){
        ArrayList<Integer> list = new ArrayList<Integer>();
        while(number%2==0){
            list.add(2);
            number/=2;
        }

        for(int i = 3; i<=Math.sqrt(number); i++){
            while(number%i==0){
                list.add(i);
                number/=i;
            }
        }

        if(number>2){
            list.add(number);
        }

        return findDivisors(list);
    }

    // Uses HashMap to convert multiples in form of
    // 2 2 2 2 4 4 to 2^4 x 4^2
    public static int findDivisors(ArrayList<Integer> list){
        int result = 1;
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i : list){
            if(map.containsKey(i))
                map.put(i, map.get(i)+1);
            else
                map.put(i, 1);

        }

        // Better take a look at [1]
        // on why I did this
        for(int i : map.keySet()){
            result = result * (map.get(i) + 1);
        }

        // the result is number of divisors
        return result;
    }

    public static int number = 0;
    public static int sequence = 1;
    // Returns the next Triangular number
    public static int nextTraingularNumber(){
        int temp = number + sequence;
        number = temp;
        sequence++;
        return temp;
    }
    public static void main(String[] args) {
        while(true){
            int i = nextTraingularNumber();
            if(getDivisors(i)>500){
                System.out.println("Found : " + i);
                break;
            }
        }
    }
}

It finds the answer in 0.812 seconds. Looking for improvements, suggestions are welcomed


texts:
I'm trying to design a database model for an API. So far, here's my attempt to do so:

I have a package called models that contains all of the models. Here, User is the database model and UserStorer is an interface that should be implemented by any store (e.g. postgres, mongodb etc.)

package models

//User represents an application user
type User struct {
    ID         int64
    Email      string
    Password   string
    FirstName  string
    MiddleName string
    LastName   string
}

...

//UserStorer represents a user store
//this can be used to store user on different
//data store
type UserStorer interface {
    List(...UserFilter) ([]User, error)
    Get(...UserFilter) (User, error)
    Create(User) error
    Update(User) error
    Delete(...UserFilter) error
}

Then I have a package called store, which contains the implementations of model stores like UserStorer

package store

import (
    "github.com/jmoiron/sqlx"

    "github.com/steven-ferrer/go-db-models/models"
)

//UserStore implements models.UserStorer
type UserStore struct {
    db *sqlx.DB
}

func (cs *UserStore) List(filters ...models.UserFilter) ([]models.User, error) {
    return nil, nil
}

func (cs *UserStore) Get(filters ...models.UserFilter) (models.User, error) {
    return models.User{}, nil
}

func (cs *UserStore) Create(User models.User) error {
    return nil
}

func (cs *UserStore) Update(User models.User) error {
    return nil
}

func (cs *UserStore) Delete(filters ...models.UserFilter) error {
    return nil
}

func NewUserStore(db *sqlx.DB) models.UserStorer {
    return &UserStore{db}
}

The question is, am I doing it right? If not, how do I improve it?

Here is the repo of the example that I used: https://github.com/steven-ferrer/go-db-models


texts:
My code works fine, but it's takes too much time, say around 65 seconds, for large input data. If there are 50,000 numbers in the list \$a\$ and we have to rotate the numbers 45,000 times then it takes 1 minute.

How can I reduce the time it takes to print all the numbers?

Problem:
perform an operation called a right circular rotation on an array of integers [a0 , a1 , a2 , ..a(n-1)]. After performing one right circular rotation operation, the array is transformed to [a(n-1) , a0 , a1 ,..a(n-2)].

Input Format

The first line contains 3 space-separated integers, \$n\$, \$k\$
and \$q\$ respectively.
The second line contains \$n\$ space-separated integers, where each
integer \$i\$ describes array element a[i] (where \$0 \le i<n\$).
Each of the \$q\$ subsequent lines contains a single integer denoting \$m\$.

n,k,q = input().strip().split(' ') #n=no of integers in the list , k=no of rotation ,q=no of lines for integer m

n,k,q = [int(n),int(k),int(q)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]

for i in range(0,k):
    a=[a.pop(n-1)]+a  #for putting the last element to the first position and del it from the last pos

for a0 in range(q):    # printing value of a at a given index
  m = int(input().strip())
  print(a[m])

Sample Input

3 2 3
1 2 3
0
1
2

Sample Output

2
3
1

Explanation

After the first rotation, the array becomes [3, 1, 2].
After the second (and final) rotation, the array becomes [2, 3, 1].
Let's refer to the array's final state as array \$b\$. For each query, we
just have to print the value of b[m] on a new line:
\$m=0\$, so we print \$2\$ on a new line.
\$m=1\$, so we print \$3\$ on a new line.
\$m=2\$, so we print \$1\$ on a new line.


texts: Strongly-typed reading values from CSV DataTable

texts:
Is there a way to do this using parameters so the value is automatically converted to whatever datatype the keyfield has in the datatable?

This code should be reusable for future bulk update applications hence the constant and the check on multiple datatypes.

private const string DBKEYFIELDNAME = "CustomerNr";

...
for (int i = 1; i <= csvLines.Length - 1; i++) // i=1 => skip header line
{
    string[] csvFieldsArray = csvLines[i].Split(';');
    int indexKeyField = csvHeaders.IndexOf(CSVKEYFIELDNAME.ToLower());

    object csvKeyValue = csvFieldsArray[indexKeyField];

    // ... some more code here that is not relevant

    // Find the matching row for our csv keyfield value
    Type keyType = parameters.DataTableOriginal.Columns[DBKEYFIELDNAME].DataType;
    DataRow[] rowsOriginal = null;
    if (keyType.IsAssignableFrom(typeof(string)))
        rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + "='" + csvKeyValue.ToString() + "'");
    else if (keyType.IsAssignableFrom(typeof(Int16)) || keyType.IsAssignableFrom(typeof(Int32)) || keyType.IsAssignableFrom(typeof(Int64)) || keyType.IsAssignableFrom(typeof(bool)))
        rowsOriginal = parameters.DataTableOriginal.Select(DBKEYFIELDNAME + "=" + csvKeyValue);

    if (rowsOriginal != null && rowsOriginal.Length == 1)
    {
        // Do some processing of the row here
    }
}


texts:
I have to write a comparison logic.

Following is the code to refactor (as it is looking bad).

  // 1. item has filter criteria
  // 2. return true if current matches filter criteria
  // 3. Criteria -> 3 fields should be matched ( Security, OrderType, CounterType)
  // 4. Criteria -> User can specify All (*), If any matching field is All, (NONE for enum), only that field should not be matched, other should be matched
  private static bool CompareOrderItem(Item item, Item current)
{
    String all="All";
    bool flag = true;

    if (!( String.Equals(item.Security, all) ||String.Equals(current.Security, item.Security)))
        flag = false;

    if (!( item.OrderType == OrderTypeEnum.None ||Enum.Equals(current.OrderType, item.OrderType)))
        flag = false;

     if (!( String.Equals(item.Counterparty, all) || String.Equals(current.Counterparty, item.Counterparty)))
        flag = false;

    return flag  ;
}


texts: Is my code for a forum page vulnerable for sql injections?

texts:
This is the backend code for the page where you upload a post. I have already tried to do a sql attack on this page, but it didn't work.

<?php
include_once 'includes1/dbh.inc.php';
session_start();
//*skåd ifall man är inloggad *//
if (isset($_POST['topic_submit'])) {
    $newFileName = "annons"; //Här ska egentligen vara $_POST['topic_title'];//
    if (empty($newFileName)) {
        $newFileName = "annons";
    } else {
        $newFileName = strtolower(str_replace(" ", "-", $newFileName));
    }
        $cid = $_POST['cid'];
        $title = $_POST['topic_title'];
        $content = $_POST['topic_content'];
        $creator = $_SESSION['UserName'];
        $imageNamn = $_POST['filenamn'];
        $imageMail = $_POST['filemail'];
        $imageNummer = $_POST['filenummer'];
        $imagePris = $_POST['filepris'];
        $imagestad = $_POST['filestad'];

    $file = $_FILES['file'];

    $fileName = $file["name"];
    $fileType = $file["type"];
    $fileTempName = $file["tmp_name"];
    $fileError = $file["error"];
    $fileSize = $file["size"];

    $fileExt = explode(".", $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array("jpg", "jpeg", "png", "image/jpg");

    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
          if ($fileSize < 2000000000) {
            $imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
            $fileDestination = "img/gallery/" . $imageFullName;

            include_once 'includes1/dbh.inc.php';

            if (empty($title) || empty($content) || empty($imageNamn) || empty($imageMail) || empty($imagestad) || empty($imagePris)) {
                header("Location: ../index.php?upload=empty");
                exit();
            } else {
                $sql2 = "SELECT * FROM gallery;";
                $stmt = mysqli_stmt_init($conn);
                if (!mysqli_stmt_prepare($stmt, $sql2)) {
                    echo "SQL statement failed!";
                } else {
                    mysqli_stmt_execute($stmt);
                    $result2 = mysqli_stmt_get_result($stmt);
                    $rowCount = mysqli_num_rows($result2);

                    $sql = "INSERT INTO topics (category_id, topic_title, topic_creator, topic_date, topic_reply_date, imgFullNameGallery, topic_pris) VALUES ('".$cid."', '".$title."', '".$creator."', now(), now(), '".$imageFullName."', '".$imagePris."')";
                    $result = mysqli_query($conn, $sql);
                    $new_topic_id = mysqli_insert_id($conn);
                    $sql2 = "INSERT INTO gallery (category_id, topic_id, post_creator, titleGallery, descGallery, namnGallery, emailGallery, nummerGallery, prisGallery, stad, post_date, imgFullNameGallery)
                     VALUES ('".$cid."', '".$new_topic_id."', '".$creator."', '".$title."', '".$content."', '".$imageNamn."', '".$imageMail."', '".$imageNummer."', '".$imagePris."', '".$imagestad."', now(), '".$imageFullName."')";
                    $result2 = mysqli_query($conn, $sql2);
                    $sql3 = "UPDATE categories SET last_post_date=now(), last_user_posted='".$creator."' WHERE id='".$cid."' LIMIT 1";
                    $result3 = mysqli_query($conn, $sql3);
                    if (!mysqli_stmt_prepare($stmt, $sql2)) {
                        echo "SQL statement failed!";
                    } else {
                        mysqli_stmt_bind_param($stmt, "sssssssssss", $cid, $new_topic_id, $creator, $title, $content, $imageNamn, $imageMail, $imageNummer, $imagePris, $imagestad, $imageFullName);
                        move_uploaded_file($fileTempName, $fileDestination);

                        header("location: view_topic.php?cid=".$cid."&tid=".$new_topic_id);
                    }
                }
            }
        } else {
        echo "File size is too big!";
        exit();
        }
    } else {
    echo "You had an error!";
    exit();
    }
} else {
    echo "You need to upload a proper file type!";
    exit();
}
}
?>


texts: Effective Python 2/3 two-dimensional array initialisation

texts:
Recently I noticed that the idiomatic python two-dimensional array initialisation is extremely slow. I am wondering, is there a good, proper way of doing this simple task fast? Also, are those two variants equivalent?

Here are some code snippets using timeit

import timeit

A = 5000
B = 7000

N = 10

def list_comprehension_xrange():
    matrix = [[0 for j in xrange(A)] for i in xrange(B)]
def list_comprehension_range():
    matrix = [[0 for j in range(A)] for i in range(B)]
def multiplication():
    matrix = [[0] * A] * B

print "list_comprehension_xrange:", timeit.timeit(list_comprehension_xrange, number=N)
print "list_comprehension_range:", timeit.timeit(list_comprehension_range, number=N)
print "multiplication:", timeit.timeit(multiplication, number=N)

list_comprehension_xrange: 11.4952278137
list_comprehension_range: 13.5112810135
multiplication: 0.00100612640381


texts: Thread safe object pool, is this object pool thread safe?

texts:
If many threads Borrow() and Return() an instance of Packet from/to PacketPool could the Exception in Packet.Init() ever be thrown? Assuming only PacketPool ever called the Init() and UnInit() methods on a Packet.

class PacketPool
{
    private Stack<Packet> pool;

    public PacketPool(int initalNum)
    {
        pool = new Stack<Packet>(initalNum);

        for (int i = 0; i < initalNum; i++)
        {
            Packet p = new Packet();
            pool.Push(p);
        }
    }

    public Packet Borrow()
    {
        Packet p;

        lock (pool)
        {
            if (pool.Count == 0)
            {
                p = new Packet();
            }
            else
            {
                p = pool.Pop();
            }
        }

        p.Init();

        return p;
    }

    public void Return(Packet p)
    {
        p.UnInit();

        lock (pool)
        {
            pool.Push(p);
        }
    }
}

class Packet
{
    bool isInitialized;

    public void Init()
    {
        if(isInitialized)
            throw new InvalidOperationException("Already initialized!");
        isInitialized = true;
    }

    public void UnInit()
    {
        isInitialized = false;
    }
}


texts:
I have this below code where i am sending some content over a POST and then consuming the response. I would like to know if there can be any optimizations that can be done and is there any possibility of connection leak.

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;

class Test implements Serializable {

    static String getR(String xml, String requestUrl, int retryWaitTime, int socketTimeOut) throws IOException {
        long startTime = Calendar.getInstance().getTimeInMillis();
        StringBuilder xmlString = new StringBuilder();
        String out;
        HttpURLConnection connection = null;
        try {

            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(retryWaitTime);
            connection.setReadTimeout(socketTimeOut);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/xml");
            connection.setRequestProperty("Content-Type", "application/xml; charset=UTF-8");
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            writer.write(xml);
            writer.close();

            int statusCode = connection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String line;
                while ((line = br.readLine()) != null) {
                    xmlString.append(line);
                }

                br.close();

               out = xmlString.toString();

            } else {

                out = statusCode + "^" + xml;
            }
            if (connection.getInputStream() != null)
                connection.getInputStream().close();

        }
        catch (Exception e) {

            out = "X^" + xml;
            assert connection != null;
            if (connection.getErrorStream() != null)
                connection.getErrorStream().close();
        }
        String Response = out.replace("\n", "").replace("\r", "");
        return Response;
    }

}


texts: helper function to determine if html text is wrapped with a certain tag

texts:
I have this code that I've made to parse a string of HTML and tell me if it is all enclosed within a specified tag:

const textIsWrappedWithTag = (text, tag) => {
  const tempDocument = new DOMParser().parseFromString(text, "text/xml");
  if (tempDocument.getElementsByTagName("parsererror").length) {
    return false;
  }
  if (tempDocument.children.length === 1 && tempDocument.children[0].tagName.toLowerCase() === tag.toLowerCase()) {
    return true;
  }
  return false;
};

My test cases do what I want them to do:

const yes = '

one

two

';
const no = '
one

two

three
';
const no2 = '

one

two

three

';

textIsWrappedWithTag(yes, 'p');
> true
textIsWrappedWithTag(no, 'p');
> false
textIsWrappedWithTag(no2, 'p');
> false

I played around with this in the console to develop it, but I'm not super famliar with DOMParser and parsererror, so I want to be sure that I'm not overlooking something


texts:
I'm trying to create a dependent dynamic dropdown in jQuery, in which the number of dropdowns is not fixed. Let's say we've four provinces, each has cities, and each city has sections. Each section may or may not have a sub-section, and the list continues to ten or more dropdowns.
I wrote a sample code and it works, but I believe there are better ways to do so. First there's an array(Obj) to keep the data for each dropdown depending on the selected item. The id for dropdown in this sample is #1,#2,#3 ... By clicking on each item, it'll get the index of the dropdown, and set the index of newDropdown. Then there's a set of if logic to check existence of second dropdown. At the end, if the parent dropdown is changed, the rest of the dropdowns must be removed except the first child.
and here's the complete sample code run the code here
    $('body').on('click', '.combo', function() {

  var selectedValue = $(this).val();
  //alert(this.id);
  if (this.id < objs) {
    var childVal = obj[this.id][selectedValue];
  }
  //get the index of current combobox
  var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
  // set the index of new combobox
  var newComboBoxIndex = thisComboBoxIndex + 1;
  var id = newComboBoxIndex

  //if we clicked on the dropdown and dropdown already exists:
  // then just update dropdown items
  if ($("#" + id).length && childVal) {
    jQuery('#' + id).children().remove();
    jQuery.each(childVal, function(val, text) {
      jQuery('#' + id).append(
        jQuery('<option></option').val(val).html(text)
      );
    })
  }

  //if dropdown does not exists:
  //then add the dropdown
  if ($("#" + id).length == 0 && childVal) {

    jQuery('body').append('<select class= "combo" data-index="' + newComboBoxIndex + '" id="' + id + '"></select>');
    jQuery.each(childVal, function(val, text) {
      jQuery('#' + id).append(
        jQuery('<option></option').val(val).html(text)
      );
    })
  }

    //if there's no value, then remove dropdown
  if ($("#" + id).length && !childVal) {
    jQuery('#' + id).remove();

  }
  //if we changed the item of parent, remove the children
  if (this.id >= 0) {
    var id_changed_combo = this.id;
    // Gets the number of elements with class .combo
    var numItems = $('.combo').length
    $(".combo").each(function(index, element) {
      if (index > (parseInt(id_changed_combo) + 1)) {
        jQuery('#' + index).remove();
      }
    });

  }

});


texts: Asynchronously accepting multiple client connections without impacting main thread

texts:
I am implementing a multi-player game in C# and having seen all sorts of projects, from indie developers all the way to large studios struggle to patch networking into existing products in the past, have made the decision to get the networking aspect done first, and build the game on top of that.

I've so far gotten to the stage where my server can accept clients asynchronously, but I have a strong feeling that I've implemented the threading very badly. I think it is possible that I am misunderstanding and/or misusing async/await and Tasks, but having read documentation and similar questions I think I will need practical experience to get my head wrapped around the correct usage of these.

As a result, I am hoping that someone would be generous enough to look over my code and help push me onto the right track. I have excluded 'using' statements and the client code for the purposes of this question, however I can confirm the code does function correctly.

I am not too concerned about issues such as naming, and the fact that I have a bit too much code logic in the Main function right now -- these will be modified and extracted to more appropriate locations  respectively as the project progresses.

I have denoted lines I am particularly concerned about with <---- THIS

namespace Game_Server {
    class ServerMain {
        static void Main(string[] args) {
            Server server = new Server();

            server.Start().Start(); //<---- THIS

            while (true) {
                Console.WriteLine($"Number of connected users: {server.clients.Count}");
            }
        }
    }

    class Server {
        private TcpListener server { get; }
        private ConcurrentBag<TcpClient> _clients { get; set; }
        public List<TcpClient> clients { get {
                return _clients.ToList();
            } } //<---- THIS (This was just something I threw up to test my connection model, but any suggestions for handling a thread-safe list of clients would be greatly appreciated!)

        public Server() {
            server = new TcpListener(
                IPAddress.Parse("127.0.0.1"),
                6780
                );
            _clients = new ConcurrentBag<TcpClient>();
        }

        public Task Start() {
            server.Start();

            return new Task(async () => { // <---- THIS
                while (true) {
                    TcpClient client = await server.AcceptTcpClientAsync();
                    _clients.Add(client);
                    Console.WriteLine("Connection on port 6780 from client " + client.Client.RemoteEndPoint);
                }
            });
        }
    }
}

Additionally, my usage of any features in more recent C# iterations (C# 6 most notably) may not be up to scratch, so I'd appreciate any suggestions for making my code more condensed or 'modern'

I apologise if this question doesn't fit perfectly here -- I was concerned it was a bit too specific and if it is, please comment and I'll try to open it up a bit.


texts:
I have a few constants in a game that I'm doing for hobby. I need to store constants for the total size of the a Physical World and the size of the Screen.

I can position the world's objects to the screen or vice versa.

To position the images on the screen for example I get the position that the body occupies in the physical world and transform to the screen by doing:

(Full Screen Size / Total size of the World) * position of the object in the world.

I came up with an ingenious way to keep these constant while I do conversion operations using the enum below:

import com.badlogic.gdx.math.Vector2;
import static br.com.games.Test.Sizes.*;

public class Test {

    public static enum Sizes {
        WORLD(new Vector2(25.806f, 15.48f)), SCREEN(new Vector2(800f, 480f)), TRANSFORM(
                new Vector2(-1, -1));

        private Vector2 value;

        private Sizes(Vector2 value) {
            this.value = value;
        }

        private Vector2 inputValue;
        private Vector2 sourceValue;

        public Sizes value(Vector2 value) {
            inputValue = value;
            return this;
        }

        public Sizes from(Sizes size) {
            sourceValue = size.value;
            return this;
        }

        public Vector2 to(Sizes size) {
            float x = size.value.x / sourceValue.x * inputValue.x;
            float y = size.value.y / sourceValue.y * inputValue.y;
            return Vector2.Zero.set(x, y);
        }

        public Vector2 getValue() {
            return value;
        }
    }

}

I can use it this way:

    public static void main(String[] args) {
        TRANSFORM.value(new Vector2(10, 10)).from(WORLD)
                .to(SCREEN);
    }

Vector2 class is here.

What do you think of this way of using constants and operations? Do you see any problems? Could you point out some improvement?


texts:
I have this "pretty" date string generator in C# - pass it a date and it returns a string with "5 minutes ago" or "2 weeks, 3 days ago", etc.

It's a little verbose and hogs 61 lines, and I'm wondering if I'm missing out on some nice C# features or something. What (if any) is the best way to clean up this code? Are there any cool c# features I can use here?

public static string getTimeSpan(DateTime postDate)
{
    string stringy = "";
    TimeSpan diff = DateTime.Now.Subtract(postDate);
    double years = Math.Floor(diff.TotalDays / 365);
    double weeks = Math.Floor(diff.TotalDays / 7);
    double days = diff.Days;
    double hours = diff.Hours + days * 24;
    double minutes = diff.Minutes + hours * 60;
    if (minutes <= 1) {
        stringy = "Just Now";
    } else if (years >= 1) {
        if (years >= 2) {
            stringy = years.ToString() + " years ago";
        } else {
            stringy = "1 year ago";
        }
    } else if (weeks >= 1) {
        if ((days - weeks * 7) > 0) {
            if ((days - weeks * 7) > 1) {
                stringy = ", " + (days - weeks * 7).ToString() + " days";
            } else {
                stringy = ", " + (days - weeks * 7).ToString() + " day";
            }
        }
        if (weeks >= 2) {
            stringy = weeks.ToString() + " weeks" + stringy + " ago";
        } else {
            stringy = "1 week" + stringy + " ago";
        }
    } else if (days >= 1) {
        if ((hours - days * 24) > 0) {
            if ((hours - days * 24) > 1) {
                stringy = ", " + (hours - days * 24).ToString() + " hours";
            } else {
                stringy = ", " + (hours - days * 24).ToString() + " hour";
            }
        }
        if (days >= 2) {
            stringy = days.ToString() + " days" + stringy + " ago";
        } else {
            stringy = "1 day" + stringy + " ago";
        }
    } else if (hours >= 1) {
        if ((minutes - hours * 60) > 0) {
            if ((minutes - hours * 60) > 1) {
                stringy = ", " + (minutes - hours * 60).ToString() + " minutes";
            } else {
                stringy = ", " + (minutes - hours * 60).ToString() + " minute";
            }
        }
        if (hours >= 2) {
            stringy = hours.ToString() + " hours" + stringy + " ago";
        } else {
            stringy = "1 hour" + stringy + " ago";
        }
    } else if (minutes > 1) {
        stringy = minutes.ToString() + " minutes ago";
    }
    return stringy;
}


texts: Game of Life in Scala with a sparse representation

texts:
While reviewing another Scala implementation of the Game of Life, I ended up drastically rewriting it.  The board is represented as a Set[(Int, Int)] containing the coordinates of the live cells.

I'm not sure whether the case class is appropriate here, and not too happy about the long parameter list.  I'm also dissatisfied with the implementation of parse.

import java.io.File
import java.nio.file.Files

case class GameOfLife(living: Char='X', dead: Char=' ', height: Int=0, width: Int=0, liveCells: Set[(Int, Int)]=Set()) {

  /**
   * Parses a string representation of the board.  Returns a GameOfLife
   * object whose dimensions are at least as large as the current board,
   * and expanded if necessary.
   */
  def parse(board: String): GameOfLife = {
    var h = height
    var w = width
    val cells = board.lines.zipWithIndex.flatMap({case (line, r) => {
      h = h max (r + 1)
      line.view.zipWithIndex.flatMap({
        w = w max line.length
        _ match {
          case (`living`, c) => Some((r, c))
          case _             => None
        }
      })
    }}).toSet
    GameOfLife(living, dead, h, w, cells)
  }

  override def toString = {
    (0 to height).map((r) =>
      (0 to width).map((c) => if (isLive((r, c))) living else dead).mkString
    ).mkString("\n")
  }

  private val neighborOffsets = Set(
    (-1, -1), (-1,  0), (-1, +1),
    ( 0, -1),           ( 0, +1),
    (+1, -1), (+1,  0), (+1, +1)
  )

  private def neighbors(cell: (Int, Int)): Set[(Int, Int)] = {
    neighborOffsets.map(offset => (cell._1 + offset._1, cell._2 + offset._2))
                   .filter(isInBounds)
  }

  def isLive(cell: (Int, Int)): Boolean = liveCells.contains(cell)

  def isInBounds(cell: (Int, Int)): Boolean = {
      0 <= cell._1 && cell._1 < height &&
      0 <= cell._2 && cell._2 < width
  }

  def nextGen(): GameOfLife = {
    val candidates = liveCells.flatMap(neighbors).union(liveCells)
    GameOfLife(living, dead, height, width, candidates.filter(c => {
      neighbors(c).count(isLive) match {
        case 2 => isLive(c)
        case 3 => true
        case _ => false
      }
    }))
  }

}

object GameOfLife {
  def main(args: Array[String]): Unit = {
    val initBoard = new String(Files.readAllBytes(new File(args(0)).toPath))
    val initGame = GameOfLife().parse(initBoard)
    lazy val generations: Stream[GameOfLife] = initGame #:: generations.map(_.nextGen)
    generations.takeWhile(!_.liveCells.isEmpty).foreach(println)
  }
}


texts: Finding subsequences of vector from a vector

texts:
I'm trying to find subsequences of vector from a vector.

For example, if I want to find {2, 3} from {1, 2, 3, 1, 2, 3, 4}, the result should be {1, 4}.

Here's what I wrote so far.

vector<int> v1 = {1, 2, 3, 1, 2, 3, 4}; //source vector
vector<int> v2 = {2, 3}; //the subsequence to find
vector<size_t> founds; //positions found

for (size_t i=0; i<v1.size(); ++i) {

    auto it = search(v1.begin()+i, v1.end(), v2.begin(), v2.end());

    if (it != v1.end()) {

        size_t pos = distance(v1.begin(), it);
        founds.push_back(pos);
        i += pos;
    }
}
for (size_t i=0; i<founds.size(); ++i) {

    cout << founds[i] << endl; //prints 1, 4
}

While this seems to work, I would appreciate any advice to make the code simpler and efficient.

EDIT : I updated the code based on @user1118321's advice.

Here's an updated code.

vector<int> source = {5, 8, 1, 2, 1, 2, 1, 2, 1}; //source vector
vector<int> toSearch = {1, 2, 1}; //the subsequence to find
vector<size_t> results; //positions found

const auto srcBegin = source.begin();
const auto srcEnd = source.end();

for (auto nextIndex = srcBegin; nextIndex < srcEnd; nextIndex++)
{
    const auto it = search(nextIndex, srcEnd, toSearch.begin(), toSearch.end());

    if (it != srcEnd) {

        const size_t pos = distance(srcBegin, it);
        results.push_back(pos);
        nextIndex = srcBegin + pos;
    }
}
for (size_t i=0; i<results.size(); ++i) {

    cout << results[i] << endl; //prints 2, 4, 6
}

And if I want to ignore the overlapping copies of a subsequence, I can change nextIndex = srcBegin + pos; to nextIndex = srcBegin + pos + toSearch.size(); Then it prints 2, 6


texts: Decode FEN string into separate variables for the 6 categories

texts:
FEN strings are compact representations of chess board positions which allows you to derive the necessary information to start playing a chess game from that position. This includes things like the pieces on the board, castle statuses, etc. More information here: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
I have written a simple function in go to decode a FEN string into separate variables with suitable types for each of the desired pieces of information that FEN strings represent, and I would like to see if I am parsing the FEN string in a reasonable manner.
import (
    "strings"
)

type pair struct {
    x, y int8
}

func decodeFen(fen string) ([8][8]int8, int8, [4]bool, pair, int8, int) {
    split := strings.Split(fen, " ")
    var board [8][8]int8
    board_split := strings.Split(split[0], "/")
    for r, row := range board_split {
        var col_ind int8
        for _, char := range row {
            if char >= 49 && char <= 57 {
                for i := int8(0); i < int8(char) - 48; i++ {
                    board[r][col_ind] = '-'
                    col_ind++
                }
            } else {
                board[r][col_ind] = int8(char)
                col_ind++
            }
        }
    }
    var color int8
    if split[1] == "w" {
        color = 1
    } else {color = 2}
    var castle_status [4]bool
    var status_map = map[rune]int8 {
        'K' : 0, 'Q' : 1, 'k' : 2, 'q' : 3}
    if split[2] != "-" {
        for _, char := range split[2] {
            castle_status[status_map[char]] = true
        }
    }
    var ep_pos pair = pair{-1, -1}
    if split[3] != "-" {
        x_label := split[3][0]
        y_label := split[3][1]
        y_label -= 48
        ep_pos = pair{int8(x_label - 97), int8(y_label - ((y_label - 1) - (8 - y_label)) - 1)}
    }
    var halfmove_clock int8 = int8(split[4][0]) - 48
    var fullmove_number int = int(split[5][0]) - 48
    return board, color, castle_status, ep_pos, halfmove_clock, fullmove_number
}

This is really just a parsing problem, and to split the strings I decided to use the Split() function from the strings go library, rather than writing my own. Any improvements and feedback for this code would be great, and I apologize if I am not correctly asking this question as this is my first post in this community.


texts: Printing the largest sum from integers in a file

texts:
I am writing a program for learning purposes that takes an input of a file structured similarly to:

13,22,13,14,31,22, 3, 1,12,10
11, 4,23, 7, 5, 1, 9,33,11,10
40,19,17,23, 2,43,35,21, 4,34
30,25,16,12,11, 9,87,45, 3, 1
1,2,3,4,5,6,7,8,9,10

Which will then read the values from the file, figure out and print the largest sum you can make from the digits on each line which is 50 or less (also cannot be the same number used twice).

I think I've come to a good solution, but there are a few issues. I want to try and separate the code into separate functions. I'm additionally looking for code optimization advice.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  FILE *fp;
  int hv, lv,line,i, linecount,val[5][10]; //hv + lv = the two highest values on a line, line=sum of hv and lv.
  int j=0;

  // test file succesfully opened
  if((fp=fopen(argv[1], "r")) == NULL){
    printf("Cannot open file.\n");
    exit(1);
  }

  //Store values in 2d array
  for(i=0;!feof(fp);i++){
    while(j<10){
      fscanf(fp, "%d,",&val[i][j++]);
    }
  j=0;
  }
  linecount=i-1; //set linecoutn to No of lines

//test and print result
 for(i=0; i<=linecount; i++){ // for each line
   hv=0, lv=0, line=0; //reset values for each line
   for(j=0;j<10;j++){ // for each value
     for(int a =0; a<10; a++) { //test against all in line
       if(a!=j && (val[i][j]+val[i][a]<=50)){ //if two values arent equal and sum is less than 50
     if((val[i][j]+val[i][a])>line){ //if value is greater than previous value
       hv=val[i][j];
       lv=val[i][a];
       line=hv+lv;
     }
       }
     }
   }
   printf("Line %d: largest pair is %d and %d, with a total of %d\n", i+1, hv, lv, line);
 }

 fclose(fp);
}


texts: Binary Search Tree find_successor of inputNode

texts:
Wanted to ask for feedback for my coding challenge for BST. python find_successor of inputNode inOrder.
https://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/
find the successor(Inputnode).

#########################################################
# CODE INSTRUCTIONS:                                    #
# 1) The method findInOrderSuccessor you're asked      #
#    to implement is located at line 30.                #
# 2) Use the helper code below to implement it.         #
# 3) In a nutshell, the helper code allows you to       #
#    to build a Binary Search Tree.                     #
# 4) Jump to line 88 to see an example for how the      #
#    helper code is used to test findInOrderSuccessor.  #
#########################################################

# A node
class Node:
    # Constructor to create a new node
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.parent = None

# A binary search tree
class BinarySearchTree:
    # Constructor to create a new BST
    def __init__(self):
        self.root = None

    def find_in_order_successor(self, inputNode):
        # check the right node of inputNode
        succ = None

        if self.root == None:
            return 'Null'
        # start with root
        while self.root:
            if self.root.key > inputNode.key:
                succ = self.root
                self.root = self.root.left
            else:  # inputNode.right:
                self.root = self.root.right
        return succ

    # Given a binary search tree and a number, inserts a
    # new node with the given number in the correct place
    # in the tree. Returns the new root pointer which the
    # caller should then use(the standard trick to avoid
    # using reference parameters)
    def insert(self, key):

        # 1) If tree is empty, create the root
        if (self.root is None):
            self.root = Node(key)
            return

        # 2) Otherwise, create a node with the key
        #    and traverse down the tree to find where to
        #    to insert the new node
        currentNode = self.root
        newNode = Node(key)
        while (currentNode is not None):

            if (key < currentNode.key):
                if (currentNode.left is None):
                    currentNode.left = newNode;
                    newNode.parent = currentNode;
                    break
                else:
                    currentNode = currentNode.left;
            else:
                if (currentNode.right is None):
                    currentNode.right = newNode;
                    newNode.parent = currentNode;
                    break
                else:
                    currentNode = currentNode.right;

    # Return a reference to a node in the BST by its key.
    # Use this method when you need a node to test your
    # findInOrderSuccessor function on
    def getNodeByKey(self, key):

        currentNode = self.root
        while (currentNode is not None):
            if (key == currentNode.key):
                return currentNode

            if (key < currentNode.key):
                currentNode = currentNode.left
            else:
                currentNode = currentNode.right

        return None

#########################################
# Driver program to test above function #
#########################################

# Create a Binary Search Tree
bst = BinarySearchTree()
bst.insert(20)
bst.insert(9);
bst.insert(25);
bst.insert(5);
bst.insert(12);
bst.insert(11);
bst.insert(14);

# Get a reference to the node whose key is 9
test = bst.getNodeByKey(12)

# Find the in order successor of test
succ = bst.find_in_order_successor(test)

# Print the key of the successor node
if succ is not None:
    print("\nInorder Successor of %d is %d " % (test.key, succ.key))
else:
    print("\nInorder Successor doesn't exist")


texts:
This code searches for the word "Disbursements" and copies all of the rows with data below it, including the row with the specified word. After the rows are copied to a new sheet, the unnecessary rows below the contiguous range of data are deleted. In order to search for the last cell, I used a function that finds the last cell with data.
Instead of deleting the rows below the contiguous range, should I just copy the contiguous rows to begin with? Is there a better way to delete the rows below the first blank row?
Sub Reformat_ZZ_CM_BNREG()

Application.ScreenUpdating = False
Application.Calculation = xlManual
Application.DisplayAlerts = False

'declare variables to search for within bank register
Dim searchText As String
Dim ws As Worksheet
Dim searchCell As Range
Dim newWS As Worksheet
Dim lastCell As String
Dim firstCell As String
Dim lastRow As Long

'set variables to sheet name, search text, and searchCell
searchText = "Disbursements"
Set ws = Sheets("ZZ_CM_BNREG")
lastCell = FindLast(3, "ZZ_CM_BNREG")
'Set lastCell = Range(Cells.Find("*", , xlFormulas, , xlRows, xlPrevious, , , False), Cells.Find("*", , xlFormulas, , xlColumns, xlPrevious, , , False))
Set newWS = Sheets.Add(After:=Sheets("ZZ_CM_BNREG"))
newWS.Name = "Bank Register"

'Unmerge all cells in Column A & get cell address of searchCell
With ws

    ws.Activate

    Range("A:A").UnMerge

    Set searchCell = .Cells.Find(What:="Disbursements", _
        SearchFormat:=True)

    If searchCell Is Nothing Then
        MsgBox ("Error")
    Else
        firstCell = searchCell.Address
    End If

End With

'copy range using above function to get last cell in range
'paste range onto the new sheet
'we are starting with the cell containing disbursements
ws.Range(firstCell, lastCell).Copy _
    Destination:=newWS.Range("A1")

DeleteRowsAndSheet

End Sub

Sub DeleteRowsAndSheet()

Dim LR As Long
LR = Sheets("Bank Register").Range("A1").End(xlDown).Row

Sheets("Bank Register").Activate
Rows(LR + 1 & ":" & LR + 20).Delete

Sheets("Bank Register").Range("1:1").Delete

Sheets("ZZ_CM_BNREG").Delete

Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True

End Sub


texts: Extracting single files from a tarball (spreadsheets)

texts:
I've created a program that will pull spreadsheets out of a large tarball.

First it specifies the file name through the "folio" number which is given as an argument when the program is called. From there it runs a bash command that will list a text file containing the information needed to find the tarball, the information needed is a date. It then collects the information finds the tarball, runs another bash command to unarchive the spreadsheet from the tarball, and then moves the spreadsheets.

I would like some critique on my work. Are there better ways to extract from a tar? Would this be better as a module then a class?

I know it doesn't delete the directory that is created from extracting the spreadsheets, mostly because I don't trust myself enough to remove a directory called home.

#!/usr/local/bin/ruby

require 'rubygems'
require 'colored'
require 'fileutils'

class ArchiveManager

  attr_accessor :folio_num

  def initialize(folio_num)
    @folio_num = folio_num
    @src_dir = "/home/<dir>/<user>/<dir>/home/common/4000_UW_spreadsheets/#{folio_num}.ods"
    @dst_dir= "/home/<dir>/<user>/<dir>"
  end

  def num_check
    if folio_num =~ /^\d{4,7}$/
      search_for_spreadsheet
    else
      puts
      puts "                  Invalid Folio length".red.bold,
       "        USAGE: unarchive_ss <folio number 4-7 digits>".red.bold
      puts
    end
  end

  def search_for_spreadsheet
    location = FileUtils.chdir("/home/<dir>/<user>/<dir>")
    digits = `grep -lr #{@folio_num}.ods *.txt`
    file_name = digits.match(/\d+/).to_s
    puts "Spreadsheet found in UW_archive_#{file_name}.tgz".green.bold
    extract(file_name, location)
  end

  def extract(file_name, location)
    if File.exist?("#{@dst_dir}/#{@folio_num}.ods")
      found_error = raise SecurityError.new("File: #{@folio_num} exists within directory: #{@dst_dir}; will not continue..")
      abort("File exists in directory, either use file as parachute, or get rid of it..".red.bold)
    else
      tar_location = "home/common/4000_UW_spreadsheets"
      `tar -x -f UW_archive_#{file_name}.tgz #{tar_location}/#{@folio_num}.ods`
      move(tar_location, location)
    end
  end

  def move(tar_location, location)
    if File.exist?("#{@src_dir}")
      puts "File extracted, and being moved.".green.bold
      sleep(1)
      FileUtils.mv("#{@src_dir}", "#{@dst_dir}")
      puts "File: #{@folio_num}.ods, is now located in directory path: #{@dst_dir}".blue.bold
      puts "Remove created directories manually".red.bold
    else
      puts "Unable to locate file: #{@folio_num}.ods; source not found.".red.bold
      src_error = raise LoadError.new("Unable to find file: #{@folio_num}.ods; in directory #{@src_dir}")
    end
  end
end

ss = ArchiveManager.new(ARGV[0])
ss.num_check

Example of usage: File 2715015


texts: Displaying job status in a jQuery Datatable

texts:
I was wondering if there was a better way to write this:

#Define Jquery Datatable
if $('#dtable').length
  table = $('#dtable').DataTable()

#If job is created, make new row in Jquery datatables
if data.status == "Created" then (
  count = 0
  new_data = [
    data.job_id
    data.start_ip
    data.end_ip
    data.ilo_username
    data.ilo_password
    data.status
    create_date
    'Details'
  ]
  new_row = table.row.add(new_data).draw().nodes().to$().find('td').each ->
    $(this).attr 'id', 'td_' + count++ + '_' + data.job_id
  new_row
  id = $('#row' + data.job_id).val()
  table.row(new_row).node().id = 'row' + data.job_id
)

#If job status is running
else if data.status != "Created" and data.status != "Job Deleted" and data.status != "Scan Complete" then (
  #Update Jquery datatable if it exists
  if $('#dtable').length
    table.cell('#td_5_' + data.job_id).data wait_status

  #Update job detail status if it exists
  if $(detail_status).length
    $(detail_status).html wait_status

  #Detail Status
  if $(respond_message).length then (
    if data.count == null or data.server_count != 0
      $(respond_message).html wait_message
    else if data.server_count == 0
      $(respond_message).html no_respond
  )
)
#If job status is complete
else if data.status == "Scan Complete" then (
  #Update Jquery Datatable if it exists
  if $('#dtable').length
    table.cell('#td_5_' + data.job_id).data(data.status)

  #Update job detail status if it exists
  if $(detail_status).length
    $(detail_status).html data.status

  #Detail Status
  if $(respond_message).length then (
    if data.server_count == 0
      $(respond_message).html no_respond
    else if data.server_count != 0
      $(respond_message).html respond_finish
  )

#Remove disabled class on buttons if exists
  if $('#edit_disable_' + data.job_id).length and data.status == 'Scan Complete'
    $('#edit_disable_' + data.job_id).removeClass 'disabled'
  if $('#delete_disable_' + data.job_id).length and data.status == 'Scan Complete'
    $('#delete_disable_' + data.job_id).removeClass 'disabled'
)
#If job is deleted, remove table row from Jquery datatable
else if data.status == "Job Deleted"
  tr = "#row" + data.job_id
  table.row(tr).remove().draw()

Even though it is working, the code seems a little sloppy to me with all the if/else statements.  Is there any way to simplify it?  I'm new to coffeescript.


texts: XML node removal method with 5 arguments

texts:
I read somewhere that you should try to have as few method arguments as possible to make code easier to read, understand and use. I agree with this to a point but I'm not sure how I can make the following method easier. I think all 5 of the arguments are required.

Should I leave it as is? I think, if I was to add some comments, I may remember what this does if I come back to it later but there's a chance I won't know exactly what each argument is for.

public static void RemoveXMLNode(string pathToDocument, string descendant, string element, string elementValue,string newDocumentPath)
{
    var xDoc = XDocument.Load(pathToDocument);
    xDoc.Descendants(descendant)
    .Where(n => (string)n.Element(element) == elementValue)
    .Remove();
    xDoc.Save(newDocumentPath);
}


texts: Designing a stack such that getMin() is both constant time and constant space

texts:
I'm attempting the SpecialStack problem on GeeksforGeeks.

  Design a data-structure SpecialStack (using the STL of stack) that
  supports all the stack operations like push(), pop(), isEmpty(),
  isFull() and an additional operation getMin() which should return
  minimum element from the SpecialStack. Your task is to complete all
  the functions, using stack data-Structure.

  Input Format: The first line of input contains an integer T denoting
  the no of test cases. Then T test cases follow. Each test case
  contains two lines. The first line of input contains an integer n
  denoting the number of integers in a sequence. In the second line are
  n space separated integers of the stack.

  Output Format:

  For each testcase, in a new line, print the minimum
  integer from the stack.

  Your Task:

  Since this is a function problem, you don't need to take
  inputs. Just complete the provided functions.

  Constraints:

  1 <= T <= 100

  1 <= N <= 100

  Example:

  Input:

  1

  5 18 19 29 15 16

  Output: 15

This is my code, including the Driver Code which was provided beforehand by the interface (the Driver Code is not modifiable):

// { Driver Code Starts
#include<iostream>
#include<stack>
using namespace std;
void push(int a);
bool isFull(int n);
bool isEmpty();
int pop();
int getMin();
//This is the STL stack (http://quiz.geeksforgeeks.org/stack-container-adaptors-the-c-standard-template-library-stl/).
stack<int> s;
int main(){
    int t;
    cin>>t;
    while(t--){
        int n,a;
        cin>>n;
        while(!isEmpty()){
            pop();
        }
        while(!isFull(n)){
            cin>>a;
            push(a);
        }
        cout<<getMin()<<endl;
    }
}// } Driver Code Ends
/*Complete the function(s) below*/

int minEle = 0; // Holds minimum element so far, as elements are pushed into stack

void push(int a)
{
     if (s.empty()) // If stack is empty push a and update minEle to a
     {
         minEle = a;
         s.push(a);
         return;
     }

     if (a < minEle) // If a is less than minEle push (a-minEle) and update minEle to a
     {
         s.push(a - minEle);
         minEle = a;
         return;
     }

     if (a > minEle) // If a is greater than minEle then push a but don't update minEle
     {
         s.push(a);
     }
}

bool isFull(int n)
{
     return (s.size() == n);
}

bool isEmpty()
{
     return s.empty();
}

int pop()
{
    int top = s.top();
    if (top < 0) // If the top element of stack is negative, we reconstruct the previous minEle
    {
        minEle = minEle - top;
        s.pop();
    }
    else // Otherwise, just pop the top element
    {
        s.pop();
    }
    return top;
}

int getMin()
{
    return minEle;
}

I've tried to explain the logic in the comments. This code gives the correct solution for all the test cases (with positive integers) I tried so far. For instance:

For Input:
2
5
18 19 29 15 16
11
34 335 1814 86 82 7 332 82 221 95 40
Your Output is:
15
7

which is the correct solution!

However, when I try to submit the code, it says:

Your program took more time than expected.Time Limit Exceeded
Expected Time Limit < 1.3672sec
Hint : Please optimize your code and submit again.

As far as I understand, my code is \$\mathcal{O}(1)\$ in both time and space complexity and it uses no extra stacks. I'm not quite sure how to optimize the code runtime further. Any ideas?


texts:
Problem Statement:

  You will be given a list of integers, arr, and a single integer k.
  You must create an array of length k from elements of arr such that
  its unfairness is minimized. Call that array subarr.

  Unfairness of an array is calculated as: max(subarr) - min(subarr)

  Where:

  max denotes the largest integer in subarr
  min denotes the smallest integer in subarr

  Complete the maxMin function in the editor below. It must return  an integer that denotes the minimum possible value of unfairness.

Solution:

 static int maxMin(int k, int[] arr) {
    int arrLen = arr.length;
    Arrays.sort(arr);
    int[] subArr = Arrays.copyOfRange(arr, 0, k);
    int minUnfairness = subArr[k - 1] - subArr[0];

    for ( int j = 1; j < arrLen - k + 1; j++ ) {

        subArr = Arrays.copyOfRange(arr, j, j+k);

        int tempMinUnfairness = subArr[ k - 1 ] - subArr[0];

        if ( tempMinUnfairness < minUnfairness ) {
            minUnfairness = tempMinUnfairness;
        }
    }

    return  minUnfairness;
 }

  /**
   * Valid Test Case For Reference
   */
   private static void validTest() {
        int[] arr = { 10,100,300,200,1000,20,30 };
        int expected = 20;
        int result = maxMin(3, arr);
        assert (result == expected);
    }

The main function to review is maxMin().

Looking forward to your reviews on -

What other improvements can be done?
What other ways could be there    to the problem, as the current
approach is Greedy?

Thank you.


texts: How secure is this PDO Portfolio Script?

texts:
I was wondering if someone could take some time to look over my portfolio script and see let me know if it's secure enough to be uploaded live and connected to my database. My previous mySQL script was VERY insecure...

The Database Connection:

    public function  __construct($server, $databaseName, $username, $password)
    {
        $this->server = $server;
        $this->databaseName = $databaseName;
        $this->username = $username;
        $this->password = $password;
        $this->openConnection();
    }

    protected function openConnection()
    {
        $this->databaseLink = new PDO("mysql:host=$this->server;dbname=$this->databaseName", $this->username, $this->password);
    }

    public function getLink()
    {
        return $this->databaseLink;
    }
}

$database = new Database("localhost", "XXXXXXX", "XXXXXXX", "XXXXXXX");
$databaseLink = $database->getLink();
?>

The Client Detail Page

$client = $_GET["client"];

$getClientDataSql = "SELECT * FROM `client` WHERE `client`=:client";
$statement = $databaseLink->prepare($getClientDataSql);
$statement->bindParam(":client", $client, PDO::PARAM_STR);
$statement->execute();

if(!$statement->rowCount())
{
    echo "No Clients Found";
}
else
{
    $row = $statement->fetch(PDO::FETCH_ASSOC);

    // Title
    echo "
";
    echo "
".$row["title"]."
";
    echo "
".$row["description"]."
";

    // Tags
    $tags = explode(",", $row["tags"]);
    if (count($tags))
    {
        echo "
";
    foreach ($tags as $tag)
        {
            echo "".$tag."";
    }
        echo "
";
    }

    // Colours
    $colours = explode(",", $row["colours"]);
    if (count($colours))
    {
        echo "

Colours
";
    foreach ($colours as $colour)
    {
            echo "

";
    }
    echo "
";
    }

    // Services
    $services = explode(",", $row["services"]);
    if (count($services))
    {
        echo "

Services

";
    foreach ($services as $service)
    {
            echo "
".$service."
";
    }
    echo "

";
    }
    echo "
Visit Website
";
    echo "
";
    echo "

";
    echo "
";
    echo "

";
    echo "

";
    echo "

";
    echo "
";
}

?>

The Client List Page

$getPortofolioDataSql = "SELECT `id`, `title`, `description`, `client` FROM `client`";
$statement = $databaseLink->prepare($getPortofolioDataSql);
$statement->execute();
if($statement->rowCount() == 0)
{
    echo "No Portfolio Found";
}
else
{
    while($portofolioDetails = $statement->fetch(PDO::FETCH_ASSOC))
    {
        echo "
";
    echo "";
        echo "
";
    }
}
?>


texts: IndexOrDefault that functions like FirstOrDefault

texts:
I don't know why this is not in the .NET Library, but I need to be able to use an index against a list and not have it throw an exception if it is outside the bounds of the list.

This is what I came up with:

public static class LinqHelpers
{
    public static TListType IndexOrDefault<TListType>(this List<TListType> list,
                                                      int index)
    {
        var count = list.Count();
        if (index > count -1)
            return default(TListType);
        if (index < 0)
            return default(TListType);
        return list[index];
    }
}

This is my test:

List<string> somelist = new List<string> {"B", "A", "Q", "a", "t", "h"};
for (int i = -100; i < 100; i++)
{
    Console.WriteLine(somelist .IndexOrDefault(i));
}

I would appreciate any advice on missing error handling or if I am reinventing an already existing feature.  I also would not mind advice on a way to use an IEnumerable instead of a List with out iterating the IEnumerable more than once.


texts:
I wanted to know If there was a way to make it more versatile or shorter/simpler. Here's the code:
// Take only std::byte parameter and return an unsigned integral
constexpr auto bytes_to_uint(std::same_as<std::byte> auto... bytes) -> std::unsigned_integral auto {
    constexpr auto N = sizeof...(bytes);

    // Integral types large enough to hold N bytes
    using types = std::tuple<
        std::uint8_t,
        std::uint16_t,
        std::uint32_t,
        std::uint32_t,
        std::uint64_t,
        std::uint64_t,
        std::uint64_t,
        std::uint64_t
    >;

    using result = std::tuple_element_t<N, types>;

    return [&]<std::size_t... S>(std::index_sequence<S...>) {
        // Accumulate the part of the number using the bitwise or operator for each bytes
        return ((static_cast<result>(bytes) << CHAR_BIT * (N - S - 1)) | ... );
    }(std::make_index_sequence<N>{});
}

It is meant to be used like this:
bytes_to_uint(std::byte{0xaa}, std::byte{0xbb}); // std::uint16_t: 0xaabb

bytes_to_uint(
    std::byte{0x11},
    std::byte{0x22},
    std::byte{0x33},
    std::byte{0x44}
); // std::uint32_t: 0x11223344


texts:
I need to create an administration board that allows devs to create or modify options and display them in a panel. The Admin needs to be the same on each call made to it.
I've chosen to make all dependencies as singletons wrapped under Admin. This code only covers the approach, disconsider the lack of details.

class Admin {
    private static $instance;

    public static function getInstance() {
        if ( null === static::$instance ) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    private function __clone() {

    }

    private function __wakeup() {

    }

    public $Options;
    public $Panel;

    protected function __construct() {
        $this->Options = Options::getInstance();
        $this->Panel = Panel::getInstance();
        $this->run();
    }

    protected function run() {
        $this->Panel->run();
    }
}

class Options {
    private static $instance;

    public static function getInstance() {
        if ( null === static::$instance ) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    private function __clone() {

    }

    private function __wakeup() {

    }

    protected $options = array();

    public function getOptions() {
        return $this->options;
    }

    public function addOption($option) {
        $this->options[] = $option;
    }
}

class Panel {
    private static $instance;

    public static function getInstance() {
        if ( null === static::$instance ) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    private function __clone() {

    }

    private function __wakeup() {

    }

    protected $title = 'Panel';

    public function run() {
        $this->render();
    }

    public function render() {
        $Options = Options::getInstance();
        $options = $Options->get_options();
        foreach($options as $option) {
            echo $option['name'];
        }
    }
}

$Admin = Admin::getInstance();
$Admin->Options->addOption( array( 'name' => 'Test' ) );


texts:
What do you say about the code structure below? This is one of the recommended ways of writing JS code in my education.

What is the pros and cons with writing code this way?
Can you recommend any better and maybe more elegant ways of writing code?

var DESKTOP = DESKTOP || {};
DESKTOP.Init = DESKTOP.Init || {};
DESKTOP.Windows = DESKTOP.Windows || {};
DESKTOP.desktop = DESKTOP.desktop || {};

DESKTOP.Windows = function(width, height){
    this.width = width;
    this.height = height;
};

DESKTOP.Windows.prototype.buildWindow = function(){
    // code here...
};

DESKTOP.Windows.prototype.showMenu = function(text){
    // code here...
};

DESKTOP.Windows.bgChange = function(width, height){
    DESKTOP.Windows.call(this, width, height);

    this.content = 'the content';
    this.title =  'the title'
};

DESKTOP.Windows.bgChange.prototype = new DESKTOP.Windows();

DESKTOP.Windows.bgChange.prototype.loadImages = function(){
    // code here...
};

DESKTOP.Desktop = function(){
    // code here...
};

and so on...


texts:
I am writing a simple game with pyGame.

Structure-wise, I have separated my game into several files:

main.py # the main runner, it loads up the environment
class_tank.py # it defines the player-controlled tank class
class_shell.py # it defines the shells that shoot from the player's tank
class_mob.py # it defines the enemies

The relationship of the modules above is:

main.py imports class_tank.py, class_shell.py and class_mob.py
all of class_tank.py, class_shell.py and class_mob.py are subclasses of pygame.Sprite.sprite.

Currently, I noticed that I am repeating myself by having the following code snippets in all four files:

current_path = os.path.dirname(os.path.realpath(__file__))
resource_path = os.path.join(current_path, 'Resources')
img_folder_path = os.path.join(resource_path, 'Images')
bg_img_path = os.path.join(img_folder_path, "xxxx.png")

xxxx.png is the image I need to load for the background (main.py), for the player (class_tank.py), for bullets (class_shell.py) and for enemies (class_mob.py).

Logically, this code snippet does belong to each of the file, but is there any elegant way to not repeat myself? The only way I can think of is to define an additional helper class.


texts:
I am using spring boot in my application.

@EnableAutoConfiguration
@SpringBootApplication
public class PushMysqlTestApplication implements CommandLineRunner {
    private static Logger LOGGER = LoggerFactory.getLogger(RunQuery.class);
    @Autowired
    JdbcTemplate jdbcTemplate;

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(PushMysqlTestApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        startTransaction();
    }

    public void startTransaction() throws InterruptedException {
        LOGGER.info("=========== Transaction started ===========");
        jdbcTemplate.execute("start transaction");
        jdbcTemplate.execute("select * from push_multithread where status = 1 for update");
        Thread.sleep(5000);
        jdbcTemplate.execute("update push_multithread set status = 30 where id=1");
        Thread.sleep(10000);
        jdbcTemplate.execute("commit");
        LOGGER.info("========= Transaction ending ===========");
    }

}

What the above code does is, it starts transaction, update a table and commit using JDBCTemplate.

Is their any better way to achieve above transation in spring boot using anootations or JPA etc?


texts:
I am trying to use a dictionary in Odd Occurrence. Any suggestions on how I could optimize the program? Codility is giving me a result of 66%.

var dictionary = new Dictionary<int, short>();
int oddVal = 0; //Collect the number with Odd Occurrence

//Add the numbers in the dictionary with value 1-odd pair or 2-pair
if(A.Length != 0)
{
    for (var i = 0; i < A.Length; i++)
    {
        if (dictionary.ContainsKey(A[i]))
            dictionary[A[i]] = 2;
        else
            dictionary.Add(A[i], 1);

    }
    //review with the dictionary entry to see which key is the odd occurrence 1
    //Once odd occurrence is determined then break out of the loop
    foreach (KeyValuePair<int, short> entry in dictionary)
    {
        if (entry.Value == 1)
        {
            oddVal = entry.Key;
            break;
        }
    }

    return (int)oddVal;
}

else
    return 0;


texts: Downsampling n-dimensional data from bins in one dimension

texts:
So I'm writing some code to perform a quite specific task given a large numpy array with N rows and 3 columns representing points in 3D. The 3D points are to be binned along one of the dimensions between specified bin edges. For each of these bins, there is a set fraction by which I must reduce the number of points in that bin, perfectly (pseudo)randomly.

Here is the code I have written to perform this task. I found myself spending a lot of time trying to figure out the most 'pythonic' way to achieve this. It still seems very clunky, so I'm sure there must be a more elegant way that capitalises on numpy's array performance. Any tips?

# Initialise the array of 3D points
radecz = np.zeros((N, 3))

# grab the point data from elsewhere
points[:, 0] = ...
points[:, 1] = ...
points[:, 2] = ...    # this is the dimension we bin in, call it z

# Create an array of M + 1 elements for the edges of M bins
binedges = ...    # (they do not span all of the space of points by the way)

# Find the counts per bin
H = np.histogram(points[:, 2], bins=binedges)

# The number to downsample to in each bin is already known
num_down = ("""some M-dimensional array of fractions""") * H[0]

# initialise a mask for the final array for my analysis with dimension N
finmask = np.array(points.shape[0] * [False])

# loop over bins (do I really need to do this??)
for i, nd in enumerate(num_down):

    # First get the array ids of the points in each bin
    zbin_ids = np.where( ( (binedges[i] < points[:, 2]) & \
                           (points[:, 2) <= binedges[i + 1]) ) == True )

    # Choose ids at random without replacement
    keep = np.random.choice(zbin_ids[0], size=cn, replace=False)

    # What's left is turned on in the mask for the final array
    finmask[keep] = True

points = points[(finmask,)]


texts:
There are APIs like the Except extension that require the IEqualityComparer<T> to work. I find it's too much work for such a simple task to implement an interface so I thought why not automate it.

I implemented this interface in a reusable fashion so that I can use it with any value and any number of properties.

internal class AutoEqualityComparer<T> : IEqualityComparer<T>
{
    public AutoEqualityComparer(IEnumerable<Func<T, object>> selectors)
    {
        Selectors = selectors;
    }

    private IEnumerable<Func<T, object>> Selectors { get; }

    public bool Equals(T left, T right)
    {
        return
            !ReferenceEquals(left, null) &&
            !ReferenceEquals(right, null) &&
            Selectors.All(selector => selector(left).Equals(selector(right)));
    }

    public int GetHashCode(T obj)
    {
        unchecked
        {
            return Selectors
                .Select(selector => selector(obj).GetHashCode())
                .Aggregate(17, (hashCode, subHashCode) => hashCode * 31 + subHashCode);
        }
    }
}

I then build a new extension which also can accept any number of selectors to compare:

internal static class Enumerable
{
    public static IEnumerable<T> Except<T>(
        this IEnumerable<T> first,
        IEnumerable<T> second,
        params Func<T, object>[] compare)
    {
        var mec = new AutoEqualityComparer<T>(compare);
        return first.Except(second, mec);
    }
}

Example:

Select all properties of an exception that are not in the base exception:

var exceptionProperties =
    typeof(ArgumentException)
    .GetProperties()
    .Except(typeof(Exception).GetProperties(), x => x.Name);

// result: ParamName is the only property


texts: Unity Static Singleton JSON Serialisation

texts:
I have a static PlayerData singleton which stores all the data for the player (gold, upgrades, heroes etc) but JsonUtility cannot serialise static or private methods so I have implemented a singleton with an intermediate SaveFile struct which is used in the serialisation.
PlayerData will have more complex objects likes HeroCollection etc but for now, I simply have a gold stat.
I am looking for a potentially better alternative solution or simply how to improve this.
Thanks.
struct SaveFile
{
    public int Gold;
}

public class PlayerData
{
    static PlayerData Instance = null;

    // # - Private Attributes - #
    int _Gold;

    // ... Heroes
    // ... Upgrades
    // ... Etc
    // # - - - - - - - #

    // # - Public Static Attributes - #
    public static int Gold { get { return Instance._Gold; } set { Instance._Gold = value; } }
    // # - - - - - - - #

    public static void Create(string json)
    {
        if (Instance == null)
            Instance = FromJson(json);
    }

    public static string ToJson()
    {
        return JsonUtility.ToJson(

            new SaveFile()
            {
                Gold = Instance._Gold
            }

        );
    }

    static PlayerData FromJson(string json)
    {
        SaveFile save = JsonUtility.FromJson<SaveFile>(json);

        return new PlayerData()
        {
            _Gold = save.Gold
        };
    }
}


texts:
I've written up some code that represents the Mandelbrot set in an, admittedly, quite inefficient way. It probably looks awful due to the fact that I did this completely solo, without any external sources aside from the wiki page. What I was wondering is, how can I, without rewriting it completely, fix my code so that it either runs faster, or is higher definition?

Final image:

import turtle
x = -200
y = 99
RN = -2
i = float(1.0)
c = complex(RN+i)
win = turtle.Screen()
win.setup(400,400)
t = turtle.Turtle()
t.speed(0)
t.penup()
t.ht()
pattern = []

#this calculates what the color hex value each pixel will be. if the 10th
#iteration results in a number greater than 2, then that pixel is outside
#of the set.
def set_color(RN,pattern,z,c):
    for v in range(10):
        z = z**2 + c
        pattern.append(z)
    if abs(z) > 3.7918623e+90:
        t.color("#191970")
    elif abs(z) > 1.9472705e+45:
        t.color("#16167F")
    elif abs(z) > 4.4127888e+22:
        t.color("#13138F")
    elif abs(z) > 210066388901:
        t.color("#10109F")
    elif abs(z) > 458330:
        t.color("#0D0DAF")
    elif abs(z) > 677:
        t.color("#0B0BBF")
    elif abs(z) > 26:
        t.color("#0808CF")
    elif abs(z) > 5:
        t.color("#0505DF")
    elif abs(z) > 2:
        t.color("#0202EF")
    elif abs(z) > 1.75:
        t.color("yellow")
    elif abs(z) > 1.5:
        t.color("gold")
    elif abs(z) > 1.25:
        t.color("goldenrod")
    elif abs(z) > 1:
        t.color("darkgoldenrod")
    else:
        t.color("black")

#draws the set
def Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c):
#draws line by line, 100 times
    for e in range(100):
        t.pendown()
#draws one line
        for e in range(precision):
            z = 0
            set_color(RN,pattern,z,c)
            pattern = []
            RN = float(RN + move_rate)
            c = complex(RN,i)
            x = x + check_rate
            t.setposition(x,y)
#sets up values you'll need next row
        RN = -2.0
        i = i-.02
        t.penup()
        x = -200
        y = y - 2
        t.setposition(x,y)
    t.penup()

#purely decorative black background for the set
def borders():
    t.color("black")
    t.setposition(-200,200)
    t.pendown()
    t.begin_fill()
    for i in range(4):
        t.forward(400)
        t.right(90)
    t.end_fill()

precision = 400
check_rate = float(400 / precision)
move_rate = float(check_rate/100)

t.penup()
borders()
t.setposition(x,y)
Mandelbrot(RN,pattern,precision,check_rate,move_rate,x,y,i,c)