Does this PDO process look protected from SQL injection? Does this process look protected from SQL injection attacks?

Is there something I could possibly change to make it more protected?

<?php
  include("../include/database.php");

  if(isset($_POST['details']))
  {
    $values = $_POST['details'];

    $param1 = htmlspecialchars(trim($values['param1']));
    $param2 = htmlspecialchars(trim($values['param2']));

    $conditions = [];
    $parameters = [];

    if (!empty($param1))
    {
        $conditions[] = 'COLUMN1 LIKE ?';
        $parameters[] = $param1."%";
    }
    if (!empty($param2))
    {
        $conditions[] = 'COLUMN2 = ?';
        $parameters[] = $param2."%";
    }

    try {
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $select = "SELECT COLUMN1, COLUMN2 FROM table";

        if ($conditions)
        {
            $select .= " WHERE ".implode(" AND ", $conditions);
        }

        $stmt = $conn->prepare($select);
        $stmt->execute($parameters);

        $out = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $out[] = $row;
        }

        echo json_encode($out);
    }
    catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }

    $conn = null;
  }
?>

It looks like your script is part of a basic ajax searching technique.

$_POST is typically used when writing to the database (or when there is a distinct reason that $_GET is unsuitable). Since you are merely SELECTing data, just use $_GET.
if you are going to validate your incoming data, don't bother acquiring resources until after you have validated the incoming data and determined that it qualifies for a trip to the database.  If you are going to default to SELECTing the whole table, then it doesn't matter.
it looks like if params 1 and 2 are missing, you are happy to perform a full table SELECT.  So why deny the full table SELECT if details isn't declared?
empty() is greedy -- it is looking for any falsey value.  Even the string 0 - which has a length of 1 - is deemed empty. Perhaps do a strlen() check instead.
I don't think that trimming should be forced on the data if part of a search string -- maybe the user wants to include the space.
don't htmlspecialchars() as an attempt to improve security.  The prepared statement is going to protect you from string injections.  This call should be used when printing to screen, not querying the db.
I think you have a typo in your second WHERE condition in that you mean to use a second LIKE but you have used = and kept the % appended to the value.
I recommend that you design your table names and column names as lowercase strings to differentiate them from MYSQL keywords.
you are not performing an data manipulations on the result set in this layer, so it will be more direct to fetchAll()
always provide a response string from this script; ideally every response should be json so that your response receiving script can be simpler.
never show end users the raw error message. Give them a vague indication of an error and nothing more.
As @YourCommonSense commented, you should move your $conn->setAttribute call your include file.
Normal execution of your script will not be generating any errors.  Catching the errors will prevent the logging of the errors.  I recommend removing the try catch block.  For continued researching, start here.

Code:

$conditions = [];
$parameters = [];

foreach (['param1' => 'COLUMN1', 'param2' => 'COLUMN2'] as $param => $column) {
    if (isset($_GET['details'][$param]) && strlen($_GET['details'][$param])) {
        $conditions[] = $column . " LIKE ?";
        $parameters[] = $_GET['details'][$param] . "%";
    }
}

include("../include/database.php");
$select = "SELECT COLUMN1, COLUMN2 FROM table";
if ($conditions) {
    $select .= " WHERE " . implode(" AND ", $conditions);
}
$stmt = $conn->prepare($select);
$stmt->execute($parameters);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

In your ajax call, do not tell declare the response type as html -- it's not html, it is json.  In doing so, you won't need to parse it.


Faster copying of images to change their PixelFormat I have the following code below that creates a new Bitmap object the same as the original but to ensure that its PixelFormat is 24bppRgb. Does anyone know if there is a faster way to do this:

using (Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb))
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
    }

    //...

To remove the alpha channel, you could use Bitmap.Clone :

public static Bitmap RemoveAlphaChannel(Bitmap bitmap) {
    var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
    return bitmap.Clone(rect, PixelFormat.Format24bppRgb);
}

Another way is to lock the bits without the alpha channel and then copy the memory to a new bitmap:

public static Bitmap RemoveAlphaChannel(Bitmap bitmap) {
    Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
    Bitmap bitmapDest = (Bitmap)new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
    BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
    BitmapData dataDest = bitmapDest.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
    NativeMethods.CopyMemory(dataDest.Scan0, data.Scan0, (uint)data.Stride * (uint)data.Height);
    bitmap.UnlockBits(data);
    bitmapDest.UnlockBits(dataDest);
    return bitmapDest;
}

static class NativeMethods {

    const string KERNEL32 = "Kernel32.dll";

    [DllImport(KERNEL32)]
    public extern static void CopyMemory(IntPtr dest, IntPtr src, uint length);

}


PHP Factory Method Pattern Implementation This is an attempt at the Factory Method Pattern
It emulates the logical model

and also the physical model

Resources:

http://en.wikipedia.org/wiki/Factory_method_pattern

http://msdn.microsoft.com/en-us/library/ee817667.aspx

http://www.oodesign.com/factory-pattern.html

Is this a correct implementation of the Factory Method Pattern? I think I have followed all the required features of it. Any suggestions are welcome.

/** contract for all flyable vehicles **/
interface iFlyable {
    public function fly();
}

/* concrete implementations of iFlyable interface */
class JumboJet implements iFlyable {
    public function fly() {
        return "Flying 747!";
    }
}

class FighterJet implements iFlyable {
    public function fly() {
        return "Flying an F22!";
    }
}

class PrivateJet implements iFlyable {
    public function fly() {
        return "Flying a Lear Jet!";
    }
}

/** contract for conrete Factory **/
/**
* "Define an interface for creating an object, but let the classes that implement the interface
* decide which class to instantiate. The Factory method lets a class defer instantiation to
* subclasses."
**/
interface iFlyableFactory {
    public static function create( $flyableVehicle );
}

/** concrete factory **/
class JetFactory implements iFlyableFactory {
    /* list of available products that this specific factory makes */
    private  static $products = array( 'JumboJet', 'FighterJet', 'PrivateJet' );

    public  static function create( $flyableVehicle ) {
        if( in_array( $flyableVehicle, JetFactory::$products ) ) {
            return new $flyableVehicle;
        } else {
            throw new Exception( 'Jet not found' );
        }
    }
}

$militaryJet = JetFactory::create( 'FighterJet' );
$privateJet = JetFactory::create( 'PrivateJet' );
$commercialJet = JetFactory::create( 'JumboJet' );

$militaryJet = JetFactory::create( 'FighterJet' );
$privateJet = JetFactory::create( 'PrivateJet' );
$commercialJet = JetFactory::create( 'JumboJet' );

This is a Factory pattern.  I'm not sure that I'd call it the Factory method pattern.  Look at the Wikipedia example for C# -- this looks like the before version.  If you were doing the same thing as the after version here, you'd have

$militaryJet = FighterJetFactory::create();
$privateJet = PrivateJetFactory::create();
$commercialJet = JumboJetFactory::create();

Where FighterJetFactory, PrivateJetFactory, and JumboJetFactory would all extend or implement JetFactory.

The question here is why not just say

$militaryJet = new FighterJet();
$privateJet = new PrivateJet();
$commercialJet = new JumboJet();

Given this example, you don't need any variation of the Factory pattern.  You could just create the objects directly.  As a general rule, you shouldn't look to use design patterns.  You should meet problems that can be solved by the design pattern.  You don't have a problem that needs a design pattern to solve.

Example of a problem that needs a Factory pattern solution:  given a passenger count and a cargo weight, return an object representing a plane that is capable of carrying those passengers with that cargo.

Example of a problem that needs a factory method solution:  define an interface for a plane and another that will allow you to create a plane object.  Give the interfaces to two partners.  Have one write a BoeingFactory that implements your factory interface and the other an AirbusFactory.  Both should return plane objects that implement your plane interface.


Universal reference in a class template I'm writing a templatized container and wanted to use an universal reference for the Add(T&& object) function. Check out isocpp if you need an update on your universal/rvalue references. A quick example from that page states that, since the class is templatized, T&& is fully specified and therefore a rvalue, not an universal reference.

template <class T, class Allocator = allocator<T> >
class vector {
public:
    ...
    void push_back(T&& x);       // fully specified parameter type ⇒ no type deduction;
    ...                          // && ≡ rvalue reference
};

This means that I cannot pass lvalues to the push_back function above.

vector<T> list;

list.Add(T()); // rvalue, compiles fine.

T data;
list.Add(data); // lvalue, does not compile.

In the case of std::vector this is solved by having a push_back(const T& object) overload.
However, since the code in my Add function is quite complex, I didn't want to copy it over.

However, if I am to templatize my add function, it does become universal reference. So I came up with the following code.

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

template <class T>
class Container
{
    public:
    template <class UR = T>
    void Add(UR&& object)
    {
        static_assert(std::is_same<std::remove_cv_t<std::remove_reference_t<UR>>, T>::value, "UR and T should be the same!");
        m_Vector.push_back(std::forward<UR>(object));
    }
    std::vector<T> m_Vector;
};

class Data
{
    public:
    int x;
    int y;
};

int main() {
    Container<Data> list;
    Data d;
    list.Add(d);
    return 0;
}

I've added the static assert to make sure that people do not actually templatize the Add function. Does anyone know a cleaner solution, since this feels a bit of template magic? Should I follow the std method and just copy my add function (which is a bit more complex than this minimal example)? Can anyone come up with a case where my solution will not work?

Here is a small ideone version for you to play around with.

Your solution is principally correct. If you want to play nice with potential generic traits (at the cost of a potentially uglier error message), you'd replace the static_assert with SFINAE:

template <
    class UR = T,
    class TypeMustBeT = std::enable_if_t<std::is_same<std::remove_reference_t<UR>, T>::value>
>
void Add(UR&& object)
{
    m_Vector.push_back(std::forward<UR>(object));
}

This way, the function Add will not exist at all when UR is not a forwarding reference for T1.

If you don't like the "template magic" involved in this and/or the compiler errors generated from misuse, you can solve this by providing the two strongly-typed overloads as std does and forward to a common private implementation:

void Add(const T& object)
{
  AddImpl(object);
}

void Add(T&& object)
{
  AddImpl(std::move(object));
}

private:
template <class UR>
void AddImpl(UR&& object)
{
    static_assert(std::is_same<std::remove_cv_t<std::remove_reference_t<UR>>, T>::value, "UR and T should be the same!");
    m_Vector.push_back(std::forward<UR>(object));
}

This way, you can keep the static_assert-using version and keep the static assertion just to check your code's correctness, not the client code's.

Note that the static_assert needs to do std::remove_cv after std::remove_reference, otherwise it will fail for UR = const T&. The same applies to the original code in the question too.

Unrelated to the question at hand, but I assume using namespace std; is for this reduced example only and is not present in your real code. It's very bad practice to put that into header files in real code.

1 Note that "forwarding reference" is the preferred term instead of "universal reference," since it captures the semantics better.


"String" contains function in C This function checks whether or not a substring needle exists in another string haystack and returns the position if it does or 0 if it doesn't, unless the position is 0 in which case, it won't be located.

Looking for ways to improve this code, specifically better error handling.

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

size_t contains(const char * needle, const char *haystack);

int main(void)
{
    char *needle = "test";
    char *haystack = "This is a dinosaurtest.";
    printf("Position: %lu", contains(needle, haystack));

    return EXIT_SUCCESS;
}

size_t contains(const char * needle, const char *haystack)
{
    if(needle == NULL || haystack == NULL)
    {
        return 0;
    }
    long int first_char_pos = -1;
    size_t len_h = strlen(haystack);
    size_t len_n = strlen(needle);
    size_t i, j;
    size_t exist_count = 0;

    // Find the first character. If it doesn't exist, we're done.
    for(i = 0; i < len_h; i++)
    {
            if((haystack[i] == needle[0]) && (first_char_pos == -1))
            {
                first_char_pos = i;
                exist_count++;
            }
    }

    if(first_char_pos == -1)
    {
        return 0;
    }
    printf("First char match index: %li\n", first_char_pos);
    printf("Char: %c\n", haystack[first_char_pos]);
    size_t current_index = (size_t) first_char_pos;
    for(i = first_char_pos; i < len_h; i++)
    {
        if(haystack[i] == needle[exist_count] && (i == (current_index + 1)))
        {
            current_index = i;
            exist_count++;
        }
        printf("Exist count: %lu\n", exist_count); //<--Debugging
        if(exist_count == len_n)
        {
            return first_char_pos;
        }
    }
    return 0;
}

Just a couple of remarks:

You should add a newline after the last line:

  $ ./nh
  First char match index: 18
  Char: t
  Exist count: 1
  Exist count: 2
  Exist count: 3
  Exist count: 4
  Position: 18 $

I don't know what compiler you use but with when compiled with gcc and -Wall -Wextra -pedantic you get:

gcc -O2 nh.c -lm -o nh -Wall -Wextra -pedantic
nh.c: In function ‘contains’:
nh.c:25:15: warning: unused variable ‘j’ [-Wunused-variable]
 size_t i, j;
           ^

Code formatting should be more consistent. For example, in this line you put a whitespace before needle but don't put a whitespace before haystack:

size_t contains(const char * needle, const char *haystack);

%lu is not a portable specifier for size_t type, you should use %zu introduced in C99.
You said:

  returns the position if it does or 0 if it doesn't, unless the
  position is 0 in which case, it won't be located.

This is really not good. For example, with this it returns 0:

char *needle = "This";
char *haystack = "This is a dinosaurtest.";

With this, it also returns zero:

char *needle = "non-existent";
char *haystack = "This is a dinosaurtest.";

You can't tell the difference between success and failure in this two
examples. Actually, atoi() has the same problem. I don't know what
operating system you use but maybe you could use ssize_t as the
return type if it's available and return -1 in case of failure.


Get the next date based on a collection of valid weekdays public static DateTime NextByDayOfWeek(this DateTime target, IEnumerable<DayOfWeek> validDaysOfWeek)
{
    validDaysOfWeek = validDaysOfWeek
        .OrderBy(item => item);

    var nextDayOfWeek = validDaysOfWeek
        .Where(item => item > target.DayOfWeek)
        .FirstOrDefault();

    return nextDayOfWeek != 0
        ? target.AddDays(nextDayOfWeek - target.DayOfWeek)
        : target.AddDays((validDaysOfWeek.First() + 7) - target.DayOfWeek);
}

Usage:

DateTime.Today.NextByDayOfWeek(new[] { DayOfWeek.Monday, DayOfWeek.Friday })

I don't think there are any possible edge cases here, at least some initial tests don't reveal any problem.

I think it's short and readable, but readability is often hard to judge when you're the author.

Any remarks?

You can just step forward one day at a time, until you find a week day that is valid. If you change the second parameter to a params parameter, as svick suggested, the code gets very straight forward:

public static DateTime NextByDayOfWeek(this DateTime target, params DayOfWeek[] validDaysOfWeek) {
  do {
    target = target.AddDays(1);
  } while (!validDaysOfWeek.Contains(target.DayOfWeek));
  return target;
}

You can also make a bitmask out of the valid days, so that you don't have to use the Contains method, which would loop through the collection of valid days for each iteration:

public static DateTime NextByDayOfWeek(this DateTime target, IEnumerable<DayOfWeek> validDaysOfWeek) {
  int valid = 0;
  foreach (DayOfWeek d in validDaysOfWeek) {
    valid |= 1 << (int)d;
  }
  do {
    target = target.AddDays(1);
  } while ((valid & 1 << (int)target.DayOfWeek) == 0);
  return target;
}

I tested both these functions with a range of different values, and they seem to give the correct result in all cases.


URL link SEO and security using Laravel I'm trying to figure out what the best way to do this is.

I have a part on my website where people can search for a particular card based on multiple different factors. Like the name of the card, color, cost, etc. When the user types in the criteria, I send the information via ajax GET. So the url looks something like this:

http://sitename.dev/search?query=asdf&color=red&etc=

The good thing is, the above provides a url so the user can easily copy paste and share the results with friends. The not so good part is, it's not so good for search engine optimization.

First question: How do I make these type of links good for SEO and is this secure? It seems like it would be easy to inject code?

Second question:

After getting the corresponding input from the user, I have the following in my SearchController to deal with the input:

public function postSearchResults() {
        $searchStr = Input::get('query');
        $color = Input::get('color');
        $etc = Input::get('etc');

        $query = DB::connection('mysql')->table('cards')
            ->where('name', 'LIKE', '%'.$searchStr.'%')
            ->where('color', 'LIKE', '%'.$color.'%')
            ->where('etc', 'LIKE', '%'.$etc.'%')
            ->get();

        return parent::ajaxView('results', compact('query'));
}

Is the above secure or is there something I should do in addition to make it secure?

First question: How do I make these type of links good for SEO

I can't confidently say that it's bad in its current state as I'm not too clued up on SEO, see this link for some more info https://webmasters.stackexchange.com/questions/15393/is-a-url-with-a-query-string-better-or-worse-for-seo-then-one-without-one

I'm guessing if you wanted to make it somewhat more human and or seo friendly you can set your route up as so:

Route::get('{search}/{color}/{etc}', [
  'uses' => 'SearchController@postSearchResults'
]);

Then you'd need to add some parameters to the controller:

public function postSearchResults($search, $color, $etc) {

        $query = DB::connection('mysql')->table('cards')
            ->where('name', 'LIKE', '%'.$search.'%')
            ->where('color', 'LIKE', '%'.$color.'%')
            ->where('etc', 'LIKE', '%'.$etc.'%')
            ->get();

        return parent::ajaxView('results', compact('query'));
}

Note: you may want to change your method name to getSearchResults() instead of postSearchResults(), as you are using the GET ajax method when calling the route, right?

and is this secure? It seems like it would be easy to inject code?

From the Laravel Documentation: http://laravel.com/docs/5.0/queries#introduction

  Note: The Laravel query builder uses PDO parameter binding throughout
  to protect your application against SQL injection attacks. There is no
  need to clean strings being passed as bindings.

Second question: After getting the corresponding input from the user, I have the following in my SearchController to deal with the input:

... your code

Is the above secure or is there something I should do in addition to make it secure?

I'd like to think it's pretty secure based on what is aforementioned regarding how the query builder works.

Finally, don't consider this a complete answer. I'd definitely do some more digging around or maybe someone with more knowledge will come and post another answer! All the best!


Finding the number of vowels in a string I'm new to Java and is trying to solve the beginners problem of finding out the number of vowels in a string. I was just wondering if there is any alternatives to any of the steps that can improve efficiency as well as simplicity.

import java.util.Arrays;
import java.util.Scanner;

public class CountVowels{

    public static void main(String[] args) {
        Scanner sc1 = new Scanner(System.in);
        String userInput = sc1.next();
        sc1.close();
        CountVowels cv1 = new CountVowels();
        int numberOfVowels = cv1.countingVowels(userInput);
        System.out.println(numberOfVowels);
    }

    public int countingVowels(String s1){
        String lowerCaseString = s1.toLowerCase();
        int vowelCount = 0;
        for (int i = 0; i < lowerCaseString.length(); ++i){
            Character charCharacter = lowerCaseString.charAt(i);
            char[] vowels = {'a', 'e', 'i', 'o', 'u'};
            if(Arrays.binarySearch(vowels, charCharacter) >= 0){
                vowelCount += 1;
            }
        }
        return vowelCount;
    }
}

Outline

In this case, instantiating a new CountVowels() is overkill.  all you need is a function.

As a rule, classes should be named as nouns.  A better name for the class would be VowelCounter.

public class VowelCounter {
    public static int vowelCount(String s) {
        …
    }

    public static void main(String[] args) {
        …
        System.out.println(vowelCount(userInput));
    }
}

Implementation

Your countingVowels() function is fine, but could be simpler.

public static int vowelCount(String s) {
    int count = 0;
    for (char c : s.toLowerCase().toCharArray()) {
        if ("aeiou".indexOf(c) >= 0) {
            count++;
        }
    }
    return count;
}

Specifically, note:

Using an enhanced for loop is less tedious than a counting loop.
Avoid boxed types such as Character, when a primitive char will do.
For such a short array, a binary search is overkill.

Your main() is also OK, but I would write it this way:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        String userInput = scanner.next();
        System.out.println(vowelCount(userInput));
    }
}

In particular:

A Scanner is AutoCloseable, so a try-with-resources block is tidier than calling close() on it manually.
There doesn't seem to be much point in the …1 suffix on your variable names sc1, cv1, and s1.


Maximum sub array sum equal to k Given an array of integers and an integer k, you need to find the
  total number of continuous subarrays whose sum equals to k.

  For example:

  Input: nums = [1,1,1], k = 2

  Output: 2

  The length of the array is in range [1, 20,000]. The range of numbers
  in the array is [-1000, 1000] and the range of the integer k is [-1e7,
  1e7].

I came up with the following solution, which fails for a list with a 10,000 elements due to maximum recursion depth.

What changes can I make in the following code to improve it? Also, I am learning to use recursion, so what best practices can I employ for problems of this kind?

class Solution(object):
    def subarraySum(self, nums, k):  #driver method
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k==0:
            return 0
        return self.func2(0,nums,k,[],0)

    def func2(self,index,nums, k, path, cnt):
        """
        index= index of the array
        nums=input array
        k=sum
        path=elements seen so far in contiguous manner whose sum is less than or equal to k
        cnt=counter of no of subarrays found so far
        """
        if index==len(nums):
            return cnt
        if nums[index]+sum(path)<k: #if total sum is less than k
            path.append(nums[index])
            cnt=self.func2(index+1,nums,k,path, cnt)
        elif nums[index]+sum(path)==k: #if total sum is equal to k
            path.append(nums[index])
            path=path[1:]
            cnt+=1
            cnt=self.func2(index+1,nums,k,path,cnt)
        else: #if total sum > k
            path=path[1:]
            if len(path)>0:
                cnt=self.func2(index,nums,k,path,cnt)
            else:
                cnt=self.func2(index+1,nums,k,path,cnt)
        return cnt

What you implemented is different from what you were asked. Both the numbers in the array as well as k can be positive and negative, while it seems like you assumed both are strictly positive.

Even if you made those assumptions, it still doesn't produce the desired output. For example, if your list of numbers were 5,10,2,4 and your sum is 12, then your subroutine would return 0 when it should return 1.


setjmp and longjmp implementation in mmix I've written an implementation of setjmp and longjmp in MMIX (assuming no name mangling).
I also hand-assembled it.
Are there any mistakes anyone can spot?
    // Memory stack pointer is stored in $254.
    // jmp_buf is rO, next address after setjmp call, memory stack pointer,
    // frame pointer, then possibly other data (for sigsetjmp/siglongjmp).
    // rG is preserved over a longjmp call
    // (not that it should change over one, anyway)
setjmp IS @
    GET    $1,rO            // FE01000A
    STOU   $1,$0,0          // AF010000
    GET    $1,rJ            // FE010004
    STOU   $1,$0,8          // AF010008
    STOU   $254,$0,16       // AFFE0010
    STOU   $253,$0,24       // AFFE0018
    POP    0,0              // F8000000
longjmp IS @
    LDOU   $254,$0,0        // 8FFE0000
    SAVE   $255,0           // FAFF0000
    GET    $1,rG            // FE000013
    // why 15? We save 13 special registers, two local registers,
    // and the number 2, as well as any global registers.
    // That's 256-rG + 16, and we add only 15 because $255 is the address
    // of the saved rGA.
    SETL   $0,271           // E300010F
    SUBU   $1,$1,$0         // 26010100
    SLU    $1,$1,3          // 39000003
    // now $255 is topmost saved register, $255+$1 is bottommost such,
    // $254 is rO after.
    SUBU   $0,$254,$1       // 2600FE01
    LDOU   $2,$255,$1       // 8E02FF01
    STOU   $2,$0,$1         // AE020001
    INCL   $1,8             // E7010008
    PBNZ   $1,@-12          // 5B01FFFD
    SET    $255,$0          // C1FF0000
    UNSAVE 0,$255           // FB0000FF
    // now we have restored rO, but not other stuff
    LDOU   $253,$0,24       // 8FFD0018
    LDOU   $254,$0,16       // 8FFE0010
    LDOU   $0,$0,8          // 8F000008
    PUT    rJ,$0            // F6040000
    POP    2,0              // F8020000

The register stack was the hard part here. Everything between the SAVE and the UNSAVE inclusive is essentially just “set register stack pointer properly”; after that it takes no time at all to fix up the other registers and return.
If you have any other questions, I'm happy to explain my reasons for each tetra of that code.

Looks like your setjmp takes the jmp_buf parameter as $0 - but how is jmp_buf defined - how much space does it need for example?
Also longjmp takes 2 parameters - the same jmp_buf and an int - I don't see $1 being used for the second input parameter in your longjmp
You can find commandline tools to run MMIX programs at https://mmix.cs.hm.edu/exe to try out your implementation - there's a Windows GUI debugger too - could you show sample MMIX code that calls your setjmp and longjmp?


DoublingQueue in Java Inspired by this CR question, I decided to create my own queue! If you guys see anything taboo or have any improvements, please let me know. Ultimately I want it to be feature rich and bug free, with every possible case tested, so if there's anything else that can be added (like an iterator) and thoroughly tested, please mention it.

IDoublingQueue.java

public interface IDoublingQueue<E> {
    public boolean isEmpty();
    public int size();

    public void enqueue(E item);
    public E dequeue();
}

DoublingQueue.java

public class DoublingQueue<E> implements IDoublingQueue<E> {

    private E[] queue;
    private int size = 0;
    private int first = 0;

    public DoublingQueue() {
        queue = (E[]) new Object[2];
    }

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

    @Override
    public int size() {
        return size;
    }

    private void resize(int max) {
        assert max >= size;

        E[] temp = (E[]) new Object[max];

        for (int i = 0; i < size; ++i) {
            temp[i] = queue[(first + i) % queue.length];
        }

        queue = temp;
        first = 0;
    }

    @Override
    public void enqueue(E item) {
        // be sure no null items make it into the queue
        if (item == null) {
            throw new IllegalArgumentException("ERROR: Null elements cannot be inserted!");
        }

        if (size == queue.length) {
            resize(2 * queue.length);
        }

        queue[size++] = item;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("ERROR: Queue underflow");
        }

        E item = queue[first];

        queue[first] = null;
        size--;
        first++;

        if (first == queue.length) {
            first = 0;
        }

        // shrink the queue if necessary
        if (size > 0 && size == queue.length / 4) {
            resize(queue.length / 2);
        }

        return item;
    }
}

Tests

public class DoublingQueueTest {

    private final DoublingQueue<Integer> queue = new DoublingQueue();

    @Test(expected = IllegalArgumentException.class)
    public void enqueueNullTest() {
        queue.enqueue(null);
    }

    @Test(expected = RuntimeException.class)
    public void dequeueEmptyTest() {
        queue.dequeue();
    }

    @Test
    public void enqueueTest() {
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);

        assertTrue(queue.size() == 3);
    }

    @Test
    public void dequeueTest() {
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);

        int num = queue.dequeue();

        assertTrue(num == 1);
    }
}

Edit:
As coderodde excellently pointed out in his answer, your implementation has the issue of not reusing previous entries in the array that have already been dequeued. This means that your array will always keep on growing in size. See his answer for an explanation on this.

First of all, good job on improving your coding skills through an exercise like this. More people should be doing this. Now lets get into the criticism from which you will hopefully learn even more.

Constructor

It's strange that you do not allow the user to specificy the initial size of the queue. Even if this were to be a design choice, I think 2 is too low of a value. Also the magic number 2 should be moved to a constant like DEFAULT_QUEUE_SIZE to increase readability and maintainability.

Size

Your size variable is quite confusing. For a while I thought it was the current size of the queue, meaning it would start at 2 and then double over time. But later I found out that it actually represents the amount of items currently in the queue. I think that this might also be confusing to anyone calling your size() method.

isFull()

In your enqueue() method you check size == queue.length. This is essentially the isFull() method. Replacing this with a call to isFull() would not only increase the readability of your enqueue() method, but also add the isFull()method to the public API of your class, fulfilling the symmetry with isEmpty().

resize()

To improve coherence and readability, I would add two methods called doubleSize()and halfSize(), which would simply then call the resize() method with the correct parameters. This improves the readability and intentions in the enqueue() and dequeue() method and allows the explanatory comment // shrink the queue if necessary to be removed.

Comments

There are a lot of opinions about comments. I share mine with Robert C. Martin in that they show a failure of expressing yourself by means of code. The comment I mentioned in the section above about the resize() method is a good example of that.

The other comment in your code, // be sure no null items make it into the queue, can also be removed, because the code below it is perfectly clear. It is simply a duplication of information, and just as duplication of code is bad, this kind of duplication is bad as well. This is because comments tend to get out of sync with the code they were intended to enlighten.

Interface

Personally, I do not see the use of an interface for this implementation. I think it is merely clutter as it provides no additional information that the concrete class itself does not already provide.

Testing

There is a lot that could be improved in the testing department here. I will try to create a somewhat short, comprehensive list of the things that I think are missing or incorrect. You will find that most of the things I say about testing have also been said in the Code Review question that inspired you, so perhaps you should also read through the accepted answer there on testing.

Your enqueueTest function is testing size() functionality.
Your test function names are not very descriptive about the situation that is being tested and what the expected outcome should be. There is a small blogpost by Google on test function names that might be useful to read.

Test ALL the things.

You are not even scratching the surface of having all scenarios tested.

Are you sure that dequeue() actually halves the queue size when it can? You shouldn't be, because you haven't tested it.
isEmpty() is not even tested once. What happens when isEmpty() is called when the queue is empty, filled or full? Or full and then emptied again. All of these scenarios should be tested.
Your test for the size() method is way too simplistic. Does size() return 0 if the queue is empty? does it return the correct amount after enqueueing X items and dequeueing Y items? Does it return the correct amount after doubling and halving the queue X amount of times?
You should also test the FIFO (First In First Out) concept of your queue more elaborately. You started with it in dequeueTest(), but kept it way too simple.

Test examples

In this section I will provide some example tests for only the method isEmpty() to illustrate my points above.

@Test
public void testIsEmptyReturnsTrueWhenQueueIsEmpty() {
    assertTrue(queue.isEmpty());
}

@Test
public void testIsEmptyReturnsFalseWhenQueueIsFilled() {
    queue.enqueue(1);
    assertFalse(queue.isEmpty());
}

@Test
public void testIsEmptyReturnsFalseWhenQueueIsFull() {
    // Since your magic starting queue size number
    // is 2 I enqueue two items.
    queue.enqueue(1);
    queue.enqueue(2);

    assertFalse(queue.isEmpty());
}

@Test
public void testIsEmptyReturnsTrueWhenQueueIsEmptiedAfterUse() {
    for (int i = 0; i < 10; i++) queue.enqueue(i);
    for (int i = 0; i < 10; i++) queue.dequeue();

    assertTrue(queue.isEmpty());

    // This second part is debatable since you generally want
    // to test only one thing per test.
    for (int i = 0; i < 10; i++) {
        queue.enqueue(i);
        queue.dequeue();
    }

    assertTrue(queue.isEmpty());
}


Mutex Protected Object (scoped object wrapper) This is a class that holds mutex and associated object. On checkout/access the mutex is locked while the stack object lives and a reference to object is obtained. Any suggestions or improvements is welcomed.

#include <mutex>

template<class T>
class MutexProtectedObject {
  //this relies on benign use and it is just a helper rather than a foolproof solution - ie. anyone may still save a pointer to obj etc. and access it later
public:
  class Access {
  public:
    Access(std::mutex& m, T& obj) : sl_(m), obj_(obj) {
    }
    T& obj_;
  private:
    std::scoped_lock<std::mutex> sl_;//mutex is locked here (by RAII)
  };

  Access access() {
    return Access(mutex, obj);
  }

  MutexProtectedObject(const MutexProtectedObject&) = delete;
  MutexProtectedObject& opreator=(const MutexProtectedObject&) = delete;

private:
  std::mutex mutex;
  T obj;
};

Access

I don't like the fact that Access gives you a reference to the object directly. This leads to issues with somebody accidentally keeping a reference to the object after the Accesses object is destroyed or accidentally making a copy of the object.

T&  myRef = wrapped.access().obj_;   // Now I have a reference to the object
                                     // But the Accesses object is gone.

myRef.doStuffWithNoLock();

// or

T   myCopy = wrapped.access().obj_;  // I made a copy of the object.

How about Access delegating all accesses via operator ->? That way you don't leak the object to external code.

class Access
{
    public:
        T* operator->() {return &obj_;}
    private:
        T&  obj_;
};

Now you can use Access like it was a T*:

auto foo = wrapper.access();
foo->fun1(args);
foo->fun2(args);

Initializer list

The order of initialization of members is the order of declaration. If you define the order deferently in the initializer list this can be confusing (most compilers will warn you about it).

class Access {
    public:
    Access(std::mutex& m, T& obj)
        : sl_(m)             // This is not the order they are
        , obj_(obj)          // initialized in. The obj_ will be done first
    {}

    T& obj_;

    private:
    std::scoped_lock<std::mutex> sl_;//mutex is locked here (by RAII)
};

Best practice is to keep the initializer list in the same order as the declaration order in the class.


Codility: An activity selection problem about scheduling two enemies to watch movies at a festival I don't remember the exact wording of the question, but it is clearly an activity selection problem, which is

  [...] notable in that using a greedy algorithm to find a solution will always result in an optimal solution.

I put a rough description of the problem in the docstring, and present it together with my solution:

def solution(movies, K, L):
    """
    Given two integers K and L, and a list movies where the value at the ith index
    represents the number of movies showing on the (i + 1)th day at the festival, returns
    the maximum number of movies that can be watched in two non-overlapping periods of K and
    L days, or -1 if no two such periods exist.
    """
    kl_days = [
        sum(movies[k_start:k_start + K] + movies[l_start:l_start + L])
        for k_start in range(len(movies) - K)
        for l_start in range(k_start + K, len(movies) - L + 1)
    ]
    lk_days = [
        sum(movies[k_start:k_start + K] + movies[l_start:l_start + L])
        for l_start in range(len(movies) - L)
        for k_start in range(l_start + L, len(movies) - K + 1)
    ]
    days = [-1] + kl_days + lk_days
    return max(days)

Is there a more elegant way to solve this?

P.S. The function name is fixed for grading purposes.

Your code is probably around the best it can be performance wise. And so there's not much point splitting hairs finding anything better.

However you should be able to find something that uses less memory. Something about \$O(L + K)\$ rather than \$O(M^2)\$
I'd split finding indexes, and sums into two separate functions.
Your code, to me, looks slightly wrong.

range(l_start + L, len(movies) - K + 1)

Should probably be:

range(l_start + L, len(movies) - K)

Finally I'd split your code into two more functions, one that performs the sum, and then one that performs the max.

And so I'd change your code to:

def _solution_indexes(movies, K, L):
    for k in range(movies - K):
        for l in range(k + K, movies - L):
            yield k, l

    for l in range(movies - L):
        for k in range(l + L, movies - K):
            yield k, l

def solution_(movies, K, L):
    for k, l in _solution_indexes(len(movies), K, L):
        yield sum(movies[k:k + K]) + sum(movies[l:l + L])

def solution(movies, K, L):
    return max(solution_(movies, K, L), default=-1)


Longest Substring Without Repeating Characters in Scala Question is taken from Leetcode and solution works for their test cases. I do see a scope of improvement and make it more functional (getting rid of vars and mutables data structures). Please suggest improvement to help me.

Problem

Given a string, find the length of the longest substring without repeating characters.

Input: "abcabcbb"
Output: 3

Input: "bbbbb"
Output: 1

Input: "pwwkew"
Output: 3

code

import scala.collection.mutable.HashMap

object Solution extends App{

    def lengthOfLongestSubstring(s: String): Int = {
      if (s.isEmpty) 0
      else {
      val lookupTable = HashMap[Char,Int]()
      var start = 0
      var length = 0
      for ( (c, i) <- s.zipWithIndex) {
        if (!(lookupTable contains c)) {
          lookupTable(c) = i
        } else {
          val newLength = i - start
          if (newLength > length) length = newLength
          start = lookupTable(c) + 1
          lookupTable.retain((k,v) => v >= start)
          lookupTable(c) = i
        }
      }
      Math.max(length, (s.length - start))
    }
  }
    Seq("abcabcbb", "pwwkew", "", "nnnn", "b", "  ", "aab" , "abca" ,"abba") foreach { s =>
      println(s + " = " + lengthOfLongestSubstring(s))
    }
}

Output

abcabcbb = 3
pwwkew = 3
 = 0
nnnn = 1
b = 1
   = 1
aab = 2
abca = 3
abba = 2

Some observations while looking over the code:

if (s.isEmpty) 0 - This isn't necessary. The code produces the correct results without this test. Removing it would reduce the level of indenting for the rest of the code.
if (!(lookupTable contains c)) - Dijkstra suggests that it is usually better to test for the positive condition, especially when there is an else block. It's often much easier to read and parse that way. In this case the else condition is "NOT table has c == false". (Ouch!)
val newLength - You actually don't need this variable. Try:length = length max i - start
lookupTable(c) = i - This assignment is made on both sides of the if test, which means it really doesn't belong there.

if (lookupTable contains c) {
  length = length max i - start
  start = lookupTable(c) + 1
  lookupTable.retain((k,v) => v >= start)
}
lookupTable(c) = i

But, of course, the most noteworthy is the use of mutable variables and data structures. Sometimes we have to fall back on imperative programming if functional means/methods are creating a bottleneck, but, short of that, the point of learning/using Scala is its Functional Programming capability.

Here's a reworking of the same algorithm using two index values to access a static array of characters. Each index is advanced via tail-recursive methods so everything remains immutable.

def lengthOfMaxSubstring(s: String): Int = {
  val chars: Array[Char] = s.toArray

  def headForward(leadx: Int, rearx: Int, cSet: Set[Char], best: Int): Int = {

    def tailForward(tlx: Int, cs: Set[Char]): (Int, Set[Char]) =
      if (chars(tlx) == chars(leadx)) (tlx + 1, cs)
      else tailForward(tlx + 1, cs - chars(tlx))

    if (leadx >= chars.length) best max leadx-rearx
    else if (cSet(chars(leadx))) {
      val (newTail, newSet) = tailForward(rearx, cSet)
      headForward(leadx+1, newTail, newSet, best max leadx-rearx)
    } else
      headForward(leadx+1, rearx, cSet + chars(leadx), best)
  }
  headForward(0, 0, Set(), 0)
}


Link to a parent object I have a couple of nested objects, where A is always a part of B.

May I use the following code to access owner's properties and methods?

function A( owner ) {
  this.value = function () { return owner.value() + 1 };
}

function B() {
  this.value = function () { return 1; };
  this.a = new A( this );
}

var b = new B();
alert( b.a.value() );

Actually, it works. But I would like to know whether it is correct or not.

Actually, it works. But I would like to know whether it is correct or
  not.

It works because you create new instance of parent and access it there:

this.a = new A( this );

The correct way (for inheritence) is to set child's prototype and constructor:

A.prototype = new B();
A.prototype.constructor = A;

For more explanation, have a look at this question.


(REALLY) simple neural network program This is a simple program to create neural networks. It only includes weighting of connections and activation values for the neurons. It doesn't include any learning feature of any kind, and it is really just a first attempt at creating something resembling a neural network.

Main.java

package uniliniarnetwork;

public class Main {

public static void main(String[] args) {
    Neuron inputNode = new Neuron(0,1,"InputNode",1);

    Neuron hiddenNode_One = new Neuron(0.5f,0.9f,"HiddenNode_One",1);
    Neuron hiddenNode_Two = new Neuron(0.5f,0.9f,"HiddenNode_Two",1);
    Neuron hiddenNode_Three = new Neuron(0.5f,0.9f,"HiddenNode_Three",1);

    Neuron outputNode = new Neuron(0,0.9f,"OutputNode",3);

    inputNode.connect(hiddenNode_One);
    inputNode.connect(hiddenNode_Two);
    inputNode.connect(hiddenNode_Three);

    hiddenNode_One.connect(outputNode);
    hiddenNode_Two.connect(outputNode);
    hiddenNode_Three.connect(outputNode);

    inputNode.input(1);
}

}

Neuron.java

package uniliniarnetwork;

import java.util.ArrayList;

public class Neuron {
private float activationValue, weight;
private String neuronName;
private ArrayList<Neuron> outputs = new ArrayList<Neuron>();
private float[] inputs;
int inputCounter = 0, nInputs;

public Neuron(float activationValue, float weight, String neuronName, int nInputs){
    this.activationValue = activationValue;
    this.weight = weight;
    this.neuronName = neuronName;
    this.nInputs = nInputs;

    inputs = new float[nInputs];
}

public void connect(Neuron neuron){
    outputs.add(neuron);
}

public void input(float inputValue){
    inputs[inputCounter] = inputValue;
    inputCounter++;

    if(inputCounter == nInputs){
        fire();
    }
}

public void fire(){
    float sum = 0;
    for(int i = 0; i < nInputs; i++){
        sum+=inputs[i];
    }

    float signal = sum*weight;

    if(signal > activationValue){
        for(int i = 0; i < outputs.size(); i++){
            outputs.get(i).input(signal);
        }
    } else{
        for(int i = 0; i < outputs.size(); i++){
            outputs.get(i).input(0);
        }
    }
    System.out.println(neuronName + ":" + signal);
}
}

Basically main creates Neuron objects from the Neuron class which have an activationValue and a weight value. I know it's not perfect and it doesn't include most of the most important features of a neural network.

My question is whether this is a good place to build from towards more advanced neural networks, for example those which can classify images. It would be greatly appreciated if you could explain in terms a high-school student (with only a rudimentary understanding of calculus) would understand.

I'm not really into Neural Networks, but I do read code and I do have some suggesting for what to do next related to this code.

Code and Style Comments

Number in variable names, not good – Even though you spelt out the number, still having numbers in a variable names indicates that you might be doing something wrong. I'm thinking of the hiddenNode_One& co.
Please fix your indentation – This excerpt is taken directly from your code:

public class Neuron {
private float activationValue, weight;
private String neuronName;
private ArrayList<Neuron> outputs = new ArrayList<Neuron>();
private float[] inputs;
int inputCounter = 0, nInputs;

public Neuron(float activationValue, float weight, String neuronName, int nInputs){
    this.activationValue = activationValue;

This looks like a list of variable declaraction outside of classes and methods, and only with a second look it's possible to see that you are actually declaring a class Neuron, its class variables, and a class constructor of public Neutron(). And finally you indent for the method definition.  Here is the same code with better indentation:

public class Neuron {
    private float activationValue, weight;
    private String neuronName;
    private ArrayList<Neuron> outputs = new ArrayList<Neuron>();
    private float[] inputs;
    int inputCounter = 0, nInputs;

    public Neuron(float activationValue, float weight, String neuronName, int nInputs){
        this.activationValue = activationValue;

This looks a lot better, and it's easier to follow the program flow.
Is it wise to lock the number of inputs? – In your constructor you lock the number of inputs for any given Neuron, which might lead to confusing situations later on if you want to reorder your network.
Feature: To many input()'s will trigger index error – Since you keep increasing the inputCounter whenever this method is called, you'll run out of array elements to update, and will finally trigger an index error.

In the same code, you'll only fire() once when the inputCounter exactly equals the preset number of inputs. So if the input of a Neuron changes afterwards, the network is never updated. Neither of these seems to be correct.
Always generate input() even when not over the activation value? – In light of preceding point, it seems kind of strange to do the input(0) sequence, as that might for some networks trigger the index error before it should. Wouldn't it be better to leave out the no input part?

That is, unless that is a requirement due to the value swapping from over and under the activationValue during the lifetime of the network, in which case you really need to address the case of connecting inputs to the Neuron receiving the input.
Why delay the summation of inputs, and the signal value – In my mind it would be better to update a sum and the signal value whenever receiving an input, instead of when doing the fire().

Imaging having a network of thousands of nodes, and you having to calculate this for each fire event you trigger, even though the input possibly didn't change?  To me it makes more sense to do this within the input() having a sum variable, and to have a class variable (or method) holding (or returning) the sum * weight.

Do however know that this would require proper knowledge of which input is being updated, so that if you receive a secondary input on that Neuron you'll correctly adjust the sum, and not blatantly keep adding the new value.
Order of calculation and output – Most likely your System.out.println(neuronName + ":" + signal) should be replaced with a call to some logger, but I would also put this one in front of the signal > activationValue loops. As it is in a bigger network you would get the output of the latter nodes, before the first nodes. For the output to make sense, it would be wiser to have the output directly after the calculation of signal.

Some General Thoughts on Neural Networks

In my mind a neural network is something dynamic, which could/should easily be able to change and reconnect towards other neurons (or nodes). So here are some concerns I have related to your code:

No visualization of the neural network – It's not possible to visualize your network. I think it would've been nice to have a way to visualize it, so that you can see how it is connected with which triggers and so on.
No connection of the input towards the neurons – There is no connection between the neurons connected to another neuron and the input. In other words, if the hiddenNode_Two decides to change its input, and thusly it fires an output, you don't have a way to know which of the inputs of the outputNode actually changed. This doesn't seem correct.
No dynamic in neuron connection – You've got no methods to remove and change your network. In addition you've limited the neuron at construction time to a given set of inputs. Thusly disallowing a re-ordering of your network based on any future learning.

Imaging having a network doing something related to alphabetic calculation. At the start you could start out with a few nodes, but after a while you see the need to split the a-e node as it is overworked. Your code as it stands, would require a full reconstruction, and not a simple replacement of that node with a few extra nodes.

One way to implement this interconnection, and related sums and signal values, could be to introduce a static list of Neurons, and extend each Neuron with dynamic lists of indexes into this list to describe its inputs and outputs.

This would allow for methods identifying all the inputs or outputs, by checking whether the input or output list for a given neuron is empty or not. You could also make static methods traversing based on input nodes describing the paths to new nodes (possibly with circular node connection detection) until you reaches the output nodes.


Powershell remote script execution pattern On a CredSSP enabled server is a .psm1 script file that gets executed remotely from a client technology.  The client passes in a couple execution parameters and the server script returns an object back to the client.
This works great but the pattern I've implemented feels clunky. Is there room for improvement?

Client code calling remote server script:

$firstStanza=@{
    a = "Mary had"
    b = "a little"
    c = "lamb"
}

$secondStanza=@{
    d = "its fleece"
    e = "was white"
    f = "as snow"
}

$scriptBlock = {
    Param([Parameter(Mandatory=$true)]$param1,[Parameter(Mandatory=$true)]$param2)
    Import-Module C:\CreateNewObject.psm1
    CombineBothStanzas -firstStanza $param1 -secondStanza $param2
}
$bothStanzasCombined = Invoke-Command -ComputerName serverName.internalDomain.com -ScriptBlock $scriptBlock -ArgumentList $firstStanza,$secondStanza
Write-Output $bothStanzasCombined

Contents of remote script on server c:\CreateNewObject.psm1:

function CombineBothStanzas {
    Param([Parameter(Mandatory=$true)]$firstStanza,[Parameter(Mandatory=$true)]$secondStanza)
    return ($firstStanza + $secondStanza).GetEnumerator() | sort -Property name
}

Remote server script operation returns this object to the client:

Name                           Value
----                           -----
a                              Mary had
b                              a little
c                              lamb
d                              its fleece
e                              was white
f                              as snow

A couple of things I see, if it is as simple as you suggest. First is the $using: context, where you can use local variables in remote execution. For example, you could remove the parameters from your scriptblock, and not have to pass arguments to the Invoke-Command call by doing this:

$scriptBlock = {
    Import-Module C:\CreateNewObject.psm1
    CombineBothStanzas -firstStanza $using:firstStanza -secondStanza $using:secondStanza
}

Second is that if your .psm1 file has but one purpose, and that is a singular function, why not just make it a script with parameters? Then you don't have to first import it then execute it.

Contents of remote script on server c:\CreateNewObject.ps1:

Param([Parameter(Mandatory=$true)]$firstStanza,[Parameter(Mandatory=$true)]$secondStanza)
return ($firstStanza + $secondStanza).GetEnumerator() | sort -Property name

Putting both of those into use, you end up with something like:

$firstStanza=@{
    a = "Mary had"
    b = "a little"
    c = "lamb"
}

$secondStanza=@{
    d = "its fleece"
    e = "was white"
    f = "as snow"
}

$scriptBlock = {
    . C:\CreateNewObject.ps1 -firstStanza $using:firstStanza -secondStanza $using:secondStanza
}

Invoke-Command -ComputerName serverName.internalDomain.com -ScriptBlock $scriptBlock


Extension pattern in a flask controller using importlib I am trying to load a module according to some settings. I have found a working solution but I need a confirmation from an advanced python developer that this solution is the best performance wise as the API endpoint which will use it will be under heavy load.

The idea is to change the working of an endpoint based on parameters from the user and other systems configuration. I am loading the correct handler class based on these settings. The goal is to be able to easily create new handlers without having to modify the code calling the handlers.

This is a working example:

./run.py:

from flask import Flask, abort
import importlib
import handlers

app = Flask(__name__)

@app.route('/')
def api_endpoint():
    try:
        endpoint = "simple" # Custom logic to choose the right handler
        handlerClass = getattr(importlib.import_module('.'+str(endpoint), 'handlers'), 'Handler')
        handler = handlerClass()
    except Exception as e:
        print(e)
        abort(404)

    print(handlerClass, handler, handler.value, handler.name())

    # Handler processing. Not yet implemented

    return "Hello World"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=True)

One "simple" handler example. A handler is a module which needs to define an Handler class:

./handlers/simple.py:

import os

class Handler:
    def __init__(self):
        self.value = os.urandom(5)

    def name(self):
        return "simple"

If I understand correctly, the import is done on each query to the endpoint. It means IO in the filesystem with lookup for the modules, ...

Is it the correct/"pythonic" way to implement this strategy?

The answer so far from the previous Stack Overflow exchange:

  I would whitelist if possible.

I already whitelist when I fill in the endpoint variable with my custom logic.

It does not seem to be a very clean solution. Each handler needs to define an Handler class (same name for different class). I am searching for a cleanest "extension mecanism". How would you clean it up?

Based on @netme answer, this is the 2.0 version

the idea is nice, but I have few concerns.
Firs of all, trying to call importlib every time you are accessing the API endpoint is a bit expensive. It will be a way better if you will introduce some cache first.

You can use 2 approaches to build that cache:

Lazy, where you lookup cache first and if you cannot find the proper handler, you are trying to load it using your trick with importlib
The standard approach where you can use e.g. pkgutil.iter_modules (https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules) and build the handler cache before you are actually start handling the API endpoints.

I have also few notes regarding your code:

Use format functions instead of concatenating strings:

".{}".format(endpoint)

Don't catch general exceptions (just use more specific classes than Exception class) and try not to put more then 1 statement under the try...except block.
Use pythonic naming handlerClass -> handler_class
In your handlers you can make names as read-only properties:

@property
def name(self):
    return "sample"

Try to follow PEP8 in module imports:

# System modules
import importlib

# 3rd party
from flask import Flask, abort

# your modules
import handlers


Singleton class and correct way to access it in C++ I'm currently trying to implement the singleton pattern in C++. After reading about it for a while now, it seems like there are a really large amount of different ways to do this.

Is the way I ended up doing it correct or did I miss out on something important here? Is this implementation thread safe in modern C++ (I read there were some changes to that in particular with C++11)? In addition I am not sure at all about the way I am accessing the class within MyFunction().

Is it really necessary to use a raw pointer there? Does this code contain any memory leaks?

#include <iostream>

class Singleton
{
private:

    Singleton();
    ~Singleton();

public:

    static Singleton& instance()
    {
        static Singleton INSTANCE;
        return INSTANCE;
    }

    void Test();
};

void Singleton::Test()
{
    std::cout << "Test() called" << std::endl;
}

Singleton::Singleton()
{
    std::cout << "CONSTRUCTOR CALLED" << std::endl;
}

Singleton::~Singleton()
{
    std::cout << "DESTRUCTOR CALLED" << std::endl;
}

void MyFunction()
{
    // use the singleton class
    Singleton * MySingleton = &Singleton::instance();
    MySingleton->Test();
}

int main()
{
    MyFunction();
    return 0;
}

Thread safety
Accessing the singleton is thread-safe. The change in C++11 has forced compilers to implement the construction of local static variables (like INSTANCE) in a thread-safe manner.
Note, however, that this doesn't make Singleton thread-safe under all circumstances: If multiple threads are calling Singleton::Test, I wouldn't be surprised to see some garbled output, as access to std::cout isn't synchronized.
Correctness
The current implementation violates the rule of 5: It has a custom destructor, but no custom copy and move constructors and assignment operators. And, to prevent making a copy of the singleton instance (or moving from it!), these 4 special functions should be deleted, like so:
public:
    Singleton(const Singleton&) = delete;
    Singleton(Singleton&&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    Singleton& operator=(Singleton&&) = delete;

Note the public specifier, this ensures that these deletions are visible everywhere needed.
Access
While taking a pointer from the reference returned by Singleton::instance() is a valid use, it seems unnecessary in MyFunction as the pointer isn't required. Why not simply capture by a reference, like so:
auto& MySingleton = Singleton::instance();
MySingleton.Test();

Or if only one call is done:
Singleton::instance().Test();


List querying capabilities in Python 3.x Either out of boredom, or my odd fascination with LINQ and SQL, this, thing, was created. Essentially, it provides list querying capabilities. At the moment, you can only query lists based on conditions, and sort them. Here's the source.

py_listq.py

import operator as oper

class QueryableListCondition:
    """
    A class used for conditions in
    QueryableList.where(*conditions).
    """
    def __init__(self, _operator: str, _value):
        self._operator = _operator.lower()
        self._value = _value
        self._operators = {
            "eq": oper.eq,
            "ne": oper.ne,
            "lt": oper.lt,
            "gt": oper.gt,
            "le": oper.le,
            "ge": oper.ge
        }

    def compare(self, value):
        """
        Compares the values, with value
        as the first compared value. Compari-
        sons look something like this:

            value operator self.value
        """
        return self._operators[self._operator](value, self._value)

    def reverse_compare(self, value):
        """
        Compares the values with self.value
        as the second compared value. Compari-
        sons look something like this:

            value operator self.value
        """
        return self._operators[self._operator](self._value, value)

class QueryableList:
    """
    A special class which is like a
    default Python list, except it
    has querying capabilities.
    """
    def __init__(self, _items: list):
        self._items = _items

    def select(self):
        """
        'Select' self._items and return it as
        a list. This is used in QueryableList.
        where as the first argument.
        """
        return self._items

    def where(self, query_list: list, compare_type: str, *conditions: QueryableListCondition):
        """
        Select elements from a QueryableList
        based on conditions.
        """
        result_list = []
        for condition in conditions:
            for item in self._items:
                if compare_type.lower() == "non-reverse":
                    if condition.compare(item) and item not in result_list:
                        result_list.append(item)
                if compare_type.lower() == "reverse":
                    if condition.reverse_compare(item) and item not in result_list:
                        result_list.append(item)
        return result_list

    def order(self, query_list: list, reverse_results=False):
        """
        Returns a sorted version of the list.
        if reverse=True then the list is
        ordererd in reverse.
        """
        return sorted(query_list, reverse=reverse_results)

Also, for reference, here's a simple example program:

test.py

from py_listq import QueryableList, QueryableListCondition

data = QueryableList([6, 2, 7, 1223, 56, 14, 6, 2435, 234, 6, 2134, 124235, 243621, 74, 378, 3, 45])
result = data.order(
    data.where(
        data.select(),
        "non-reverse",
        QueryableListCondition("gt", 1000)
    ),
    reverse_results=True
)

print(result)

I feel like I shouldn't have implemented this in an Object-Oriented way, and it feels, clunky, to use. So if you have any tips on those, they'd be very much appreciated.

The _operators attribute is not specific to an instance but a common mapping table that can be shared by all instances, so it could be turned into a class attribute instead.

The case of an unsupported operator is not handled. The class happily keys the user create a condition with an unsupported operator, and the program will crash later. Always validate the received function parameters, and signal problems as early as possible.

After the condition is created, there's no need to hold on to the string representation of the operator only to lookup the real operator in the common mapping table. Better to lookup once, in the constructor, and store the real operator, not its string representation.

If a condition has two modes, non-reverse and reverse, consider using a boolean to represent that. Forcing the user to remember to pass on the right magic string is not very user friendly and prone to errors. If you use a boolean, there are 2 possible values, instead of an infinite spacer of invalid values. More intuitive api, and higher chance that users get it right.

These conditions cannot both be true at the same time:

            if compare_type.lower() == "non-reverse":
                # ...
            if compare_type.lower() == "reverse":

So the second one should be an elif. Converting the compare type variable to lower case twice is also not pretty.

I think par of the reason the current implementation feels clunky is that it is not fluent. For example, a fluent api to select a list of name-email pairs from a collection objects, matching a name, ordered by age, look something like this:

queryset.where(name="Jack").order_by("age").select("name", "email")

disclaimer: inspired by queries in Django


Ordinary Data Processing Task in Haskell: Vague Misgivings This is an ordinary data processing task: read a list of dates and amounts (for example, deposits and withdrawals from a bank account) and report the date on which the lowest balance was recorded and what that balance was. While I do get the correct answer--always a virtue--with the code below, I can't help thinking that it could be done better (e.g. more concisely). I've included the preliminary input parsing code so that the whole thing can be compiled and run as is.

module Main where

import Text.ParserCombinators.Parsec
import Data.Time
import Numeric
import Control.Applicative ((<$>), (<*>), (*>))
import Control.Monad.State as CM

--The purpose is to sum up a list of dated values (example: transactions in a bank
--account) and produce the date and amount of the lowest recorded balance.
--For the three lines below, the output would be:
--     DtdBal {runningBal = 4859.96, lowDt = 2013-01-23, lowBal = 4859.96}

--12/1/12,  6844.79
--1/1/13,   992.41
--1/23/13,  -2977.24

data DtdVal = DtdVal { dt :: Day
                     , amt :: Double
                     } deriving Show

data DtdBal = DtdBal { runningBal :: Double
                     , lowDt :: Day
                     , lowBal :: Double
                     } deriving Show

main = do res <- parseFromFile sched "escrow.txt"
          case res of
            Right l -> putStrLn . show $ process l
            Left _ -> error "Oops"
    where process (x:xs) = execState (minBal xs) (initState x)
          initState x = DtdBal { runningBal = amt x, lowDt = dt x, lowBal = amt x }

minBal :: [DtdVal] -> CM.State DtdBal ()
minBal [] = return ()
minBal (x:xs) = do
  rBal <- runningBal <$> get
  lBal <- lowBal <$> get
  lDt  <- lowDt <$> get
  if amt x + rBal < lBal
     then put $ DtdBal { runningBal = rBal + amt x, lowDt = dt x, lowBal = amt x + rBal}
     else put $ DtdBal { runningBal = rBal + amt x, lowDt = lDt, lowBal = lBal }
  minBal xs

sched :: CharParser () [DtdVal]
sched = line `endBy` newline

line :: CharParser () DtdVal
line = DtdVal <$> dts <*> (char ',' >> spaces *> readSgnd)

dts :: CharParser () Day
dts = toDay <$> many digit `sepBy` char '/'
    where toDay [x, y, z] = fromGregorian (2000 + read z) (read x) (read y)

readSgnd :: CharParser () Double
readSgnd = do
  optional (char '+')
  inp <- getInput
  let [(num, inp')] = readSigned readFloat inp
  setInput inp'
  return num

recursive part of minBal is mapM_
multiple get is better to refactor into one
get - process - put part of minBal is modify
state monad is not necessary - you can use plain foldr instead of mapM_ and modify
runningBal is better to implement using scanr. Then zip running balances and source list and foldr the resulting list of tuples
use minimum to find the minimum

Here is a more idiomatic approach to minBal:

runningBal' = scanl1 (+) . map amt

rb l = zip (runningBal' l) l

mb l = minimumBy (compare `on` fst) l

minDay = mb . rb

minBal' l = DtdBal {
    runningBal = fst $ last runningBals,
    lowDt = dt $ snd md,
    lowBal = fst md }
    where
        runningBals = rb l
        md = minDay l

You can inline all the small functions for the final code but that's the order I created them in. Note that rb is calculated twice, but I was not sure if you really need the final balance. In your algorithm it was a byproduct.

main can be rewritten too:

main' = (parseFromFile sched >=> process >=> print) "escrow.txt" where
    process (Right l) = return $ minBal' l
    process (Left _) = error "Oops"

Basically, putStrLn . show is print and composition is your friend. >=> is monadic variant of .. It's advantage over >>= is associativity - it lets you refactor your code more easily.

Here is a shorter version of minBal' which also saves a few calculations, but last is still O(N):

minBal' l = DtdBal {
    runningBal = last runningBals,
    lowDt = dt $ snd md,
    lowBal = fst md }
    where
        md = minimumBy (compare `on` fst) $ zip runningBals l
        runningBals = scanl1 (+) $ map amt l

Let me know how this works for very large files.


Simple function in Java This is a JUnit asserts for this function:

    assertEquals(0, obj.generateListSize(0));
    assertEquals(1, obj.generateListSize(1));
    assertEquals(1, obj.generateListSize(2));
    assertEquals(3, obj.generateListSize(3));
    assertEquals(3, obj.generateListSize(4));
    assertEquals(5, obj.generateListSize(5));
    assertEquals(5, obj.generateListSize(6));
    assertEquals(7, obj.generateListSize(7));
    assertEquals(7, obj.generateListSize(8));
    assertEquals(7, obj.generateListSize(9));
    assertEquals(10, obj.generateListSize(10));
    assertEquals(10, obj.generateListSize(11));
    assertEquals(10, obj.generateListSize(12));

and this is my implementation:

public int generateListSize(int listSize) {
        int result;
        if (listSize < 1) {
            result = 0;
        } else if (7 < listSize && listSize < 10) {
            result = 7;
        } else if (10 <= listSize) {
            result = 10;
        } else if (listSize % 2 == 0) {
            result = listSize - 1;
        } else {
            result = listSize;
        }
        return result;
    }

This function is use to truncate list to 1,3,5,7,10 elements.
When list has 8 elements then return is 7.

I wouldn't search for a "rule", just store the "truncate points"

private final static int[] truncateSizes = {10,7,5,3,1,0};

public int generateListSize(int listSize) {
   for(int truncateSize  : truncateSizes) {
      if (listSize >= truncateSize) {
        return truncateSize;
      }
   }
   throw new IllegalArgumentException("Negative list size");
}


Looping through DOM to modify elements I'm using this PHP to modify A elements in a DOM fragment (a vBulletin $post['message'] if that matters) so that links to external sites always open new tabs. This is actually the default in vBulletin but it's not always reliable. Anyway, the code works, but looking at the loop makes me think it could be done better. Any suggestions?

$as = $doc->getElementsByTagName('a');
for ( $i = $as->length; --$i >= 0; ) {
    $a = $as->item($i);
    $aParts = parse_url ( strtolower ( $a->getAttribute('href') ) );
    if ( $aParts['host'] !== $localDomain ) {
        $a->setAttribute ( 'title', @$a->getAttribute ('title') . " [external link to {$aParts['host']}]" );
        $a->setAttribute ( 'target', '_blank' );
    }   // if
} // for

To make it elegant clean code I would:

make proper use of blank lines;
abide by the coding standards defined by PHP-FIG;
use the DOMNodeList object as an array so I can use foreach();
be consistent with either single ' or double quotes ";
use a guard clause.

Refactored code:

$aEls = $doc->getElementsByTagName('a');

foreach ($aEls as $a) {
    $url = parse_url(strtolower($a->getAttribute('href')));

    if ($url['host'] === $localDomain) {
        continue;
    }

    $title = $a->getAttribute('title') . ' [external link to ' . $url['host'] . ']';

    $a->setAttribute('title', $title);
    $a->setAttribute('target', '_blank');
}

(not tested)


Same function but use different array data I have these two carousels that randomly pick up pictures. [fiddle] Each of them picks up pictures and links from their own different inner array. It works fine as it is, but I was just wondering if there's any part that I can encapsulate/shorten. The only thing I can come up with that doesn't return any error is them sharing the same $(document).ready(function(){ [fiddle].

$('#carousel1').jsCarousel({ onthumbnailclick: function(src) { load(src); }, autoscroll: true, circular: true, masked: false, itemstodisplay: 3, orientation: 'h' });

$('#carouselu').jsCarousel({ onthumbnailclick: function(src) { load(src); }, autoscroll: true, circular: true, masked: false, itemstodisplay: 3, orientation: 'h' });

var theImages = [
                ['img1','url_1'],
                ['img2','url_2'],
                ['img3','url_3'],
                ['img4','url_4'],
                ['img5','url_5'],   ];

var shuffled = [];

while (theImages.length) {
    shuffled.push(theImages.splice(Math.random() * theImages.length, 1)[0]);
}

$(document).ready(function(){

var imgPath = "/pic/";
var urlPath = "/url/";

    $("#carousel1 .1").each(function(index){
        $(this).prepend('');

    });

});

/* Second rotator */

var theImagesabc = [
                ['imga','url_a'],
                ['imgb','url_b'],
                ['imgc','url_c'],
                ['imgd','url_d'],
                ['imge','url_f']    ];

var shuffledabc = [];

while (theImagesabc.length) {
    shuffledabc.push(theImagesabc.splice(Math.random() * theImagesabc.length, 1)[0]);
}

$(document).ready(function(){

var imgPath = "/pic/";
var urlPath = "/url/";

    $("#carouselu .u").each(function(index){
        $(this).prepend('');

    });

});

Beyond the repetition in the JS, you've got some repetition across the HTML and JS; I'd avoid having both the array and the empty divs. If you have more divs than you have images in the array, weird stuff starts happening. There's no reason to manually have to manage both of those "lists" when you can just add divs as necessary.

Here's how I might write it, to include that while avoiding the repetition

function randomizeCarousel(selector, images) {
  var i, l, carousel = $(selector);

  function shuffle(images) {
    var i, shuffled = [];
    while(images.length) {
      i = Math.floor(Math.random() * images.length);
      shuffled = shuffled.concat(images.splice(i, 1));
    }
    return shuffled;
  }

  function addImage(src, href) {
    var container = $("
"),
        link      = $("").attr("href", href).appendTo(container),
        img       = $("").attr("src", src).appendTo(link);
    carousel.append(container);
  }

  images = shuffle(images.slice(0));
  for(i = 0, l = images.length; i < l; i++) {
    addImage("/pic/" + images[i][0], "/url/" + images[i][1]);
  }

  carousel.jsCarousel({
    onthumbnailclick: function(src) { load(src); },
    autoscroll:       true,
    circular:         true,
    masked:           false,
    itemstodisplay:   3,
    orientation: 'h'
  });
}

$(function () {
  randomizeCarousel("#carousel1", [...]); // add your 1st array here
  randomizeCarousel("#carousel2", [...]); // add your 2nd array here
  // ... etc.
});


Pandas calculations per columns and per rows for very big datasets I am using a panda's dataframe and I am doing filtering and some calculations per column and per row.

The dataframe looks this:

   100  200  300  400
0    1    1    0    1
1    1    1    1    0

Each header of the dataframe represents a company ID (x) and the rows represent specific users (y). If the user has accessed that firm, then the in the cell x*y the value is equal with 1 or 0 otherwise. What I want to do is see how searched are 2 firms are in comparison with the other firms. If it is necessary I can go into more detail about the general formula.

for base in list_of_companies:
    counter = 0
    for peer in list2_of_companies:
        counter += 1
        if base == peer:
            "do nothing"
        else:

            # Calculate first the denominator since we slice the big matrix
            # In dataframes that only have accessed the base firm
            denominator_df = df_matrix.loc[(df_matrix[base] == 1)]
            denominator = denominator_df.sum(axis=1).values.tolist()
            denominator = sum(denominator)-len(denominator)

            # Calculate the numerator. This is done later because
            # We slice up more the dataframe above by
            # Filtering records which have been accessed by both the base and the peer firm
            numerator_df = denominator_df.loc[(denominator_df[base] == 1) & (denominator_df[peer] == 1)]
            numerator = len(numerator_df.index)

            annual_search_fraction = numerator/denominator
            print("Base: {} and Peer: {} ==> {}".format(base, peer, annual_search_fraction))

In total I have data for 13 years. I have a ryzen 2700x and it only managed to do 2 days in about 12 hours.

Edit 1 (added example input):

The metric is the following:

1) The metric that I am trying to calculate is going to tell me how many times 2 companies are searched together in comparison with all the other searches.

2) The code is first selecting all the users which have accessed the base firm (denominator_df = df_matrix.loc[(df_matrix[base] == 1)])line. Then it calculates the denominator which counts how many unique combinations between the base firm and any other searched firm by the user are there and since I can count the number of firms accessed (by the user), I can subtract 1 to get the number of unique links between the base firm and the other firms.

3) Next, the code filters the previous denominator_df to select only the rows which accessed the base and the peer firm. Since I need to count the number of users which accessed the base and the peer firm, I use the command:  numerator = len(numerator_df.index) to count the number of rows and that will give me the numerator.

The expected output from the dataframe at the top is the following:

Base: 100 and Peer: 200 ==> 0.5
Base: 100 and Peer: 300 ==> 0.25
Base: 100 and Peer: 400 ==> 0.25
Base: 200 and Peer: 100 ==> 0.5
Base: 200 and Peer: 300 ==> 0.25
Base: 200 and Peer: 400 ==> 0.25
Base: 300 and Peer: 100 ==> 0.5
Base: 300 and Peer: 200 ==> 0.5
Base: 300 and Peer: 400 ==> 0.0
Base: 400 and Peer: 100 ==> 0.5
Base: 400 and Peer: 200 ==> 0.5
Base: 400 and Peer: 300 ==> 0.0

4) The sanity check to see if the code gives the correct solution: all the metrics between 1 base firm and all the other peer firms have to sum up to 1 (all the metrics between base 100 and peer[200,300,400] summed together give 1.

One quick and obvious improvement is possible in these two lines:

denominator = denominator_df.sum(axis=1).values.tolist()
denominator = sum(denominator)-len(denominator)

This is equivalent to:

denominator = denominator_df.sum(axis=1)
denominator = denominator.sum() - len(denominator)

which should be a lot faster since converting to a temporary list will be quite slow, as is summing using the Python built-in instead of using the pandas vectorized method.

Since you only care for the count in the numerator case, just use sum:

numerator = (denominator_df[peer] == 1).sum()

Note that checking for denominator_df[base] == 1 is unnecessary since that was already done in the construction of denominator_df.

But the real speed gains are probably in eliminating the double for loop altogether and writing this using vectorized methods. With some example input that might be possible.


Fading content for each TD I have an HTML table and I use jQuery to fade some content for each TD:

Demo

My code works great, but I want to know if my solution can be better.

Inserer un produit

Inserer un nv crédit

    Afficher les produits
    Afficher les crédits courante

jQuery

$( "#first" ).click(function() {
if( $("#Element2" ).show || $("#Element3" ).show || $("#Element4" ).show){
    $("#Element2").hide();
    $("#Element3").hide();
    $("#Element4").hide();
}
$( "#Element1" ).fadeToggle("slow");
});
$( "#second" ).click(function() {
if( $("#Element1" ).show || $("#Element3" ).show || $("#Element4" ).show){
    $("#Element1").hide();
    $("#Element3").hide();
    $("#Element4").hide();
}
$( "#Element2" ).fadeToggle( "slow");
});
$( "#third" ).click(function() {
if( $("#Element1" ).show || $("#Element2" ).show || $("#Element4" ).show){
    $("#Element1").hide();
    $("#Element2").hide();
    $("#Element4").hide();
}
$( "#Element3" ).fadeToggle( "slow");
});
$( "#fourth" ).click(function() {
if( $("#Element1" ).show || $("#Element2" ).show || $("#Element3" ).show){
    $("#Element1").hide();
    $("#Element2").hide();
    $("#Element3").hide();
}
$( "#Element4" ).fadeToggle( "slow");
});

You can DRY your JS code, assuming you modify the HTML this way:

On each of the four selector s, add a selector class and a data-id="N" attribute, where "N" refers to the #ElementN.
On each of the four selectable s, add a selectable class.

So your HTML part becomes:

Inserer un produit

Inserer un nv crédit

    Afficher les produits
    Afficher les crédits courants

<table id="Element1" class="selectable formInsertTab" ...

BTW, note that I affected data-value in the order showed by your demo (1, 4, 2, 3), while the code posted in your question is 1, 2, 3, 4.

Then in the JS part you can:

Take advantage of the above HTML changes to bind click event only once for all selectors.
Hide selectable elements without previously checking if they show.
Warning, anyway your test was falsy: $('#ElementN').show always returns true, since it checks if the show() method exists, not if the element is showing!
Add the improvement proposed by @Roamer-1888: chain fadeToggle() before hiding other elements.
BTW here is an interesting demo from him, which illustrates how you can have fine control on the fadeToggle() execution.

The resulting code is so much reduced:

$('.selector').click(function() {
  $element = $('#Element' + $(this).data('id')).fadeToggle('slow');
  $('.selectable').not($element).hide();
}


Brute force passwords in C (CS50 exercise) This script attempts to crack passwords by going through all possible 'words', hashing them, and comparing the hash to the input.

It seems to work, but I don't know if I have written 'good' C. I'm looking for advice on what areas would be most important/beneficial to focus on (e.g. efficiency, design, readability, something else?) in the next thing I write and how to improve within those. I also don't feel that comfortable with low level concepts like memory and pointers and I'm not sure if I'm using them right.

I'm not really sure what I want though so please give me whatever advice you think I need.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cs50.h>
#include <crypt.h>

char ALPHABET[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int alphabetSize = 52;

int max_length = 4;

void check(char *guess, char *salt, char *hash)
{
    string hashedGuess = crypt(guess, salt);
    if (!strcmp(hash, hashedGuess))
    {
        printf("%s\n", guess);
        free(guess);
        exit(0);
    }
}

// recursively fill the buffer and check it each time
void brute_force(char *buf, int index, int length, string salt, string hash)
{
    for (int i = 0; i < alphabetSize; i++)
    {
        sprintf(buf + index, "%c", ALPHABET[i]);

        if (index < length)
        {
            brute_force(buf, index + 1, length, salt, hash);
        }
        else
        {
            check(buf, salt, hash);
        }
    }
}

char *crack(string hash, string salt)
{
    // create a buffer big enough to hold the longest possible password
    char *buf = (char *) malloc(max_length + 1);

    // increment guess length starting from 1
    for (int length = 0; length < max_length; length++)
    {
        brute_force(buf, 0, length, salt, hash);
    }
    return "";
}

bool valid_args(int argc, string argv[])
{
    if (argc == 2)
    {
        return true;
    }
    return false;
}

int main(int argc, string argv[])
{
    if (valid_args(argc, argv))
    {
        string hash = argv[1];

        char salt[3];
        strncpy(salt, hash, 2); // salt is first 2 characters of hash

        string password = crack(hash, salt);
    }
    else
    {
        printf("Invalid arguments\n");
        return 1;
    }
    return 0;
}

valid_args is a well-known anti-idiom:

    if (condition) {
        return true;
    }
    return false;

is a long way to say

    return condition;

crack always return an empty string "". It is as good as returning nothing.
check terminates the program on success. This seriously limits its utility: the business logic doesn't belong to such depth of the call tree. Consider returning a boolean instead.
I do not endorse recursion when an iterative approach suffices. Try to express a power set generation iteratively (hint: think of base-52 numbers).
From what we can see, it is impossible to tell whether crypt returns a static buffer, or allocates a new one for each call. Consider documenting that.
I happen to know that <cs50.h> defines string as an alias to char *. I don't think it is a good idea to begin with; in any case you should be consistent: brute_force passes salt and hash as string, while check receives them as char *.


Shell Sort Comparisons/Exchanges Counter I need to analyze shell-sort. Currently I am working with it having an increment of N/2. I will then go on to try more efficient increments.

However, my count for comparisons/exchanges seems too low for an array of 2000 elements. I've tried changing it around some but still everything seems too low. Could someone look over my code and see if my counters are in the right places?

public class Sort {
    static int exchanges= 0;
    static int comparisons= 0;

    public static void SegmentedInsertionSort (AnyType[] array, int N, int gap)
    {
        for (int index = gap ; index < N ; index++)
        {
            AnyType temp;
            int j = index - gap;
            while (j >= 0)
            {
                  comparisons++;
                  if (array[j].isBetterThan(array[j+gap]))
                  {
                       temp = array[j];
                       array[j] = array[j + gap];
                       array[j + gap] = temp;
                       j = j - gap;
                       exchanges++;
                  }
                  else j = -1;
            }
        }
    }

    public static void shellSort (AnyType[] array)
    {
        int N = 2000;
        int gap = N/2;
        while (gap > 0)
        {
            SegmentedInsertionSort(array, N, gap);
            gap = gap / 2;
        }
    }
}

Also, I know there are other ways to code this, but the pseudo-code template I was given by my professor looked like this.

Your counting code seems correct.
comparison increments on each compare operation,
exchanges increments only on exchange.

On reversed array of 2000 elements I have got: comparison = 26416 and exchanges = 10400

\$log_{2000} {26416} \approx 1.34\$
So you have \$O(n^{1.34})\$ complexity.
Which is between \$O(n^{3/2}) = O(n^{1.5})\$ and \$O(n^{5/4}) = O(n^{1.25})\$
So according to wiki it's okay for usual gap sequence.
exchanges = 10400 is less then average move count \$0.41N\ln N (\ln \ln N + 1/6)\$ which in case of N = 2000 is approximately 13500, but it depends on gap sequence. E.g if you start with gap = N / 8 it will be equal to 14400.


Query builder with OOP design I am designing a query builder, where the user can just add conditions or groups, and each group can, in turn, have conditions in it. I came up wit the below class design. Can this design be improved?

public enum RuleType
{
    Group,
    Condition
}
public enum Operator
{
    And,
    Or
}
public enum ConditonValues
{
    GreaterThan = 1,
    EqualTo = 2,
    LessThan = 3
}
public abstract class RuleParent
{
    public Guid Id { get; set; }
    public int Order { get; set; }
    public RuleType RuleType { get; set; }
}
public class RuleSet : RuleParent
{
    public ConditonValues Condition { get; set; }
    public string Field { get; set; }
    public object Data { get; set; }
}
public class MyGroup : RuleParent
{
    public Operator Operator { get; set; }
    public List<RuleParent> Rules { get; set; }
    public MyGroup()
    {
        Rules = new List<RuleParent>();
    }
}

Example usage:

var groupM = new MyGroup();
groupM.Rules.AddRange(new List<RuleParent>
{
     new RuleSet() { Condition =  ConditonValues.EqualTo, Field="name", Data ="reza" , RuleType = RuleType.Condition },
     new MyGroup() {
         Rules = new List<RuleParent>()
         {
             new RuleSet() { Condition =  ConditonValues.EqualTo, Field="category", Data ="Tools" , RuleType = RuleType.Condition  },
             new RuleSet() { Condition =  ConditonValues.GreaterThan, Field="price", Data ="100" , RuleType = RuleType.Condition  }
         }
         , RuleType = RuleType.Group
     }
});

welcome to code review.

Your organization is clean, I mostly just see a few holes in your logic:

Combining groups - A group applies the same operator (and, or) to all rules in it.  e.g. rule1 AND rule2 AND rule3.  However, since groups cannot contain other groups, you cannot combine operations, e.g. rule1 AND (rule2 OR rule3)
Missing Operator/condition - you should add NOT to your enum(s) of operators and/or conditions
Rule Type - I'm not sure what the purpose of this enum is.  If you think that you need it, you could leave it is as, or alternatively make an IRuleParent interface, then make ConditionRuleParent and GroupRuleParent subclasses (this would be the more C#-ish way to model it).  By doing it the swcond way, you can declare the type (condition/group) in the class name when you instantiate it, rather than tacking it on as a mandatory argument.
Clunky syntax - it's object oriented, but very verbose to use and mentally parse, which leads us to...
Greenspun's tenth rule - Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp. (or LINQ in this case).  While there are benefits to rolling your own implementation, you are basically recreating a subset of LINQ (the fluent syntax style).  If you want something like LINQ, just use LINQ.  If you are rolling your own, you might want to spend a little bit of time learning how it works (from a user point of view, at a minimum) and then steal ideas from it as you write your own version.


How do I handle the file system? I'm trying to get my head around asyncronous programming in node.js.
My example is reading all the files from a directory.

I know I can avoid asyncronous programming by using the syncronous methods:

var fs = require('fs');

names = fs.readdirSync(".");
for(i in names) {
  fileinfo = fs.statSync( names[i] );
  if( fileinfo.isFile() ) console.log( names[i] + " has size " + fileinfo.size );
};

I know how to write it in the classic node style:

fs.readdir(".", function (err, names) {
  if (err) throw err;
  names.forEach(function(n){
    fs.stat( n, function(err, fileinfo) {
      if( fileinfo.isFile() ) console.log( n + " has size " + fileinfo.size );
    });
  });
});

But now I'm trying "functional reactive programming" with bacon.js and I'm not sure if I really get it.  This is my first sketch:

var fs = require('fs')
  , Bacon = require("baconjs").Bacon;

fs.readdir(".", function (err,names) {
  if (err) throw err;
  Bacon.fromNodeCallback( fs.stat_with_filename, Bacon.fromArray(names) )
    .filter(".isFile")
    .onValue(function(stat) {
      console.log(stat.filename + " has size " + stat.size);
  });
});

But I had to monkeypatch fs to get the filename inside the stat object to achive this:

fs.stat_with_filename = function( filename, callback ) {
   fs.stat( filename, function (err,stats) {
     stats.filename = filename;
     callback( err, stats );
   });
};

Is there a better way to write this in node + bacon?

If you want to expose directory contents with stats as a Bacon EventStream or a Property, you can use the combine-family of functions to combine the filename and stats without monkey-patching:

var fs = require("fs")
var Bacon = require("../dist/Bacon.js")

// statsForFile :: String -> Property { filename :: String, stats :: Stats }
function statsForFile(filename) {
  return Bacon.combineTemplate({
    name: filename,
    stats: Bacon.fromNodeCallback( fs.stat, filename )
  })
}

You can expose directory contents as a stream of filenames:

// directoryContents :: String -> EventStream String
function directoryContents(dir) {
  return Bacon.fromNodeCallback(fs.readdir, dir)
    .flatMap(function(names) { return Bacon.fromArray(names)})
}

Then you can compose these two like

function statsForDir(dir) {
  return directoryContents(dir).flatMap(statsForFile)
}

And see what happens:

statsForDir(".").log()

So that's how you can compose these things asynchronously using Bacon.js and FRP. This is not a prime example of where FRP is really useful yet, but when more composition is involved the benefits will be greater. Hope this helps!