texts:
I'm currently rolling a little Float16 implementation. It's minimalistic and can't handle infinity, NaN and will neither work properly with overflows nor with underflows. (That's not the goal btw.)

Is there something particular wrong with the following implementation which could lead to major issues?

class Float16
{
public:
    Float16(float other)
    {
        IEEESingle f32;
        f32.Float = other;

        if (other == 0.0f)
        {
            bits.IEEE.Exp = 0;
            bits.IEEE.Man = 0;

            return;
        }

        bits.IEEE.Sign = f32.IEEE.Sign;
        bits.IEEE.Exp  = f32.IEEE.Exp - 112;
        bits.IEEE.Man  = f32.IEEE.Man >> 13;
    }

    operator float() const
    {
        if (bits.IEEE.Exp == 0 && bits.IEEE.Man == 0)
        {
            return 0.0f;
        }

        IEEESingle f32;

        //112-->F32 Exponent = N + 127, F16 Exponent = N + 15;

        f32.IEEE.Sign = bits.IEEE.Sign;
        f32.IEEE.Exp  = bits.IEEE.Exp + 112;
        f32.IEEE.Man  = bits.IEEE.Man << 13;

        //<< 13 since Mantisse f32 = 23 and Mantisse F16 = 10

        return f32.Float;
    }

private:
    union IEEEHalf
    {
        uint16_t bits;
        struct
        {
            uint16_t Man  : 10;
            uint16_t Exp  : 5;
            uint16_t Sign : 1;
        } IEEE;
    } bits;

    union IEEESingle
    {
        float Float;
        struct
        {
            uint32_t Man  : 23;
            uint32_t Exp  : 8;
            uint32_t Sign : 1;
        } IEEE;
    };
};

int main()
{
    Float16 f16 = 1.5f;
    float   f32 = (float)f16;

    return 0;
}

I am aware that my calculations will happen at F32 level and I don't intend to implement direct F16 calculations. I am planning to add some operators to the class, but the question focuses mostly on the conversion between f16 and f32. I am aware of the precision and rounding issues of Float16 values.


texts: Find the smallest number greater than "n" with the same digit sum as "n"

texts:
Here is my code:

def func(n):
    sum_digits_n = 0
    for i in str(n):
        sum_digits_n+=int(i)

    num = n+1

    while True:
        s = 0
        for i in str(num):
            s+=int(i)
        if s==sum_digits_n:
            return num
            break
        else:
            num += 1

It works for small to moderate sized n. But it takes forever to run with big values of n. How can I optimize it?

For example, let's check the run times for different sized inputs:

import time
inputs = [7,70,700,7000,70000,700000,7000000,70000000]
for i in inputs:
    t = time.time()
    ans = func(i)
    print('Input: {}. Ans: {}. Time taken: {}s\n'.format(i, ans, time.time()-t))

As you can see, even with a not-so-huge input as 70 million, the code takes ~1.5 mins to run.


texts: Responsive bullets with horizontal and vertical centered HTML content

texts:
In my current project I develop a responsive site which has only on desktop a fixed width. Otherwise it's fluid. My client or rather my art director ;) want's fluid bullets with horizontal and vertical centered content on the site. To illustrate that I created a dabblet.

Here is my HTML for the bullet:

Some text or markup

And my CSS for the bullet looks so:

.ib {
  overflow: hidden;
  padding-bottom: 100%;
  position: relative;

  border-radius: 50%;

  background: #f90;
}

.ib:hover {
  background: #790;
}

.ib_ow {
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
}

.ib_iw {
  display: table;
  height: 100%;
  width: 100%;
}

.ib_c {
  display: table-cell;

  text-align: center;
  vertical-align: middle;
}

Full code of my example you can find here. And as a playground you can use this dabblet.

It works fine, but is there a solution with less code? I've tried pseudo elements based on this article on css-tricks.com with no success. My problem is: I have no fixed width or height for the container. The bullet should use all available spaces.


texts: If/else that contains HTML blocks, which contain additional PHP functions

texts:
I have a form that posts (a,b) values into the following .php file, and displays an error message when the user tries to reach the .php file directly, instead via POST request.

This code is probably pretty messy, for example, I'm not sure I can post
 tags right away, instead of having them inside the  tags, but since it's an if/else function, I'm not sure how to build this in the most efficient way.

<?php
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
?>

You didn't come here through a Post.

<?php
    } else {

if(isset($_POST['a'])){

    switch ($_POST['a']) {

    case "1":
        $var1 = "word1";
        break;

    case "2":
        $var1 = "word2";
        break;

    default:
        $var1 = "other";
    }
}

if(isset($_POST['b'])){

    switch ($_POST['b']) {

    case "1":
        $var2 = "word3";
        break;

    case "2":
        $var2 = "word4";
        break;

    default:
        $var2 = "other";
    }
}

?>
<!doctype html>

<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

HTML-blocks that contain PHP such as <?php echo $var1; ?>, and <?php echo $var2; ?>.

<?php
    }
?>


texts:
I have been getting back into C++ today, after a few years of Python and R. I am completely rusty, but decided to create a matrix object to re-familiarise. In reality I wouldn't use this class, since I know Boost has matrix objects, but it's good practice!

It can be compiled with g++ -std=c++11 matrix.cpp -o m.

Any thoughts or comments are most welcome.

#include <iostream>
#include <vector>

class matrix {
    // Class: matrix
    //
    // Definition:
    // creates a 2d - matrix object as a vector of vectors and
    // populates with (int) zeros.
    //
    // Methods: get_value, assign_value, get_row.

    // create vector of vectors
    std::vector<std::vector<int> > m;
    public:
        // constructor for class, matrix dimension (rows=X, cols=Y).
        matrix( int X, int Y) {
        m.resize(X, std::vector<int>(Y, 0));
    }

    class row {
        //class for matrix row object. Pass in a
        // vector and overload `[]`.

        std::vector<int> _row;
        public:
            // constructor
            row(std::vector<int> r) : _row(r) {
            }

            // overload `[]` to return y element.
            // note `.at()` does a range check and will throw an error
            // if out of range
            int operator[]( int y) {
                return _row.at(y);
            }
    };

    // overload [] to return x element
    row operator[]( int x) {
        return row(m.at(x));
    }

    int get_value ( int x, int y ) {
        //  Function: get_value
        //  Definition: returns value `v` of element
        //  `xy` in matrix `M`.
        return m[x][y];
    }

    void assign_value ( int x, int y, int v ) {
        //  Function: assign_value
        //  Definition: Assigns value `v` to element
        //  `xy` in matrix.
        m[x][y] = v;
    }

    std::vector<int> get_row(int y, int X){
        // Function get_row
        // Definition: returns a vector object with row
        // of x-values of length X at y.
        std::vector<int> ROW;
        for ( int i=y; i<=y;i++){
            for (int j=0; j<=X-1;j++){
                ROW.push_back(m[i][j]);
            }
        }
        return ROW;
    }

};

int main(){

    // specify matrix dimensions
    int N = 10; // number of rows
    int M = 10; // number of cols

    // create a matrix object
    matrix mm(N,M);

    // print elements
    int i, j;
    for (i=0; i<=N-1;i++){
        for (j=0;j<=M-1; j++){
            std::cout << mm[i][j];
        }
        std::cout << std::endl;
    }

    // grab a value and print it to console
    std::cout << mm.get_value(0,0) << std::endl;

    // assign a new value (v = 1) to element (0,0)
    mm.assign_value(0,0,1);

    // re-print the updated matrix
    for (i=0; i<=N-1;i++){
        for (j=0;j<=M-1; j++){
            std::cout << mm[i][j];
        }
        std::cout << std::endl;
    }

    // `get_row()` test
    std::vector<int> R = mm.get_row(0, M);
    for( int i: R){
        std::cout << i << ' ';
    }
}


texts: Is there a good way to do this C++ single-player class?

texts:
I am making a little single-player game and to help with scoring I have created a Player class. Can you review my implementation?

I know that for a multiplayer game this isn't good. For multiplayer I would need to call functions and have all players in one instance.

File player.h

namespace SDLGamecore {
namespace player {

    class Player
    {
    private:
        long cash;
        int workers;
        std::string name;
    public:
        Player(std::string playerName)
        {
            name = playerName;
            cash = 0;
            workers = 0;
        }
        ~Player(){}

        long getCurrentCash() const;
        int getWorkers() const;
        std::string getPlayerName() const;
    };
}}

File player.cpp

namespace SDLGamecore {
namespace player {

    long Player::getCurrentCash() const
    {
        return cash;
    }

    int Player::getWorkers() const
    {
        return workers;
    }

    std::string Player::getPlayerName() const
    {
        return name;
    }

}}

File main.cpp

Player player("Test");

std::string pName = player.getPlayerName();
std::cout << pName << std::endl;

The code works as expected. Thank you for any feedback and assistance in improving my single player class.


texts: Escaping photo caption to avoid cross site script attack

texts:
I am a PHP newbie and this is part of a gallery code. I recently read about SQL injection and cross site scripting attack, I am trying to avoid that by html escaping on dynamically produced data. I am not sure if I am heading in the right direction here. I created an array with URL parameters then a function for HTML escaping. Can you critique this code and let me know what I am doing wrong?

$parameters_new = array('name' => $name,'pcaption' => $caption_array[$new]);

function html_escape($input, $encoding)
{
    return htmlentities($input, ENT_QUOTES, $encoding);
}

$result_final .= '

'.$photo_caption.'

'.$photo_description.'

;


texts: Project Euler #16 - Sum of all digits of 2^1000

texts:
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

  What is the sum of the digits of the number 2^1000?

    BigInteger big = new BigInteger("2");
    big = big.pow(1000);
    String num = big.toString();
    System.out.println(num);
    int result = 0;
    for(char i : num.toCharArray()) {
        result += Integer.parseInt(String.valueOf(i));
    }
    System.out.println(result);


texts:
I have written VERY simple code that converts a string to a character array and then displays the ASCII value of each character. Let me know if this is the most effective/safe way of doing what I described above.

#include <iostream>

using namespace std;

int main(int argc, char *argv[]){
    //Declare Variables.
    string input;
    int size;

    //Display message to user asking them to enter a string or character.
    cout << "What character/string do you need the ascii value(s) of? " << endl;

    //Assign user input to string input.
    cin >> input;

    //Get string length of user input.
    size = input.length();

    //Copy the string into a character array.
    const char * chars = input.c_str();

    //Itterate through the character array using the string size.
    for(int i = 0; i < size; i++){
            //Return Ascii values of each character.
            cout << "The value of character " << chars[i] << " is " << (int)chars[i] << endl;
    }

    return 0;
}


texts: Window Factory and Manager using MVVM pattern

texts:
I am fairly new to Factories and Dependency Injection in MVVM.

I've build my View(Window) factory with help from SO, and I would like to know if I had implemented everything properly(code works just fine).

I'm sorry for the length, but there was no other way for me to show my complete example.

First, there is the WindowFactory class. Its purpose is to delegate the creation of windows and coupling it with their ViewModels, so that I can avoid referencing View in its respective ViewModel (following MVVM pattern).

public class WindowFactory : IWindowFactory
{
    private readonly IWindowManager _windowManager;

    public WindowFactory(IWindowManager windowManager)
    {
        this._windowManager = windowManager;
    }

    public void CreatePhoneWindow()
    {
        var view = new PhoneWindow();
        var viewAdapter = new ViewAdapter(view, _windowManager);
        var viewModel = new PhoneWindowViewModel(viewAdapter);

        _windowManager.addWindow(view);
        view.DataContext = viewModel;
        view.Show();
    }

    // Here are copies of the above method, one for each different window that I create
}

WindowManager class. Its purpose is to keep track of current open windows, and allow certain operations on them (like checking if any window is open at a time, so that I can prevent other windows from being created)

class WindowManager : IWindowManager
{
    private ObservableCollection<Window> _windows;

    public WindowManager()
    {
        _windows = new ObservableCollection<Window>();
    }

    public void addWindow(Window window)
    {
        if (_windows.Contains(window) == false) { _windows.Add(window); }
    }

    public void removeWindow(Window window)
    {
        if (_windows.Contains(window) == true) { _windows.Remove(window); }
    }

    public bool isAnyWindowOpen()
    {
        if (_windows.Count == 0) { return true; }
        else { return false; }
    }
}

ViewAdapter class. Its purpose is to handle View close commands, that are comming from inside the View's ViewModel (again, to decouple).

class ViewAdapter : ICloseable
{
    private readonly Window _view;
    private readonly IWindowManager _windowManager;

    public ViewAdapter(Window view, IWindowManager windowManager)
    {
        this._view = view;
        this._windowManager = windowManager;
    }

    public void Close()
    {
        _windowManager.removeWindow(_view);
        _view.Close();
    }
}

Finally, I instantiate my WindowFactory and WindowManager in my MainWindow (Main, startup/default View) code-behind:

public MainWindow()
{
    InitializeComponent();

    var windowManager = new WindowManager();
    var windowFactory = new WindowFactory(windowManager);
    MenuItemsStackPanel.DataContext = new SideMenuViewModel(windowFactory, windowManager);
}

  I'm not including the Interfaces, since they contain simply the mocks of the used functions, nothing else.

I would really appreciate any feedback on my Factory design especially, since I might have made mistakes that I am unaware of, OR there could be a much better, cleaner way to achieve this.


texts:
I just wrote a simple script cmd to hide private folders by combining several scripts from the Internet.  Can anyone give me suggestions for improvement?

This batch file uses a password hidden by powershell script. Then I create a shortcut and run attrib -s -h, so it is not easy to find.
It works just gave attrib -s -h on the desired folder. Location folder can only be changed by editing the file. Also passwords can only be changed by editing the batch file. The last two things are quite cumbersome.

@echo off
title Privat Locker
set _folder="E:\Private"

dir /a:h %_folder%>nul 2>nul
if %errorlevel%==0 goto PASS1

dir /a:s %_folder%>nul 2>nul
if %errorlevel%==0 goto PASS1

:CONFIRM
echo Do you want to lock the Private Folder?! [Y/N]
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto end
if %cho%==N goto end
echo Error! Wrong answer, please type [Y/N]
goto CONFIRM

:LOCK
attrib +h +s %_folder%
echo The folder sucsessfully locked...
pause
goto end

:PASS1
set "psCommand=powershell -Command "$pword = read-host 'Masukkan PIN!' -AsSecureString ; ^
     $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
           [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
if NOT "%password%"=="YOURPINHERE" goto FAIL1
attrib -s -h %_folder%
goto EXP

:PASS2
set "psCommand=powershell -Command "$pword = read-host 'Masukkan PIN!' -AsSecureString ; ^
     $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
           [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
if NOT "%password%"=="YOURPINHERE" goto FAIL2
attrib -s -h %_folder%
goto EXP

:PASS3
set "psCommand=powershell -Command "$pword = read-host 'Masukkan PIN!' -AsSecureString ; ^
     $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
           [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
if NOT "%password%"=="YOURPINHERE" goto FAIL3
attrib -s -h %_folder%

:EXP
echo Folder successfully unlocked, do you want to look it? [Y/N]
set/p "tuju=>"
if %tuju%==Y goto BUKA
if %tuju%==y goto BUKA
if %tuju%==n goto end
if %tuju%==N goto end
echo Error! Pilihan salah, ketik [Y/N]
goto EXP

:BUKA
echo Go to folder...
pause
start explorer %_folder%
goto end

:FAIL1
echo Wrong PIN!
echo Try again, 2 remaining
goto PASS2

:FAIL2
echo Wrong PIN!
echo Try again! 1 remaining
goto PASS3

:FAIL3
echo Wrong PIN!
echo Device will reboot!

:PIL
set/p "rst=Automatic Restart? [Y/N]"
if %rst%==Y goto RST
if %rst%==y goto RST
if %rst%==N goto MNL
if %rst%==n goto MNL
echo Error! wrong choice, pleas type [Y/N]
goto PIL

:RST
shutdown -r -t 15 -c "Computer will reboot on 15 second's"
pause
goto end

:MNL
echo If device not rebooting on 15 minutes, all data[s] in the folder
echo will be erased...
pause

:end


texts: Presenting a boolean as an int for XMLSerialization in C#

texts:
I'm working with an XML structure that requires booleans to be represented as 1 or 0.

So, suppose the XML output has to look like:

<valid>1</valid>

Several nodes can be represented this way, so I made a struct to handle this. The solution I found works, but lacks oomph. OK, no, it doesn't just lack oomph, it sucks.

(Implemented in .NET 4)

public struct MyCrappyBool : IXmlSerializable
{
    private int _IntValue;
    private bool _BoolValue;

    public int IntValue
    {
        get { return _IntValue; }
        set
        {
            if (value < 0 || value > 1)
                throw new ArgumentOutOfRangeException();
            _IntValue = value;
            _BoolValue = value == 1;
        }
    }
    public bool BoolValue
    {
        get { return _BoolValue; }
        set
        {
            _BoolValue = value;
            _IntValue = value ? 1 : 0;
        }
    }

    public MyCrappyBool(int intValue) : this()
    {
        IntValue = intValue;
    }
    public MyCrappyBool(bool boolValue): this()
    {
        BoolValue = boolValue;
    }

    #region IXmlSerializable Members
    public XmlSchema GetSchema() { return null; }
    public void ReadXml(XmlReader reader)
    {
        IntValue = int.Parse(reader.ReadString());
    }
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteString(IntValue.ToString());
    }
    #endregion
}

This is incredibly tedious, first and foremost because I need to instantiate every time:

MyCrappyBool isValid = new MyCrappyBool(true);

But even then, some nifty implicit overloading can address that:

    public static implicit operator MyCrappyBool(bool boolValue)
    {
        return new MyCrappyBool(boolValue);
    }
    public static implicit operator MyCrappyBool(int intValue)
    {
        return new MyCrappyBool(intValue);
    }

That's still a lot of code for one... crappy boolean.

Later, it can be (XML) serialized as part of any other class:

[XmlElement("valid")]
public MyCrappyBool IsValid { get; set; }
[XmlElement("active")]
public MyCrappyBool IsActive { get; set; }

Is there a simpler way about this I'm not seeing?

Update: Reverse implicit operator overloading!

    public static implicit operator bool(MyCrappyBool myCrappyBool)
    {
        return myCrappyBool.BoolValue;
    }

    public static implicit operator int(MyCrappyBool myCrappyBool)
    {
        return myCrappyBool.IntValue;
    }

This means all my properties can be private.


texts:
Because a website I need data from doesn't have any API or RSS feed for their service status, I use a Web Scraper I built using PHP to grab the data I need and structure it as JSON.  However I want to make sure the script is as resilient as possible.

<?php

error_reporting(E_ALL & ~E_NOTICE);
header('Content-Type: application/json');

// Load the Cached json file
$json = json_decode(file_get_contents('service.json'));

// Calculate if the cahced json file isn't older than 5 minutes
$current_time = new DateTime('now');
@$cache_time = new DateTime($json->meta->cache_time);
$interval = $current_time->diff($cache_time, true);
if($interval->i > 5){

    // If the cached json file is older than 5 minutes, make a request to grab a fresh copy
    $ch = curl_init();

    // Setting the curl options
    curl_setopt($ch, CURLOPT_URL, "http://www.translink.ca/en/Schedules-and-Maps/Alerts.aspx");

    // The page tries to set a cookie using JS to see if JS is enabled.  Here I just trick it into thinking we have JS.
    curl_setopt($ch, CURLOPT_COOKIE, "YPF8827340282Jdskjhfiw_928937459182JAX666=<my public ip>");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);

    curl_close($ch);

    // Load everything up into a DOMDocument
    $doc = new DOMDocument();
    @$html = $doc->loadHTML($res);

    // Set the metadata
    $status = array();
    $status['meta']['cached'] = true;
    $status['meta']['cache_time'] = date("Y-m-d H:i:s");

    // Grab the Current Conditions tab - #tab0
    $tab0 = $doc->getElementById("tab0");
    if(empty($tab0)){
        die('{"error":"Unable to retrieve service status", "code":101}');
    }

    // Grab all of the table rows
    $tr0 = $tab0->getElementsByTagName("tr");
    $lastIndexedService = "";
    // Begin to sort everything
    foreach ($tr0 as $row) {
        $class = $row->getAttribute('class');

        // Each table row has two divs, one with the alert information and another with the description
        if($class == "alertInfo"){

            // Getting the specific information from the table
            $status_td = $row->childNodes->item(1);
            $service = $row->childNodes->item(2)->nodeValue;
            $service = strtolower(str_replace(' ','',$service));
            $summary = trim($status_td->childNodes->item(1)->nodeValue);
            $severity = $row->childNodes->item(3)->nodeValue;
            $status['data']['current'][$service]['status']['summary'] = $summary;
            $status['data']['current'][$service]['status']['severity'] = $severity;
            $status['data']['current'][$service]['status']['effective'] = $row->childNodes->item(4)->nodeValue;

            // There is a line break in the effective line, we just fix that.  Obviously this will need to be updated with its 2015.
            $status['data']['current'][$service]['status']['effective'] = str_replace('2014', '2014 ', $status['data']['current'][$service]['status']['effective']);
            $lastIndexedService = $service;
        }

        // Getting the Alert Description
        if($class == "alertDesc" && $lastIndexedService !== ""){
            $div = $row->getElementsByTagName("div");
            $div = $div->item(0);
            if(!empty($div->nodeValue)){

                // We store it as html as there is formatting we'd like to preserve
                $status['data']['current'][$lastIndexedService]['description'] = $doc->saveHTML($div);
            }
        }
    }

    // Store the fresh data into the cached file
    file_put_contents('service.json', json_encode($status));

    // Because we initially set the cached flag to true in at the top before we save it, we now flip it back.
    $status['meta']['cached'] = false;

    // Print out the results
    echo(json_encode($status));
} else {

    // Print out the cached results
    echo(file_get_contents('service.json'));
}
?>


texts:
I have just finished learning basic-intermediate Python subjects and wanted to test myself. This word-guessing game is one of the first programs I have written.

import random

def pick_random_word():
    word_list = ["python", "c", "java", "swift", "html", "css", "go", "ruby"]
    random_word = random.choice(word_list)
    return random_word

def make_word_classified(word):
    classified_list = ["_" for i in word]
    return classified_list

def guess():
    word = pick_random_word()
    classified_word = make_word_classified(word)
    print(*classified_word)
    total_attempts = 0

    while True:
        try:
            answer = input("Guess a letter (Write only one letter)>: ").lower()
            if len(answer) > 1:
                raise Exception
        except Exception:
            print("Only one letter at a time!")
            continue
        total_attempts += 1

        if total_attempts >= 7:
            print("Sorry but you lost!")
            try_again = input("Wanna play again? (write y or n) >: ")
            if try_again == 'y':
                guess()
            elif try_again == 'n':
                print("Goodbye!")
                quit()

        for i in range(len(word)):
                if answer == word[i]:
                    classified_word[i] = answer
                if "".join(classified_word) == word:
                    print("You won!")
                    quit()

        print(*classified_word, f"\nTotal attempts left: {7 - total_attempts}")

if __name__ == "__main__":
    guess()

So, what do you think? How can I make it better? What are my mistakes?


texts: Create a state dropdown with an abbreviation option and a full option

texts:
I have this simple function here because I am too lazy to write out a state dropdown every time I need one. I already have an array with all the states set up, abbreviations as keys and names as values. It works just fine, but I like to write concise, clean, legible code, and I am still very unseasoned, so I find I miss a lot of stupidly simple s*** (the price I pay for teaching myself and not practicing often enough).

I see the four lines of redundant code inside the two primary conditionals, and I would move them outside the if statement, except that I have that last echo statement, which is really the whole purpose for the condition in the first place, and I don't think retesting the $style variable is all that kosher.

function create_state($style, $form = NULL) {
  global $state;
  echo '<select name="state">'."\n";
  echo '<option value="">--</option>'."\n";
  if ($style === 'abbr') {
    ksort($state);
    foreach ($state as $abbr => $name) {
      echo "<option value=\"$abbr\"";
      if($form === $abbr)
        echo 'selected="selected"';
      echo ">$abbr</option>\n";
    }
  } else {
    asort($state);
    foreach ($state as $abbr => $name) {
      echo "<option value=\"$abbr\"";
      if($form === $abbr)
        echo 'selected="selected"';
      echo ">$name</option>\n";
    }
  }
  echo '</select>'."\n";
}


texts: Remove all trailing blanks and spaces from a string

texts:
This is my solution to K&R Ex 1-18 which requires us to remove all trailing blanks and spaces from a string. I specifically wanted to use a separate function for processing the input (via gtLine()) to promote code re-usability. Please tell me ways in which I could have made my program shorter/better. Also, please point out anything wrong that you might find with my programming logic or algorithm.

#include<stdio.h>
#define MAXLEN      100
#define STORELEN    1000

#define T   1
#define F   0

int gtLine(char[]);
int process(char[],int);
void append(char[],char[],int);

main()
{
    char line[MAXLEN],str[STORELEN];
    int len,pos;
    len=pos=0;

    while((len=gtLine(line))>0)
    {
        len=process(line,len);
        append(str,line,pos);
        pos+=len;
    }

    printf("\nThe text : %s\n" AC_RESET,str);
    return 0;
}

/*** Gets a line for Input from the user Till EOF or a new line is read. Returns the position of NULL ***/

int gtLine(char arr[])
{
    int c,i;

    for(i=0;(i<MAXLEN-1) && ((c=getchar())!=EOF) && (c!='\n');++i)
        arr[i]=c;
    if(c=='\n')
    {
        arr[i]=c;
        ++i;
    }
    arr[i]='\0';
    return i;
}

/*** Processes the input string to remove all trailing spaces from the text. ***/
/*** Returns the new length of string                                        ***/

int process(char arr[],int len)
{
    int pc,nl;
    nl=F;                   // New line Flag
    if(arr[0]!='\n')
    {
        pc=arr[len-1];
        while(pc==' '||pc=='\t'||pc=='\n')
        {
            if(pc=='\n')
                nl=T;       // Set to 1 if at anypoint a new line character is encountered.
            --len;
            if(len!=0)
                pc=arr[len-1];
        }
        if(nl==T && len!=0)
            arr[len++]='\n';
        arr[len]='\0';
        return len;
    }
    else
    {
        arr[0]='\0';
        return (len=0);
    }
}

/*** Appends the string from[] to the end of to[] from to[pos] where pos= position of NULL in to[] ***/

void append(char to[],char from[],int pos)
{
    int i=0;

    while((pos<STORELEN) && ((to[pos]=from[i])!='\0'))
    {
        ++i;
        ++pos;
    }
    to[pos]='\0';
}


texts:
I have the following code to calculates and retrieves pair combinations:

public static void calculateCombinations(int x){
        int number = combination(x);
        int counter=0,y=0;
        while(counter<number){
            y++;
            for(int i=1; i<=x; i++){
                if(y!=i && !(i<y)){
                    System.out.println(y + " -- " + i);
                }
            }
            counter++;
        }
    }

    public static int combination(int n)
    {
        return permutation(n) / (permutation(2) * permutation(n - 2));
    }

    public static int permutation(int i)
    {
        if (i == 1)
        {
            return 1;
        }
        return i * permutation(i - 1);
    }

The code works well but it doesn't seem an efficient and professional code. One thing I am worried about here is the running cost of this code because it is part of a very huge project, which I care about the running time. What I want is to re-write it in a very professional way. I found lot of codes that do the same job I want but I only want to write my own code. I am asking you here to suggest how I can improve this function.


texts: Calculation of an inflation on volume/year

texts:
I would like to find out if my current solution to the problem described below is "good enough" or if there is an alternative way of achieving it. All I care about is the length (no. of lines) of the code and its efficiency. I am trying to follow the "DRY" principle and come up with something that when seen by another developer in the future will be considered a "good practice".
I am forced[1] to enter a few formulas into spreadsheet cells via vba. The formula is for a calculation of an inflation (say labour rate) on volume/year. It has some constants and some variants but the tricky bit is a variable inflation rate added each year. In my real life example this is far more complicated but I have shortened it and came up with an SSCCE.
SSCCE
You can view the example as a spreadsheet on Google Docs, or have a quick look through below:

The formulas are:
D6 = -$B$12*D4*(D8+1)
E6 = -$B$12*E4*(D8+1)*(E8+1)
F6 = -$B$12*F4*(D8+1)*(E8+1)*(F8+1)
G6 = -$B$12*G4*(D8+1)*(E8+1)*(F8+1)*(G8+1)
H6 = -$B$12*H4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)
I6 = -$B$12*I4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)
J6 = -$B$12*J4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)
K6 = -$B$12*K4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)
L6 = -$B$12*L4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)*(L8+1)

I tried it but didn't like it. There are 9 really long and ugly lines (remember, in my real life example there are many more variables).
Range("D6").Formula = "-$B$12*D4*(D8+1)"
Range("E6").Formula = "-$B$12*E4*(D8+1)*(E8+1)"
Range("F6").Formula = "-$B$12*F4*(D8+1)*(E8+1)*(F8+1)"
Range("G6").Formula = "-$B$12*G4*(D8+1)*(E8+1)*(F8+1)*(G8+1)"
Range("H6").Formula = "-$B$12*H4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)"
Range("I6").Formula = "-$B$12*I4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)"
Range("J6").Formula = "-$B$12*J4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)"
Range("K6").Formula = "-$B$12*K4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)"
Range("L6").Formula = "-$B$12*L4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)*(L8+1)"

Or Cells:
Cells(6, 4).Formula = "-$B$12*D4*(D8+1)"
Cells(6, 5).Formula = "-$B$12*E4*(D8+1)*(E8+1)"
Cells(6, 6).Formula = "-$B$12*F4*(D8+1)*(E8+1)*(F8+1)"
Cells(6, 7).Formula = "-$B$12*G4*(D8+1)*(E8+1)*(F8+1)*(G8+1)"
Cells(6, 8).Formula = "-$B$12*H4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)"
Cells(6, 9).Formula = "-$B$12*I4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)"
Cells(6, 10).Formula = "-$B$12*J4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)"
Cells(6, 11).Formula = "-$B$12*K4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)"
Cells(6, 12).Formula = "-$B$12*L4*(D8+1)*(E8+1)*(F8+1)*(G8+1)*(H8+1)*(I8+1)*(J8+1)*(K8+1)*(L8+1)"

But try to play with the right hand side of the statement. I see so much potential** in terms of optimising it, but the best I could have come up with in vba is:
Sub Main()

    Dim i As Long
    Dim s As String

    For i = 4 To 12
        s = s + "*(" + Cells(8, i).Address + "+1)"
        Cells(6, i).Formula = "=-$B$12*" + Cells(4, i).Address + s
    Next i

End Sub

I realize that I am concatenating Strings to achieve my goal. The code is working fine in this SSCCE and in my real life problem. It's not slow but I am purely curious if there is any other approach or if my current one can be optimized any further.
Questions

Can this be optimized any further?
Would you do this differently? If so, how? Why would your solution be any better than my current one?

[1] Forced because the real life example pulls its values from multiple places like another closed workbook, database, website, user input etc. For example, INDIRECT() does not work with closed workbooks so I can't rely on pure built-in functions.


texts: Deleting ranges of rows from a spreadsheet

texts:
I'm currently trying to create a macro, to edit a document that is around 280k rows and 12 columns. For the first steps I found a macro to delete the rows I don't want based on certain criteria, but the code repeats itself a lot. Every time I run it, I change the criteria and link the macros.

Also, is there a better way to reuse this code, rather than to modify it each time?

Sub jbeck1()
Dim i As Long
Dim LR As Long

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

LR = Cells(Rows.Count, 1).End(xlUp).Row

For i = LR To 2 Step -1

If Range("E" & i) = "0020" Then
    Range("E" & i).EntireRow.Delete Shift:=xlUp
End If

Next i

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.Run "jbeck2"

End Sub
Sub jbeck2()
Dim i As Long
Dim LR As Long

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

LR = Cells(Rows.Count, 1).End(xlUp).Row

For i = LR To 2 Step -1

If Range("E" & i) = "0021" Then
    Range("E" & i).EntireRow.Delete Shift:=xlUp
End If

Next i

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.Run "jbeck3"
End Sub


texts:
I have written the following tiny extension method to help me when I'm working with sequences in which I have to find a pattern.

public static IEnumerable<T[]> SearchPattern<T>(this IEnumerable<T> seq, params Func<T[], T, bool>[] matches)
{
      Contract.Requires(seq != null);
      Contract.Requires(matches != null);
      Contract.Requires(matches.Length > 0);

      var matchedItems = new List<T>(matches.Length);
      int itemIndex = 0;

      foreach (T item in seq)
      {
          if (matches[matchedItems.Count](matchedItems.ToArray(), item))
          {
              matchedItems.Add(item);

              if (matchedItems.Count == matches.Length)
              {
                  yield return matchedItems.ToArray();

                  matchedItems.Clear();
              }
          }
          else
          {
              if (matchedItems.Any())
              {
                  foreach (T[] results in seq.Skip(itemIndex - matchedItems.Count + 1).SearchPattern(matches)) // is this a tail call? can it be optimized?
                  {
                      yield return results;
                  }
                  break;
              }
          }
          itemIndex++;
      }
}

It appears to be working fine, but I'm wondering if there's a better way to do it.
Primarily I'm concerned with the recursive call (at the nested foreach), which makes the method very inefficient, not to mention potential stack-overflows when working with very large collections.

I know about tail-calls, and that they can be optimized into a loop (like in F#). I also recall having seen something about tail-calls on an IL level. What confuses me is that I'm already using the iterator pattern (yield return) - so is it a tail call at all? If it is, is it one I can eliminate?

Any input would be much appreciated!

Edit: usage sample:

var results = (new int[] { 0, 1, 2, 3, 3, 4, 4, 5, 7, 9 }).SearchPattern(
    (prevs, curr) => true,
    (prevs, curr) => prevs[0] == curr,
    (prevs, curr) => curr % 2 != 0
); // => { [ 4, 4, 5 ] }


texts: Is it worth to compromise on speed to follow PEP 8 guidelines?

texts:
I have this long line of code:

enc = encoder.predict(np.array([data[stock][4*i:4*(i+30)] for i in range(lens[stock]+days-30)]))

The problem is, the number of characters (97) exceed 79, which is not allowed by PEP 8. To follow the PEP 8 guideline I can

temp = [data[stock][4*i:4*(i+30)] for i in range(lens[stock]+days-30)]
enc = encoder.predict(np.array(temp))

But this creates a new variable that is stored in memory, rather then just a temporary storage in the first case. I'm assuming this takes slightly more time as well. The question is, is it worth compromising on speed to follow the guidelines/improve readability?

(PS: If there is a way to break down that one line of code into multiple lines, I would like to know)


texts: A Sine Template Function For Boost.MultiArray in C++

texts:
This is a follow-up question for An element_wise_add Function For Boost.MultiArray in C++. Besides the basic add operation applying onto each element, I am trying to implement a sine template function which can apply std::sin() on each element. A new concept with_std_sin is created as below.
template<typename T>
concept with_std_sin = requires(T x)
{
    std::sin(x);
};

The main body of this sin template function is here. The similar recursive technique is also used in order to go through all elements.
template<class T> requires (with_std_sin<T>)
auto sin(const T& input)
{
    return std::sin(input);
}

template<class T> requires (is_multi_array<T>)
auto sin(const T& input)
{
    boost::multi_array output(input);
    for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)
    {
        output[i] = sin(input[i]);
    }
    return output;
}

The test of this sin template function:
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);

// Assign values to the elements
int values = 1;
for (index i = 0; i != 3; ++i)
    for (index j = 0; j != 4; ++j)
        for (index k = 0; k != 2; ++k)
            A[i][j][k] = values++;

for (index i = 0; i != 3; ++i)
    for (index j = 0; j != 4; ++j)
        for (index k = 0; k != 2; ++k)
            std::cout << A[i][j][k] << std::endl;

auto test_result = sin(A);

for (index i = 0; i != 3; ++i)
    for (index j = 0; j != 4; ++j)
        for (index k = 0; k != 2; ++k)
            std::cout << test_result[i][j][k] << std::endl;

All suggestions are welcome.

Which question it is a follow-up to?
An element_wise_add Function For Boost.MultiArray in C++

What changes has been made in the code since last question?
The previous question is the implementation of applying add operation onto each element in Boost.MultiArray. The main idea in this question is to implement a sin template function for calculating trigonometric sine value of each element.

Why a new review is being asked for?
In my opinion, I am not sure is this a good idea about the implementation and the usage of the with_std_sin concept here. If there is any possible improvement, please let me know.


texts: Seperate out validations from a service and use custom exceptions for entities not found

texts:
I am using spring-boot, spring data, and Java 6. Here is an example from a business layer to save student details.

Srvice interface:

public interface StudentService
{
    public StudentDTO save(Integer stdId, Integer divisionId, StudentDTO studentDTO);
}

Service implementation:

@Service("studentService")
public class StudentServiceImpl implements StudentSerivce
{

     @Autowire
     private StudentDAO studentDAO;

     @Autowire
     private STDDAO stdDAO;

     @Autowire
     private DivisionDAO divisionDAO;

     @Autowire
     private TSBeanMapper beanMapper;

     @Override
     public StudentDTO save(Integer stdId, Integer divisionId, StudentDTO studentDTO)
     {
         STDEntity std = stdDAO.findOne(stdId);
         if (std == null)
         {
              throw new BadRequestException("Invalid standard");
         }

         DivisionEntity division = divisionDAO.finsOne(divisionId);
         if (division == null)
         {
              throw new BadRequestException("Invalid division");
         }
         StudentEntity student = beanMapper.map(studentDTO, StudentEntity.class);
         student.setSTD(stdEntity);
         student.setDivision(divisionEntity);
         return beanMapper(studentDAO.save(studentEntity), StudentDTO.class);

     }
}

For stdId and divisionId, I have called findOne and checked against null.

I would prefer that findOne throws an exception rather that return null for my case. But in this bug report it looks like currently it's not possible.

As for those 3 lines:

Fetch entity
Check null
ifNull then throw an exception

These lines of code are needed in other services for stdId and divsionID.

What is the best practice to separate those validations from serviceImpl and put it in other reusable components?


texts: Select comparison function for sorting based on type information

texts:
So I'm working on a patch for the python interpreter where you go through the list and look at the types of the elements and try to use optimized special-case comparison functions that are much cheaper than the default comparison function. This is the code that goes through and checks the list elements and then assigns the comparison function. I put a lot of thought into the design, refactoring it many times; I really want this to be readable. Is it? How can I improve the form of this? I'm not looking for performance fixes, this just executes once per sort so performance isn't a big deal... I'm looking more for style/refactoring feedback.

/* Turn off type checking if all keys are same type,
 * by replacing PyObject_RichCompare with lo.keys[0]->ob_type->tp_richcompare,
 * and possibly also use optimized comparison functions if keys are strings or ints.
 */
/* Get information about the first element of the list */
int keys_are_in_tuples = (lo.keys[0]->ob_type == &PyTuple_Type &&
                          Py_SIZE(lo.keys[0]) > 0);

PyTypeObject* key_type = (keys_are_in_tuples ?
                          PyTuple_GET_ITEM(lo.keys[0],0)->ob_type :
                          lo.keys[0]->ob_type);

int keys_are_all_same_type = 1;
int strings_are_latin = 1;
int ints_are_bounded = 1;

/* Test that the above bools hold for the entire list */
for (i=0; i< saved_ob_size; i++) {

  if (keys_are_in_tuples &&
      (lo.keys[i]->ob_type != &PyTuple_Type || Py_SIZE(lo.keys[0]) == 0)){
    keys_are_in_tuples = 0;
    keys_are_all_same_type = 0;
    break;
  }

  PyObject* key = (keys_are_in_tuples ?
                   PyTuple_GET_ITEM(lo.keys[i],0) :
                   lo.keys[i]);

  if (key->ob_type != key_type) {
      keys_are_all_same_type = 0;
      break;
  }

  else if (key_type == &PyLong_Type && ints_are_bounded &&
             Py_ABS(Py_SIZE(key)) > 1)
    ints_are_bounded = 0;

  else if (key_type == &PyUnicode_Type && strings_are_latin &&
             PyUnicode_KIND(key) != PyUnicode_1BYTE_KIND)
    strings_are_latin = 0;
}

/* Set compare_function appropriately based on values of the above bools */
if (keys_are_all_same_type) {

  if (key_type == &PyUnicode_Type && strings_are_latin)
    compare_function = unsafe_unicode_compare;

  else if (key_type == &PyLong_Type && ints_are_bounded)
    compare_function = unsafe_long_compare;

  else if (key_type == &PyFloat_Type)
    compare_function = unsafe_float_compare;

  else if ((richcompare_function = key_type->tp_richcompare) != NULL)
    compare_function = unsafe_object_compare;

} else {
  compare_function = safe_object_compare;
}

if (keys_are_in_tuples) {
  tuple_elem_compare = compare_function;
  compare_function = unsafe_tuple_compare;
}
/* End of type-checking stuff! */


texts: Recommender system accuracy testing using GridSearchCV

texts:
I'm trying to improve my Alternating Least Squares (ALS) model performance by testing using different model parameters, but the model performance is seemingly very low.

Since the Alternating Least Squares model is relatively different from other models under the evaluation perspective, I needed to set up my custom evaluation and cross-validation method in order for the GridSearchCV function to correctly work. To improve the performance, I tried to set up different param_grid and model to the testing function with apparently no results at all. My guess is that the custom parameters are not properly working. For reference, I looked at Jbochi's piece of code (https://gist.github.com/jbochi/2e8ddcc5939e70e5368326aa034a144e) to set up Discounted cumulative gain (DCG) for measuring my model score and the function Predefinedsplit from sklearn.model_selection (as you can see in the LeavePOutByGroup class) to set up the cv parameter.

class LeavePOutByGroup():
    def __init__(self, X, p=5, n_splits = 3):
        self.X = X
        self.p = p
        self.n_splits = n_splits
        test_fold = self.X.groupby("fullvisitorid").cumcount().apply(lambda x: int(x / p) if x < (n_splits * p) else -1)
        self.s = PredefinedSplit(test_fold)

grid_search = GridSearchCV(rec_pipeline, param_grid,
                           cv=LeavePOutByGroup(train_set, p=5, n_splits=3),
                           scoring=ndcg_scorer, verbose=1)
grid_search.fit(train_set)

I expected the mean_test_score to significantly change by changing the model parameters, instead I got almost no improvements at all. This is what I got (the float shows the mean_test_score for each set of parameters tested with the ALS model):

cvres = grid_search.cv_results_
for mean_score, params in zip(cvres["mean_test_score"], cvres["params"]):
    print(mean_score, params)

Output:

0.012434668656604229 {'als__factors': 20, 'als__regularization': 0.001, 'matrix__confidence': 10}

0.011882640120018911 {'als__factors': 20, 'als__regularization': 0.001, 'matrix__confidence': 40}

0.01271910407436217 {'als__factors': 20, 'als__regularization': 0.0001, 'matrix__confidence': 10}
...

0.011947024379421394 {'als__factors': 100, 'als__regularization': 0.0001, 'matrix__confidence': 10}

0.010698034031201297 {'als__factors': 100, 'als__regularization': 0.0001, 'matrix__confidence': 40}

0.010091750744302954 {'als__factors': 100, 'als__regularization': 0.0001, 'matrix__confidence': 100}

My question is: is there any other approach I can try for solving the bad performance issue? What is your experience on that? Or should I just try another evaluation metric for my ALS model? If so, which one?


texts: Delete from multiple tables using temp table variable

texts:
I'm previewing the data I'm about to delete, but this SQL looks a little redundant.  Is there a better way to write this?

declare @history table(pid int)
insert into @history select pid from plans p where p.pidSynergy = 'P0022' and p.pid != 2885

select * from forecast_FTEs where pid in (select pid from @history)
select * from forecast_phases where pid in (select pid from @history)
select * from budget_FTEs where pid in (select pid from @history)
select * from budget_phases where pid in (select pid from @history)
select * from plans where pid in (select pid from @history)


texts: Return array of objects with matching keys

texts:
For an exercise, I've written a function that, given an array of objects and a key (2nd argument), returns a new array of objects that contain all properties from a key. How'd I do?

function where(collection, source) {
  var arr = [];
  var keys = Object.keys(source);
  var countMatchingProps = 0;
  var currentProp;

  for (var i = 0; i < collection.length; i++) {
    countMatchingProps = 0;
    for(var j = 0; j < keys.length; j++){
      // assigned to variable for a bit of readability.
      currentProp = keys[j];
      // if object contains key ->
      if(collection[i].hasOwnProperty(currentProp)){
        // -> then compare their values nad increment counter
        if(collection[i][currentProp] === source[currentProp]){
          countMatchingProps++;
        }
      }
      // if number of matched properties are
      // equal to keys we can push current object to array
      if (countMatchingProps === keys.length) arr.push(collection[i]);
    }
  }
  return arr;
}

where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 3 }], { "a": 1});
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })


texts: Structuring code that shells out to an external script

texts:
This code that shells out to an external script could use some input in order to read smoother, I think.  Praise and critique are welcome.

module CompanyLib
  class S3

    attr_reader :output

    def set_path local, remote
      @path = [local, remote]
    end

    def get_bucket
      /(^[^\/]*)/.match(@path[1])[0]
    end

    def sync
      @output = `aws s3 sync #{@path[0]} s3://#{@path[1]} --acl public-read`
      raise Exception, "S3 sync command failed: #{output}" unless $?.success?
    end

    def parse
      self.sync
      normalize = output.gsub("\n", "\\n")
      normalize.scan(/s3:\/\/#{self.get_bucket}(.*?)\\n/).flatten
    end

    def sync_out
      self.parse
    end
  end
end


texts:
mails = []
mails.concat(@note.cc_emails) unless @note.cc_emails.nil?
mails.concat(@note.to_emails) unless @note.to_emails.nil?

Everything what I'm doing here is checking is @note.cc_emails is not nil then concatenating it in mails array.
How can I write it in more efficient way & also reduce the number of lines in the code (if possible)?


texts:
I wrote a module with 3 services that execute the oauth (and set the api key) for the google api and return the token object if the promise is positive.

Here is the whole working module:

angular.module('gapiOAuth', [])
.controller('gapiOAuthController', ['$scope', function($scope){
}])

.factory('gapiCredentialsSrvc', function(){
    return {
        gapiClientId: 'xxx',
        gapiScopeUrl: ['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/blogger'],
        gapiKey: 'xxx'
    }
})

.factory('gapiGetTokenSrvc', ['$q','gapiCredentialsSrvc', function($q, gapiCredentialsSrvc){
    return function (){
        var q = $q.defer();
        angular.element(document).ready(function(){
            gapi.auth.authorize({client_id: gapiCredentialsSrvc.gapiClientId, scope: gapiCredentialsSrvc.gapiScopeUrl, immediate: true}, function(response){
                if(response && !response.error){
                    q.resolve(response);
                } else {
                    q.reject({});
                }
            });
        });
        return q.promise;
    };
}])

.factory('gapiLogInSrvc',['$q','gapiCredentialsSrvc', function($q, gapiCredentialsSrvc){
    return function(){
        var q = $q.defer();
        angular.element(document).ready(function(){
            gapi.auth.authorize({client_id: gapiCredentialsSrvc.gapiClientId, scope: gapiCredentialsSrvc.gapiScopeUrl, immediate: false}, function(response){
                if(response && !response.error){
                    q.resolve(response);
                }else{
                    q.reject(response.error);
                }
            });
        });
        return q.promise;
    };
}])

.factory('gapiSetApiKeySrvc',['gapiCredentialsSrvc', function(gapiCredentialsSrvc){
    return function(){
        angular.element(document).ready(function(){
            gapi.client.setApiKey(gapiCredentialsSrvc.gapiKey);
            return true;
        });
    };
}])

Do you think there will be security issues if I put this code I made onto the client side?

How can I improve it?


texts:
I have been reading about pointers in C and I thought implementing a linked list would be a good exercise to test my knowledge.

Below is my code and it is 100% functional. All I am looking for is some criticism, such as how to make the functions more efficient or defining *pointerToLinkedList in a better spot.

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

//Structure represents a node of a Linked List
struct node {
    int data;
    struct node* link;
};

//Pointer to the head node
struct node *pointerToLinkedList = NULL;

//Function inserts a new node at the beginning of the linked list
void insertNodeBeginning(int aData){
    //pointer to the new node
    struct node *newNode = (struct node*) malloc(sizeof(struct node));

    //fill in data in new node
    newNode->data = aData;
    //point new node to the previous head (now second node in linked list)
    newNode->link = pointerToLinkedList;

    //adjust pointerToLinkedList accordingly with the new head
    pointerToLinkedList = newNode;
}

//Function inserts a new node at the end of the linked list
void insertNodeEnd(int aData){

    //pointer to the new node
    struct node *newNode = (struct node*) malloc(sizeof(struct node));

    //fill in data in new node
    newNode->data = aData;
    //point new node to NULL, because its last node in list
    newNode->link = NULL;

    //link second last node to the newly created last node of the linked list
    //start at beginning of list
    struct node *secondLastNode = pointerToLinkedList;
    //loop until it becomes second last
    while(secondLastNode->link != NULL){
        secondLastNode = secondLastNode->link;
    }
    //actual linking
    secondLastNode->link = newNode;
}

//Function deletes node at the beginning of the linked list
void deleteHead(){

    //get reference of the head that will be deleted
    struct node *temp = pointerToLinkedList;

    //adjust pointerToLinkedList to the new head (previously the second node)
    pointerToLinkedList = pointerToLinkedList->link;

    //free memory of the old head
    free(temp);
}

//Function deletes node at the end of the linked list
void deleteTail(){

    //get reference of the head to iterate through linked list
    struct node *temp = pointerToLinkedList;
    struct node *newTail;

    //iterate through linked list
    while(temp->link != NULL){
        newTail = temp;
        temp = temp->link;
    }

    //free memory of old tail
    free(newTail->link);

    //adjust the new tail and point it to NULL
    newTail->link = NULL;
}

Two more things apart from the criticism:

Am I using the free() function properly? Is the structure actually being removed from the dynamic memory?
What other functions apart from the four currently installed, would you recommend to implement as an exercise?


texts: Refactoring digital clock - JavaScript ES5 Functional Programming

texts:
I'm making a digital clock with ES5 ( no arrow stuff and so ). The location and temperature I'll do later.
How can I improve/refactor the current code that I have with functional programming?

CodePen: https://codepen.io/Aurelian/pen/opaxqx?editors=1010

This is the HTML:

United Kingdom, Manchester

NAN

This is the JS:

// Get te location
// Make the : blink

//var location = document.querySelector('.clock-location');

function abbrev(a,b) {
  return a.substr(0,b);
}

 function checkTime(i) {
      if (i < 10) {
        i = "0" + i
      };
      return i;
  }

function displayTime() {

  var clockTime = document.querySelector('.clock-time');
  var clockDate = document.querySelector('.clock-date');
  var clockDay = document.querySelector('.clock-day');
  var clockWeekdays = document.querySelector('.clock-weekdays');
  while(clockWeekdays.firstChild) clockWeekdays.removeChild(clockWeekdays.firstChild);

  var date = new Date();

  var weekday = new Array(7);
  weekday[0] = "Sunday";
  weekday[1] = "Monday";
  weekday[2] = "Tuesday";
  weekday[3] = "Wednesday";
  weekday[4] = "Thursday";
  weekday[5] = "Friday";
  weekday[6] = "Saturday";

  var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

  var singleDay = [];

  for (var i = 0; i < weekday.length; i++) {
    var day = weekday[i];
    var li = document.createElement('li');
    li.textContent = abbrev(day,3);
    if (i === date.getDay()) {
        li.classList.add('active');
    }
    clockWeekdays.appendChild(li);
  }

  // Mechanics
  var todayDay = weekday[date.getDay()];
  var h = date.getHours();
  var m = checkTime(date.getMinutes());
  var s = checkTime(date.getSeconds());

  var year = date.getFullYear();
  var month = date.getMonth();

  // Display
  clockDay.textContent = abbrev(todayDay,3);
  clockTime.textContent = h + ":" + m + ":" + s;
  clockDate.textContent = monthNames[month] + " / " +  year;

}

window.setInterval(displayTime, 1000);

//displayTime();

// Get the time

//Loop Throw weekdays - show 3 letters

CodePen: https://codepen.io/Aurelian/pen/opaxqx?editors=1010


texts:
I have implemented Astar algorithm for a problem on an online judge relating to maze given start and end positions along with a grid representing the maze. I output the length of the path along with the path itself. The following is the implementation in Python using the Euclidean distance:
import heapq, math, sys

infinity = float('inf')

class AStar():

    def __init__(self, start, grid, height, width):
        self.start, self.grid, self.height, self.width = start, grid, height, width

    class Node():
        def __init__(self, position, fscore=infinity, gscore=infinity, parent = None):
            self.fscore, self.gscore, self.position, self.parent = fscore, gscore, position, parent

        def __lt__(self, comparator):
            return self.fscore < comparator.fscore

    def heuristic(self, end, distance = "Euclidean"):
        (x1, y1), (x2, y2) = self.start, end
        if (distance == "Manhattan"):
            return abs(x1 - x2) + abs(y1 - y2)
        return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

    def nodeNeighbours(self, pos):
        (x, y) = pos
        return [(dx, dy) for (dx, dy) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] if 0 <= dx < self.width and 0 <= dy < self.height and self.grid[dy][dx] == 0]

    def getPath(self, endPoint):
        current, path = endPoint, []
        while current.position != self.start:
            path.append(current.position)
            current = current.parent
        path.append(self.start)
        return list(reversed(path))

    def computePath(self, end):
        openList, closedList, nodeDict = [], [], {}
        currentNode = AStar.Node(self.start, fscore=self.heuristic(end), gscore = 0)
        heapq.heappush(openList, currentNode)
        while openList:
            currentNode = heapq.heappop(openList)
            if currentNode.position == end:
                return self.getPath(currentNode)
            else:
                closedList.append(currentNode)
                neighbours = []
                for toCheck in self.nodeNeighbours(currentNode.position):
                    if toCheck not in nodeDict.keys():
                        nodeDict[toCheck] = AStar.Node(toCheck)
                        neighbours.append(nodeDict[toCheck])

                for neighbour in neighbours:
                    newGscore = currentNode.gscore + 1
                    if neighbour in openList and newGscore < neighbour.gscore:
                        openList.remove(neighbour)
                    if newGscore < neighbour.gscore and neighbour in closedList:
                        closedList.remove(neighbour)
                    if neighbour not in openList and neighbour not in closedList:
                        neighbour.gscore = newGscore
                        neighbour.fscore = neighbour.gscore + self.heuristic(neighbour.position)
                        neighbour.parent = currentNode
                        heapq.heappush(openList, neighbour)
                    heapq.heapify(openList)
        return None

if __name__ == '__main__':

    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')

    matrix = [[int(num) for num in line.split()] for line in sys.stdin]
    size = matrix.pop(0)
    coordinates = matrix.pop(0)
    n, m = size[0], size[1]
    x1, y1, y2, x2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]
    path = AStar((x1-1, y1-1), matrix, n, m).computePath((y2-1, x2-1))
    print(len(path))
    for pos in path:
        print(pos[0] + 1, pos[1] + 1)


texts:
I'm wondering if this code can be simplified. I'm less than thrilled about the fact that I repeat the Draw method in both CatModel and DogModel. For that matter, I'm not real happy that that method is even in the models at all. Trying to move it up to the AnimalModel superclass forces a cast.

EDIT: The "Model" classes should probably have been named "ViewModel" as that's the role they are playing in the actual project.

namespace GenericInterface
{
  public interface IDrawer {
  }

  public interface IDrawer<TModel>: IDrawer
    where TModel: IAnimalModel<TModel>
  {
    void Draw(TModel model);
  }

  public interface IAnimalModel
  {
    void Draw();
  }

  public interface IAnimalModel<TModel>: IAnimalModel
    where TModel: IAnimalModel<TModel>
  {
    IDrawer<TModel> GetDrawer();  // parent interface might like to know that it can get some kind of drawer, but it gets messy with the types.
  }

  public class CatDrawer: IDrawer<CatModel> {
    // eventually, we want to have different types of CatDrawers.
    public void Draw(CatModel model) {
      Console.WriteLine(model.NWhiskers + " whiskers");
    }
  }

  public abstract class AnimalModel {
    public abstract void Draw();
  }

  public abstract class AnimalModel<TModel>: AnimalModel, IAnimalModel<TModel>
    where TModel: class, IAnimalModel<TModel> {
    public abstract IDrawer<TModel> GetDrawer();
  }

  public class CatModel: AnimalModel<CatModel> {
    // The repetition of "CatModel" in the above line is less than ideal. It is driven by the fact that, as best I can tell, there is no way to say that a type parameter should always be equal to the name of the current class.
    public int NWhiskers { get; set; }
    // <summary>Would eventually become IDrawer<CatModel> GetDrawer(DrawerFactory factory) { return factory.GetCatDrawer(this); }
    public override IDrawer<CatModel> GetDrawer() {
      return new CatDrawer();
    }
    // Once we have different CatDrawers, this would become
    // public override void Draw(DrawerFactory factory) { this.GetDrawer(factory).Draw(this); {
    public override void Draw() {
      this.GetDrawer().Draw(this);
    }
  }

  public class DogModel: AnimalModel<DogModel>
  {
    public string Breed { get; set; }
    public override IDrawer<DogModel> GetDrawer() {
      return new DogDrawer();
    }
    public override void Draw() {
      this.GetDrawer().Draw(this);
    }
  }

  public class DogDrawer: IDrawer<DogModel> {
    public void Draw(DogModel model) {
      Console.WriteLine(model.Breed);
    }
  }

  class MainClass {
    public static void Main(string[] args) {
      // Works. Output is:
      // 9 Whiskers
      // collie
      CatModel cat = new CatModel();
      cat.NWhiskers = 9;
      DogModel dog = new DogModel();
      dog.Breed = "collie";
      List<IAnimalModel> animals = new List<IAnimalModel>(){ cat, dog };
      foreach (IAnimalModel animal in animals) {
        animal.Draw();
      }
    }
  }
}


texts: Console Commands with dependency injection (C#)

texts:
So I'm writing a big server and I've made a simple start on console commands. I'm not sure if the way I'm doing it in is correct so I'd like to have it reviewed.

I have a class called ServiceCollectionExtensions where extension methods are defined that can be used on ServiceCollection. In there I have a function to register all console commands:

public static void RegisterConsoleCommands(this IServiceCollection serviceDescriptors)
{
    serviceDescriptors.AddTransient<ICommand, ClearCommand>();
}

In my Nordlys class in my entry point, I have the following code:

IServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddLogging(builder => builder.AddConsole());
serviceDescriptors.AddSingleton<ConsoleCommandHandler>();
serviceDescriptors.RegisterConsoleCommands();

And at the end of the entry point I have this code to wait for user input:

while (true)
{
    string input = await System.Console.In.ReadLineAsync();

    if (input.Length > 0)
    {
        await serviceProvider.GetService<ConsoleCommandHandler>().TryHandleCommandAsync(input);
    }
}

And this is my ConsoleCommandHandler class:

public class ConsoleCommandHandler
{
    private readonly ILogger<ConsoleCommandHandler> logger;
    private readonly Dictionary<string, ICommand> commands;

    public ConsoleCommandHandler(ILogger<ConsoleCommandHandler> logger, IEnumerable<ICommand> commands)
    {
        this.logger = logger;
        this.commands = commands.ToDictionary(command => command.Command);
    }

    public async Task TryHandleCommandAsync(string input)
    {
        int spacePosition = input.IndexOf(' ');
        string header = spacePosition >= 0 ? input.Substring(0, spacePosition) : input;

        if (commands.Any(command => command.Key == header))
        {
            await commands[header].RunAsync(input.Substring(spacePosition + 1).Split(' '));
        }
        else
        {
            logger.LogWarning("'{0}' is not recognized as an internal command", header);
        }
    }
}


texts: Printing a nested data structure in Clojure

texts:
I wrote the following code which transforms a nested data structure

(def board [[{:mine true}             {:warn 1 :explored true} {:explored true}]
           [{:warn 1 :explored true}  {:warn 1 :explored true} {}              ]
           [{}                        {}                       {:flag true }   ]])

into a printable form and prints it

(("[ ]" "[1]" "[E]") ("[1]" "[1]" "[ ]") ("[ ]" "[ ]" "[F]"))

The functions for the transformation are the following:

(defn cell->icon
  [cell]
  (letfn [(cell->str [v] (format "[%s]" v))]
    (if (:explored cell)
      (cond (:mine cell) (cell->str "M")
            (:warn cell) (cell->str (:warn cell))
            :else        (cell->str "E"))
      (cond (:flag cell) (cell->str "F")
            :else        (cell->str " ")))))

(defn board->icons
  [board]
  (map (partial map cell->icon) board))

So far so good (if you have any recommendations for a nicer approach though, do not hesitate to mention).

The function which I don't like though is the following:

(defn print-board
  [board]
  (doall
    (map println
       (map (partial clojure.string/join " ")
            (board->icons board)))))

I don't like to use println together with map since it is not a pure function (has side-effects)!? Maybe I am a bit too critical but I would be glad if somebody could advice me or give a hint how to do it in a nicer Clojure like way.


texts:
I have implemented this algorithm, but I would like to get ride of the variable res, which is outside the Solution class, could anyone help me with this?

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
res = []
class Solution:
    """
    @param root: The root of the binary search tree.
    @param k1 and k2: range k1 to k2.
    @return: Return all keys that k1<=key<=k2 in ascending order.
    """
    def searchRange(self, root, k1, k2):
        # write your code here
        if root is None:
            return []
        if root.val > k1:
            self.searchRange(root.left, k1, k2)
        if root.val >= k1 and root.val <= k2:
            res.append(root.val)
        if root.val < k2:
            self.searchRange(root.right, k1, k2)
        return res


texts:
I wrote a finite automata implementation in C years ago. C's access to mutable, unsafe, raw pointers made it quite simple for me to link/relink the states of a finite automata.

I read the official Rust Book and wanted to rewrite it in Rust. I ran into problems with recursive references (individual state nodes acting as a linked list). The only thing I could think of is to use Rc<RefCell<State>> - which, as I understand it, are essentially the "unsafe" raw pointers Rust aims to minimize. Am I overthinking it or is this OK Rust code?

use std::cell::RefCell;
use std::rc::Rc;

type RefState = Rc<RefCell<State>>;

#[derive(Clone)]
enum State {
    Symbols(RefState, String),
    Epsilon(RefState),
    SplitEpsilon(RefState, RefState),
    Accepting
}
pub struct Sequence {
    start: RefState,
    end: RefState
}

impl State {
    fn wrap(self) -> RefState {
        Rc::new(RefCell::new(self))
    }
    fn accepting() -> RefState {
        Rc::new(RefCell::new(State::Accepting))
    }
    fn symbols(chars: &str, connect: RefState) -> RefState {
        Rc::new(RefCell::new(
            State::Symbols(connect, chars.to_string())
        ))
    }

    fn epsilon(connect: RefState) -> RefState {
        Rc::new(RefCell::new(
            State::Epsilon(connect)
        ))
    }
    fn split(connect1: RefState, connect2: RefState) -> RefState {
        Rc::new(RefCell::new(
            State::SplitEpsilon(connect1, connect2)
        ))
    }

}
impl Sequence {

    pub fn concat(mut self, other: Sequence) -> Sequence {
        *(self.end.borrow_mut()) = State::Epsilon(other.start);
        self.end = other.end;
        self
    }
    pub fn union(mut self, other: Sequence) -> Sequence {
        let end = State::accepting();
        let start = State::split(self.start.clone(), other.start.clone());

        *(self.end.borrow_mut()) = State::Epsilon(end.clone());
        *(other.end.borrow_mut()) = State::Epsilon(end.clone());
        self.start = start;
        self.end = end;

        self
    }
    pub fn star(mut self) -> Sequence {
        let end = State::accepting();
        let split = State::SplitEpsilon(self.start.clone(), end.clone());
        let start = split.clone().wrap();

        *(self.end.borrow_mut()) = split;
        self.start = start;
        self.end = end;

        self
    }
    pub fn symbols(chars: &str) -> Sequence {
        let end = State::accepting();
        let start = State::symbols(chars, end.clone());

        Sequence { start, end }
    }
}


texts: Improve Performance of Comparing two Numpy Arrays

texts:
I had a code challenge for a class I'm taking that built a NN algorithm.  I got it to work but I used really basic methods for solving it.  There are two 1D NP Arrays that have values 0-2 in them, both equal length. They represent two different trains and test data  The output is a confusion matrix that shows which received the right predictions and which received the wrong (doesn't matter ;).

This code is correct - I just feel I took the lazy way out working with lists and then turning those lists into a ndarray.  I would love to see if people have some tips on maybe utilizing Numpy for this? Anything Clever?

import numpy as np

x = [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 2, 0, 0, 0, 0, 0, 1, 0]
y = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
     2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

testy = np.array(x)
testy_fit = np.array(y)

row_no = [0,0,0]
row_dh = [0,0,0]
row_sl = [0,0,0]

# Code for the first row - NO
for i in range(len(testy)):
    if testy.item(i) == 0 and testy_fit.item(i) == 0:
        row_no[0] += 1
    elif testy.item(i) == 0 and testy_fit.item(i) == 1:
        row_no[1] += 1
    elif testy.item(i) == 0 and testy_fit.item(i) == 2:
        row_no[2] += 1

# Code for the second row - DH
for i in range(len(testy)):
    if testy.item(i) == 1 and testy_fit.item(i) == 0:
        row_dh[0] += 1
    elif testy.item(i) == 1 and testy_fit.item(i) == 1:
        row_dh[1] += 1
    elif testy.item(i) == 1 and testy_fit.item(i) == 2:
        row_dh[2] += 1

# Code for the third row - SL
for i in range(len(testy)):
    if testy.item(i) == 2 and testy_fit.item(i) == 0:
        row_sl[0] += 1
    elif testy.item(i) == 2 and testy_fit.item(i) == 1:
        row_sl[1] += 1
    elif testy.item(i) == 2 and testy_fit.item(i) == 2:
        row_sl[2] += 1

confusion = np.array([row_no,row_dh,row_sl])

print(confusion)

the result of the print is correct as follow:

[[16 10  0]
 [ 2 10  0]
 [ 2  0 22]]


texts:
What difference does this make:

<script type="text/javascript">
//<![CDATA[ ...code

Compared to this

<script type="text/javascript"> ...code


texts:
I'm learning Python and have made this start of a ATM program, I'm very new to this so please be gentle..

Is there a better way to rewrite this?

CHECKING_BALANCE = 4000
SAVINGS_BALANCE = 1000

def welcome_screen():
    print """
    Welcome to the Bank of Bam!
    To continue please follow the instructions:
       Press 1 for Checking Account
       Press 2 for Savings Account
       Press 3 for Balance Inquiries
       Press 4 to return card and exit
    """
    choice = int(raw_input("> "))
    if choice == 1:
        checking_account()
    elif choice == 2:
        savings_account()
    elif choice == 3:
        balance_inquiries()
    else:
        print "Exiting..."

def checking_account():
    print "You have $%i available" % (CHECKING_BALANCE)
    print """
    What would you like to do:
    [W]ithdrawl
    [D]eposit
    [T]ransfer funds
    """
    choice = raw_input("> ")
    if choice == "W":
        withdraw_funds()
    elif choice == "D":
        deposit_funds()
    elif choice == "T":
        transfer_funds
    else:
        print "Invalid input.."

def savings_account():
    print "You have $%i available" % (SAVINGS_BALANCE)
    print """
    [W]ithdrawl
    [D]eposit
    [T]ransfer
    """
    choice = raw_input("> ")
    if choice == "W":
        withdraw_funds()
    elif choice == "D":
        deposit_funds()
    elif choice == "T":
        transfer_funds()
    else:
        print "Invalid input.."

welcome_screen()

Example of usage:

    Welcome to the Bank of Bam!
    To continue please follow the instructions:
       Press 1 for Checking Account
       Press 2 for Savings Account
       Press 3 for Balance Inquiries
       Press 4 to return card and exit

> 1
You have $4000 available

    What would you like to do:
    [W]ithdrawl
    [D]eposit
    [T]ransfer funds

> Traceback (most recent call last): #<= CRTL - C
  File "atm.py", line 58, in <module>
    welcome_screen()

C:\Users\Justin\MyScripts>python atm.py

    Welcome to the Bank of Bam!
    To continue please follow the instructions:
       Press 1 for Checking Account
       Press 2 for Savings Account
       Press 3 for Balance Inquiries
       Press 4 to return card and exit

> 2
You have $1000 available

    [W]ithdrawl
    [D]eposit
    [T]ransfer

> Traceback (most recent call last): #<= CTRL - C
  File "atm.py", line 58, in <module>
    welcome_screen()
  File "atm.py", line 17, in welcome_screen
    savings_account()
  File "atm.py", line 48, in savings_account
    choice = raw_input("> ")
EOFError


texts: LeetCode: Binary Tree Zigzag Level Order Traversal C#

texts:
https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/

  Given a binary tree, return the zigzag level order traversal of its
  nodes' values. (ie, from left to right, then right to left for the
  next level and alternate between).

  For example:

Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

  return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/
/// </summary>

[TestClass]
public class ZigzagLevelOrderTest
{
    [TestMethod]
    public void TestZigZag()
    {
        /*     3
              / \
             9  20
                /  \
               15   7
          */
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        IList<IList<int>> res = ZigzagLevelOrderClass.ZigzagLevelOrder(root);
        CollectionAssert.AreEqual(new List<int> { 3 }, res[0].ToList());
        CollectionAssert.AreEqual(new List<int> { 20, 9 }, res[1].ToList());
        CollectionAssert.AreEqual(new List<int> { 15, 7 }, res[2].ToList());
    }

    [TestMethod]
    public void FailedTest()
    {
        /*     1
              / \
             2   3
            /     \
            4      5
             */

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.right.right = new TreeNode(5);
        IList<IList<int>> res = ZigzagLevelOrderClass.ZigzagLevelOrder(root);
        CollectionAssert.AreEqual(new List<int> { 1 }, res[0].ToList());
        CollectionAssert.AreEqual(new List<int> { 3, 2 }, res[1].ToList());
        CollectionAssert.AreEqual(new List<int> { 4, 5 }, res[2].ToList());
    }

}

public class ZigzagLevelOrderClass
{
    public static IList<IList<int>> ZigzagLevelOrder(TreeNode root)
    {
        List<IList<int>> result = new List<IList<int>>();
        if (root == null)
        {
            return result;
        }
        Stack<TreeNode> currentLeveL = new Stack<TreeNode>();
        Stack<TreeNode> nextLevel = new Stack<TreeNode>();
        currentLeveL.Push(root);
        while (currentLeveL.Count > 0 || nextLevel.Count > 0)
        {
            var nodes = new List<int>();
            while (currentLeveL.Count > 0)
            {
                var curr = currentLeveL.Pop();
                if (curr.left != null)
                {
                    nextLevel.Push(curr.left);
                }

                if (curr.right != null)
                {
                    nextLevel.Push(curr.right);
                }
                nodes.Add(curr.val);
            }

            if (nodes.Count > 0)
            {
                result.Add(nodes);
            }
            nodes = new List<int>();
            while (nextLevel.Count > 0)
            {
                var curr = nextLevel.Pop();
                if (curr.right != null)
                {
                    currentLeveL.Push(curr.right);
                }
                if (curr.left != null)
                {
                    currentLeveL.Push(curr.left);
                }
                nodes.Add(curr.val);
            }

            if (nodes.Count > 0)
            {
                result.Add(nodes);
            }
        }

        return result;
    }
}

Please review for performance. this is the second time I solved this question.
I think I did a better job now.


texts: Pascal Triangle c# code space complexity

texts:
can you give me your impression of my implementation of Pascal triangle problem?
I'm especially interested in space complexity evaluation
thank you all!

public List<List<int>> generate(int A)
{
    List<List<int>> result = new List<List<int>>();

    int currenctRowLength = 1;
    List<int> previousRow = new List<int>();
    for (int i = 0; i < A; i++)
    {
        List<int> row = new List<int>();
        row.Add(1);
        currenctRowLength = i + 1;
        int j = 1;
        while (j < currenctRowLength - 1)
        {
            row.Add(previousRow[j] + previousRow[j - 1]);
            j++;
        }

        if (i > 0)
        {
            row.Add(1);
        }

        previousRow=row;
        result.Add(row);
    }
    return result;
}


texts: PDO insert data through transaction method

texts:
I have an import books function to insert more than 5000 rows at once, I did some research and did this one but some other places I saw a different kind of methods to insert without looping and execute this. is my code got any trouble with the performance of app

public function importBooks($data, $no_of_rows)
{
    try {
        // Start transaction
        $this->db->beginTransaction();

        // Init query
        $this->db->query('INSERT INTO books_pre (title, author, publication, container, tmp_no, created_by, created_at) VALUES (:title, :author, :publication, :container, :tmp_no, :created_by, now())');

        for ($i=2; $i<=$no_of_rows; $i++) {
            // Bind values
            $this->db->bind(':title', $data[$i]['B']);
            $this->db->bind(':author', $data[$i]['C']);
            $this->db->bind(':publication', $data[$i]['D']);
            $this->db->bind(':container', $data[$i]['E']);
            $this->db->bind(':tmp_no', $data[$i]['A']);
            $this->db->bind(':created_by', $_SESSION['user_id']);

            // Execute query
            if (!$this->db->execute()) {
                return false;
            }
        }
        // Commit data
        $this->db->commitTransaction();
    } catch (Exception $e) {
        $this->db->cancelTransaction();
        echo "Failed: " . $e->getMessage();
    }
}


texts:
Context:

My project has a hand-rolled ORM (... yeah ... I know) ...

built around the MS DataSet objects that represent wrapped collections of rows of DBtables (... yeah ... I know) ...

and which use negative ints to represent identity columns on new Rows which haven't yet been synched with the DB (... yeah ... I know) ...

the upshot of which is we objects that generally expect an identity to start at -1 and be decremented until they reach int.MinValue

Furthermore, we sometimes need to tell these objects that they can only use a certain sub-set of the negative integer range, so that multiple threads can create rows, which can then be combined without risk of ID conflicts. (... yeah ... I know) ...

and occasionally this subdivision has to happen repeatedly :(

All of this is to explain why it is that I need a method that is going to take a range of negative numbers, and sub-divide it. But that these ranges want to be thought of as running from, say, -100 to -999 (i.e. they run the 'wrong way').

Alas, all of this set-up is completely non-negotiable. so the plethora of comments along the lines of "the best way to fix this code is to not need it, or to change what it's trying to do" are (whilst completely correct) not at all useful.

We need to split an arbitrary negative range into n sub-ranges, all of which MUST be strictly dis-joint. It's NOT necessary that we use all the integers (though it's preferable not to waste too many).
It's not necessary that we always use the boundary values, though again preferable.

We're guaranteed to be given the range (-1, int.MinValue), so have to support that.

Primary goal of review is primarily to spot bugs and edge cases, and gather views on readibility/understandability of code.
Other aesthetic/design comments welcome too.
Unit Test suite will be written, given the ease of testing.

So, the code:

public static void IdentifyIndexRangeForDataSetUse(
  int xiExistingRangeStart,
  int xiExistingRangeEnd,
  int xiTotalNumberOfDivisionsBeingMade,
  int xiIndexOfTargetDivision,
  out int xoTargetRangeStart,
  out int xoTargetRangeEnd)
{
  if (xiExistingRangeStart < xiExistingRangeEnd)
  { throw new System.InvalidOperationException("The SMALLER value MUST be provided first. Note that since values are negative, this first value will have the larger ABSOLUTE value!"); }

  if (xiExistingRangeStart > 0 || xiExistingRangeEnd > 0)
  { throw new System.InvalidOperationException("The existing range should lie entirely within the Negative Integers."); }

  // REVERSE THE NUMBERS!!
  // We get given a range like (-1 --> -99), but it's WAY easier to think and reason about the range (1 --> 99)
  // so simply reflect the range into the positive domain and work there.
  int lPosExistingRangeStart, lPosExistingRangeEnd;

  lPosExistingRangeStart = -1 * xiExistingRangeStart;
  if (xiExistingRangeEnd == int.MinValue)
  {
    lPosExistingRangeEnd = int.MaxValue;
  }
  else
  {
    lPosExistingRangeEnd = -1*xiExistingRangeEnd;
  }

  var lTotalLengthOfExistingRange = lPosExistingRangeEnd - lPosExistingRangeStart + 1; //check overflows
  var lTotalLengthOfNewRanges = lTotalLengthOfExistingRange / xiTotalNumberOfDivisionsBeingMade;
  int lPosTargetRangeStart = lPosExistingRangeStart + (xiIndexOfTargetDivision * lTotalLengthOfNewRanges);
  int lPosTargetRangeEnd = lPosTargetRangeStart + (lTotalLengthOfNewRanges - 1); //the '-1' prevents overlaps.

  // REVERSE THE NUMBERS!!
  // To take it back into the negative domain.
  xoTargetRangeStart = -1 * lPosTargetRangeStart;
  xoTargetRangeEnd = -1 * lPosTargetRangeEnd;

}


texts:
A palindromic number reads the same both ways.

The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

<?php

function isPalindrome($input) {
    return (string) $input === strrev($input);
}

$max = 999;
$min = 100;
$found = 0;

for ($i = $max; $i >= $min; $i--) {
    for ($j = $max; $j >= $min; $j--) {
        $result = $i * $j;
        if (isPalindrome($result)) {
            if ($result > $found) {
                $found = $result;
                $a = $i;
                $b = $j;
            }
        }
    }
}

print sprintf("Found %d times %d = %d", $a, $b, $found);


texts:
I have an app written with node.js, I have a function which takes an image file name and generates a few variations of this image, code below. The issue I am having is that when I have to generate resized images from multiple original images(20+) it sucks up all of the resources on my developing machine, CPU bumps to 100% as well as RAM. While If I run this on the server the process is killed since it sucks up all resources. I am using gm npm module which works on top of GraphicsMagick and ImageMagick. The way I use them is pretty identical to the example on their page.

My developing machine is macbook air with 8gb ram and 1.7GHz i7 processor.
My server is 10$ droplet on digitalocean with 1 GB / 1 CPU

On both I have

Node v6.10.1
NPM v4.2.0
GraphicsMagick v1.3.25
ImageMagick v6.9.8-3

I know that generating images is not an effortless task, but I am sure this should not be taking so much resources and break the app each time I have to generate images from 20+ originals on the server. I tried other npm packages like jimp, node-imagemagick-native, imagemagick and lwip. But the outcome is the same, my question is there something I can do to optimize the resources usage of the machine it is running on?

'use strict';
const path = require('path');
const gm = require('gm');
const debug = require('debug');

module.exports = (imgName) => {

  let sizes = [{
    width: 150,
    height: 150
  }, {
    width: 150,
    height: 150,
    crop: true,
    shortName: 'thumb'
  }, {
    width: 300,
    height: 300
  }, {
    width: 300,
    height: 300,
    crop: true,
    shortName: 'grid-300'
  }, {
    width: 500,
    height: 500
  }, {
    width: 500,
    height: 500,
    crop: true,
    shortName: 'grid-500'
  }, {
    width: 900,
    height: 600
  }, {
    width: 1400,
    height: 900
  }];

  sizes.forEach((size) => {

    if (imgName === undefined) return;

    let w = size.width;
    let h = size.height ? size.height : size.width;
    let ext = path.extname(imgName);
    let name = path.basename(imgName, ext);
    let suffix = `${w}x${h}`;
    let readPath = path.join(__dirname, '../uploads/' + imgName);

    if (typeof size.shortName === 'string') suffix = size.shortName;

    let relativePath = `../public/img/place/${name}-${suffix}.jpg`;
    let newPath = path.join(__dirname, relativePath);

    if (size.crop === true) {

      gm(readPath)
        .resize(w, h, '^')
        .gravity('Center')
        .crop(w, h)
        .quality(90)
        .write(newPath, (err) => {
          if (err) debug(err);
          return;
        });

    } else {

      gm(readPath)
        .resize(w, h)
        .quality(90)
        .write(newPath, (err) => {
          if (err) debug(err);
          return;
        });

    }

  });

};

Update:

in the uploads folder I have 40 images from 500kb to 2mb with resolution around 2000x3000px. The sizes for generated images are listed in the array.


texts: Class for simple python object to be hashed and referenced

texts:
I need objects in python that I can compare, reference to and hash.

In principal a tuple or list would be good enough just that
a list I cannot hash and the tuple I cannot change,
except replacing it which means losing references to it.

So I created a class for it, but still have the feeling there should be a simpler/better solution to it.

class MyClass:
    def __init__(self, k, l=0, m=0):
        self.k = k
        self.l = l
        self.m = m
    def __hash__(self):
        n_attr = len(self.__dict__)
        return sum(hash(attr)/n_attr for attr in self.__dict__.values())
    def __eq__(self, other):
        return all(sa==oa for sa, oa in zip(self.__dict__.values(),
                                           other.__dict__.values()))

Now I can do what I need: creating some objects

x = MyClass(1,2,3)
y = MyClass(7)
z = MyClass(7,1,0)

and some references

a = x; b = y; c = y; d = z

and compare, manipulate ...

b == c # True
b == d # False
b.l = 1
b == c # still True
b == d # now True
s = {a, d, (a,b)}
b in s # True
c in s # True
(a,c) in s # True

I wished I could just forget about the class and do

x = 1,2,3
y = 7,
z = 7,1

etc ...

Is writing this class the best way to approach this problem? Or did I miss something?

edit:

After the comment by WinstonEwert I confirmed that the objects cause breakage as keys in dictionary

s = {a: 'a', b: 'b'}
s[c] # 'b'
c.l = 99
s[c] # key error
s # key error

and decided to replace dictionaries that use these objects as keys by

class MyDict:
    def __init__(self, d={}):
        self._data = d.items()
    def __getitem__(self, key):
        for k, v in self._data:
            if k == key: return v
        raise KeyError
    def __setitem__(self, key, value):
        for i, (k, v) in enumerate(self._data):
            if k == key:
                self._data[i] = key, value
                return
        self._data.append((key,value))
    def __contains__(self, key):
        for k, v in self._data:
            if k == key: return True
        return False

Now I have the desired behavior

s = MyDict()
s[a] = 'a'
s[b] = 'b'
s[c] # 'b'
c.l = 99
s[c] # still 'b'

And I do not need MyClass any more and can use list

x = [1,2,3]
y = [7,0,0]
z = [7,1,0]


texts: Game where two players take turns picking numbers until a target sum (part 2)

texts:
Here is a continued discussion (Game where two players take turns picking numbers until a target sum) from here since my previous code has bug, I fixed it with totally new algorithm implementation.

Working on the problem of sum game. Suppose we have consecutive numbers from 1 to n, and an expected sum number, there are two players, and each player tries to select one number in turn (once a number is selected by one player, the other player cannot select it again), and the selected numbers are summed together. The player who first get a sum which is >= expected sum wins the game. The question is trying to find if first player has a force win solution (means no matter what numbers 2nd player will choose each time, the first player will always win), and also try to find all possible force win solutions of player 1.

For example, if we have numbers from 1 (inclusive) to 5 (inclusive) and expected sum is 7, if the first player select 1, no matter what the 2nd player select, in the final the first player will always win.

Areas which I want to improve, but do not know how in my below code, asking for advice,

I think the use of first_player_initial_choice is a bit ugly, but I do not know how to remove it;
I check len(path) == 1 to see if it is first choice by player 1, so that I can record when player 1 force win, what is the first selected number -- which could be used for further filter purpose, it seems a bit ugly as well;
I tried to find all possible winning solution of player 1, when try to filter (by using if result[0] in first_player_initial_choice to see if winning soluton of player 1 is actually a player 1 force win solution.) It seems a bit ugly as well, but I cannot figure out a way which pick-up only player 1 force win solution only in an efficient recursive solution way.

My code,

results = []
first_player_initial_choice = set()
def force_win(numbers, flags, current_value, expected_value, path):
    current_win = False
    for i in range(len(flags)):
        if not flags[i]:
            if numbers[i] + current_value >= expected_value:
                path.append(numbers[i])
                if len(path) % 2 != 0:
                    results.append(path[:])
                if len(path) == 1:
                    first_player_initial_choice.add(numbers[i])
                path.pop(-1)
                current_win = True
            else:
                flags[i] = True
                path.append(numbers[i])
                opponent = force_win(numbers, flags, current_value+numbers[i], expected_value, path)
                if len(path) == 1 and not opponent:
                    first_player_initial_choice.add(numbers[i])
                path.pop(-1)
                flags[i] = False
                if not opponent:
                    current_win = True

    # for
    return current_win

if __name__ == "__main__":
    win = force_win([1,2,3,4,5],[False]*5, 0, 8, [])
    print win
    if win:
        final_result = []
        print results
        print first_player_initial_choice
        for result in results:
            if result[0] in first_player_initial_choice:
                final_result.append(result)

        print final_result


texts: Check if any of class properties is not null/empty/was assigned

texts:
I have a class that I use to display on a web page fieldset. However, all of the properties of this class are optionally filled in by the user, which means all of them could be null/default. In this case I would like not to render the fieldset at all, instead of displaying an empty one.

I wrote a simple isEmpty() method that checks all property values using reflection, but I'm afraid this may become way too expansive.

public class User
{
    [Display(Name = "First Name:")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name:")]
    public string LastName { get; set; }

    public bool isEmpty()
    {
        Type t = this.GetType();

        var properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (var prop in properties)
        {
            var value = prop.GetValue(this, null);

            if (value != null && (string)value != "")
            {
                return false;
            }
        }

        return true;
    }
}

The isEmpty(), of course, assumes all properties are strings.

What do you think? Will this become potentially expansive as the class grows?


texts:
What's the neatest way to increment all values in a HashMap by 1? The map is <String, Integer>, but the key doesn't matter as every value will be incremented.

Is it "cleaner" to use lambdas with forEach/compute/etc. or just loop through the entries?

HashMap<String, Integer> map = mobCounter.get(mob);
for (Entry<String, Integer> e : map.entrySet()) {
    map.put(e.getKey(), e.getValue() + 1);
}

This doesn't look too messy to me but I'm wondering if people like seeing lambdas more.


texts:
I have implemented simple tree class as follows:
public class MoveTreeNode
{
    public MoveTreeNode Parent
    {
        get;
        set;
    }

    private List<MoveTreeNode> children = new List<MoveTreeNode>();

    public IEnumerable<MoveTreeNode> Children
    {
        get
        {
            return children;
        }
    }

    public void Add(MoveTreeNode child)
    {
        child.Parent = this;
        children.Add(child);
    }

    private IEnumerable<MoveTreeNode> Flatten()
    {
        yield return this;

        foreach(var child in Children.Select(x=> x.Flatten()).SelectMany(x=>x))
        {
            yield return child;
        }
    }
}

This works, but I have concerns about the following line:
foreach(var child in Children.Select(x=> x.Flatten()).SelectMany(x=>x))
Since I'm using yield I'd prefer to gain some of the benefits of lazy evaluation but I fear that while each child of the root will be lazily evaluated, the childrens' children, etc will be evaluated at once when their parents are evaluated.
Is there some way I can refactor this to make the most of lazy evaluation, or am I better off leaving it this way?