Enable Jquery Containment without using position: relative I was trying to constrain ui-modal-dialog closed by the "body" of html using Jquery's constrainment. I thought it was possible to just set .draggable( { containment: 'body' }): However, ui-modal-dialog always escapes and I can overscroll more than containment area such as "body" in this case( I also tried some rectangle [0, 0, 1024, 768] though, ui-modal-dialog can break its boundary). Now, I set the position: relative in the "html" and "body" in the code and it seems work so far.

My question is that I can use draggable({containment: some-container}) for constraining the ui-modal-dialog  without using relative: position.?

My JS fiddle: Containment not working

https://jsfiddle.net/kimihiro/qmgs37re/

My JS fiddle: Containment with position: relative in  "html" and "body" of styling Jquery.

https://jsfiddle.net/kimihiro/jtb3yhs8/

The same "Containment not working" code is below but not working here...

$.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
   _title: function(title) {
     if (!this.options.title) {
       title.html("&#160;");
     } else {
       title.html(this.options.title);
     }
   }
 }));
 $("#dialog").dialog({
   autoOpen: false,
   　　height: 300,
   width: 830,
   dialogClass: 'myTitleClass',
   modal: true,

   title: "Carpe Diem. Nunca Acredito Posteiro",
   closeOnEscape: false,
   open: function(event, ui) {
     $('.ui-dialog-titlebar-close', ui.dialog | ui);
   },

   buttons: {

     "Save": function() {
       $(this).trigger(updateKeyword());
     }
   }
 }).draggable({ containment: 'body' });

 $("#opener").click(function() {
   $("#dialog").dialog("open");
 });
input#opener {
  height: 30px;
  width: 200px;
  left: 50%;
  margin-top: -15px;
  /* = -height / 2   */
  margin-left: -100px;
  /* = -width / 2    */
  position: fixed;
  top: 80%;
  background: rgba(4, 115, 184, 0.9);
  color: #fff;
  font-style: Arial;
  font-size: 16px;
  font-weight: 700;
  line-height: 1.5;
  border-style: outset;
  display: flex;
  transition: .5s ease;
  vertical-align: middle;
  justify-content: center;
}

.myTitleClass .ui-dialog-title {
  white-space: normal;
}

.myTitleClass .ui-dialog-titlebar {
  background: rgba(4, 115, 184, 0.9);
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  height: 60px;
}

.myTitleClass .ui-widget-content .ui-state-default {
  background-image: none;
  background-color: rgba(4, 115, 184, 0.6);
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  border-style: none;
}

.myTitleClass .ui-widget-content .ui-state-hover {
  background-image: none;
  background-color: rgb(4, 127, 184);
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  border-style: none;
}

.ui-widget-overlay {
  position: fixed;
  background: black;
}

.myTitleClass .ui-dialog-titlebar-close {
  background: rgba(4, 115, 184, 0.9);
  border-radius: 17px;
  height: 33px;
  margin: -10px 0 0;
  padding: 1px;
  position: absolute;
  right: -28px;
  top: -24%;
  width: 33px;
}

.myTitleClass.ui-icon-close {
  background: url("http://download.jqueryui.com/themeroller/images/ui-icons_*COLOR*_256x240.png");
}

.ui-dialog {
  overflow: visible;
}

#footer {
  background: #0473b8;
  color: #fff;
  font-size: 12px;
  line-height: 50px;
  text-align: center;
  bottom: 0;
  height: 50px;
  position: fixed;
  width: 100%;
}
html {
  height: 100%;
   overflow-x: hidden;

}

body {
  height: 100%;
  overflow: hidden;

}

}

<link href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<input type="button" id="opener" value="Register Keyword">
</button>

Merry Christmas.

footer

In Firefox Dev edition your original code worked fine unless I a) resized the dialog or b) the body was too small for the dialog. The fix for each is to set the containment on the resizable widget too and don't let the dialog start out larger than the body to begin with, respectively.

var maxWidth = $('body').width() - 20;
var maxHeight = $('body').height() - 20;
$("#dialog").dialog({
  autoOpen: false,
  height: maxHeight > 300 ? 300 : maxHeight,
  width: maxWidth > 830 ? 830 : maxWidth,
  dialogClass: 'myTitleClass',
  modal: true,
  draggable: true,
  title: "Carpe Diem. Nunca Acredito Posteiro",
  closeOnEscape: false,
  open: function(event, ui) {
    $('.ui-dialog-titlebar-close', ui.dialog | ui);
  },
  buttons: {
    "Save": function() {
      $(this).trigger(updateKeyword());
    }
  }
}).draggable({
  containment: 'body'
}).resizable({
  containment: 'body'
});

Here's the updated fiddle.


Summing data from two arrays, grouped and sorted by date I have multiple multidimensional arrays that each have the same structure with different lengths.

arr1 = [["23 Jan",3],["29 Jan",10],["19 Jan",23],["25 Jan",23]]
arr2 = [["31 Jan",7],["29 Jan",12],["01 Feb",4]]

My result would be a merged array without duplicate dates ordered by the date. For the dates that get combined, like 29 Jan above, I would add the second values together.

Here is what the outcome to the above arrays should be:

arr = [["19 Jan",23],["23 Jan",3],["25 Jan",23],["29 Jan",22],["31 Jan",7],["01 Feb",4]]

As you can see the two with the date, 29 Jan, were combined and added.

Here is my current solution:

(arr1 | arr2).group_by(&:first).
  map { |k, v| [k, v.map(&:last).inject(:+)] }.
  sort_by { |x| x.first.to_date }

Which does indeed get my the correct result, I just want to refactor it. Any suggestions/insights would be appreciated.

It looks as if you have chosen the wrong data structure. The multidimensional Array looks very much like a Hash. Even your code mentions the terms key (k) and value (v).

If you were to use a Hash, you could use Hash#merge:

one = Hash[[["23 Jan",3],["29 Jan",10],["19 Jan",23],["25 Jan",23]]]
two = Hash[[["31 Jan",7],["29 Jan",12],["01 Feb",4]]]

one.merge(two) { |_value, old, new| old + new }
# => {"23 Jan"=>3, "29 Jan"=>22, "19 Jan"=>23, "25 Jan"=>23, "31 Jan"=>7, "01 Feb"=>4}

Note: If you're using a recent version of Ruby, you can replace Hash::[] with Array#to_hash

If you really do need multidimensional Arrays, you could still use Hashes internally and convert to the required format (Hash#to_a) when needed.


Spiral printing of 2D matrix Please comment about code complexity, and coding style, I'm preparing for a code interview, so any comment would be appreciated.

Example:

Input

1    2   3   4
5    6   7   8
9   10  11  12
13  14  15  16

Output:

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Code:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JobInterviewTests
{

    //Spiral printing of 2D matrix.
    [TestClass]
    public class Spiral2Dmatrixprint
    {
        [TestMethod]
        public void TestSpiralPrint()
        {
            int[,] matrix = new int[3, 3];
            matrix[0, 0] = 1; matrix[0, 1] = 2; matrix[0, 2] = 3;
            matrix[1, 0] = 8; matrix[1, 1] = 9; matrix[1, 2] = 4;
            matrix[2, 0] = 7; matrix[2, 1] = 6; matrix[2, 2] = 5;
            SpiralPrint(matrix);

        }

        private void SpiralPrint(int[,] matrix)
        {
            int colRight = 2;
            int colLeft = 0;
            int rowTop = 0;
            int rowEnd = 2;

            PrintRight(matrix, colLeft, colRight, rowTop, rowEnd);
        }

        private void PrintRight(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                System.Diagnostics.Debug.Write(matrix[colRight,rowTop]);
                return;
            }
            for (int i = colLeft; i <= colRight; i++)
            {
                System.Diagnostics.Debug.Write(matrix[rowTop, i]);
            }
            PrintDown(matrix, colLeft, colRight, ++rowTop, rowEnd);
        }

        private void PrintDown(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                return;
            }
            for (int i = rowTop; i <= rowEnd; i++)
            {
                System.Diagnostics.Debug.Write(matrix[i, colRight]);
            }
            PrintLeft(matrix, colLeft, --colRight, rowTop, rowEnd);
        }

        private void PrintLeft(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                return;
            }
            for (int i = colRight; i >= colLeft; i--)
            {
                System.Diagnostics.Debug.Write(matrix[rowEnd, i]);
            }
            PrintUp(matrix, colLeft, colRight, rowTop, --rowEnd);
        }

        private void PrintUp(int[,] matrix, int colLeft, int colRight, int rowTop, int rowEnd)
        {
            if (colRight == colLeft && rowTop == rowEnd)
            {
                return;
            }
            for (int i = rowEnd; i >= rowTop; i--)
            {
                System.Diagnostics.Debug.Write(matrix[i, colLeft]);
            }
            PrintRight(matrix, ++colLeft, colRight, rowTop, rowEnd);
        }
    }
}

Hard code col and row counts is not good

int colRight = 2;
int colLeft = 0;
int rowTop = 0;
int rowEnd = 2;

Test method should print out results - not method

I think this will fail if the matrix is not square

if (colRight == colLeft && rowTop == rowEnd)

I think this is cleaner

public static void TestSpiralPrint()
{
    int[,] matrix = new int[5, 4];
    matrix[0, 0] = 1;  matrix[0, 1] = 2;  matrix[0, 2] = 3;  matrix[0, 3] = 4;
    matrix[1, 0] = 5;  matrix[1, 1] = 6;  matrix[1, 2] = 7;  matrix[1, 3] = 8;
    matrix[2, 0] = 9;  matrix[2, 1] = 10; matrix[2, 2] = 11; matrix[2, 3] = 12;
    matrix[3, 0] = 13; matrix[3, 1] = 14; matrix[3, 2] = 15; matrix[3, 3] = 16;
    matrix[4, 0] = 17; matrix[4, 1] = 18; matrix[4, 2] = 19; matrix[4, 3] = 20;
    List<int> output = SpiralPrint(matrix);
    foreach (int i in output)
        Debug.WriteLine(i);
    Debug.WriteLine("");
}
private static List<int> SpiralPrint(int[,] matrix)
{
    List<int> output = new List<int>();
    if (matrix.Length > 0)
    {
        int top = 0;
        int btm = matrix.GetLength(0);
        int lft = 0;
        int rht = matrix.GetLength(1);

        while (lft < rht && top < btm)
        {
            for (int i = lft; i < rht; i++)
                output.Add(matrix[top, i]);
            top++;

            for (int i = top; i < btm; i++)
                output.Add(matrix[i, rht - 1]);
            rht--;

            if (lft < rht)
            {
                for (int i = rht - 1; i >= lft; i--)
                    output.Add(matrix[btm - 1, i]);
                btm--;
            }

            if (top < btm)
            {
                for (int i = btm - 1; i >= top; i--)
                    output.Add(matrix[i, lft]);
                lft++;
            }
        }
    }
    return output;
}


FIFO getch/ungetch Functions I'm currently working myself through K&R and just read about implementing getch() and ungetch().

In K&R these functions are implemented like this:

#include <stdio.h>

#define BUFSIZE 100
char buf[BUFSIZE];     /* buffer for ungetch */
int bufp = 0;          /* next free position in buf */

int getch(void) /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)    /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

As you can see this is implemented like a stack (last in -> first out). This somehow bothers me. In the example:

ungetch('a');
ungetch('b');
ungetch('c');

getch()will return 'c' at the first function call. 'b' on the second function call and 'a' on the third function call. I liked the idea of getting the first 'ungetch()'-ed char at the start and the last 'ungetch'-ed char in the end.

This is what I did:

#include <stdio.h>

#define BUFSIZE 10
static int reorder_buf(void);

char buf[BUFSIZE];
int bufrp = 0;    //buffer read position
int bufwp = 0;    //buffer write position

int getch(void)
{
    if (bufrp < bufwp)
        return buf[bufrp++];
    else {
        if(bufwp != 0)
            bufwp = bufrp = 0;

        return getchar();
    }
}

void ungetch(int c)
{
    if (bufwp < BUFSIZE)
        buf[bufwp++]=c;
    else
    {
        if (reorder_buf() != 0)     //successful reorder
        {
            buf[bufwp++]=c;
        } else                      //full buffer
        {
            printf("Failed to ungetch(%c).\n", c);
        }
    }
}

/**
 * Tries to move buffer content to the start of the buffer.
 *
 * @return 1 on successful reorder, 0 otherwise
 */
static int reorder_buf(void)
{
    if (bufrp > 0)
    {
        int i;
        for(i = 0; bufrp < bufwp; bufrp++, i++)
             buf[i] = buf[bufrp];

        bufrp = 0;
        bufwp = i;
        return 1;
     } else
     {
         return 0;
     }
}

I also had the idea to replace the error message in ungetch() with returning an int, which includes the information if the unget process was successful and provides it to the caller.

reorder_buf() is horribly inefficient, and it's unnecessary if you use the buffer as a circular-list.  What you want is called a ring buffer.

/* Store up to 10 characters */
#define BUFSIZE 11

char buf[BUFSIZE];
int qhead = 0, qtail = 0;

int getch(void) {
    if (qhead != qtail) {
        int c = buf[qhead];
        qhead = (qhead + 1) % BUFSIZE;
        return c;
    } else {
        return getchar();
    }
}

void ungetch(int c) {
    if ((qtail + 1) % BUFSIZE == qhead) {
        fprintf(stderr, "Buffer full, dropped %c.\n", c);
    } else {
        buf[qtail] = c;
        qtail = (qtail + 1) % BUFSIZE;
    }
}

Errors should go to stderr rather than stdout.


Is this contact form safe? Here is the code that I am using on a website's contact form:

HTML file:

    <form name="ajax-form" id="ajax-form" action="php-file.php" method="post">
        Name: *
            please enter name

        <input name="name" id="name" type="text" />
        E-Mail: *
            please enter e-mail
            e-mail is not a valid format

        <input name="email" id="email" type="text" />
        Message:
        <textarea name="message" id="message"></textarea>
        <button id="send">Submit</button>

There was a problem validating the form please check!

The connection to the server timed out!

    </form>

Successfully sent!!

PHP file (php-file.php):

<?php

$send_to = "contact@example.com";
$send_subject = "Ajax form ";

$f_name = cleanupentries($_POST["name"]);
$f_email = cleanupentries($_POST["email"]);
$f_message = cleanupentries($_POST["message"]);
$from_ip = $_SERVER['REMOTE_ADDR'];
$from_browser = $_SERVER['HTTP_USER_AGENT'];

function cleanupentries($entry) {
    $entry = trim($entry);
    $entry = stripslashes($entry);
    $entry = htmlspecialchars($entry);

    return $entry;
}

$message = "This email was submitted on " . date('m-d-Y') .
"\n\nName: " . $f_name .
"\n\nE-Mail: " . $f_email .
"\n\nMessage: \n" . $f_message .
"\n\n\nTechnical Details:\n" . $from_ip . "\n" . $from_browser;

$send_subject .= " - {$f_name}";

$headers = "From: " . $f_email . "\r\n" .
    "Reply-To: " . $f_email . "\r\n" .
    "X-Mailer: PHP/" . phpversion();

if (!$f_email) {
    echo "no email";
    exit;
}else if (!$f_name){
    echo "no name";
    exit;
}else{
    if (filter_var($f_email, FILTER_VALIDATE_EMAIL)) {
        mail($send_to, $send_subject, $message, $headers);
        echo "true";
    }else{
        echo "invalid email";
        exit;
    }
}

?>

Is this code safe? How secure is the email address from users? Am I using best practices in this implementation?

Your code is safe as far as I can tell. You may consider adding some additional levels of spam checking though to stop invalid requests sooner.

Use a token generated by your server when the form renders, pass that to php-file.php to check when processing the submission, if it isn't in your token list, it didn't come from your server. These tokens should only be used once before they are discarded. It will help you stop Cross Site Request Forgery attempts. It would mean having a storage medium to keep track of the tokens though, so it adds a little bit of overhead to the process.
Honeypot field(s). These are just input fields that you hide with CSS so that a normal user would not fill them in. If they have a value when you process your script you should stop execution.


Division without / operator I created a method that does division without the / operator. I believe this code is a bit slow and can be improved, but I am not sure how to do so. I'm not so good with shift operators (>> and >>>), but I believe that this will help a bit. How can I change my code to increase the speed of the division. I am open the changing my logic as well.

public class DivisionReplace {
    public static void divide(int N, int D) {
        int result = 0;

        if (D == 0) {
            System.out.println("Cannot divide by 0");
        }
        else if (N == 0) {
            System.out.println(0);
        }
        else if (N == D) {
            System.out.println(1);
        }
        else if (N > 0 && D > 0 && N < D) {
            System.out.println(0);
        }
        else {
            // both negative
            if (N < 0 && D < 0) {
                while (N <= D) {
                    N += -1 * D;
                    result++;
                }
                System.out.println(result);
            }
            // either N or D negative
            else if (N < 0 || D < 0) {
                if (N < 0) {
                    N = -1 * N;
                }
                else {
                    D = -1 * D;
                }
                while (N >= D) {
                    N -= D;
                    result--;
                }
                System.out.println(result);
            }
            // both positive
            else {
                while (N >= D) {
                    N -= D;
                    result++;
                }
                System.out.println(result);
            }
        }
    }

    public static void main(String[] args) {
        divide(-4,-10);
    }
}

A couple of comments first

It would be better to let your divide method should return an int, not do the output to System.out itself. Do the output in main like this:

public static void main(String[] args) {
    System.out.println(divide(-4,-10));
}

The variables N and D are short and don't follow the Java naming conventions. Parameter names should start with a lowercase letter and use camelCase. I would recommend calling them numerator and denominator.

If denominator == 0 is a quite exceptional case, I would recommend throwing an ArithmeticException stating that it was caused by division by zero.

You treat more special cases than you need to. I don't think you need to handle either numerator == denominator or numerator == 0 as a special case. It should be possible to handle that using the normal logic for division.

If you were doing divisions by a power of 2 (2, 4, 8, 16, etc.) you could use right shift numerator >> 1, numerator >> 2 etc. However, your code should support more than just those cases which makes things more difficult.

In the end, you are trying to re-implement division by using repetitive subtraction. It will be slow, no matter what you do. If you want to be possibly somewhat faster for bigger numbers, or want to try another approach (I can't promise you it will be faster, but I believe that for big enough numbers it will be significantly faster), you could try to implement division by using one of the good old "pen and paper" ways. Think about the division 303364 / 596. Try to solve that by hand! and think about what it is that you are doing. (Hint: Also think about how you do multiplications by hand, how would you solve 583 * 42 ?)

However, in reality though, the fastest solution is to use the / operator in Java, but that wouldn't be a challenge now, would it? So I guess that's out of the question :)


Bash functions to modify PATH I am working on improving my bash environment. I have added the following function to my ~/.bashrc in order to facilitate modifying my PATH as well as removing duplicate entries from my PATH which may occur from sourcing ~/.bashrc again.

# $1 the path to be added as an absolute path
# $2 a boolean for whether the path should be prepended. default: false
# $3 the path variable to add to
function addToPath {
    # ${!3} dereferences $3 to use the value the variable refers to. For example $3=PATH would give $PATH
    if [ -z ${3+x} ]; then TMP_PATH="$PATH"; TMP_NAME="PATH"; else TMP_PATH="${!3}"; TMP_NAME="$3"; fi
    if [ ! -d $1 ]; then echo "WARNING: Added $1 to $TMP_NAME but $1 doens't seem to exist"; fi

    case ":$TMP_PATH:" in # Add trailing :'s to cover first and last entries
        *":$1:"*)
            ;; # Exists Already
        *)
            case true in
                $2)
                    TMP_PATH="$1:$TMP_PATH"
                    ;;
                *)
                    TMP_PATH="$TMP_PATH:$1"
                    ;;
            esac
            ;;
    esac

    # Remove potential wrapping ":" chars
    TMP_PATH=${TMP_PATH#":"}
    TMP_PATH=${TMP_PATH%":"}
    if [ -z ${3+x} ]; then export PATH="$TMP_PATH"; else export $3="$TMP_PATH"; fi
}

And then, to build my path and remove duplicates I use the following code.

# Set up basic PATH variable
addToPath /usr/local/bin
addToPath /usr/bin
addToPath /usr/sbin
addToPath /bin
addToPath /sbin

# Remove duplicates from path
NEW_PATH=""
IFS=':' read -r -a path_array <<< "$PATH"
for element in "${path_array[@]}"
do
    addToPath $element false NEW_PATH
done
export PATH=$NEW_PATH

Quoting

You should double-quote variables that may contain spaces when used as command arguments. For example here:

addToPath $element false NEW_PATH

You will get strange results if $element contains spaces. Double-quote it, and also in the conditional inside the function:

if [ ! -d "$1" ]; then

One statement per line

It's easiest to read code from top to bottom,
without having to carefully read from left to write too. For this reason it would be better to split the conditionals you crammed on a single line.

Simple solutions are better

The optional third parameter of the function is quite clever, appending to a specified variable instead of the default, at the expense of some added complexity. Instead of all that, you could simply reset PATH after setting path_array and before calling the function. That way you could get rid of the third parameter of the function and its added complexity.

Note also that your function does not add duplicates. So instead of removing duplicates at the end, it will be better to remove duplicates at the beginning, as that will process fewer path elements.

case with two cases

When a switch-construct is used with only two cases,
it's usually easier to read converted to an if-else.


Trigonometry Circle representation using Python and Pygame I wrote this code using Python 3.5 and Pygame to help me learn more about sine waves. Its goal is to show the variations in the sine and cosine values in the Trigonometry Circle as the distance covered by a point in the circumference increases.

I'd appreciate suggestions and advices about the code, specially about the math involved and my usage of Pygame.

Thanks.

import pygame
import math

SCR_WIDTH = 220
SCR_HEIGHT = 480

RAD_SIZE = 100
CIRCLE_X = int(105)
CIRCLE_Y = int(285)

STD_FONT_SZ = 25

def drawChart(frequency, time, turns, sin, cos, surface):
    """Draws the frequency, time, distance, and sine and cosine values on the given surface"""

    freq_txt = font.render("Frequency: {:.3}Hz".format(frequency), False, (0,0,0))
    time_txt = font.render("Time: {:.3}s".format(time), False, (0,0,0))
    turn_txt = font.render("Turns: {:.3}".format(turns), False, (0,0,0))
    sin_txt = font.render("Sine: {:.3}".format(sin), False, (0,0,0))
    cos_txt = font.render("Cosine: {:.3}".format(cos), False, (0,0,0))

    surface.blit(time_txt,(0,0))
    surface.blit(freq_txt,(0,STD_FONT_SZ))
    surface.blit(sin_txt,(0,STD_FONT_SZ*2))
    surface.blit(cos_txt,(0,STD_FONT_SZ*3))
    surface.blit(turn_txt,(0,STD_FONT_SZ*4))

def drawCircle(x,y, surface):
    """Draws the Trigonometry circle on the given surface in position x, y"""

    pygame.draw.line(surface,(0,0,0),(x-RAD_SIZE,y),(x+RAD_SIZE,y))  #x-axis
    pygame.draw.line(surface,(0,0,0),(x,y-RAD_SIZE),(x,y+RAD_SIZE))  #y-axis
    pygame.draw.circle(surface,(0,0,0), (x,y), RAD_SIZE, 1) #main circle
    surface.blit(x_txt,(x+RAD_SIZE, y)) #x character
    surface.blit(y_txt,(x,y-RAD_SIZE-STD_FONT_SZ-4)) #y character

pygame.init()
pygame.display.set_caption("SineRep v. 1.0")

screen = pygame.display.set_mode((SCR_WIDTH, SCR_HEIGHT), 0, 32)
font = pygame.font.SysFont("arial",STD_FONT_SZ)

frequency = 0.1

x_txt = font.render("x", False, (0,0,0))
y_txt = font.render("y", False, (0,0,0))

while True:
    screen.fill((255,255,255))

    time = pygame.time.get_ticks()/1000
    distance = 2*math.pi*time*frequency
    turns = time*frequency
    cos = math.cos(distance)
    sin = math.sin(distance)

    #size of cosine and sine in pixels
    cos_pxl = int(cos*RAD_SIZE)
    sin_pxl = int(-sin*RAD_SIZE)

    ##### Draw stuff in the screen
    drawChart(frequency, time, turns, sin, cos, screen)
    drawCircle(CIRCLE_X, CIRCLE_Y, screen)

    pygame.draw.circle(screen,(255,0,0), (CIRCLE_X+cos_pxl,CIRCLE_Y+sin_pxl), 5, 0) #dot

    #Auxiliary shapes
    pygame.draw.circle(screen,(255,0,0), (CIRCLE_X+cos_pxl,CIRCLE_Y), 3, 1) #cosine dot
    pygame.draw.circle(screen,(255,0,0), (CIRCLE_X,CIRCLE_Y+sin_pxl), 3, 1) #sine dot

    pygame.draw.line(screen,(255,0,0),(CIRCLE_X,CIRCLE_Y),(CIRCLE_X+cos_pxl,CIRCLE_Y), 2)  #projection in x (cos)
    pygame.draw.line(screen,(255,0,0),(CIRCLE_X,CIRCLE_Y),(CIRCLE_X,CIRCLE_Y+sin_pxl),2) #projection in y (sine)

    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        break

    pygame.display.update()

pygame.quit()

A few remarks

CIRCLE_X = int(105)
CIRCLE_Y = int(285)

Python is a duck typed language, you don't need a type in order to invoke a method or variable. You could omit the int() call here

if __name__ == '__main__':

guards, use them!

pygame.init()
pygame.display.set_caption("SineRep v. 1.0")
screen = pygame.display.set_mode((SCR_WIDTH, SCR_HEIGHT), 0, 32)
font = pygame.font.SysFont("arial",STD_FONT_SZ)
frequency = 0.1
x_txt = font.render("x", False, (0,0,0))
y_txt = font.render("y", False, (0,0,0))

These should not be global, maybe a function? def setup_game()

You have a few PEP8 violations. A good style creates more readable code :)


R: Optimize algorithm speed that estimates hourly temperature and relative humidity I built an algorithm to estimate real-time temperature and humidity values based on daily values of the same variables. The algorithm works, however the speed with which it processes the information is too slow and this causes me problems when the data is of many years or decades.

I need to increase the processing speed. I attach the algorithm:

names(hrTable) <- c("date","tmin","tminnext","tmax","tdew","tdewnext", "dayIndex")

hrTable is a dataframe that contains 8 columns, the first is "date" that contains the date in format "%Y-%m-%d". The rest are numerical variables.

Ejemplo : 1995-01-20, 12, 13, 25, 15, 16, 360

CalculateHumidHoursAndHumidTemp1 <-
function(hrTable,yearLength,lat,incli,rhThreshold,verbose) {

nrowTab = nrow(hrTable);
lines2 = split(hrTable,rep(1:nrowTab,each=1));
hrResult = c("hrvalues");
HumHr = 0;
AccumHumHr = 0;
HumTm = 0;
AccumHumTm = 0;
day0 = 1;
dayn = nrowTab;

for(k in day0:dayn) {
  line2 = lines2[[k]];
  HumHr = 0;

  tempArray2 = line2;
  date2 = tempArray2[1];
  tMin = tempArray2[2];
  tMinNext = tempArray2[3]; #ENTERO PARA PODER COMPARAR EN LA TABLA
  tMax = tempArray2[4];
  tDew = tempArray2[5];
  tDewNext = tempArray2[6];
  dayIndex = tempArray2[7];

  alpha = tMax - tMin;
  t0 = tMax - 0.39*(tMax - tMinNext);
  r = tMax - t0;
  sindec = -1.0*incli*cos(6.283185307179586*((dayIndex + 10)/yearLength));
  cosdec = sqrt(abs(1.0 - (sindec * sindec)));
  b = cos(lat*(3.141592653589793/180.0))*cosdec;
  a = sin(lat*(3.141592653589793/180.0))*sindec;
  dayLength = 12.0*(1.0 + (0.6366197723675814*sin(a/b)));
  ho = 12.0 + (dayLength/2.0);
  hn = 12.0 - (dayLength/2.0);
  hp = hn + 24.0;
  beta = (tMinNext - t0)/(sqrt(abs(hp - ho)));
  hx = ho - 4.0;
  h = as.numeric(round(hn));

  if (verbose) {
    print(paste(hn,ho));
  }

  for(n in 1:24) {
    tAux1 = 0;
    tAux2 = 0;
    tAux3 = 0;
    hour = h + n;

if (hour >= hn && hour < hx) {
  tAux1 = tMin + alpha*sin(((hour - hn)/(hx - hn))*(3.141592653589793/2.0));

}

if (hour >= hx && hour <= ho) {
  tAux2 = t0 + r*sin(1.5707963267948966 + ((hour - hx)/4.0)*(3.141592653589793/2.0));

}

if (hour > ho && hour <= hp) {
  tAux3 = t0 + beta*sqrt(hour - ho);

}

tSum = tAux1 + tAux2 + tAux3;

if (verbose) {
  print(paste("Indice=",n,"\tHour", hour,"\ttSum=",tSum ,"\tTaux1=",tAux1,"\ttAux2=",tAux2,"\ntAux3=",tAux3," dayLength=",dayLength," a=",a," b=",b));
}

es = 611.0*exp(17.27*(tSum/(237.3+tSum)));

if (hour <= 24) {
  e = 611.0*exp(17.27*(tDew/(237.3+tDew)));
  hr = (e/es)*100.0;

  if (hr > rhThreshold) {
    HumHr = HumHr + 1;
    HumTm = tSum + HumTm;
  }

  if (verbose) {
    print(paste("Indice=",n,"\tHour",hour,"\te=",e,"\tes=",es));
  }
}

if (hour > 24) {
  e = 611.0*exp(17.27*(tDewNext/(237.3+tDewNext)));
  hr = (e/es)*100;

  if (hr > rhThreshold) {
    AccumHumHr = AccumHumHr + 1;
    AccumHumTm = tSum + AccumHumTm;
  }

  if (verbose) {
    print(paste("Indice=",n,"\tHour",hour,"\te=",e,"\tes=",es));

  }

}
hrResult = paste(hrResult,hr,tSum)
}

if (verbose) {
    print(paste("Horas Humedas= ",HumHr,"Temp Humedad= ",HumTm));
  }

}
return(hrResult)
}

HhrandHt <- CalculateHumidHoursAndHumidTemp1(hrTable,365,-12,12,90,T)

The first thing to improve about your code/procedure is readability.
Not "just" for others trying to understand your code, but for your latter self should you want to maintain it.
I don't know the first thing about R. The first style guide a superficial web search turned up is from Hadley Wickham's Advanced R, characterised as short and sweet.

Things I think to harm readability:

(lack of) structuring source code by formatting
(lack of) documentation in the source code: What is "everything" about?
What is the problem to solve, the sequence of well-defined steps perceived to solve it?
abbreviated names without an illuminating comment: is "hr" for hour or  humidity, relative or something entirely else?
hx seems to be four hours before sunset - what does the x signify, and why 4 hours?
in-line arithmetic with magical constants: while I can guess that lat*(3.141592653589793/180.0) is radian(latitude in degrees), I'd rather not.
What is the significance of 10 in dayIndex + 10,
0.39 in tMax - 0.39*(tMax - tMinNext), why isn't the latter just 0.39*tMinNext + 0.61*tMax?
computing things that don't get used
The only things I see used (pasted to hrResult - see below) are hr and tSum;
some code struggles with HumHr/HumTm and "their Accum counterparts".

Once the code is readable, one can start pondering performance impact:
Is there anything straining the memory hierarchy?
Do costly actions get repeated instead of results reused?
Then, there is general advice like Use Vectorisation,
and (resource demand) pitfalls - using paste() to accumulate the result may be one.


Strategy design pattern for writing to a file or to the console I have this interface for all strategies:

type PrintStrategy interface {
    Print() error
}

of two types:

type ConsoleStrategy struct{}

type FileStrategy struct {
    DestinationFilePath string
}

with two concrete implementations of strategy:

func (c *ConsoleStrategy) Print() error {
    fmt.Println("ConsoleStrategy")
    lister, _ := template.New("foo").Parse(tplTemplate())
    lister.Execute(os.Stdout, tplParams())
    return nil
}

func (c *FileStrategy) Print() error {
    fmt.Println("FileStrategy")
    var t bytes.Buffer
    foo, _ := template.New("bar").Parse(tplTemplate())
    foo.Execute(&t, tplParams())

    f, err := os.Create(c.DestinationFilePath)
    if err != nil {
        panic(err)
    }
    defer f.Close()
    f.Write(t.Bytes())
    return nil
}

and finally a main function that gets the strategy from the console and prints the content built inside tplTemplate() to the console or a file.

func main() {
    strategy := flag.String("strategy", "console", "selected strategy")
    flag.Parse()

    var printStrategy PrintStrategy

    switch *strategy {
    case "console":
        printStrategy = &ConsoleStrategy{}
    case "file":
        printStrategy = &FileStrategy{"bigciao"}
    default:
        printStrategy = &ConsoleStrategy{}
    }

    printStrategy.Print()
}

Is this a good example of using the pattern?

According to the GoF, Strategy pattern:

  Define a family of algorithms, encapsulate each one, and make them
  interchangeable. Strategy lets the algorithm vary independently from
  the clients that use it.

See that the objective is disacouplished client (context object) of your possibles behaviours. So there is two basics elements in this pattern: context object and strategies.

The contexts objects have domain problems that must be separated from each other, so different algorithms. See in image(source in: https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm):

All this allow that you can work to an interface without worrying implementation strategy.

In your code there is no context object, so this is wrong. If there is no context object, the problem does not exist either.

Refactoring your code, we will have the following strategies:

// ----------------------------------------------
// in strategies.go files
// ----------------------------------------------

type PrintStrategy interface {
    Print() error
}

type ConsoleStrategy struct{}
func (c ConsoleStrategy) Print() error {
  fmt.Println("Hello, playground by console strategy")
  return nil
}

type FileStrategy struct {DestinationFilePath string}
func (c FileStrategy) Print() error {
  //print in file c.DestinationFilePath
  fmt.Println("Hello, playground by file strategy")
  return nil
}

type DefaultStrategy struct{}
func (c DefaultStrategy) Print() error {
  //print in printer device
  fmt.Println("Hello, playground by default strategy")
  return nil
}

And the following context object:

// ----------------------------------------------
// in context.go files
// ----------------------------------------------
type MyContextObject struct {
  ps PrintStrategy
}

func (m MyContextObject) Print(){
  //check if PrintingStrategy is not nil
  err := m.ps.Print()
  if err != nil {
    panic("Fail on PrintMyDatas")
  }
}

func NewMyContextObject(p PrintStrategy) MyContextObject{
  if (p != nil){
    return MyContextObject{p}
  } else {
    return MyContextObject{DefaultStrategy{}}
  }
}

See that on instancing of MyContextObject an behaviour is passed. In your case the behaviour for this context is provided by argument passing on executing. In another case you might like change the behaviour in according with the content size. These are different context using same strategy.

func main() {
    //read args
    strategy := flag.String("strategy", "console", "selected strategy")
    flag.Parse()

    //context object that needs to print your datas in according with
    //an user arg.
    var m MyContextObject

    //this statments can be replaced by factory method
    switch *strategy {
    case "console":
        m = NewMyContextObject(ConsoleStrategy{})
    case "file":
        m = NewMyContextObject(FileStrategy{"bigciao"})
    default:
        m = NewMyContextObject(nil)
    }
    //
    m.Print()
}

Now you can does more strategies or share this behaviour in other contexts.
This is a good practical of reuse!!

This code is in https://play.golang.org/p/P-kGGOwDDRt.

I hope I helped you!


Divide a clock signal by 8 I'm a fresh verilog / HDL programmer and I'm writing this post to get some feedback from more experienced verilog / HDL programmers.

My very first task was to divide a clock by eight.

I know there are some better methods to do this, but as I'm new to HDL this is my first, naive, attempt:

module prescaleMainCLK(CLK, prescaledCLK);
    input CLK;
    output reg prescaledCLK;

    // ''Define'' a 4bit counter, max value: 15
    reg [3:0] counter;

    initial begin
        // Initialise both variables
        prescaledCLK <= 0;
        counter      <= 0;
    end

    always @ (posedge CLK) begin

        // Did the counter reach its end?
        if (counter > 7) begin

            // Reset the counter
            counter <= 0;

            // Toggle the prescaled clock output
            prescaledCLK <= ~prescaledCLK;

        end else begin

            // Increment counter
            counter <= counter + 1;

        end

    end

endmodule

The Simulation output (EDAPlayground) is as I expect it to be:

Now I want to know if that code is suitable for real applications or if there are some things I need to reconsider.

I would recommend a using modern Verilog header:

module prescaleMainCLK(
    input      CLK,
    output reg prescaledCLK
);

adding bit size to your constants is best practice. 'b0 for all zeros with auto sizing. 0 is an integer likely only 32 bits long which can get you in trouble if you start applying to regs bigger than than 32 bits.

The use of initial is only valid in FPGA synthesis, for ASIC you should use a active low async reset.

reg [3:0] counter;

initial begin
    // Initialise both variables
    counter      <= 'b0;
end

always @ (posedge CLK) begin
  counter <= counter + 1'd1;
end

Versus for ASIC:

always @ (posedge CLK or negedge rst_n) begin
  if(~rst_n) begin
    counter <= 'd0;
  end
  else begin
    counter <= counter + 1'd1;
  end
end

You can reuse the counter bits (as mentioned in another answer) for your slower clocks

wire clk_div2  = counter[0];
wire clk_div4  = counter[1];
wire clk_div8  = counter[2];
wire clk_div16 = counter[3];

At faster frequencies this often becomes tricky to balance clocks correctly. A standard industry practice would be to use enables (derived from this counter) for a clock gate. The clock gate allows a pulse from the faster clock through, you loose the 50 50 duty cycle of the clock but balancing the clock tress becomes much easier.


Array-based unordered list implementation in Java This class, UnorderedList, implements an Unordered list in Java. In this class, duplicates are allowed. remove(argument) will delete the first occurrence of the argument. I was wondering to add other functions named add(int index, int data) and set(int index, int data) or not. Since the class is unordered, I thought I would not need it. The size of the class is limited although that does not concern me (UnorderedLinkedList coming up next).

I tried to make sure all the functionality and behaviours are correct. If this class is lacking any method(s) and/or correct usage of exception and anything else please comment below. Any kind of suggestions and advice is appreciated.

//Node class

package lists.arrayLists.unorderedList;

public class Node
{
    private int data;

    public Node(int data)
    {
        this.data = data;
    }

    public int getData()
    {
        return data;
    }
}

//UnorderedList class

package lists.arrayLists.unorderedList;

import java.lang.IndexOutOfBoundsException;
import java.util.NoSuchElementException;

public class UnorderedList
{
    public static final int MAX_SIZE = 100;
    private int size;
    private Node[] nodeElements;
    private int currentIndex;                           // to navigate/iterate over list

    public UnorderedList()
    {
        nodeElements = new Node[MAX_SIZE];
    }

    public boolean isFull()
    {
        return (size() == MAX_SIZE);
    }

    public boolean isEmpty()
    {
        return (size() == 0);
    }

    public int size()
    {
        return size;
    }

    public boolean add(int data)
    {
        try
        {
            Node node = new Node(data);
            nodeElements[size++] = node;
            return true;
        }
        catch (IndexOutOfBoundsException ex)
        {
            System.out.println(ex.getMessage());
            throw new IndexOutOfBoundsException();
        }
    }

    public void remove(int data)
    {
        int index = locate(data);
        try
        {
            nodeElements[index] = nodeElements[size() - 1];
            size--;
        }
        catch (IndexOutOfBoundsException ex)
        {
            throw new NoSuchElementException();
        }
    }

    public boolean find(int data)
    {
        boolean found = false;
        try
        {
            if(locate(data) >= 0)
            {
                found = true;
            }
            return found;
        }
        catch (NoSuchElementException ex)
        {
            throw new NoSuchElementException();
        }
    }

    // locate function looks for an element in the array, if there is one then returns its index
    private int locate(int data)
    {
        int i = 0;
        int index = -1;
        boolean found = false;
        while (i < size() && !found)
        {
            if (data == nodeElements[i].getData())
            {
                found = true;
                index = i;
            }
            i++;
        }
        return index;
     }

    //Navigator methods

    public void reset()
    {
        currentIndex = 0;
    }

    public boolean hasNext()
    {
        return (currentIndex == size());
    }

    public void next()
    {
        if (!hasNext()) currentIndex++;
    }

    public int currentElement()
    {
        return nodeElements[currentIndex].getData();
    }
}

I would recommend using Log4j instead of System.out.println() with some meaningful message to the user. Also, you can implement locate() method as mentioned below to avoid initializing the flag

private int locate(int data)
{
    int i = 0;
    int index = -1;
    while (i < size())
    {
        if (data == nodeElements[i].getData())
        {
           index = i;
           break;
        }
        i++;
    }
    return index;
 }

Change: Use break; to come out of the loop rather than using flag to check it.


Sort stack in ascending order I am using two more helper stacks to sort. Kindly suggest improvements in terms of space and time.

import java.util.ArrayDeque;
import java.util.Deque;

public class SortStackAscendingOrder {

    Deque<Integer> stackhelper1 = new ArrayDeque<>();
    Deque<Integer> stackHelper2 = new ArrayDeque<>();

    public Deque<Integer> sortStack(Deque<Integer> mainStack) {
        if (mainStack.isEmpty()) {
            return null;
        }

        while (!mainStack.isEmpty()) {
            int mainItem = mainStack.pop();
            int helperItem1 = -1;
            if (!stackhelper1.isEmpty()) {
                helperItem1 = stackhelper1.peek();
            }
            if (mainItem > helperItem1) {
                // push all helperItem1 to helperItem2, till it is in ascending
                // order
                while (!stackhelper1.isEmpty() && mainItem > helperItem1) {
                    stackHelper2.push(stackhelper1.pop());
                    helperItem1 = stackhelper1.peek();
                }
                // push mainItem.
                stackhelper1.push(mainItem);
                // bring back all the helperItem2
                while (!stackHelper2.isEmpty()) {
                    stackhelper1.push(stackHelper2.pop());
                }
            } else {
                // directly push in stackhelper1
                stackhelper1.push(mainItem);
            }
        }

        return stackhelper1;

    }

}

Possible bug:

The following demo will throw a NullPointerException:

public static void main(String[] args) {
    Deque<Integer> stack = new ArrayDeque<>();

    stack.addLast(2);
    stack.addLast(-1);
    stack.addLast(-3);
    stack.addLast(1);

    System.out.println("Original stack: " + stack);
    SortStackAscendingOrder sorter = new SortStackAscendingOrder();

    Deque<Integer> sortedStack = sorter.sortStack(stack);

    System.out.println("Sorted original stack: " + sortedStack);

    stack.clear();
    stack.addLast(11);
    stack.addLast(8);
    stack.addLast(9);
    stack.addLast(10);

    System.out.println("Another stack: " +
            sorter.sortStack(stack));

    System.out.println("Sorted original stack again: " + sortedStack);
}

Most likely the problem above is due to the fact that you return stackhelper1, which is an essential internal facility in your algorithm.

API design:

First of all, I would consider implementing the stack sort as a static method that does not "leak" any internals. The idea here is that you sort the input stack: just like sorting methods in java.util.Arrays, all are void and modify the input arrays instead of returning a sorted copy.

All in all, I had this in mind:

public static void sortStack(Deque<Integer> mainStack) {
    Deque<Integer> stackHelper1 = new ArrayDeque<>();
    Deque<Integer> stackHelper2 = new ArrayDeque<>();

    while (!mainStack.isEmpty()) {
        int mainItem = mainStack.pop();
        int helperItem1 = -1;

        if (!stackHelper1.isEmpty()) {
            helperItem1 = stackHelper1.peek();
        }

        if (mainItem > helperItem1) {
            while (!stackHelper1.isEmpty() && mainItem > helperItem1) {
                stackHelper2.push(stackHelper1.pop());
                helperItem1 = stackHelper1.peek();
            }

            stackHelper1.push(mainItem);

            while (!stackHelper2.isEmpty()) {
                stackHelper1.push(stackHelper2.pop());
            }
        } else {
            stackHelper1.push(mainItem);
        }
    }

    mainStack.clear();
    mainStack.addAll(stackHelper1);
}


Limit and merge saving operations Use case:
I want to automatically save data in the storage when a property of an object that implements INotifyPropertyChanged changes. Therefore I subscribe to the PropertyChanged event and call a method that saves the object.

Problem:
It can be that a lot of properties change over a short period of time and that is a problem because the saving method is an I/O operation.

My solution:
Accumulate the save orders over a period of time in a singleton class and perform the saving operations for the last order.

Code:

internal sealed class AccumulatedSaver
{
    private readonly Queue<Tuple<string, object>> _saveOrders = new Queue<Tuple<string, object>>();
    private bool _busy = false;

    internal static AccumulatedSaver Instance { get; } = new AccumulatedSaver();

    internal async Task SaveToAppData<T>(T item, string fileName)
    {
        _saveOrders.Enqueue(new Tuple<string, object>(fileName,item));
        if (_busy)
        {
            return;
        }
        _busy = true;
        await Task.Run(async() => await Task.Delay(500));

        while (_saveOrders.Count > 0)
        {
            Tuple<string, object> saveOrder = _saveOrders.Dequeue();
            if (_saveOrders.All(o => o.Item1 != saveOrder.Item1))
            {
                await SaveHelper.TrySaveToAppData(saveOrder.Item2, saveOrder.Item1);
            }
        }
        _busy = false;
    }
}

Question:
Is that a good idea to do that like that?
What can be made better?

Alternative: Rx
Creating your own producer/consumer solution is not always easy and is one option but you could also use the tools that are already there. One such tool are the Reactive Extensions (NuGet-Package: System.Reactive). It can be very helpful in your scenario.
I requires two parties

an observable and
an observer

Your not yet real observables are the POCO objects that implement the INotifyPropertyChanged interface. You can turn them into observables with helper factories that can derive an IObservable from the PropertyChanged event pattern.
class Person : INotifyPropertyChanged, IObservable<EventPattern<PropertyChangedEventArgs>>
{
    private readonly IObservable<EventPattern<PropertyChangedEventArgs>> _observable;

    private string _name;

    public Person()
    {
        _observable =
            Observable
                .FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
                    handler => PropertyChanged += handler,
                    handler => PropertyChanged -= handler
                );
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
        }
    }

    public IDisposable Subscribe(IObserver<EventPattern<PropertyChangedEventArgs>> observer)
    {
        return _observable.Subscribe(observer);
    }
}

Now you only need a task to process a collection of them. You can create it in many different ways so here is just one of them. I created an observable from an array of persons that I Merge into a single observable that I want to watch. I'd like this to be processed either every ten items or every two seconds (there are also other options). Then each batch is processed with the ForEachAsync loop.
var persons = new[]
{
    new Person { Name = "John"},
    new Person { Name = "Tom" }
};

var savePersonBatchTask =
    persons
        .Merge()
        .Buffer(timeSpan: TimeSpan.FromSeconds(2), count: 10)
        .Where(batch => buffer.Count > 0)
        .ForEachAsync(batch =>
        {
            Console.WriteLine($"New batch arrived: {batch.Count}");
        });

You can test this simulation by creating another loop that modifies the person's name 27 times.
for (int i = 0; i < 27; i++)
{
    foreach (var person in persons)
    {
        person.Name = i.ToString();
    }
}

await savePersonBatchTask;

The output will look like this
New batch arrived: 10
New batch arrived: 10
New batch arrived: 10
New batch arrived: 10
New batch arrived: 10
New batch arrived: 4

There is a lot more it can do and all that is explained very nicely on Introduction to Rx.

Review
And I also have a couple of comments about your code...

private readonly Queue<Tuple<string, object>> _saveOrders

You can simplify this and make it easier to use by using strong tuples with named properties. All you need is to throw away the Tuple type and let the compiler derive the tuple for you.
 private readonly Queue<(string FileName, object Item)> _saveOrders = ..;

later in code you also don't need it anymore
saveOrders.Enqueue((fileName,item));

Your while loop will become simpler too because tuples can be deconstructed into variables:
while (_saveOrders.Count > 0)
{
    var (fileName, item) = _saveOrders.Dequeue();
    if (_saveOrders.All(o => o.FileName != fileName))
    {
        await SaveHelper.TrySaveToAppData(fileName, item);
    }
}


Determine if someone has won a game of Tic-Tac-Toe on a board of any size I was asked this question in interview yesterday:

  Write the code for winning condition in an NxN matrix for tick tack toe.For example A function named "input_event(player_info, x_position,
  y_position)" will be triggered when the player inputs O or X, how will
  you check if the player has won inside this function ? Given: NxN
  matrix N>=3 and <=100

I managed to answer this by checking by loops horizontal, vertical and diagonal elements depending upon the current position. But the interviewer was not pleased and wanted me to achieve this without using so many repeated loops.

I searched on the internet on how to achieve this optimally and found this. I have posted the my implementation below:

#include <iostream>
#include <vector>
using namespace std;

class TicTacToe {
  vector<vector<char> > board;
  vector<int> winArr;
  int N;
public:
  TicTacToe(int sz) : N(sz) {
    board.resize(N);
    winArr.resize(2*N+2, 0);
    for(int i = 0; i < N; i++)
      board[i].resize(N, '.');
  }
  void playMove(char player, int nRow, int nCol) {
    cout << player << " Marks board[" << nRow << "]["<<nCol << "].\n";
    board[nRow][nCol] = player;
    updateWinArr(player, nRow, nCol);
    checkWinCondition();
  }
  void updateWinArr(char player, int nRow, int nCol) {
    int nVal = (player == 'X' ? 1 : -1);
    winArr[nRow] += nVal;
    winArr[N + nCol] += nVal;
    // check diagonals :
    if(nRow == nCol) // left diagonal
      winArr[2*N] += nVal;
    else if(nRow+nCol == N-1) // right diagonal
      winArr[2*N+1] += nVal;
  }
  void checkWinCondition() {
    bool bWin = false;
    char winner = '\0';
    for(int i = 0; i < winArr.size(); i++) {
      if(winArr[i] == -N) {
        bWin = true;
        winner = 'O';
        break;
      }
      else if(winArr[i] == N) {
        bWin = true;
        winner = 'X';
        break;
      }
    }
    if(bWin == true)
      cout << "Congrats!, " << winner << " has won the game\n";
  }
};

int main() {
  TicTacToe tt(3);
  tt.playMove('X', 0, 0);
  tt.playMove('O', 0, 2);
  tt.playMove('X', 1, 1);
  tt.playMove('O', 0, 1);
  tt.playMove('X', 2, 2);
  return 0;
}

I welcome any suggestions since I'm a beginner in C++.

You should not use namespace std. It is bad practice, that will hurt you in the long run.
I do not really like your constructor:

TicTacToe(int sz) : N(sz) {
   board.resize(N);
   winArr.resize(2*N+2, 0);
   for(int i = 0; i < N; i++)
      board[i].resize(N, '.');
}

The argument should be const. Then you should use the initializer list for all variables:

TicTacToe(const int sz)
    : board(sz, std::vector<char>(sz, '.')), winArr(2*sz+2), N(sz) {}

In your updateWinArr() function you only check the diagonal in one direction:

// check diagonals :
if(nRow == nCol) // left diagonal
    winArr[2*N] += nVal;
else if(nRow+nCol == N-1) // right diagonal
    winArr[2*N+1] += nVal;

However, there are 4 attached diagonal points you should check.
You logic is flawed. An X negates all previous 'O's. However, in your code you simply decrement:

int nVal = (player == 'X' ? 1 : -1);
winArr[nRow] += nVal;
winArr[N + nCol] += nVal;

This will make the following sequence a win, although it is not valid:

Sequence: X X O X X
Values  : 1 2 1 2 3

I think it would be better to create a simple struct, that holds the relevant information:

X or O
left diagonal value
right diagonal value
horizontal value
vertical value

Now you can calculate the appropriate values by first checking, whether the mark is the right one and then add the horizontal value of the left/right neighbor and so on.


Watch a directory and insert new entries into database This program's main function is to:

Watch a directory.
If there are new files, insert those as entries into the database.
Delete the files from the directory.

My below code runs well, but I want to optimize it and I think it needs better error handling.

import os
import time
import mysql.connector
import MySQLdb
import pooop

file_path = 'C:\\path\\to\\watch\\'

#send files to database
def insert_csv(file,filename):
    try:
        cnx = mysql.connector.connect(user='user',
                                    password ='pass',host='192.168.1.1',
                                  database='test')
        cursor = cnx.cursor()
        thedata = open(file, 'rb').read()
        sql = "INSERT INTO testing(file_backup,file_name) VALUES (%s,%s)"
        cursor.execute(sql,(thedata,filename))
        cnx.commit()

   except MySQLdb.OperationalError, e:
      print e
   except MySQLdb.ProgrammingError, e:
      print e
   finally:
      cursor.close()

def walk():
    try:
        for dirpath, dirnames, files in os.walk(file_path):
            for i in files:
                file = dirpath+i
                try:
                    insert_csv(file,i)
                except Exception, e:
                    print e
                finally:
                    os.remove(file)
                print 'File successfully removed\n'+"-"*80
    except Exception, e:
         print e

#main loop that watches the directory
if __name__ == "__main__":
    print "Application starts running\n"+"-"*80
    while True:
        walk()

The application will run on Windows XP. I'm using Python 2.7.

Naming

Nothing in the code suggests that csv files are special. Why a backup is called backup_csv?
Exception handling

The main code removes the file regardless of the insertion success. For example, if connect fails, the file is still removed. Is this an intended behaviour? I recommend to call os.remove() inside backup_csv.
misc

What is the purpose of time.sleep(1)?
I don't see a reason for if files clause. The for i in files works as expected if files is empty.


Fraction Class in Python I decided to train myself in OOP with a simple perfect precision Fraction class.

from __future__ import division
import doctest

class Fraction:
    """
    Implements a Fraction Class with perfect precision
    operations and utility methods. The built-in operators
    are overwritten to provide a more natural interface.
    """
    def __init__(self,num,den):
        if den == 0:
            raise ValueError("Denominator must not be zero.")

        self.num = num
        self.den = den

    @staticmethod
    def greatest_common_divisor(a,b):
        """
        Returns the greatest number 'n' existing such
        that a % n == 0 and b % n == 0.
        This number may be one if 'a' and 'b' are coprimes.

        >>> Fraction.greatest_common_divisor(20,15)
        5
        """
        def common(a,b):
            return [i for i in a if i in b]

        def div(n):
            return [i for i in range(1,n+1) if n % i == 0]

        return max(common(div(a),div(b)))

    @staticmethod
    def invert(fraction):
        """
        Returns a fraction where the numerator is the previous
        denominator and vice-versa.

        >>> Fraction.invert(Fraction(3,5))
        5/3
        """
        return Fraction(fraction.den,fraction.num)

    def from_string(text):
        """
        Generates a Fraction object from a string rapresentation
        of two integers seperated by '/'.

        >>> Fraction.from_string('4/9') + Fraction.from_string('2/18')
        5/9
        """
        return Fraction(*[int(i) for i in text.split('/')])

    def simplify(self):
        """
        Returns an eqivalent but simpler Fraction.

        >>> Fraction.simplify(Fraction(210,20))
        21/2
        """
        fact = self.greatest_common_divisor(self.num,
                                       self.den)
        return Fraction(self.num // fact, self.den // fact)

    def __mul__(self,fraction):
        """
        Fraction multiplication.

        >>> Fraction(4,3) * Fraction(1,20)
        1/15
        """
        return Fraction.simplify(
            Fraction(self.num*fraction.num,
                       self.den*fraction.den))

    def __add__(self,fraction):
        """
        Fraction addition.

        >>> Fraction(4,9) + Fraction(11,7)
        127/63
        """
        common_den = self.greatest_common_divisor(
            self.den,fraction.den)
        num1 = self.num * fraction.den
        num2 = fraction.num * self.den
        return Fraction.simplify(
            Fraction(num1+num2, fraction.den*self.den))

    def __sub__(self,fraction):
        """
        Fraction subtraction.

        >>> Fraction(1,2) - Fraction(1,3)
        1/6
        """
        return self + Fraction(-fraction.num,
                                fraction.den)

    def __truediv__(self,fraction):
        """
        Fraction division.

        >>> Fraction(4,8) / Fraction(9,2)
        1/9
        """
        return self * self.invert(fraction)

    def __repr__(self):
        """
        Returns a printable representation of the fraction
        that can also be fed back into the class via
        'Fraction.from_string'.
        This method is called automatically on printing.

        >>> Fraction(5,8)
        5/8
        >>> Fraction(2,9)
        2/9
        """
        return '{}/{}'.format(self.num, self.den)

def main():
    doctest.testmod()

if __name__ == "__main__":
    main()

The from_string() function is missing a @staticmethod decorator, and thus does not work in Python 2.

Your greatest_common_divisor() function works using brute force: it literally tests every possible divisor and picks the greatest one that is common to both.  A much faster method is the Euclidean Algorithm.

@staticmethod
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

Validation and error handling could be tightened up a bit.

The rejection of floating-point arguments is inconsistent:

>>> Fraction(3.14, 1)
3.14/1
>>> Fraction.from_string('3.14/1')
Traceback (most recent call last):
  […]
  File "fraction.py", line 55, in <listcomp>
    return Fraction(*[int(i) for i in text.split('/')])
ValueError: invalid literal for int() with base 10: '3.14'

Instantiating a Fraction with strings initially appears to work, but fails in an odd way later.  Either both of these statements should work, or both should fail.

>>> Fraction('1', '3')
1/3
>>> Fraction('1', '3') + Fraction('2', '3')
Traceback (most recent call last):
  […]
  File "fraction.py", line 32, in div
    return [i for i in range(1,n+1) if n % i == 0]
TypeError: Can't convert 'int' object to str implicitly

In Fraction.from_string(), the abstraction is slightly leaky.  I would prefer to see a ValueError instead of the following:

>>> Fraction.from_string('1/3/5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "fraction.py", line 55, in from_string
    return Fraction(*[int(i) for i in text.split('/')])
TypeError: __init__() takes 3 positional arguments but 4 were given

Personally, I would choose to raise a ZeroDivisionError if the denominator is 0.

>>> Fraction(1, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "fraction.py", line 13, in __init__
    raise ValueError("Denominator must not be zero.")
ValueError: Denominator must not be zero.


Quick sort implemented in Python This code implements quick sort and takes advantage of passing the list by reference. I'm looking for performance and general best practices.

import random

def quicksort(array, l=0, r=-1):
    # array is list to sort, array is going to be passed by reference, this is new to me, try not to suck
    # l is the left bound of the array to be acte on
    # r is the right bound of the array to act on

    if r == -1:
        r = len(array)

    # base case
    if r-l <= 1:
        return

    if r == -1:
        r = len(array)

    piviot = int((r-l)*random.random()) + l

    i = l+1 # Barrier between below and above piviot, first higher element
    swap(array, l, piviot) #piviot is now in index l

    for j in range(l+1,r):
        if array[j] < array[l]:
            swap(array, i, j)
            i = i+1

    swap(array, l, i-1) # i-1 is now the piviot

    quicksort(array, l, i-1)
    quicksort(array, i, r)

    return array

def swap(array, a, b):
    # a and b are the indicies of the array to be swapped

    a2 = array[a]
    array[a] = array[b]
    array[b] = a2

    return

# array is list to sort, array is going to be passed by reference, this is new to me, try not to suck
# l is the left bound of the array to be acte on
# r is the right bound of the array to act on

A comment like that would be better as a docstring.

if r == -1:
    r = len(array)

You wrote that twice.  The second time is dead code.

piviot = int((r-l)*random.random()) + l

The correct spelling is pivot.  To generate the random integer, use random.randrange(l, r).

def swap(array, a, b):
    # a and b are the indicies of the array to be swapped

    a2 = array[a]
    array[a] = array[b]
    array[b] = a2

    return

The correct spelling is indices.

The return is superfluous.  I would omit it.

The swap can be written more simply as array[a], array[b] = array[b], array[a].  That is simple enough that it might be better not to write a swap() function at all.


Categorize & sub categorize from contents of one row and more execute even more queries in results I have a table called sales and it has below columns:

'id'
'product_type'
'soldDate'
'text'

'product_type' examples are: Tshirt-XL, Tshirt-L, Tshirt-M, Trousers-XL, Trousers-L, Trousers-M etc.

I have an array called products which is;

$products = array('Tshirt','Trausers');

My output is after executing below code:

Tshirt

Tshirt-L

lorem impsum dolat

Tshirt-XL

lorem impsum.
another text. ball.

Trousers

Trousers-M

text for this one.

And the code itself:

$products = array('Tshirt','Trousers');

foreach ($products as $product) {
    echo "";
    echo $product;
    echo "
";

    $q = "
    SELECT      *,
    SUBSTRING_INDEX(product_type, '-', 1) AS product_typeMain
    FROM        sales
    WHERE       SUBSTRING_INDEX(product_type, '-', 1) = '".$product."'";
    $statement = $db->prepare($q);
    $results = $statement->execute();
    $results = $statement->fetchAll();

    $unique_product_types = array();

    foreach($results as $filter_result){
        if ( in_array($filter_result->product_type, $unique_product_types) ) {
            continue;
        }
        $unique_product_types[] = $filter_result->product_type;

        echo $filter_result->product_type;
        echo "
";

        $q = "
        SELECT      *
        FROM        sales
        WHERE       product_type = '".$filter_result->product_type."'
             ";
        $statement = $db->prepare($q);
        $results = $statement->execute();
        $results = $statement->fetchAll(PDO::FETCH_OBJ);

        foreach ($results as $value) {
            echo "
".$value->text."
";
        }

    }

}

I know there are so many foreach loops, so many queries. Also I have worries about performance (more than 100.000 rows, and more than 100 product_type.) Plus I will need to add another query in last foreach loop to make searches (multiple, not one).

I am looking forward to hear best practices to improve. Thanks in advance.

PDO has some rather handy fetching options.  FETCH_GROUP is good for grouping the first level (product categories), but some extra handling is necessary to group the second level (product name-sizes).  To perform this nested grouping, I'll show the implementation of a temporary variable to track whether or not the current iteration is processing a new group or the same group as the previous iteration.

It is important to point out that you should not be making multiple trips to the database.  Since this script can be sensibly executed with a single trip to the database, it should be.
Prepared statements should be used for stability/security.

 tags must live inside
 tags for proper html markup.

Tested Code:

$products = ['Tshirt', 'Trousers'];
$placeholders = str_repeat('?,', count($products) - 1) . '?';

$stmt = $conn->prepare("
     SELECT SUBSTRING_INDEX(product_type, '-', 1) AS product_group, product_type, text
     FROM sales
     WHERE SUBSTRING_INDEX(product_type, '-', 1) IN ($placeholders)
     ORDER BY product_type
     ");
$stmt->execute($products);
$results = $stmt->fetchAll(PDO::FETCH_GROUP);
foreach ($results as $productGroup => $subarray) {
    echo "
{$productGroup}
";
    $typeGroup = null;
    foreach ($subarray as $row) {
        if ($row['product_type'] != $typeGroup) {
            if ($typeGroup) {
                echo "

";
            }
            echo "

{$row['product_type']}

";
        }
        echo "
{$row['text']}
";
        $typeGroup = $row['product_type'];
    }
    echo "

";
}

Sample data / Rendered output:

...yeah, didn't try very hard on the images.


Creating a dictionary from two lists I have working code here which takes two lists and turns them into a dictionary with the first list being the keys and the second being the values. If the keys exceed the values the value "None" will be assigned to that key.

def createDict(keys, values):
    i = 0
    dictionary = {}

    # go through all the values in the first list
    for key in keys:
        # if our keys index is equal or exceeds our value list's length
        # then extend the list with a None value
        if i >= len(values):
            values.extend([None])
        dictionary[key] = values[i]
        i = i + 1
    return dictionary

I was hoping for to get some feedback.

A common way to create a dictionary from two lists is zipping. The zip built in takes two lists and creates a list of pairs from them. In turn, a list of pairs can be used to create a dictionary directly.

Your case has an extra twist: we need to pad the list of values to the same length as the list of keys, otherwise the keys with no corresponding values would simply get dropped.

Even with this minor complication, the function can be written simpler quite easily:

def create_dict(keys, values):
    return dict(zip(keys, values + [None] * (len(keys) - len(values))))

Btw I renamed the function with snake_case to follow recommended PEP8 conventions.

Another alternative somewhat more compact alternative is using itertools.zip_longest:

from itertools import zip_longest

def create_dict(keys, values):
    return dict(zip_longest(keys, values[:len(keys)]))


Makes a navbar for a website with object oriented php I do this as sort of hobby and want to no if I can improve.
This is a simplified version of my code that normal works with bootstrap classes and id's.
At the bottom there is the input of the classes.
I have already a working version connected with SQL Database.
but want to take it a step further with object oriented php.

The next step for me is to create the content page underneath the navbar.
I work with a .htaccess file that redirects everything to index.php, and then use the URI to show the right content.

The main class

<?php

class Main
{
  public $URL;
  public $PageName;
  public function __construct($PageName)
  {
    $this->PageName = $PageName;
    $this->URL = $_SERVER['REQUEST_URI'];
  }
  public static function header() {
    echo '<!DOCTYPE html>

    ...
  ';
  }

  public static function navstart() {
    echo '
';
  }

  public static function navend() {
    echo '
';
  }
}

the navitem class is for making the items in the nav bar

class navItem extends Main
{

    public function __construct($PageName)
  {
    parent::__construct($PageName);
    $ActiveUrl = ($this->URL == "/".$this->PageName) ? " active " : " ";
    echo     '

      PageName.'">'.$this->PageName.'
 &nbsp;';
  }
}

The nav dropdown class to make the dropdown in the navbar

class navDropdown extends Main
{
  public function __construct($PageName, $Item)
  {
    parent::__construct($PageName);
    $shortURL = substr($this->URL, 0, strpos($this->URL, "_"));
    $ActiveUrl = ($shortURL == "/".$this->PageName) ? " active " : " ";
    echo '

        '.$this->PageName.'

';
        foreach ($Item as $Item) {
          $ActiveUrl = ($this->URL == "/".$this->PageName.'_'.$Item) ? " active " : " ";
          echo '
          PageName.'_'.$Item.'" >'.$Item.'';
        }
        echo '

 &nbsp;';
  }
}

the variables to make the page

main::header();
main::navstart();
$test = new navDropDown("test", array('test1' , 'test2', 'test3' , 'test4'));
$home = new navItem("home");
$about = new navItem("about");
$pages = new navDropDown("pages",array("one", "two", "three" ));
$contact = new navItem("contact");
main::navend();

I think you have some reading/research to do as I'm not sure you understand OOP...

What is Main?

Main is setup as a class, used as a namespace in instantiation, then extended(why?).
Generally in the context it seems to be intended to be used App or <AppName> are better options

When to extend

Why do all elements extend Main?

It appears to be solely for it's constructor which it never uses itself. (Extra Baggage in Main)
Main also only contains functions the other elements never need or use (Extra Baggage in the Sub-Objects)

Extending a class makes more sense if the classes extended from it share functionality

What even is an Object? ##

You seem to be using your objects as functions disguised as things.

For example: when you create a navItem:
You create the object
It's controller prints itself to the screen
You capture it in a variable never to be used again. Why?

Who gets to be an Object?

navItem is an object navBar Isn't
navDropdown is an object navDropdownItem isn't


Change UI display order of an ObservableCollection I have an ObservableCollection that is filled with custom elements of type Video runtime. These have the properties of Name, Rating and Number of Viewers.
I want to display the Video elements in different orders based on whichever of the three criteria the user chooses during Application Runtime. I created the following Enum to store the possible choices:

public enum OrderBy
{
    [Description("Video Name")]
    Name = 0,

    [Description("Video Rating")]
    Rating = 1,

    [Description("Number of Viewers")]
    ViewerNumber = 2
}

These are fed into a ComboBox called OrderCombo allowing the user to change the order criteria (I'm displaying the Description to the user):

foreach (var item in Enum.GetValues(typeof(OrderBy)))
{
    OrderCombo.Items.Add(((OrderBy)item).GetDescription());
}

To avoid sorting, I used LINQ to get the order and I came up with the following:

IOrderedEnumerable<Video> GetOrder()
    {
        switch (OrderCombo.SelectedIndex)
        {

            case 0:
                return videos.OrderBy(x => x.Name);

            case 1:
                return videos.OrderByDescending(x => x.Rating);

            case 2:
                return videos.OrderByDescending(x => x.NumberOfViewers);

        }
        return videos.OrderBy(x => x.Name);
    }

Then, I call this function every time a new element is added or an element is delelted or the user changes the order:

VideoUIElment.ItemsSource = GetOrder();

So basically I keep re-calculating the enumerable every time, which workswpf but I'm wondering if there is a more efficient/elegant way of doing this.
Maybe store the order in one or several Func<>s? I tried them, but they can only be of a (compile-time) fixed type as in Func<Video, string> for Name and I would rather avoid using implementations like Func<Video, dynamic>.

To sort your ObservableCollection you should be using data-binding and let WPF do the work.

First let's fix the ComboBox that you currently populate manually. For the sake of this review I assume you use your code-behind file as a data-source that is bound to the Window via:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Next you need to tell the ComboBox where to find the items and how to display them:

<ComboBox
    ItemsSource="{Binding OrderOptions}"
    DisplayMemberPath="Description"
    SelectedValuePath="OrderBy"
    SelectionChanged="Selector_OnSelectionChanged">
</ComboBox>

It receives the values from the code-behind property (you of course would read the descriptions here with your reflection helpers):

public IEnumerable<OrderOption> OrderOptions
{
    get
    {
        return
            Enum
                .GetValues(typeof(OrderBy))
                .Cast<OrderBy>()
                .Select(x => new OrderOption { OrderBy = x, Description = x.ToString() });
    }
}

I created a helper object for this combo-box that looks like this:

public class OrderOption
{
    public OrderBy OrderBy { get; set; }

    public string Description { get; set; }
}

Now we need a list of videos:

private ObservableCollection<Video> _videos = new ObservableCollection<Video>(new[]
{
    new Video { Name = "Rambo", Rating = 3},
    new Video { Name = "Rocky", Rating = 8},
    new Video { Name = "Turbo Interceptor", Rating = 1}
});

where the Video is implemented as:

public class Video
{
    public string Name { get; set; }

    public int Rating { get; set; }
}

and the code-behind file has this property:

public ObservableCollection<Video> Videos => _videos;

Now comes the tricky part. You need to add a new resource to the resource-dictionary. This is a CollectionViewSource that initially will sort the items by Name.

<Window.Resources>
    <ResourceDictionary>
        <CollectionViewSource x:Key="SortedVideos" Source="{Binding Videos}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Name"></scm:SortDescription>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </ResourceDictionary>
</Window.Resources>

In order for this to work you need to add a new namespace:

xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

Now you can bind a ListView to it:

<ListView
    ItemsSource="{Binding Source={StaticResource SortedVideos}}"
    DisplayMemberPath="Name">
</ListView>

You have probably noticed the combo-box has this Selector_OnSelectionChanged event handler that in code-behind is implemented like this to get the currently select OrderBy, then the switch is used to change the sorting by first clearing the current settings and adding a new one that changes the property of the Video object that is used for sorting. In this example I only used the Name and the Rating. Now each time you change the selection WPF will update the ListView and if you add or delete an item it will use the current setting to re-order it.

private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var colView = Resources["SortedVideos"] as CollectionViewSource;
    switch (((sender as ComboBox).SelectedItem as OrderOption).OrderBy)
    {
        case OrderBy.Name:
            colView.SortDescriptions.Clear();
            colView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
            break;
        case OrderBy.Rating:
            colView.SortDescriptions.Clear();
            colView.SortDescriptions.Add(new SortDescription("Rating", ListSortDirection.Ascending));
            break;
    }
}


Generate all possible unique combinations of positive numbers these have sum equal to N This is my function to generate all possible unique combinations of positive numbers these have sum equal to N.
For example:

If the input is 4

The output should be: [ '4', '1+3', '1+1+2', '1+1+1+1', '2+2' ]

You can try it online here
const f=n=>{ // n is a positive number
  if(n==0) return ["0"]
  if(n==1) return ["1"]
  if(n==2) return ["0+2", "1+1"]
  const result = [n+"+0"]
  for(let i=n-1; i>=n/2|0; i--){
    for(const x of (f(n-i) || [])) {
      for(const y of (f(i) || [])) {
        result.push(y + "+" + x)
      }
    }
  }

  // Remove duplicated records
  const map = result.map(v=>v.split`+`.filter(x=>+x>0).sort((m,n)=>m-n).join`+`)
  return [...new Set(map)]
}

//Testing
a=f(8)
console.log(a)

My approach is using recursion, it works like that:

If I can find all possible unique combinations of positive numbers these have sum equal to N.

Then I can find all possible unique combinations of positive numbers these have sum equal to N + 1.

For example:

If all possible unique combinations of positive numbers these have sum equal to 3 are: ["3", "1+2", "1+1+1"] and all possible unique combinations of positive numbers these have sum equal to 2 are ["2", "1+1"]

Then for 4 it should be:

4 + 0 or 4

All possible unique combinations of combinations of positive numbers these have sum equal to 3 and 1

// for 3 it's combinations is
["3", "1+2", "1+1+1"]
// for 1 it is
["1"]

All possible unique combinations of combinations of positive numbers these have sum equal to 2 and 2,

// for 2 it's combinations is
["2", "1+1"]

And I only do the loops to the integer of n/2  to avoid duplicatings.
Could you please help me to review it?

const f=n=>{ // n is a positive number
  if(n==0) return ["0"]
  if(n==1) return ["1"]
  if(n==2) return ["0+2", "1+1"]
  const result = [n+"+0"]
  for(let i=n-1; i>=n/2|0; i--){
for(const x of (f(n-i) || [])) {
  for(const y of (f(i) || [])) {
    result.push(y + "+" + x)
  }
}
  }

  // Remove duplicated records
  const map = result.map(v=>v.split`+`.filter(x=>+x>0).sort((m,n)=>m-n).join`+`)
  return [...new Set(map)]
}

//Testing
a=f(8)
console.log(a)

Review
Your code is a good simple solution. The style is sloppy. The complexity is a bit high and the techniques uses are negatively impacting performance.
The template literal call  Array.split`+` always throws me, but I like it, your code reminds me to use it more often.
General points

Delimit all code blocks. Eg   if(n==0) return ["0"] better as if(n==0) { return ["0"] }
Why? JavaScript like most C style languages do not require delimited blocks for single statement blocks, however when modifying code it is very easy to over look the missing {}.

Use semicolons or be thoroughly familiar with automatic Semicolon Insertion (ASI)

Rather than use continue consider using the statement  } else {
Why? continue breaks the use of indentation that visually helps you see flow in a glance. continue and its friend break should be avoided when possible.

// Avoid using continue to skip code

for (a of list) {
    if (foo) {
        ...do something...
        continue;
    }
    ...lots of code...
}

// Rather use an else statement

for (a of list) {
    if (foo) {
        ...do something...
    } else {
        ...lots of code...
    }
}

Spaces between operators i>=n/2|0 should be i >= n / 2 | 0

When using short circuit expressions (f(n) || []) use the Nullish coalescing operator
?? eg f(n) ?? [] in rather than logical OR ||

In the two inner loops you recurse with the call to (f(n) || []). The function f() always returns an array so there is no need for || []

In the most inner loop you recurse on f(i) for every x but f(i) is the same for every x. This is forcing a lot of redundant processing.
Always move calculations to a level that is One = One, rather than One = Many to avoid unnecessary overhead.
Your inner loop

for(let i=n; i>=n/2|0; i--){
  if(i==n){
    result.push(n + "+0")
    continue
  }
  for(const x of (f(n-i)||[])) {
    for(const y of (f(i) || [])) { //  repeated call to f(i)
      result.push(y + "+" + x)
    }
  }
}

Example of moving the recursive call out of the inner loop
for (let i = n; i >= n / 2 | 0; i--) {
    if (i === n) {
        result.push(n + "+0");
    } else {
        const solvedForI = f(i); // called once only
        for (const x of f(n - i)) {
            for (const y of solvedForI) {
                result.push(y + "+" + x)
            }
        }
    }
}

Tips
Bit-wise divide and floor
Using | 0 to floor Numbers is a handy short cut, But you can divide by a power of 2 and floor in one operation.
Example n / 2 | 0 is the same as n >> 1. For every left shift you divide by 2 and for every right shift you multiply by two.
(n / 2 | 0) === (n >> 1)
(n / 4 | 0) === (n >> 2)
(n / 8 | 0) === (n >> 3)
(n / 256 | 0) === (n >> 8)

Note that the conversion to uint32 happen before the shift, thus multiplying is not equivalent. Eg 1.5 << 1 === 2 and 1.5 * 2 | 0 === 3

Note Bitwize operations convert to unsigned int 32 and thus should only be used for only for Numbers in the range \$-(2^{31})\$ to \$2^{31} - 1\$

Cache
You can use a cache to store the results of a function. For recursive functions this can save a lot of processing.
Pseudo code example of a cache
For positive integer values you can use an Array, For other types of arguments you would use a Map
// n is a positive integer
function solution(n) {     // wrapper
    const cache = [];
    return recurser(n);    // call recursive solution.

    function recurser(n) { // n is a positive integer
        var result;
        if (cache[n]) { return cache[n] }  // Return cache if available

        while ( ) {
            ...
            recurser(n - val);

            /* Some complicated code that adds to result */

            ...
        }

        return cache[n] = result;
    }
}

Complexity, Performance, & Example
TLDR
The next part of the answer addresses performance and complexity and how both can be improved with example function.
As the example is a completely different different approach It is not considered a review (rewrite) however the some of it can be used in your solution.
Complexity
Your complexity is in the sub-exponential range \$O(n^{mlog(n)})\$ where \$m\$ is some value >= 2. This is rather bad. The example reduces complexity by reducing the value of \$m\$.
Performance
Performance is indirectly related to complexity. You can increase performance without changing the complexity. The gain is achieved by using more efficient code, rather than a more efficient algorithm.

Example
The example is a completely different algorithm but some of the techniques can be applied to your solutions, such as the cache and moving the check for found combinations out of the recursing function.
Addressing complexity
I could not modify your algorithm to improve the complexity, this is not due to the not being an less complex algorithm bases on your approach, just that I was unable to find it.
Addressing performance
There is a lot of room to improve performance via caching, strings, sorts, and stuff
Cache
The example uses a cache to reduce calculations. See above Tips regarding cache.

Note the cache is set up to contain the result of n 0 to 2 which is equivalent to your first 3 if statements.

Strings
To avoid duplicates you use a Set and because two array containing the same values are not the same, you convert the array to a string that can uniquely identify the array content.
However you are manipulating the strings in the inner loops and convert from string to number and back each recusing iteration.
Using the approach of wrapping the recursive function we can avoid the conversion within the main solutions and use the set to filter duplicates once just before returning the final result.
Sort
Though the sort is not a major part of the complexity, it is where I started when doing the example.
Each iteration adds only one value to the arrays being built. By maintaining the correct order as we go the sort can be avoided completely and we just build the array inserting the new element at the correct position.
The inner most for (const v of sub) { loop does this inserting the new value to each the  sub arrays returned by the previous recursive solution.
Code Comparison
To gauge the performance and complexity I ran your code as the base and used its results to test the examples correctness.
I then added counters to both counting every countable iteration, including under the hood iterations such as those performed by spreads ..., array map and reverse, string concats, sorts, etc.
The results as follows
Counted iterations per tested n value

n value
7
8
9
10
11
12
13
... 18

Your code
4,834
14,179
36,630
101,818
268,192
733,260
1,947,968
277,569,323

Example
333
718
1,584
3,418
7,445
16,018
34,528
1,503,242

Note The example results may not look that bad as n increases, however it is still in the same complexity range of \$O(n^{mlog(n)})\$. All I have managed to do is lower \$m\$

Note To match your result I had to add a Array.reverse to the final combinations. The reverse was counted but is not required.

function combos(n) {
    const cache = [[], [[1]], [[2], [1, 1]]];
    return [...(new Set([...combo(n).map(v=>v.reverse().join`+`)]))];

    function combo(n) {
        var a = n - 1, b, insert;
        if (cache[n]) { return cache[n] }

        const res = n % 2 ? [[n]] : [[n], [n >> 1, n >> 1]];
        while (a > n - a) {
            b = n - a;
            for (const sub of combo(a--)) {
                const subRes = [];
                insert = true;
                for (const v of sub) {
                    v > b || !insert ? subRes.push(v) : (insert = false, subRes.push(b, v));
                }
                insert && subRes.push(b);
                res.push(subRes);
            }
        }
        return cache[n] = res;
    }
}


Passing a selectlist to the view based on database models from viewmodel is a MVC anti-pattern We need to select a model reference from a view. To do this we need to add a dropdownlistfor. This is based on a selectlist containing database models.

passing selectlists by viewbag

This solves our problem, but we do not like using ViewBag:

public ActionResult Create()
    {
        ViewBag.SomeModels = new SelectList(context.SomeModel, "id", "modelDescription");

        return View();
    }

Our solution

We added a context to a viewmodel to do the same, but this is MVC anti-pattern:

public class SomeModelViewModel : SomeModel
{
    private SomeContext context = new SomeContext ();

    public SelectList getSomeOtherModels()
    {
        return new SelectList(context.SomeOtherModel, "id", "modelDescription");
    }
}

Does anyone have suggestions for a clean way to solve this problem?

I think there are a few things that can be fixed here, but overall I don't think this is automatically an anti-pattern. It could just be executed a little better.

Caveat: I don't practice what I preach nearly as often as I should.

What I tend to do in my own projects, and the standard where I work, is for the view model to expose an IEnumerable<SelectListItem> (actually, when we're lazy, we put this enumerable in the ViewBag like you have but we're trying to get away from that.) Rather than giving the context to your view model, just give the items to the view model when it's constructed and have it generate the SelectListItems from them. AFAIK, that's the controller's job.

public class SomeViewModel
{
    public IEnumerable<SelectListItem> ListItems { get; private set; }

    public SomeViewModel(IEnumerable<SomeModel> items)
    {
        ListItems = items
            .Select(i => new SelectListItem()
                {
                    Text = i.Name,
                    Value = i.Id,
                    Selected = i.IsSelected // or whatever
                })
            .ToList();
    }
}

public class SomeController
{
    public ActionResult Index()
    {
        var viewModel = new SomeViewModel(_context.SomeModels);

        return View(viewModel);
    }
}

Again, I can't promise this is the more "correct" way to do it, but I've done it and seen it done on at least four different projects, and it's worked well for us so far.

P.S. Your ViewModel probably shouldn't inherit from your Model. I've never actually seen that done before, but some cursory Googling shows that it's not really recommended. You should have the exact properties you need in the view copied into your view model (I hear there are tools for his), and use a tool like AutoMapper to copy values back and forth when necessary.


Bash script to send notifications when low on ram Backstory

Recently, we've changed the PCs at my workplace to un Linux Mint.
It works amazing, is blazing fast and the adjustment time was very short.

However, I noticed my PC would freeze completely, sometimes.
I've determined that it is low RAM memory.

My working habits require me to open 10+ tabs (sometimes 100, in 5-8 Google Chrome windows).
This makes it so the swap is stuffed, as well as the RAM (Physical Memory).
Sometimes I have to use a VM running off of my PC, which takes 4GB for itself.

The code

Since old habits are hard to kill and isn't fun, I've decided to write code (which is a lot more fun).

Since Linux Mint doesn't warn about low available RAM, I've scattered around and put together a script to run every minute, and warn me when the memory is running low.

This script can also be executed from the console, displaying a message on it, if needed.
A detection method had to be added, since the output sent to cron is emailed by default.

#!/usr/bin/env bash
# based from https://askubuntu.com/questions/234292/warning-when-available-ram-approaches-zero
LANG=en_US.UTF-8

# gets available and total ram
RAM=$(free -m)
total=$(echo "$RAM"|awk '/^[mM]em\.?:/{print $2}')
available=$(echo "$RAM"|awk '/^[mM]em\.?:/{print $7}')

# warn if less than these levels is free
# warning = 20%
# critical = 10%
WARNING=$(expr $total / 5)
CRITICAL=$(expr $total / 10)

# -h int:transient:1 <-- don't store the notification
# https://unix.stackexchange.com/questions/393397/get-notify-send-to-clear-itself-from-notification-tray/401587
if [ $available -lt $CRITICAL ]; then
    # using -u critical doesn't allow the notification to go away after -t ms have past
    # this causes issues if afk, since the notifications will queue until the -u critical is closed
    notify-send -i error -h int:transient:1 -t 60000 "Low memory!" "$available/$total MB free, critical at $CRITICAL MB"
elif [ $available -lt $WARNING ]; then
    notify-send -h int:transient:1 -t 15000 "Memory is going low" "Available: $available/$total MB, warns at $WARNING MB"
fi

# outputs if not ran by cron
# https://unix.stackexchange.com/questions/46789/check-if-script-is-started-by-cron-rather-than-invoked-manually
if [ -t 0 ]; then
    echo "Available: $available/$total MB, warns at $WARNING MB, critical at $CRITICAL MB"
fi

This script runs in crontab -e, with the following:

# https://unix.stackexchange.com/questions/247860/notify-send-doesnt-work-at-cinnamon
DISPLAY=":0.0"
XAUTHORITY="/home/<username>/.Xauthority"
XDG_RUNTIME_DIR="/run/user/<output from id -u>"

* * * * * /usr/bin/env bash /home/<username>/<script-from-above>.sh

Conclusion

It was really hard to get to this point, with plenty of issues.
Most information was available online, but, making it work was a pain.

I'm not really good with Bash scripting, which probably means that I have some really bad mistakes.
As far as I know, it works as intended, when intended:

Besides that, is there anything I can improve or change?
Any optimization/optimisation I can do?
Any localization/localisation issues that may come?

Kudos to you! This is a nice little script, easy to read and to understand. However, there is no reason to reach for expr. Most shells (including dash or even busybox sh) can interpret arithmetic expressions on their own:

WARNING=$(($total / 5))
CRITICAL=$(($total / 10))

Also, in [ ] expressions, I'd use quotes around variables, to make sure that they don't contain any spaces. In this case, we can be sure that they won't contain some, but it's still good practice to use them:

if [ "$available" -lt "$CRITICAL" ]; then
    ...
elif [ "$available" -lt "$WARNING" ]; then
    ...
fi

Other than that, I'd write the -u comment as a direct negative instead of a positive:

# Don't use `-u critical', as it will keep the notification even after -t ms
# and will cause notifications to queue up.

This comment still contains the same message: "don't use -u critical", but it's much more direct.

Since no bashism are used, we can even change the shebang to #!/bin/sh. By the way, some of those remarks were also found by ShellCheck, but it rightfully marks them as info level only.


Function to test whether file is in use I needed a method to test whether a given file is in use. Is the code below up to the task?

Public Function IsFileInUse(path As String) As Boolean
    If IO.File.Exists(path) Then
        Try
            Using fs = IO.File.OpenWrite(path)
                'If stream can write to the file, it suggests the file is not in use.
                Return Not fs.CanWrite
            End Using
        Catch ex As Exception
            'An exception was raised when trying to create a write stream
            'This suggests the file is in use.
            Return True
        End Try
    Else
        'File does not exists, therefore it is not in use:
        'a file could be written anew to the provided path.
        Return False
    End If
End Function

You should first ask yourself, why do you write a method to check if a file is in use.

You can't use this method to avoid exceptions, because although your method returns False just a microsecond later the file could be opened exclusivly by another program. You still would need to do any file operation inside a Try..Catch block. So the best way would be to do just that.

Looking at your code, I would suggest to use a guard condition to save one level of indentation like so

If Not IO.File.Exists(path) Then
    Return False
End If
Try....

Using File.OpenWrite(string) would be enough because the only difference to Open(FileMode, FileAccess, FileShare) would be the FileMode value having FileMode.OpenOrCreate and the FileAccess value having FileAccess.Write

If you want to go the way you have posted as answer you could omit the FileAccess.ReadWrite and FileShare.None enumeration because the Open(FileMode) method just calls the overloaded Open(FileMode, FileAccess, FileShare) method with the same values as your call.

What I like about your code is that you apply the .NET Naming GuideLine and your using of the Using to make sure that the stream is closed properly.

What I dislike is that you don't check wether path is null. Proper method parameter validation for public methods should always be done.


Kotlin sieve using sequences While learning about functional programming the simple sieve example was brought up in Haskell. I wanted to try a Kotlin implementation using sequences.

Are there any other quick wins without modifying the structure too much?

import kotlin.coroutines.experimental.buildSequence
import kotlin.system.measureTimeMillis

fun sieve(isPrime: Int, ints: Sequence<Int>): Boolean = with(ints.first()){
    return when {
        isPrime  < 2 -> false
        isPrime == 2 -> true
        isPrime == this -> true
        isPrime.rem(2) == 0 -> false
//        isPrime.and(1) == 0 -> false // same way to check if number is even
        this > isPrime -> false
        else -> sieve(isPrime, ints.filter { n -> n.rem(this) != 0 })
    }
}

fun main(args: Array<String>) {
    val lazySeq = buildSequence { for (i in 3..Int.MAX_VALUE step 2) yield(i) }
    println("Duration = ${measureTimeMillis { println("isPrime(4057) = ${sieve(4057, lazySeq)}") }}ms")
//    (2..200).forEach { println("isPrime($it) = ${sieve(it, lazySeq)}") }
}

Here's my take on this:

import kotlin.system.measureTimeMillis

fun sieve(xs: Sequence<Int>): Sequence<Int> = sequence {
    val head = xs.first()
    val tail = xs.drop(1).filter { it % head != 0 }
    yield(head)
    for (i in sieve(tail))
        yield(i)
}

val primes = sieve(generateSequence(2) { it + 1 })
fun isPrime(n: Int) = primes.contains(n)

val durationMs = measureTimeMillis {
    println("isPrime(4057) = ${isPrime(4057)}")
}
println("Duration = $durationMs ms")

Start with the first element in the sequence - number 2
Filter out all numbers divisible by 2
Yield 2
Yield the rest recursively:

Start with the first element in the sequence - number 3
Filter out all numbers divisible by 3
Yield 3
Yield the rest recursively...