texts: Tonelli-Shanks algorithm implementation of prime modular square root

texts:
I did an implementation of the Tonelli-Shanks algorithm as defined on Wikipedia. I put it here for review and sharing purpose.

Legendre Symbol implementation:

def legendre_symbol(a, p):
    """
    Legendre symbol
    Define if a is a quadratic residue modulo odd prime
    http://en.wikipedia.org/wiki/Legendre_symbol
    """
    ls = pow(a, (p - 1)/2, p)
    if ls == p - 1:
        return -1
    return ls

Prime modular square root (I just renamed the solution variable R to x and n to a):

def prime_mod_sqrt(a, p):
    """
    Square root modulo prime number
    Solve the equation
        x^2 = a mod p
    and return list of x solution
    http://en.wikipedia.org/wiki/Tonelli-Shanks_algorithm
    """
    a %= p

    # Simple case
    if a == 0:
        return [0]
    if p == 2:
        return [a]

    # Check solution existence on odd prime
    if legendre_symbol(a, p) != 1:
        return []

    # Simple case
    if p % 4 == 3:
        x = pow(a, (p + 1)/4, p)
        return [x, p-x]

    # Factor p-1 on the form q * 2^s (with Q odd)
    q, s = p - 1, 0
    while q % 2 == 0:
        s += 1
        q //= 2

    # Select a z which is a quadratic non resudue modulo p
    z = 1
    while legendre_symbol(z, p) != -1:
        z += 1
    c = pow(z, q, p)

    # Search for a solution
    x = pow(a, (q + 1)/2, p)
    t = pow(a, q, p)
    m = s
    while t != 1:
        # Find the lowest i such that t^(2^i) = 1
        i, e = 0, 2
        for i in xrange(1, m):
            if pow(t, e, p) == 1:
                break
            e *= 2

        # Update next value to iterate
        b = pow(c, 2**(m - i - 1), p)
        x = (x * b) % p
        t = (t * b * b) % p
        c = (b * b) % p
        m = i

    return [x, p-x]

If you have any optimization or have found any error, please report it.


texts: Fetching BasicInfo, BillingInfo, and DocumentInfo objects

texts:
The repetition is super obvious here. How can I rewrite this code? I need one base method in which I pass a Django model, to call objects.filter, but I can't figure out how to do it.

from profiles.models import BasicInfo, BillingInfo, DocumentInfo

__author__ = 'vol'

class BasicInfoService:
    def __init__(self):
        pass

    @staticmethod
    def get_by_profile_id(profile_id, is_versioned):
        if is_versioned:
            return BasicInfo.objects.filter(profile_id=profile_id).order_by('-version')
        return BasicInfo.objects.filter(profile_id=profile_id).order_by('-version')[:1][0]

class BillingInfoService:
    def __init__(self):
        pass

    @staticmethod
    def get_by_profile_id(profile_id, is_versioned):
        if is_versioned:
            return BillingInfo.objects.filter(profile_id=profile_id).order_by('-version')
        return BillingInfo.objects.filter(profile_id=profile_id).order_by('-version')[:1][0]

class DocumentInfoService:
    def __init__(self):
        pass

    @staticmethod
    def get_by_profile_id(profile_id, is_versioned):
        if is_versioned:
            return DocumentInfo.objects.filter(profile_id=profile_id).order_by('-version')
        return DocumentInfo.objects.filter(profile_id=profile_id).order_by('-version')[:1][0]


texts: Return the largest palindrome from the string

texts:
Here is the question: find the largest palindrome from a string.

Ex:

ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD

Result:

ILOVEUEVOLI

I am not sure of the efficiency of the algorithm.

static void Main(string[] args)
{
    var str = "ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD";
    var longestPalindrome = GetLongestPalindrome(str);
    Console.WriteLine(longestPalindrome);
    Console.Read();
}

private static string GetLongestPalindrome(string input)
{
    int rightIndex = 0, leftIndex = 0;
    List<string> paliList = new List<string>();
    string currentPalindrome = string.Empty;
    string longestPalindrome = string.Empty;
    for (int currentIndex = 1; currentIndex < input.Length - 1; currentIndex++)
    {
        leftIndex = currentIndex - 1;
        rightIndex = currentIndex + 1;
        while (leftIndex >= 0 && rightIndex < input.Length)
        {
            if (input[leftIndex] != input[rightIndex])
            {
                break;
            }
            currentPalindrome = input.Substring(leftIndex, rightIndex - leftIndex + 1);
            paliList.Add(currentPalindrome);
            leftIndex--;
            rightIndex++;
        }
    }
    var x = (from c in paliList
             select c).OrderByDescending(w => w.Length).First();
    return x;
}


texts: Class that handles header and footer includes looks like a mess

texts:
I tried making a class that handles my header and footer of my site. It looks like a mess, because I like to preserve the indentations as is.

But I'm wondering if there maybe is an even cleaner or better way of writing this class?

<?php
class HeadFoot {
    protected $title,
              $scripts;

    public function __construct($title, $scripts) {
        $this->title = $title;
        $this->scripts = $scripts;
    }

    public function getHeader() {
        if($this->title) {
$header = <<< EOD
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>$this->title - Domain</title>
        <link rel="shortcut icon" href="/favicon.ico">
        <link rel="stylesheet" href="/stylesheets/init.css">
        <link rel="stylesheet" href="/stylesheets/layout.css">

EOD;

if($this->scripts) {
    foreach($this->scripts as $script) {
        $header .= str_repeat(' ', 8) . $script . "\n";
    }
}

$header .= <<< EOD

Domain

EOD;

$header .= Navigation::get();
$header .= str_repeat(' ', 12) . "\n";

            return $header;
        }

        return false;
    }

    public function getFooter($ads = null) {
        if($ads) {
            return
'

Copyright © 2014 - Domain.net

Terms of Service / Privacy Policy

';
        }

        return
'

Copyright © 2014 - Domain.net

Terms of Service / Privacy Policy

';
    }
}


texts: Quicksort implementation equivalent to Collections.sort()

texts:
Here is my go at understanding generics, Comparables and Comparators, as well as type bounds. I believe I made it as close to Collections.sort as possible in terms of interface. Please review.

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class QuickSort {
    private static final Random rng = new Random();

    public <T extends Comparable<? super T>> void sort(List<T> xs) {
        sort(xs, 0, xs.size() - 1);
    }

    public <T> void sort(List<T> xs, Comparator<? super T> cmp) {
        sort(xs, 0, xs.size() - 1, cmp);
    };

    private static <T extends Comparable<? super T>>
    void sort(List<T> xs, int fst, int lst) {
        sort(xs, fst, lst, (x, y) -> x.compareTo(y));
    }

    private static <T>
    void sort(List<T> xs, int fst, int lst, Comparator<? super T> cmp) {
        if (fst >= lst) return;

        int i = fst, j = lst;

        T pivot = xs.get(rng.nextInt(xs.size()));

        while (i <= j) {
            while (cmp.compare(xs.get(i), pivot) < 0)
                i++;
            while (cmp.compare(pivot, xs.get(j)) < 0)
                j--;

            if (i <= j)
                Collections.swap(xs, i++, j--);
        }

        sort(xs, fst, j, cmp);
        sort(xs, i, lst, cmp);
    }
}


texts:
After some investigation, I implemented an asynchronous TCP server as per the following example. During my investigation I was unable to find an example that cleanly shuts down the server; after some experimenting I was able to furnish my code with this functionality. I would appreciate a review of the service code for whether I might be doing something stupid/dangerous. (Please note that I have stripped out parameter validation, etc. in order to improve readability).

public class AsyncTcpServer : IDisposable
{
    public class DataReceivedEventArgs : EventArgs
    {
        public NetworkStream Stream { get; private set; }

        public DataReceivedEventArgs(NetworkStream stream)
        {
            Stream = stream;
        }
    }

    public event EventHandler<DataReceivedEventArgs> OnDataReceived;

    public AsyncTcpServer(IPAddress address, int port)
    {
        _listener = new TcpListener(address, port);
    }

    public void Start()
    {
        _listener.Start();
        _isListening = true;
        WaitForClientConnection();
    }

    public void Stop()
    {
        _isListening = false;
        _listener.Stop();
    }

    public void Dispose()
    {
        Stop();
    }

    private void WaitForClientConnection()
    {
        _listener.BeginAcceptTcpClient(HandleClientConnection, _listener);
    }

    private void HandleClientConnection(IAsyncResult result)
    {
        if (!_isListening)
        {
            return;
        }

        var server = result.AsyncState as TcpListener;
        var client = _listener.EndAcceptTcpClient(result);

        WaitForClientConnection();

        OnDataReceived?.Invoke(this, new DataReceivedEventArgs(client.GetStream()));
    }

    private readonly TcpListener _listener;
    private volatile bool _isListening = false;
}

The following test verifies the asynchronous nature of the service (test completes under 10 seconds for 5x client connections blocking for 5 seconds each).

[TestMethod]
public void TestSendReceiveDataFromMultipleClientsConcurrently()
{
    using (var server = new AsyncTcpServer(IPAddress.Any, 54001))
    {
        server.OnDataReceived += (sender, e) =>
        {
            var bytesRead = 0;
            do
            {
                // Read buffer, discarding data
                bytesRead = e.Stream.Read(new byte[1024], 0, 1024);
            }
            while (bytesRead > 0 && e.Stream.DataAvailable);

            // Simulate long running task
            Thread.Sleep(5000);

            var response = Encoding.ASCII.GetBytes("Who's there?");
            e.Stream.Write(response, 0, response.Length);
        };

        server.Start();
        var tasks = new List<Task>();

        for (var i = 0; i < 5; ++i)
        {
            tasks.Add(Task.Run(() =>
            {
                var response = new byte[1024];

                using (var client = new TcpClient())
                {
                    client.Connect("127.0.0.1", 54001);

                    using (var stream = client.GetStream())
                    {
                        var request = Encoding.ASCII.GetBytes("Knock, knock...");
                        stream.Write(request, 0, request.Length);
                        stream.Read(response, 0, response.Length);

                        Assert.AreEqual("Who's there?", Encoding.ASCII.GetString(response).TrimEnd('\0'));
                    }
                }
            }));
        }

        Assert.IsTrue(Task.WaitAll(tasks.ToArray(), 10000));
    }
}


texts:
Given the following task:

  Exercise 1.17

  The exponentiation
  algorithms in this section are based
  on performing exponentiation by means
  of repeated multiplication. In a
  similar way, one can perform integer
  multiplication by means of repeated
  addition. The following multiplication
  procedure (in which it is assumed that
  our language can only add, not
  multiply) is analogous to the expt
  procedure:

(define (* a b)
  (if (= b 0)
      0
      (+ a (* a (- b 1)))))

  This algorithm takes a number of steps
  that is linear in b. Now suppose we
  include, together with addition,
  operations double, which doubles an
  integer, and halve, which divides an
  (even) integer by 2. Using these,
  design a multiplication procedure
  analogous to fast-expt that uses a
  logarithmic number of steps.

I wrote this solution:

(define (double a) (* a 2))
(define (halve a) (/ a 2))
(define (even n) (= (remainder n 2) 0))

(define (times a b)
  (cond ((= 1 b) a)
        ((even b) (times (double a) (halve b)))
        (else (times (+ a a) (- b 1)))))

What do you think?


texts: Generate random and unique array of int values for a given size

texts:
I need to generate an array of int values for a given size, the values should be random and unique. the following implementation is "ok" for small values [1,10k], I would like to get some feedback on better implementation

/**
 * Generate an array of random & unique values in the interval [0,desiredSize*3]
 * To use only for small arrays with size in [1,50k]
 * for an array of 1k time: 0.01s
 * for an array of 10k time: 0.3s
 * for an array of 50k time: 8s
 * @param desiredSize
 * @return
 */
public int[] generateRandAndUniq(int desiredSize) {
    int[] arrayResult = new int[desiredSize];
    Random rand = new Random();
    arrayResult[0]= rand.nextInt(desiredSize);
    int counter = 0;
    while (counter < desiredSize) {
        int randValue = rand.nextInt(desiredSize*3);/* a larger interval! */
        int[] tempArray= new int[counter+2];
        System.arraycopy(arrayResult, 0, tempArray,0, counter);
        tempArray[counter+1]=randValue;
        if(!checkDuplicate(tempArray)){
            arrayResult[counter]=randValue;
            counter++;
        }
    }
    return arrayResult;
}

public boolean checkDuplicate(int[] arr) {
    boolean[] bitmap = new boolean[maxValueInArray(arr)+1]; /* just put a big number to avoid looping to get the max value? */
    for (int v : arr) {
        if (!bitmap[v]) {
            bitmap[v] = true;
        } else {
            return true;
        }
    }
    return false;
}

public int maxValueInArray(int[] arr){
    int max=-1;
    for(int v:arr){
        if(v>max)
            max=v;
    }
    return max;
}


texts: PHP checking for array key or using default value

texts:
I currently use this code pattern fairly frequently

if(array_key_exists('possible_key', $array)) {
    $my_variable = $array['possible_key'];
} else {
    $my_variable = 'my default value';
}

Is there a better way to be writing this?


texts: Safely accepting a known SSL certificate with a different host name

texts:
My app communicates with a server over an internal network through HTTPS. The SSL certificate on this server is listed for the host as its external host name. I want to accept this certificate, but I don't want to accept ANY certificate as many workarounds I've seen seem to do. I would also like to have it so that later on, in the strong possibility that his app is accessing a different server with a correct SSL certificate, that I don't have to change it. I have it working as I would like it seems, but I am very unsure of myself when it comes to implementing my own methods to override a library used for secure communications, and I am not very strong in my knowledge of SSL communications.

I would basically like input on security loopholes and its effectiveness at doing what I need.

Here is the code I have:

HttpClient httpclient = new DefaultHttpClient();
SSLSocketFactory ssf = SSLSocketFactory.getSocketFactory();
ssf.setHostnameVerifier( new X509HostnameVerifier() {

   @Override
   public void verify( String host, String[] cns, String[] subjectAlts )
         throws SSLException
   {
   }

   @Override
   public void verify( String host, X509Certificate cert ) throws SSLException
   {
   }

   @Override
   public void verify( String host, SSLSocket ssl ) throws IOException
   {
      boolean foundHost = false;
      for( javax.security.cert.X509Certificate cert : ssl.getSession().getPeerCertificateChain() )
      {
         String[] tokens = cert.getSubjectDN().getName().split( "," );
         for( String token : tokens )
         {
            String[] keyVal = token.split( "=" );

            if( keyVal.length > 1 && keyVal[0].equals( "CN" ) )
            {
               foundHost = keyVal[1].equals( context.getString( R.string.CertHostName ) );

               if(!foundHost)
               {
                foundHost = keyVal[1].equals( host );
               }
            }

            if(foundHost)
            {
               break;
            }
         }
         if(foundHost)
         {
            break;
         }
      }

      if(!foundHost)
      {
         throw new IOException( "Mismatched host in SSL certificate" );
      }
   }

   @Override
   public boolean verify( String host, SSLSession session )
   {
      return false;
   }
} );
httpclient.getConnectionManager().getSchemeRegistry().unregister( "https" );
httpclient.getConnectionManager().getSchemeRegistry().register( new Scheme( "https", ssf, 443 ) );

Basically, I found out which method to override through some log statements to see which one was being used in the anonymous inner X509HostnameVerifier class, and hopefully handled it appropriately. Input would be appreciated.


texts:
Implementing basic sorting algorithms to learn them, and coding, better. Criticisms/ critiques welcome. Also possible optimizations.

import unittest
import random

def insertion_sort(seq):
    """Accepts a mutable sequence, utilizes insertion sort algorithm to sort in
    place. Returns an ordered list"""
    #marks point between ordered sublist & unordered list
    partition = 1

    while partition < len(seq):
        temp = partition

        #while temp not in correct pos in sublist, decrement pos
        while temp != 0 and seq[temp] < seq[temp-1]:
            seq[temp], seq[temp-1] = seq[temp-1], seq[temp]
            temp -= 1

        partition += 1

    return seq

class test_insertionsort(unittest.TestCase):
    def test_insertionsort(self):
        """Test insertion_sort()"""
        seq = [random.randrange(0, 1000) for _ in range(1000)]
        self.assertEqual(insertion_sort(seq), sorted(seq))

if __name__ == '__main__':
    unittest.main()


texts: Using app.use only in routes that start with /admin

texts:
I have several routes, and I need Facebook authentication only in the routes that start with /admin:

app.get('/admin/dashboard', passport.ensureAuthenticated, .....);
app.get('/admin/dashboard/new/email', passport.ensureAuthenticated, ....);
app.get('/admin/dashboard/new/question', passport.ensureAuthenticated, ....);
app.get('/admin/dashboard/new/answer', passport.ensureAuthenticated, ....);
app.get('/admin/dashboard/new/etc', passport.ensureAuthenticated, ....);

If I can't use the app.use, is there anyone to call passport.ensureAuthenticated repetition in routes that start with /admin?


texts: Multiple indexes over an in memory collection for faster search

texts:
I have a big in-memory collection of following simplified class:

public class Product
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public int CategoryId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

I need to search for products based on different properties like UserName or CategoryId.
One way of searching would be using linq to objects like:

var userProducts = products.Where(x => x.UserName == "SomeValue")

This takes some processing when collection is too big and in my case it would be called hundreds of time each second.

What I came up with was to introduce a new collection that supports indexing over different properties:

public class FastCollection<T> : IEnumerable<T>
{
    private IList<T> _items;
    private IList<Expression<Func<T, object>>> _lookups;
    private Dictionary<string, ILookup<object, T>> _indexes;

    public FastCollection(IList<T> data)
    {
        _items = data;
        _lookups = new List<Expression<Func<T, object>>>();
        _indexes = new Dictionary<string, ILookup<object, T>>();
    }

    public void AddIndex(Expression<Func<T, object>> property)
    {
        _lookups.Add(property);
        _indexes.Add(property.ToString(), _items.ToLookup(property.Compile()));
    }

    public void Add(T item)
    {
        _items.Add(item);
        RebuildIndexes();
    }

    public void Remove(T item)
    {
        _items.Remove(item);
        RebuildIndexes();
    }

    public void RebuildIndexes()
    {
        if (_lookups.Count > 0)
        {
            _indexes = new Dictionary<string, ILookup<object, T>>();
            foreach (var lookup in _lookups)
            {
                _indexes.Add(lookup.ToString(), _items.ToLookup(lookup.Compile()));
            }
        }
    }

    public IEnumerable<T> FindValue<TProperty>(Expression<Func<T, TProperty>> property, TProperty value)
    {
        var key = property.ToString();
        if(_indexes.ContainsKey(key))
        {
            return _indexes[key][value];
        }
        else
        {
            var c = property.Compile();
            return _items.Where(x => c(x).Equals(value));
        }
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

You can initialize the collection like this:

var fc = new FastCollection<Product>(products);
fc.AddIndex(x => x.Id);
fc.AddIndex(x => x.UserName);
fc.AddIndex(x => x.CategoryId);

And finally you can search the collection like this:

var userProducts = gc.FindValue(x => x.UserName, "SomeValue");

The fast collection makes a big difference when it comes to performance.

My question is if I'm doing it right? I have used delegates and expressions to make it as generic as possible but I have this feeling that there is room for improvement!


texts: Squares with different background colors

texts:
Titles is an array populated by numbers (1, 2 and 3). Depending on the number, a Square component should have a different background colour. Now, I don't think that having that the switch statements are the best way to make the condition. I'm sure there's a better way to make Square's background depending on the mapped number.

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
//import { getStatus, getPosition, genGrid } from '../actions';
import { CardSection, Square } from './common';

class MainMaze extends Component {

  generateMaze() {
    const { tiles } = this.props.grid;
    return (
      tiles.map((sq, i) => {
        switch (sq) {
          case 3:
            return <Square key={i} style={{ backgroundColor: 'red' }}>{sq}</Square>;
          case 2:
            return <Square key={i} style={{ backgroundColor: 'blue' }}>{sq}</Square>;
          default:
            return <Square key={i} style={{ backgroundColor: 'green' }}>{sq}</Square>;
        }
      }
    ));
  }
  render() {
    const { grid, position, status } = this.props;

    return (
      <View>
        <CardSection>
          <Text>{grid.cols}</Text>
        </CardSection>
        <CardSection>
          {this.generateMaze()}
        </CardSection>
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    status: state.status,
    position: state.position,
    grid: state.grid
  };
};

export default connect(mapStateToProps)(MainMaze);

The Square component:

import React from 'react';
import { View, Text } from 'react-native';

const Square = (props) => {
  return (
    <View style={[styles.containerStyle, props.style]}>
      <Text>
        {props.children}
      </Text>
    </View>
  );
};

const styles = {
  containerStyle: {
    borderWidth: 1,
    borderColor: '#ddd',
    elevation: 1,
    alignItems: 'center',
    justifyContent: 'center',
    margin: 0,
    height: 30,
    width: 30
  }
};

export { Square };


texts: Linked list with removal function in Rust

texts:
I know there are other structures which are better than the linked list, but I want to implement a singly linked list which has a remove function for study.

After struggling for a few hours, I wrote this code.

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

type Link<T> = Option<Rc<RefCell<Node<T>>>>;

struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<T> Node<T> {
    fn new(elem: T) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Node {
            elem: elem,
            next: None,
        }))
    }
}

pub struct List<T> {
    head: Link<T>,
}

impl<T: Eq> List<T> {
    pub fn new() -> Self {
        List { head: None }
    }

    pub fn push(&mut self, elem: T) {
        let new_head = Node::new(elem);
        match self.head.take() {
            Some(old_head) => {
                new_head.borrow_mut().next = Some(old_head);
                self.head = Some(new_head);
            }
            None => {
                self.head = Some(new_head);
            }
        }
    }

    pub fn remove(&mut self, elem: T) {
        let mut head = self.head.clone().unwrap();
        if head.borrow().elem == elem {
            self.head = head.borrow().next.clone();
            return;
        }

        loop {
            let next = head.borrow().next.clone();
            match next {
                None => return,
                Some(ref node) => {
                    if node.borrow().elem == elem {
                        head.borrow_mut().next = node.borrow().next.clone();
                    }
                    head = node.clone();
                }
            }
        }
    }
}

fn main() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);
    let head = list.head.unwrap().clone();
    assert_eq!(head.borrow().elem, 1);
    let next = head.borrow().next.clone().unwrap();
    assert_eq!(next.borrow().elem, 3);
}

To iterate this list, I implemented a iterator.

pub struct Iter<T> {
    next: Link<T>
}

impl<T> Iterator for Iter<T> {
    type Item = Rc<RefCell<Node<T>>>;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.next.clone();
        let next_next = next.clone();
        self.next = match next_next {
            Some(node) => {
                node.borrow().next.clone()
            }
            None => {
                None
            }
        };
        next
    }
}

impl<T: Eq> List<T> {
    pub fn iter(&self) -> Iter<T> {
        Iter { next: self.head.clone() }
    }
}

fn main() {
    let mut list = List::new();
    list.push(3);
    list.push(2);
    list.push(1);
    list.remove(2);

    let mut it = list.iter();
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 1);
    let next_node = it.next().unwrap();
    assert_eq!(next_node.borrow().elem, 3);
    let next_node = it.next();
    assert_eq!(next_node.is_none(), true);
}

I'm not sure this code is good, because I think

there are too many clone() or borrow() calls.
code is long and not simple. (is using Rc and RefCell good?)

Are there easier or simpler ways?

Even if this code is not so bad, are there weak or dangerous points?


texts: Write a definition of a semaphore in terms of mutexes

texts:
From SICP:

  Exercise 3.47.  A semaphore (of size
  n) is a generalization of a mutex.
  Like a mutex, a semaphore supports
  acquire and release operations, but it
  is more general in that up to n
  processes can acquire it concurrently.
  Additional processes that attempt to
  acquire the semaphore must wait for
  release operations. Give
  implementations of semaphores

  a. in terms of mutexes

(define (make-semaphore max)
  (let ((count 0)
        (the-mutex (make-mutex)))
    (define (increment)
      (set! count (+ count 1)))
    (define (decrement)
      (set! count (- count 1)))
    (define (has-room?) (> max count))
    (define (the-semaphore m)
      (cond ((eq? m 'acquire)
             (if (has-room?)
                 (increment)
                 (the-mutex 'acquire)))
            ((eq? m 'release)
             (decrement)
             (if (has-room?) (the-mutex 'release)))))
    the-semaphore))

I wrote this answer and I'm hoping to find out if it is correct, and how it can be improved.  Thank you for your time.


texts: Get a nested property of a complex object at any level of depth

texts:
Given a complex object (with nested objects at any depth) I need to be able to quickly retrieve a value for a given property name.

I have designed the following code, I would like to know:

How to tune my code for maximum performance considering passing a big object?
Am I missing some case in data.a.x?
Any other improvements?

var data = {
  a: {
    a1: 'hello',
    a2: true,
    a3: false,
    a4: {},
    a5: [],
    a6: ['red', 'blue', true],
    a7: null,
    a8: undefined,
    a9: NaN,
    a10: function() {},
    a11: Math,
    a12: JSON,
    a13: /a-z/,
    a14: new ReferenceError,
    a15: new Date,
    a16: new Number(7),
    a17: new String("abc"),
    a18: new Boolean(true)
  },
  b: {
    b1: {
      b1a: true,
      b1b: 100
    },
    b2: {
      b2a: true,
      b2b: false,
      b2c: 10.10
    }
  }
}

var app = {
  findProperty: function(data, name) {
    var toType = function(obj) {
      return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
    };
    var data = data,
      process = true,
      result = {
        isFound: false,
        value: null
      };
    var recursion = function(data, name) {
      var type = toType(data);
      if (type === 'object') {
        Object.keys(data).forEach(function(property) {
          if (process) {
            if (name in data) {
              process = false;
              result.isFound = true;
              result.value = data[name];
            } else if (typeof data[property] === 'object') {
              recursion(data[property], name);
            }
          }
        });
      }
    };
    recursion(data, name);
    return result;
  }
}

console.clear();
// found
var a1 = app.findProperty(data, 'a1');
console.log('a1', a1.isFound, a1.value);

var a2 = app.findProperty(data, 'a2');
console.log('a2', a2.isFound, a2.value);

var a3 = app.findProperty(data, 'a3');
console.log('a3', a3.isFound, a3.value);

var a4 = app.findProperty(data, 'a4');
console.log('a4', a4.isFound, a4.value);

var a5 = app.findProperty(data, 'a5');
console.log('a5', a5.isFound, a5.value);

var a6 = app.findProperty(data, 'a6');
console.log('a6', a6.isFound, a6.value);

var a7 = app.findProperty(data, 'a7');
console.log('a7', a7.isFound, a7.value);

var a8 = app.findProperty(data, 'a8');
console.log('a8', a8.isFound, a8.value);

var a9 = app.findProperty(data, 'a9');
console.log('a9', a9.isFound, a9.value);

var a10 = app.findProperty(data, 'a10');
console.log('a10', a10.isFound, a10.value);

var a11 = app.findProperty(data, 'a11');
console.log('a11', a11.isFound, a11.value);

var a12 = app.findProperty(data, 'a12');
console.log('a12', a12.isFound, a12.value);

var a13 = app.findProperty(data, 'a13');
console.log('a13', a13.isFound, a13.value);

var a14 = app.findProperty(data, 'a14');
console.log('a14', a14.isFound, a14.value);

var a15 = app.findProperty(data, 'a15');
console.log('a15', a15.isFound, a15.value);

var a16 = app.findProperty(data, 'a16');
console.log('a16', a16.isFound, a16.value);

var a17 = app.findProperty(data, 'a17');
console.log('a17', a17.isFound, a17.value);

var a18 = app.findProperty(data, 'a18');
console.log('a18', a18.isFound, a18.value);

var b = app.findProperty(data, 'b');
console.log('b', b.isFound, b.value);

var b1 = app.findProperty(data, 'b1');
console.log('b1', b1.isFound, b1.value);

var b2 = app.findProperty(data, 'b2');
console.log('b2', b2.isFound, b2.value);

var b1a = app.findProperty(data, 'b1a');
console.log('b1a', b1a.isFound, b1a.value);

var b1b = app.findProperty(data, 'b1b');
console.log('b1b', b1b.isFound, b1b.value);

var b2a = app.findProperty(data, 'b2a');
console.log('b2a', b2a.isFound, b2a.value);

var b2b = app.findProperty(data, 'b2b');
console.log('b2b', b2b.isFound, b2b.value);

// not found
var xxx = app.findProperty(data, 'xxx');
console.log('xxx', xxx.isFound, xxx.value);

var yyy = app.findProperty(data, 'yyy');
console.log('yyy', yyy.isFound, yyy.value);

toTry function reference


texts: Efficiently calculating differences between file using diff file

texts:
I'm using SVNKit to get diff information between two revisions. I'm using the diff utility to generate a diff file, however I still need to parse it into numbers.

I implemented a solution, but it is rather slow. JGit does something similar, however it actually parses the values itself and returns an object, rather than a output stream, and is much much faster. I was unable to determine how to leverage that for SVNKit, so attempted the following solution:

private Diff compareRevisions(final SVNRevision rev1, final SVNRevision rev2) throws SVNException {
            final Diff diff = new Diff();

            try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

                doDiff(rev1, rev2, baos);

                int filesChanged = 0;
                int additions = 0;
                int deletions = 0;

                final String[] lines = baos.toString().split("\n");

                for (final String line : lines) {

                    if (line.startsWith("---")) {
                        filesChanged++;
                    } else if (line.startsWith("+++")) {
                        // No action needed
                    } else if (line.startsWith("+")) {
                        additions++;
                    } else if (line.startsWith("-")) {
                        deletions++;
                    }

                }

                diff.additions = additions;
                diff.deletions = deletions;
                diff.changedFiles = filesChanged;

                return diff;

            } catch (final IOException e) {
                LOGGER.trace("Could not close stream", e);
                return diff;
    }
}

I've taken to caching the values in files to improve time, but optimally I'd like to speed this up. Perhaps I could use external programs?


texts:
I'm relatively new to PHP and one of the things I miss from other languages are enums. After looking around for some samples on how can I have somewhat similar to them, I came up with this implementation. I want to know how good is it, how can it be improved or any other flaws you can find in it. It's writen in PHP 7.
Base class
abstract class BaseEnum
{
    private $value;

    protected function __construct(string $value) {
        $this->value = $value;
    }

    public function getValue(): string {
        return $this->value;
    }

    public abstract static function parse(?string $value);

    public abstract static function InitializeEnums();
}

This is the base class from where all my "enums" inherit. In short this is an immutable class that hold a single string value and a getter for it (internally all enums will be string, opposed to other languages that are often ints). There is an abstract method that takes a raw string and returns the matching enum instance that needs to be implemented in a case-by-case basis, as well as an initialization method (see below for this).
Concrete enum class
class VoucherType extends BaseEnum {
    private static $invoice;
    private static $creditNote;
    private static $advance;

    public static function InitializeEnums() {
        VoucherType::$invoice = new VoucherType("I");
        VoucherType::$creditNote = new VoucherType("C");
        VoucherType::$advance = new VoucherType("A");
    }

    public static function parse(?string $value): ?self {
        if($value === VoucherType::$invoice->getValue()) return VoucherType::$invoice;
        if($value === VoucherType::$creditNote->getValue()) return VoucherType::$creditNote;
        if($value === VoucherType::$advance->getValue()) return VoucherType::$advance;
        return null;
    }

    public static function invoice(): self {
        return VoucherType::$invoice;
    }
    public static function creditNote(): self {
        return VoucherType::$creditNote;
    }
    public static function advance(): self {
        return VoucherType::$advance;
    }
}
VoucherType::InitializeEnums();

This is one of my real enum classes. All that it does is to provide the fixed valid values and appropriate getters for each one. Also implements the parse that looks each value in turn. It stores singletons of each possible value and those are returned as needed. The initialization of the singletons is done via the InitializeEnums method, which is called outside the class (a dirty trick to simulate a static constructor).
This enables to make simple comparisons with "constant" values like $var == VoucherType::invoice(), or to convert to/from string with appropriate invalid values handling (and replaced with nulls). Variables will always be from this class type (and not simple strings) and assignment/comparision works as expected.
How can I improve it and what's good, bad or should change about it?


texts: Function from WordPress VoteItUp function

texts:
This code comes from a Wordpress plugin's forum called Vote it Up.
It sort posts by vote. A lotof people say that there is more code than is needed.
So I was wondering if someone have any idea about how to clean it a bit.

votingfunctions.php:

function ShowPostByVotes() {
    global $wpdb, $voteiu_databasetable;

    mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
    mysql_select_db(DB_NAME) or die(mysql_error());
    //Set a limit to reduce time taken for script to run
    $upperlimit = get_option('voteiu_limit');
    if ($upperlimit == '') {
        $upperlimit = 100;
    }
    $lowerlimit = 0;

    $votesarray = array();
        $querystr = "
            SELECT *
            FROM $wpdb->posts
            WHERE post_status = 'publish'
            AND post_type = 'post'
            ORDER BY post_date DESC
         ";
        $pageposts = $wpdb->get_results($querystr, OBJECT);
    //Use wordpress posts table
    //For posts to be available for vote editing, they must be published posts.
    mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
    mysql_select_db(DB_NAME) or die(mysql_error());
    //Sorts by date instead of ID for more accurate representation
    $posttablecontents = mysql_query("SELECT ID FROM ".$wpdb->prefix."posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT ".$lowerlimit.", ".$upperlimit."") or die(mysql_error());

    $returnarray = array();
    while ($row = mysql_fetch_array($posttablecontents)) {
        $post_id = $row['ID'];
        $vote_array = GetVotes($post_id, "array");
        array_push($votesarray, array(GetVotes($post_id)));
    }
    array_multisort($votesarray, SORT_DESC, $pageposts);
    $output = $pageposts;
    return $output;

}

index.php:

$pageposts = ShowPostByVotes();

?>
 <?php if ($pageposts): ?>
  <?php foreach ($pageposts as $post): ?>
    <?php setup_postdata($post); ?>

Attention! Code above is something like:

<?php if (have_posts()) : ?>

        <?php while (have_posts()) : the_post(); ?>

so in foreach loop you can use statements like in standard "The Loop" for example the_content, the_time().
To end this add

<?php endforeach; ?>

  <?php else : ?>

Not Found

Sorry, but you are looking for something that isn't here.

    <?php include (TEMPLATEPATH . "/searchform.php"); ?>
 <?php endif; ?>

EDIT:

How I run a custom loop:

        <?php $custom_posts = new WP_Query(); ?>
        <?php $custom_posts->query('category_name=Pictures'); ?>
        <?php while ($custom_posts->have_posts()) : $custom_posts->the_post(); ?>

                <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_content(); ?>

        <?php endwhile; ?>


texts:
I wrote a deque implementation in C for storing char *. It uses a doubly linked list, but I'm calling it a deque since it can only push/pop from the head and tail of the list.

I don't have much experience writing C (I'm more of a Python guy) so please let me know what can be improved! I am already aware of the following:

there are no comments (I've tried to use self-explanatory names)
the testing isn't particularly rigorous

linkedlist.h

#ifndef _LINKEDLIST_H
#define _LINKEDLIST_H
#include <stdlib.h>

struct ll_node {
    struct ll_node *prev;
    struct ll_node *next;
    char           *data;
};

struct linkedlist {
    struct ll_node *head;
    struct ll_node *tail;
    size_t         length;
};

void ll_node_init(struct ll_node *node, char *data);
void ll_init(struct linkedlist *ll);
void ll_destroy(struct linkedlist *ll);
void ll_push_head(struct linkedlist *ll, char *data);
void ll_push_tail(struct linkedlist *ll, char *data);
char *ll_pop_head(struct linkedlist *ll);
char *ll_pop_tail(struct linkedlist *ll);

#endif

linkedlist.c

#include <stdlib.h>
#include "linkedlist.h"

void ll_node_init(struct ll_node *node, char *data) {
    node->prev = NULL;
    node->next = NULL;
    node->data = data;
}

void ll_init(struct linkedlist *ll) {
    ll->head = NULL;
    ll->tail = NULL;
    ll->length = 0;
}

void ll_destroy(struct linkedlist *ll) {
    struct ll_node *node = ll->head;
    struct ll_node *next;

    while(node != NULL) {
        next = node->next;
        free(node);
        node = next;
    }
}

void ll_push_head(struct linkedlist *ll, char *data) {
    struct ll_node *node = malloc(sizeof(struct ll_node));
    ll_node_init(node, data);

    if(ll->head != NULL) {
        ll->head->prev = node;
    }

    if(ll->tail == NULL) {
        ll->tail = node;
    }

    node->next = ll->head;
    ll->head = node;
    ll->length++;
}

void ll_push_tail(struct linkedlist *ll, char *data) {
    struct ll_node *node = malloc(sizeof(struct ll_node));
    ll_node_init(node, data);

    if(ll->tail != NULL) {
        ll->tail->next = node;
    }

    if(ll->head == NULL) {
        ll->head = node;
    }

    node->prev = ll->tail;
    ll->tail = node;
    ll->length++;
}

char *ll_pop_head(struct linkedlist *ll) {
    struct ll_node *node = ll->head;
    char *data;

    if(node == NULL) {
        return NULL;
    }

    if(node == ll->tail) {
        ll->tail = NULL;
    }

    ll->head = node->next;
    ll->length--;

    data = node->data;
    free(node);

    return data;
}

char *ll_pop_tail(struct linkedlist *ll) {
    struct ll_node *node = ll->tail;
    char *data;

    if(node == NULL) {
        return NULL;
    }

    if(node == ll->head) {
        ll->head = NULL;
    }

    ll->tail = node->prev;
    ll->length--;

    data = node->data;
    free(node);

    return data;
}

ll_test.c

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "linkedlist.h"

int main(int argc, char *argv[]) {
    struct linkedlist ll;
    char *data;
    ll_init(&ll);

    ll_push_head(&ll, "Alice");
    ll_push_tail(&ll, "Bob");
    ll_push_tail(&ll, "Charlotte");
    ll_push_head(&ll, "Daniel");
    assert(ll.length == 4);

    assert(strcmp(ll_pop_head(&ll), "Daniel") == 0);
    assert(strcmp(ll_pop_tail(&ll), "Charlotte") == 0);
    assert(strcmp(ll_pop_tail(&ll), "Bob") == 0);
    assert(strcmp(ll_pop_tail(&ll), "Alice") == 0);
    assert(ll.length == 0);

    ll_destroy(&ll);
    return 0;
}


texts: Convert scalar arguments to arrays, and check that lengths are equal

texts:
I've got a Python function that takes two arguments, lat and lon. These arguments can be either scalar values (52.3) or any sort of iterable (e.g. a list or a NumPy array).

At the beginning of my function I need to check what I've been given, and convert both arguments to arrays (if needed) and check that both arguments are the same length.

# Deal with scalar values
try:
    lat_count = len(lat)
except:
    lat = [lat]
    lat_count = 1

try:
    lon_count = len(lon)
except:
    lon = [lon]
    lon_count = 1

if lat_count != lon_count:
    raise ValueError("lan and lon arrays must be the same length")

lat = np.array(lat)
lon = np.array(lon)

It feels horribly messy, but I can't work out how to make it better. Any ideas?


texts: Python implementation of Back Propagation Algorithm without bias

texts:
This program implements the back propagation algorithm of neural network with an example. Can we make it more efficient?
from setuptools.namespaces import flatten
import numpy as np
import math

inputvalues = [0.1, 0.9, 0.5, 0.2]

initialweights = [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]]

hidden_initial_weights = [[[0.2, 0.3, 0.4], [0.5, 0.6, 0.7]],
                          [[0.8, 0.9, 0.1, 0.2], [0.3, 0.4, 0.5, 0.6], [0.7, 0.8, 0.9, 0.1]],
                          [[0.2, 0.3, 0.4, 0.5, 0.6], [0.7, 0.8, 0.9, 0.1, 0.2], [0.3, 0.4, 0.5, 0.6, 0.7], [0.9, 0.8, 0.7, 0.6, 0.5]]]

Hidden_Output_Connection_weights = [[0.5, 0.4, 0.3], [0.6, 0.7, 0.8], [0.1, 0.3, 0.5], [0.7, 0.8, 0.9], [0.45, 0.34, 0.32]]
Target_Value = 0.9
learning_rate = 0.4
weight_matrix = [[initialweights],hidden_initial_weights,[Hidden_Output_Connection_weights]]

# Forward Propagation
intermediate = [inputvalues]   # Intermediate contains output from each layer
for j in range(len(weight_matrix)):
    for l in range(len(weight_matrix[j])):
        result = np.dot(inputvalues,weight_matrix[j][l])
        result1 = [(1-math.exp(-k))/(1+math.exp(-k))for k in result]
        intermediate.append(result1)
        inputvalues = result1

Final_error_from_output_layer_nodes = []
for i in intermediate[-1]:
    Error_in_final_output = (Target_Value - i)*(i)*(1-i)
    Final_error_from_output_layer_nodes.append(Error_in_final_output)

rr = [] # rr is the derivative
for i in reversed(range(len(intermediate)-1)): # subtract one because it is length of output layer
    temp = []
    for j in range(len(intermediate[i])):
        temp.append(intermediate[i][j]*(1-intermediate[i][j]))
    rr.append(temp)

transposed_weight_matrix = [] #transposed_weight_matrix
for i in reversed(range(len(weight_matrix))):
    for j in reversed(range(len(weight_matrix[i]))):
        transposed_weight_matrix.append(list(map(list, zip(* weight_matrix[i][j]))))

Backward_propagation_output = []
final_errors = [Final_error_from_output_layer_nodes]
for i in range(len(transposed_weight_matrix)-1):
    intermediate_error = np.dot(Final_error_from_output_layer_nodes,transposed_weight_matrix[i])
    temp =[]
    for num1, num2 in zip(intermediate_error,rr[i]):
        temp.append(num1 * num2)
    Backward_propagation_output.append(temp)
    Final_error_from_output_layer_nodes = Backward_propagation_output[i]
    final_errors.append(Final_error_from_output_layer_nodes)

final_errors.reverse()

change_in_weights = []
for i in range(len(intermediate)-1):
    temp1 = []
    for j in range(len(intermediate[i])):
        temp = []
        for k in range(len(final_errors[i])):
            temp.append(learning_rate*intermediate[i][j]*final_errors[i][k])
        temp1.append(temp)
    change_in_weights.append(temp1)
# print(change_in_weights)

# Updated weights
updated_weights = []
r = list(flatten(weight_matrix))
for i in range(len(r)):
    temp = []
    for j in range(len(r[i])):
        temp1 = []
        for k in range(len(r[i][j])):
            temp1.append(r[i][j][k]+change_in_weights[i][j][k])
        temp.append(temp1)
    updated_weights.append(temp)


texts: Calculate percentage of values in an array with a certain condition

texts:
I had to write a function that calculates the percentage of values in table less or equal to 2.  Is my code right or is there anything missing?

Public Function intPercentage As Integer

 Dim intAge( , ) As Integer = {{0, 2, 5, 10}

 {2, 0, 1, 3}

 {5, 1, 0, 6}

 {10, 3, 6, 0}}

Dim intRow, intCol As Integer

For intRow= 0 to 3

 For intCol = 0 to 3

 If intAge(intRow, intCol) >= 2 Then

 intTotal = intTotal + intAge(intRow, intCol)

 Next intCol

   Next intRow

 intPercentage = intTotal / 100

 End Function


texts:
I am new to coding and made myself my first little program, which lets me calculate the amount of money I make per hour doing a transcription project. While my code works (yay!) and I am proud of my first attempt at creating a program from scratch, I'm not sure I went about it the most efficient way. Could someone please look this over and let me know where I could improve?

#include <stdio.h>
#include <cs50.h>

int main(void)

{
    float clip_time;
    float real_time;
    float pay_rate;
    float pay_amt;
    float hours;

do{

printf("Transcription Rates\n");
printf("Clip Time: ");
clip_time = get_float();
}
while(clip_time <= 0);

printf("%.2f min clip pays: ", clip_time);
    pay_rate = get_float();

printf("So, $%.2f for the project \n", pay_rate * clip_time);
    pay_amt = pay_rate*clip_time;
    {

do{
    printf("Time to Complete Clip (in minutes): ");
    real_time = get_float();

   printf("Equals %.2f hours \n", real_time/60);
   hours = real_time/60;

}
while(real_time <= 0);

    {
        printf("Real time spent per audio minute: %.2f \n", real_time / clip_time);
}

{
        printf("Hourly pay $%.2f div by %.2f hours equals $%.2f ph \n", pay_amt, hours, pay_amt / hours);
    }

    }
}


texts: Read an input text file and store the tokens in 2 different arrays

texts:
I am very new to Java so please ignore if there are obvious mistakes. If my question seems redundant then please guide me towards the correct link. However, I have surfed enough in order to find the answer. Any changes in code will be greatly appreciated.

I am reading an input file and storing the elements of it in a 2D array. What I want to do is split that array in 2 separate arrays. 1st array would contain all the characters which is firstDimension in my code. Now, I want another array which stores all the integers in an array. I just have to print those arrays. This array should be created as soon as the special character > is observed.

This can be done in 2 ways:

Read the strings in the file and store all of the elements in a 2D array and then divide the array into 1 double and one 2D char array
Read only chars from the file and store it in char array and then read only double values from the file and store it in different array.

My input file has text:

a A b u>0.0001
b b X g>0.0005
Y z N H>0.0003

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Delimiter {
    public static void main(String[] args)
    {
        try {
            Scanner scanner = new Scanner(new File("hello.txt"));
            scanner.useDelimiter(System.getProperty("line.separator"));
            ArrayList<String> list = new ArrayList<String>();
                while (scanner.hasNext()) {
                list.add(scanner.next());
            }
            scanner.close();
                // finally convert the arraylist to a char[][]
            char[][] firstDimension = new char[list.size()][];
            for (int i = 0; i < list.size(); i++) {
                firstDimension[i] = list.get(i).toCharArray();
            }
                for (int i = 0; i < firstDimension.length; i++)
            {
                for (int j = 0; j < firstDimension[i].length; j++)
                {
                    //System.out.println(firstDimension[i][j]);
                    System.out.print(" "+firstDimension[i][j]);
                    System.out.println("");
                }
            }
            } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}


texts:
I need to replace the windows EOL "\r\n" with just "\n", and I want to this in the fastest way possible, as the software will have a lot of files to upload, many of them with a few thousands lines.  My current approach is:

UnicodeEncoding uniEncoding = new UnicodeEncoding();
using (MemoryStream newStream = new MemoryStream())
{
    using (TextReader stream = new StreamReader(fileInfo.Open(FileMode.Open, FileAccess.Read)))
    {
        string line = null;
        while ((line = await stream.ReadLineAsync()) != null)
        {
            line += "\n";
            await newStream.WriteAsync(uniEncoding.GetBytes(line), 0, line.Length);
        }
    }

    client.UploadFile(newStream, remote, true);
}

Another approach I was considering was to wrap the Stream I get from the file, and just not return the \n when read. I think this would consume less memory, but I am not sure if this would cause more problems as I have never really worked with streams.

Any feedback on my current approach / alternatives would be appreciated.


texts:
I have a module, that fetches some object. Then other modules can use this object. Here is a little example of this task:

var Structure = (function(){

    var tree = null,

        df = $.ajax({
            'url'       : '/some/path',
            'type'      : 'POST',
            'data'      : { some : 'data' },
            'dataType'  : 'json'
        }),

        ready = function(cb){
            if (tree) {
                cb(tree);
                return
            }

            $.when(df).then(function(data){
                tree = TreeHandler.create(data);
                cb(tree);
            });
        };

    return {
        df      : df,
        ready   : ready
    };

})();

// Usage:
Structure.ready(function(data){
     console.log (data);
     // some actions with data
});

Am I right on doing this? How can this be made better?


texts: Extract numbers from a string-Javascript

texts:
Consider the following string in javascript:

var string="border-radius:90px 20px 30px 40px";

I want to extract the 4 numbers from that string and store them in an array called numbers.To do that I developed the following code:

var numbers=string.split("border-radius:");
numbers=numbers[1].split("px");

This code is working fine but I was wondering if there is a better approach/solution.Any ideas are welcomed


texts:
This is a helper function, along with three others. It should be called as a .filter(); to return only prime numbers. It is for one of the exercises at FreeCodeCamp.com, "Sum all Primes".

I'm just trying to accumulate the charAt(*) for each n, so 10 would return 1, being 1+0 21 would return 3, being 2+1 and 977 would return 23, being 9+7+7.

I've commented out some of my attempts before thinking of charAt(0) and some n's will have as many as 3 digits, maybe more if I don't have to limit it, but the largest test case stops at 997 I think, but an extra decimal for margin of error. I finally got something to work, but it feels like I'm going the long way to get there.. Surely there's something already built into to JavaScript I'm overlooking to reduce the value of a string. Or should I be trying to turn it into an array of digits?

function isItTHREED(n) {
  //  https://www.thoughtco.com/how-to-determine-number-is-prime-2312518

   //  Try 3.  Take the number, and add the digits up, when those digits are divisible by 3, the number is not prime.
  //          Take 2469, those digits add up to 21, and 21 is divisible by 3, therefore 2469 is not a prime number.
console.log('3s',n);
  n = n.toString();
  var digitONE = Number(n.charAt(0));
  var digitTWO = Number(n.charAt(1));
  var digitTHREE = Number(n.charAt(2));
  var digitFOUR = Number(n.charAt(3));
  console.log('digits',digitONE);
  console.log('digits',digitTWO);
  console.log('digits',digitTHREE);
  console.log('digits',digitFOUR);
  var testing = digitONE + digitTWO +digitTHREE + digitFOUR
  console.log(testing);
  //if(testing % 3 != 0)

  /*
  n = n.toString();
  n = n.split('');
  //num = num.split('');
  n = [n];
  console.log("num", n);
  */
   n = testing;
  return n;
} //end of isItTHREED

isItTHREED(10); // should return 1
isItTHREED(21); // should return 3
isItTHREED(977); // should return 23.

CodePen


texts:
This is my first template implementation. I'm trying to learn C++ and Algorithms. Any constructive criticism on code quality, readability is welcome. Everyone has their own style, but there are certain rules which all good programmers should follow. Kindly remark as to if I have followed those and what rules are missing.

#include <iostream>
#include <new>
using std::cout; using std::cin; using std::endl;
using std::nothrow; using std::size_t;

template<typename T> class Stack {
 public:
  // constructor for class
  Stack() { count = 0;
            last = NULL; }
  // destructor for class
  ~Stack() {  if (count > 0) Clr(); }
  // push item at last of stack
  void Push(T item);
  // pop item from last of stack
  T Pop();
  // get size of stack
  size_t Size();
  void Clr();       // delete all the elements
  // print all the elements
  void Print();
 private:
  // the stack will store elements in the form of a linked list
  struct Node {
    T value;
    Node* next;
  };
  Node* last;   // last points to the last item of the stack
  size_t count;    // number of elements in stack
};
/*
Check for memory allocation first. If memory allocated, then Push element in
the stack.
 */
template<typename T> void Stack<T>::Push(T item) {
  Node* node = new (nothrow) Node;
  if (node == NULL) {
    cout << "Memory allocation failed " << endl;
    return;
  } else {
    node->value = item;
    if (count == 0) {
      node->next = NULL;
      last = node;
      ++count;
    } else {
      node->next = last;
      last = node;
      ++count;
    }
  }
}
/*
Delete the elements
 */
template<typename T> void Stack<T>::Clr() {
  Node* node = last;
  while (count != 0) {
    Node* tempnode = node;
    node = node->next;
    delete tempnode;
    --count;
  }
}
/*
Pop the last element of the stack and return it
 */
template<typename T> T Stack<T>::Pop() {
  if (count == 0) {
    cout << "No element to delete" << endl;
    return (T)0;
  } else {
    Node* node = last;
    T tempval = node->value;
    last = node->next;
    delete(node);
    --count;
    return tempval;
  }
}
/*
Print all the elements
 */
template<typename T> void Stack<T>::Print() {
  if (count == 0) {
    cout << "No elements to print" << endl;
    return;
  } else {
    cout << "Printing from top of the Stack to Bottom" << endl;
    Node* node = last;
    while (node != NULL) {
      cout << node->value << "->";
      node = node->next;
    }
    cout << endl;
  }
}
/*
Get the size of the Stack
 */
template<typename T> size_t Stack<T>::Size() {
  return count;
}
/*
Main function
 */
int main() {
  Stack<int> s;
  s.Push(12);
  s.Push(10);
  s.Push(23);
  s.Push(34);
  cout << "The value Popped from the Stack: " << s.Pop() << endl;
  s.Print();
  return 0;
}


texts: Present table of data, acquired from an endpoint, with option to sort by different values

texts:
I have built a Vue app which fetches data from an endpoint and presents that data in a table with sortable columns.

The app is based on this React challenge which is to create a table of users and their properties, from the data provided in the endpoint.

Here are the user stories fulfilled:

  I can see a table of the Free Code Camp campers who've earned the most brownie points in the past 30 days.
  I can see how many brownie points they've earned in the past 30 days, and how many they've earned total.
  I can toggle between sorting the list by how many brownie points they've earned in the past 30 days and by how many brownie points
  they've earned total.

Here is my code (working example):

const endpoint = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent'

const store = {
  state: {
    sortingBy: ''
  }
}

new Vue({
  el: '#app',
  data() {
    return {
      data: [],
      state: store.state
    }
  },
  mounted() {
    Vue.http.get(endpoint).then(response => {
      this.data = response.body
    }, response => {
      console.warn('There was a data error:', response)
    })
  },
  methods: {
    sortByRecent() {
      this.data = _.sortBy(this.data, 'recent').reverse()
      store.state.sortingBy = 'recentDescending'
    },
    sortByAllTime() {
      this.data = _.sortBy(this.data, 'alltime').reverse()
      store.state.sortingBy = 'allTimeDescending'
    },
    getActiveClass(string) {
      return {active: store.state.sortingBy.includes(string)}
    }
  }
})
#app {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.active {
  font-weight: bold;
}
button {
  font-size: 20px;
}
img {
  border-radius: 50%;
  height: 30px;
  width: 30px;
}

  <button @click="sortByRecent">Sort by Recent Points</button>
  <button @click="sortByAllTime">Sort by All Time Points</button>

        #

        Username
        Recent Points
        Total Points

      {{index + 1}}

      {{user.username}}
      {{user.recent}}
      {{user.alltime}}

Here is a repo with all the code (bootstrapped with vue-loader webpack).

My questions are:

I have placed a method for computing a CSS classname in methods - getActiveClass. In the documentation, it specifies that such methods can live inside the computed object:

  We can also bind to a computed property that returns an object.

However when doing so, I get the following console error in the browser:

  Uncaught TypeError: _vm.getActiveClass is not a function

Why does placing this method inside a computed object render this error?
My project was bootstrapped with vue-loader's webpack preset. In order to make the API call to my endpoint, I had to import Vue so that I could use vue-resource. Should the API call be made in main.js and then passed in as a prop to App.vue to avoid importing Vue in multiple places?
The data is received from the API call in any of the lifecycle methods beforeCreate, created, beforeMount and mounted. Which is the correct one for it to go?
Does it make sense for this code to all live in one single file component, or should it be split up into separate smaller components?


texts:
I've got a code that is working in my environment.
Nevertheless it is pretty ugly.

This is what I am trying to do.
I get a selectbox from a side with a lot of city names.
I filter some names and push them into an array and hide them. The other ones are also pushed into an array, but shown.

Now I append two options to the end of the selectbox, one is displayed, the other one hidden.

When someone clicks the option all, the options from the array otherCities are shown and defaultCities are hidden. the option all is hidden as well, less is shown.

This behavior works the other way round, too.

How can I simplify my code? Any help is welcome.

var otherCities = new Array();
var defaultCities = new Array();
var selectBoxCity = jQuery("select[name='city']");

if(selectBoxCity.size() != 0) {
        selectBoxCity.prepend('<option value="" selected="selected">-- Please Select --</option>');
    otherCities = new Array();
    defaultCities = new Array();
    var cityArray = ['OE', 'MK', 'SI', 'BO', 'DO', 'BM', 'HER', 'GE', 'HH'];
    var options = jQuery("select[name='city'] option");
    options.each(function() {
        var o = jQuery(this);
        if (jQuery.inArray(o.attr("value"), cityArray) == -1) {
            otherCities.push(o.hide());
        } else {
            defaultCities.push(o.show());
        }
    });
    selectBoxCity.find("option").end().append("<option value='all'>+</option>");
    selectBoxCity.find("option").end().append("<option value='less'>-</option>");

}

var selectBoxCity = jQuery("select[name='city']");
selectBoxCity.find("option:first").attr("selected", true);

$("select[name='city'] option[value='less']").hide();

if(selectBoxCity.val() == "all") {
    jQuery.each(otherCities,function() {
        $(this).show();
    });
    jQuery.each(defaultCities,function() {
        $(this).hide();
    });
    $("select[name='city'] option[value='all']").hide();
    $("select[name='city'] option[value='less']").show();
}
if(selectBoxCity.val() == "less") {
    jQuery.each(otherCities,function() {
        $(this).hide();
    });
    jQuery.each(defaultCities,function() {
        $(this).show();
    });
    $("select[name='city'] option[value='all']").show();
    $("select[name='city'] option[value='less']").hide();
}


texts: O(N) vs O(N * N) for Word Frequency Algorithm

texts:
I am trying to come up with a better solution to the following problem:

Statement

  You are supposed to write a function which takes the contents of a document in string format and also a whole number, n, providing how many results to return. (So that's two arguments for the function.)  The function should return the n most frequently occurring words in descending order.  The algorithm should be \$O(N)\$, not \$O(N \cdot N)\$.

My Current Solution

function freq(str, n) {
  var results = [];

  var strArray = str.split(/\s+/), countObj = {}, wordArray = [], wordObj = {};

  strArray.forEach(function(el) {
    countObj[el] ? countObj[el] += 1 : countObj[el] = 1;
  });

  for(var el in countObj) {
    wordObj[countObj[el]] ? wordObj[countObj[el]].push(el) : wordObj[countObj[el]] = [el];
  }

  for(var el in wordObj){
    wordArray.push(wordObj[el].join(' '));
  }

  for(var i = 0; i < n; i++) {
    results.push(wordArray[wordArray.length - 1 - i]);
  }

  return results.join('\n');
};

Time Complexity

The solution seems to be \$O(N)\$. Are there any improvements I could make?

Best Practices

I am using ternary operators a lot for the if-else construct. Am I overusing them?

General

Any suggestions regarding how I can make this solution 'production grade' quality?


texts: Fitter Nearest-Neighbor function with three nested loops

texts:
Background Problem

Consider a set of students that we want to place into Ng groups each of which contains Ns students.  Let's label the students 1, 2, ... , Ng * Ns, and let an assignment of students be an array of shape (Ng, Ns) that encodes the groupings of students.  For example, if Ng = 2 and Ns = 3, then an assignment of students could be:

[[1, 4, 5], [2, 3, 6]]

note that any assignment that differs either in permuting students within groups, or in permuting the groups themselves would be considered an equivalent assignment.  So for the assignment above, one equivalent assignment would be:

[[6, 3, 2], [1, 5, 4]]

For a given assignment A, we define a neighboring assignment as any inequivalent assignment that differs from A by a single swap of students.  For example, a neighbor of the first assignment above is obtained by swapping students 1 and 6 to obtain

[[1, 3, 2], [6, 5, 4]]

Additionally, we have a fitness function f that takes an assignment A as its input, and outputs a real number f(A).  The goal is to construct a function which I call fitter_neighbor which takes an assignment A and a fitness function f as its inputs and returns a fitter neighboring assignment provided such an assignment exists.  If no such assignment exists, then fitter_neighbor should return A.  It is not required that fitter_neighbor returns the fittest neighbor, and in fact, the goal is to have it systematically search through the neighbors and return the first fitter neighbor it comes across.

Current seemingly-not-very-pythonic code

def fitter_neighbor(A, f):

    Ng = len(A) #number of groups
    Ns = len(A[0]) #number of students per group
    Nn = int(Ns ** 2 * Ng * (Ng - 1) / 2) #number of neighboring assignments

    A_swap = np.copy(A) #initialize copy of assignment to be changed

    g1 = 0 #group number of person A in swap
    n_swaps = 0 #counter for number of swaps considered

    while g1 < Ng and f(A_swap) <= f(A) and n_swaps < Nn:
        s1 = 0
        while s1 < Ns and f(A_swap) <= f(A) and n_swaps < Nn:
            g2 = g1 + 1 #ensures that no swaps are repeated
            while g2 < Ng and f(A_swap) <= f(A) and n_swaps < Nn:
                s2 = 0
                while s2 < Ns and f(A_swap) <= f(A) and n_swaps < Nn:
                    A_swap = np.copy(A)
                    A_swap[g1, s1], A_swap[g2, s2] = A_swap[g2, s2], A_swap[g1, s1]
                    n_swaps += 1
                    s2 += 1
                g2 += 1
            s1 += 1
        g1 += 1
    if n_swaps < Nn:
        return A_swap
    else:
        return A

Can fitter_neighbor be  written in a more pythonic way?  In particular, is it possible to eliminate the nested while loops in some clever way?

As an example fitness function for the case Ns = 2, consider

def f2(A):
    return np.sum([(g[1] - g[0]) ** 2 for g in A])


texts:
I am writing my own game engine, and I wanted to share with my own window class written in C++ using GLFW as the windowing API. Is there someone who can help me better this class? I'm not a complete beginner in C++ but not an expert.

Window.h:

#pragma once

#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <iostream>

namespace Engine
{
    namespace graphics
    {
        class Window
        {
        private:

            int m_Width, m_Height;
            const char* m_Title;
            bool m_VSync;
            bool Init();

        public:

            GLFWwindow* m_Window;
            Window(const char* title, int width, int height, bool vsync);
            ~Window();
            void Clear(float x, float y, float z);
            void Update();
            bool Closed() { return glfwWindowShouldClose(m_Window); }
        };
    }
}

Window.cpp:

#include "Window.h"

namespace Engine
{
    namespace graphics
    {
        static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
        {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
                glfwSetWindowShouldClose(window, GLFW_TRUE);
        }

        void framebuffer_size_callback(GLFWwindow* window, int width, int height)
        {
            glViewport(0, 0, width, height);
        }

        bool Window::Init()
        {
            if (!glfwInit())
            {
                std::cout<<"ERROR::GLFW::INIT : GLFW failed to initialize"<<std::endl;
                return false;
            }

            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

            m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL, NULL);
            glfwSetKeyCallback(m_Window, key_callback);
            glfwSetFramebufferSizeCallback(m_Window, framebuffer_size_callback);

            glfwMakeContextCurrent(m_Window);

            if (glewInit() != GLEW_OK)
            {
                glfwTerminate();
                std::cout << "ERROR::GLEW::INIT : GLEW failed to initialize"<<std::endl;
                return false;
            }

            if (m_VSync)
            {
                glfwSwapInterval(1);
                std::cout << "WINDOW::OPTIONS::VSYNC::ON" << std::endl;
            }
            else
            {
                std::cout << "WINDOW::OPTIONS::VSYNC::OFF" << std::endl;
            }
            return true;
        }

        Window::Window(const char* title, int width, int height,bool vsync)
        {
            m_Title = title;
            m_Width = width;
            m_Height = height;
            m_VSync = vsync;
            Init();
        }

        void Window::Clear(float x, float y, float z)
        {
            glClearColor(x, y, z, 1.0f);
            glEnable(GL_DEPTH_TEST);
            glClear(GL_COLOR_BUFFER_BIT |GL_DEPTH_BUFFER_BIT);
        }

        void Window::Update()
        {
            int width, height;

            glfwGetFramebufferSize(m_Window, &width, &height);

            glViewport(0, 0, width, height);

            glfwSwapBuffers(m_Window);
            glfwPollEvents();
        }

        Window::~Window()
        {
            glfwTerminate();
            glfwDestroyWindow(m_Window);
        }
    }
}


texts: Faster way to group email-date pairs by date without many nested for loops?

texts:
Given list of pairs (email-date):

['ann_osman@mail.com', '2 august 1976'],
['jz_neo@mail.com', '3 august 2001'],
['keyes_signak@mail.com', '2 october 2001'],
['cassadi_algazi@hotmail.com', '2 october 2001'],
['karmen_algazi@aol.com', '2 august 2001']]

I need to turn it into dictionary grouped by dates (one date → many emails).

I can do it with for loops:

def emails_for_one_date():

        for each_entry in email_date_table:

                for each_date in each_entry:
                        current_date_as_key = each_date

                        for each_entry2 in email_date_table:
                                list_emails = []
                                if each_entry[1] == current_date_as_key:
                                        list_emails.append( each_entry[0])
                                date_for_emails_dict[current_date_as_key] = list_emails
        print("------------------- dict here")
        print(date_for_emails_dict)

But Python is such a powerful language, I want to know the 'pythonic' way of doing it!
I suspect it can be one line.


texts:
This was the problem from "30 Days of Code" on Hackerrank:

  Given set \$S = \lbrace{1,2,3,\dots,N}\rbrace\$, find two integers \$A\$ and \$B\$ (where \$A \lt B\$), from set \$S\$ such that the value of \$A\&B\$ is the maximum possible and also less than a given integer, \$K\$. In this case, \$\&\$ represents the bitwise AND operator.

  The first line contains an integer, \$T\$ , the number of test cases.
  Each of the subsequent \$T\$ lines defines a test case as 2 space-separated integers, \$N\$ and \$K\$ , respectively.

I created the program which I know is not refined but passed every test case. I want to know that does my code comes under bad programming practices.

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        int k[] = new int [T];
        int n[]  = new int [T];
        for(int  i= 0;i<T;i++){
         n[i] = in.nextInt();
         k[i]=in.nextInt();
        }
        for(int karr =0 , narr=0;karr<k.length&& narr<n.length;karr++,narr++){
             int  a[] = new int [n[narr]];
             int max =0;
             for (int i=0;i<n[narr];i++){
                 a[i]= i+1;
             }
             for(int i=0;i<a.length;i++){
                 for(int j=1;j<a.length;j++){
                     if(a[i]<a[j]){
                     int andvalue = a[i]&a[j];
                         int temp = max ;
                     if( andvalue<k[karr] ){
                         if(andvalue>temp){
                            max = andvalue;
                         }}

                     }

                 }
             }
             System.out.println(max);
        }

    }
}


texts: WordPress plugin for shipping calculation

texts:
I am writing a WordPress plugin that allows shipping calculation on the product page. Originally, shipping calculation is only available in the cart.

To calculate shipping costs on product page, three things are necessary: A product with valid dimensions, the quantity and the destination postcode.

Here's what it does before getting to the getCostPerShippingMethod() method bellow:

Receives a REST request
Sanitizes and validates it
Generate the Payload object (which extracts product dimensions, etc)
Determines Shipping Zone and Shipping Methods (Example: We offer UPS for postcode X and also Local Pickup for postcode Y)
Passes an array of Shipping Methods to getCostPerShippingMethod() bellow.

Then, at getCostPerShippingMethod():

Create a Package object for it, which calculates cubage according to product dimensions, quantity and shipping method rules (each shipping method may calculate cubage differently)
Instantiate a Handler for this shipping method, which is a internal class prepared to handle the external shipping method calculation rules
Handler validates the package dimensions per shipping method. (Example: Local pickup: no limit | UPS: max 30kg, 200cm height, etc)
Then it calls the Handler's calculate method, which does it's magic depending on the Shipping Method and payload requested and return the shipping costs

The array returned by getCostPerShippingMethod() is then cascaded down to the frontend to be displayed to the user.

/**
 * Calculates shipping costs for an array of shipping methods
 *
 * @param array $shipping_methods
 * @param Payload $payload
 * @return array
 */
public static function getCostPerShippingMethod(array $shipping_methods, Payload $payload)
{
    $instance = new self;
    $shipping_costs = array();

    foreach ($shipping_methods as $shipping_method) {
        $shipping_method_slug = sanitize_title(get_class($shipping_method));
        $response = new Response($shipping_method);

        try {
            // Create Package based on product and quantities per Shipping Method
            $package = Package::makeFrom($payload->getProduct(), $payload->getQuantity(), $shipping_method);
            $payload->setPackage($package);

            // Create CFPP handler for this Shipping Method
            $cfpp_handler = Factory::createHandler($shipping_method);

            // Gives a chance to set rules, then validate Payload per Shipping Method
            $cfpp_handler->beforeValidate()->validate($payload);

            // Calculate Costs
            do_action('cfpp_before_calculate_cost', $payload, $shipping_method);
            $shipping_costs[] = apply_filters('cfpp_response_success_' . $shipping_method_slug, $cfpp_handler->calculate($payload));

        } catch(PackageException $e) {
            do_action('cfpp_response_package_exception', $shipping_method_slug);
            $shipping_costs[] = $response->error($e->getMessage());
        } catch (FactoryException $e) {
            do_action('cfpp_response_factory_exception', $shipping_method_slug);
            $shipping_costs[] = $response->error($e->getMessage());
        } catch (ValidationErrorException $e) {
            do_action('cfpp_response_validation_exception', $shipping_method_slug);
            $shipping_costs[] = $response->error($e->getMessage());
        } catch (HandlerException $e) {
            do_action('cfpp_response_handler_exception', $shipping_method_slug);
            $shipping_costs[] = $response->error($e->getMessage());
        }
    }

    // Successes first, errors last
    $shipping_costs = $instance->orderShippingCosts($shipping_costs);

    return $shipping_costs;
}

It all works fine. However, I'm having problems testing this class. I can't see how, but this method probably has poor architecture.

How can I improve this code to make it more testable and architecturally correct?


texts:
The following responsive navigation on JSfiddle works well, however I am just wondering whether there is any way to improve what I have done. I am new at JQuery so all help appreciated: JSFiddle here

$(document).ready(function () {
    $(".menu").click(function () {
        $('#menu').animate({
            'left': '0px'
        });
    });
    $("#close").click(function () {
        $('#menu').animate({
            'left': '-100px'
        });
    });
    $(".menu").click(function () {
        $('#container').animate({
            'left': '100px'
        });
    });
    $("#close").click(function () {
        $('#container').animate({
            'left': '0px'
        });
    });
});


texts: Rendering two logos in a React search component

texts:
Using React.Perf I found that there are few bottlenecks in the render code of one component from the big React app (look at the numbers 1 and 2 in the code below). For sake of simplicity I stripped that out.

// SearchComponent
render() {

    const leftLogoElement = leftLogo && (
        <SearchLogo
            image={leftLogo.image}
            additionalClassNames={['left', leftLogo.additionalClasses]} // 1
        />
    );

    const rightLogoElement = rightLogo && (
        <SearchLogo
            image={rightLogo.image}
            additionalClassNames={['right', rightLogo.additionalClasses]} // 2
        />
    );

    return (

          { leftLogoElement }
          { // ... some other react components which should be updated quite often }
          { rightLogoElement }

    );
}

Since this component itself (where these bottlenecks reside) updates quite often, each time when it rerenders it causes to recreate different versions of additionalClassNames arrays. It obviously leads to calling wasted renders of SearchLogo component, because even though arrays looks the same, but they have different references so they are not equal.

So here is the question. How can I handle this case nicely? I'd like to see conventional approach or any best practices if they exist.

Here is the way how I've managed that. I used constructor for declaring component's variable this.classes to store the css classes I need to pass down to the components tree.

// SearchComponent

constructor() {
    this.classes = [];
}

render() {

    const leftLogoElement = leftLogo
       && this.classes.push('left', leftLogo.additionalClasses)
       && (
        <SearchLogo
            image={leftLogo.image}
            additionalClassNames={this.classes}
        />
    );

    this.classes.length = 0;
    this.classes.push('right', powerByLogo.additionalClassName);
    const rightLogoElement = rightLogo && (
        <SearchLogo
            image={rightLogo.image}
            additionalClassNames={this.classes}
        />
    );

    return (

          { leftLogoElement }
          { // ... some other react components which should be updated quite often }
          { rightLogoElement }

    );
}

It works, but it looks ugly from my perspective, and I can't figure out any better ways. So, I would appreciate any ideas.


texts: Implementing SOLID Principles with C# Asp.net

texts:
I have started learning about SOLID principles yesterday. I've got a detailed explanation of SOLID principles here. After reading it, and a few other articles, I have tried to apply these principles in one of my projects.
This is a tool for importing data from another system. Requirements are as follows:

Read some settings from SQL Server database.
Call an external system API with read settings.
API returns the result in Json format.
Returned results should be saved in SQL Server Database.

Following code sample is in C# with Asp.Net
I have a form that initiates the import process on a button's click event.
private void btnStart_Click(object sender, EventArgs e)
        {
            IReader _reader = new DBReader();
            Interfaces.IWriter _writer = new Classes.DBWriter();

            Interfaces.IExternalSystemInteraction _externalSystem = new Classes.JSonExternalSystem(_writer);

            Classes.Client _client = new PxImportApplication.Classes.Client(_reader, _externalSystem);
            _client.Invoke();
        }

DBReader class inherits from IReader interface and does the job to read settings from SQL server database. We can create a new class if there is a requirement to read from MySQL database instead of SQLServer.

Similary DBWriter writes into SQL Server database and implements IWriter interface.

JSonExternalSystem class hits the API and reads data into Json format. IWriter interface instance is passed to get the Json data so that it could write that data into the SQL Server DB.

Client class has the following implementation:
class Client
    {
        private IReader _reader;
        private Interfaces.IExternalSystemInteraction _externalSystemInformation;

        public Client(IReader reader, Interfaces.IExternalSystemInteraction externalSystem)
        {
            _reader = reader;
            _externalSystemInformation = externalSystem;

        }

    public void Invoke()
        {
            List<IProperties> lstProperties = _reader.ReadData();
            _externalSystemInformation.HitAPI(lstProperties);
        }
    }

JSONExternalSystem's implementation is as follows:
class JSonExternalSystem : Interfaces.IExternalSystemInteraction
    {

        private Interfaces.IWriter _writer;

        public JSonExternalSystem(Interfaces.IWriter writer)
        {
            _writer = writer;
        }

        #region IExternalSystemInteraction Members

        public void HitAPI(List<IProperties> properties)
        {
           foreach (IProperties property in properties)
            {
                ReadJsonFormat(property.Xproperty);
                _writer.ImportToDataBase();

            }
        }
   }

My question is: By looking at this much code, do you think that I am on the right way to implement SOLID principles? I know that this doesn't show the whole implementation but most of the code for other classes goes more or less like the above given classes. I am sure I must be lacking somewhere as this is just my second day. Kindly correct me.


texts:
The purpose of the below code is to build a shape based on the user input, specifically:

Prompt the user to enter a shape - either a triangle or a square
Determine which "texture" to use for the shape - currently set at #'s for squares, *'s for triangles
Build the shape based on the selected texture

Sample output for "Square":

#####
#####
#####

Sample output for "Triangle":

*
**
***
****
*****

How can I completely redo the structure and flow of the program to better follow convention, especially in regards to the way the classes are structured? I still want use multiple classes however, as the main thing i'm trying to do here is work out how to use classes properly. Any other general refactoring welcome too.

Also sorry for the tab spacing. It's set to 2, but is a lot more when I paste it here.

# Shape Builder v0.1

class BuildShape
  def buildShapeCheck
        if @text == "square"
            self.buildSquare
        else
            self.buildTriangle
        end
    end

    def buildSquare
        (1..3).each do
            puts @texture*5
        end
    end

    def buildTriangle
        j = 1
        (1..5).each do
            puts @texture*j
            j += 1
        end
    end
end

class Textures < BuildShape
    def shapeCheck
        @texture = ""
        if @text == "square"
            @texture = "#"
            buildShapeCheck
        else
            @texture = "*"
            buildShapeCheck
        end
    end
end

class UserInput < Textures
    def initialize(text)
        @text = text
    end

    def printInput
        print "you entered: "
        puts @text
        self.testIfValid
    end

    def testIfValid
        if @text == "square" || @text == "triangle"
            puts "#{@text} is a valid shape."
            shapeCheck
        else
            puts "#{@text} is not a valid shape, try again"
            newUserInput = UserInput.new(gets.chomp.downcase)
            newUserInput.testIfValid
        end
    end
end

puts "Enter either \"triangle\" or \"square\""
user_input = gets.chomp
newUserInput = UserInput.new(user_input.downcase)

newUserInput.printInput


texts: Unit (Integration) Test for code that interacts with a database

texts:
I am trying to create some (I believe these are Integration not Unit) tests for code that interacts with a database and I am not sure this is the right approach.

I would appreciate any reviews and possible improvements.

Using: VS2010 Unit Testing Framework

This is the function I want to test:

public IDbConnection OpenThirdPartyDatabase(string path, string password)
{
    var provider = GetProvider(path, password);
    return DBObjectFactory.GetObject().GetConnection(provider.Name, true, true);
}

Functions used by OpenThirdPartyDatabase

private static IDBProvider GetProvider(string path, string password)
{
    var providers = DBProviders.GetObject();
    var providerExists = providers.Cast<IDBProvider>().Any(dbProvider => dbProvider.Name == "MyProviderName");

    return providerExists ? providers.GetDBProvider("MyProviderName") : CreateProvider(path, password);
}

private static IDBProvider CreateProvider(string path, string password)
{
    IDBProvider provider = new DBAccessProvider("MyProviderName", path, "", password);
    DBProviders.GetObject().Add(provider);

    return provider;
}

public IDbConnection GetConnection(string ProviderName, bool OpenConnection, bool UseConnectionPool)
{
    IDBProvider dbProvider = DBProviders.GetObject().GetDBProvider(ProviderName);
    if (dbProvider == null)
        throw new UndeclaredDBProviderException(ProviderName);
    else
    {
        IDbConnection newConnection = null;
        if ((connectionPool.ContainsConnection(ProviderName)) && (UseConnectionPool))
            newConnection = connectionPool.GetConnection(ProviderName);
        else
        {
            newConnection = dbProvider.GetConnection();
            if (UseConnectionPool)
                connectionPool.AddConnection(ProviderName, newConnection);
        }
        if ((OpenConnection) && (newConnection.State == ConnectionState.Closed))
            newConnection.Open();
        return newConnection;
    }
}

Tests:

/// <summary>
/// Test Connection with valid path and password
/// </summary>
[TestMethod]
public void ThirdPartyConnection_Valid()
{
    var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("Data\\test.mdb", "pass");
    Assert.AreNotEqual(testConnection, null);
}

/// <summary>
/// Test Connection With Invalid Password
/// </summary>
[TestMethod]
[ExpectedException(typeof(OleDbException),"Not a valid password.")]
public void ThirdPartyConnection_ShouldThrowOleDbException_InvalidPassword()
{
    var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("Data\\test.mdb", "invalidpassword");
}

/// <summary>
/// Test Connection with invalid path
/// </summary>
[TestMethod]
[ExpectedException(typeof(OleDbException))]
public void ThirdPartyConnection_ShouldThrowOleDbException_InvalidPath()
{
    var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("InvalidPath\\Data\\test.mdb", "pass");
}

/// <summary>
/// Test Connection String
/// </summary>
[TestMethod]
public void ThirdPartyConnection_ConnectionString()
{
    var testConnection = _thirdPartyConnManager.OpenThirdPartyDatabase("Data\\test.mdb", "pass");
    Assert.AreEqual(testConnection.ConnectionString,"Expected Connection String","Not expected Connection String");
}


texts:
I was assigned to make a Rational class to perform functions on fractions. After awhile I got it to work, but now I'm wondering how to simplify and clean up my code. Basically how to improve and use good Java practices so I can write better Java in the future.

public class Rational {

    private int numer, denom;

//constructors
        public Rational(){
            int num = 1;
            int den = 2;
            reduce();
        }
        public Rational(int num, int den){
        numer = num;
        denom = den;
        reduce();
        }
        public Rational(Rational x){
        numer = x.numer;
        denom = x.denom;
        reduce();
        }

//setters
        public void setNumer(int num){
        numer = num;
        reduce();
        }
        public void setDenom(int den){
        denom = den;
        reduce();
        }
        public void setRational(int num, int den){
        numer = num;
        denom = den;
        reduce();
        }

//getters
        public int getNumer(){
        return numer;
        }
        public int getDenom(){
        return denom;
        }

//Copy method
        public void copyFrom(Rational x){
        numer = x.numer;
        denom = x.denom;
        reduce();
        }

//Equals method
        public boolean equals(Rational x){
        if (numer / denom == x.numer / x.denom){
        return(true);
                }
        else {
        return(false);
            }
        }

//Compare to method
        public int compareTo(Rational x){
        if (numer / denom == x.numer / x.denom){
        return (0);
        }
        else if (numer / denom < x.numer / x.denom){
        return (-1);
        }
        else{
        return (1);
            }
        }

//Find greatest common divisor
        static int gcd(int x, int y){
        int r;
        while (y != 0) {
        r = x % y;
        x = y;
        y = r;
            }
        return x;
        }

//Rational Addition
        public void plus(Rational x){
        int greatdenom = x.denom * denom;
        int multx = greatdenom / x.denom;
        int mult = greatdenom / denom;
        denom = x.denom * denom;
        numer = (x.numer * multx) + (numer * mult);
        reduce();
        }

//Rational Subtraction
        public void minus(Rational x){
        int greatdenom = x.denom * denom;
        int multx = greatdenom / x.denom;
        int mult = greatdenom / denom;
        denom = x.denom * denom;
        if (x.numer > numer){
        numer = (x.numer * multx) - (numer * mult);
            }
        else {
        numer = (numer * mult) - (x.numer * multx);
            }
        reduce();
        }

//Multiplication
        public void times(Rational x){
        numer = numer * x.numer;
        denom = denom * x.denom;
        reduce();
        }

//Division
        public void divBy(Rational x){
        numer = numer / x.numer;
        denom = denom / x.denom;
        reduce();
        }

//Fraction simplifier
        private void reduce(){
        int divisor;
        divisor = Rational.gcd(numer, denom);
        numer = numer / divisor;
        denom = denom / divisor;
        }

    @Override
        public String toString(){
        if (denom == 1){
        return numer + "";
        }
        else{
        return numer + " / " + denom;
        }
    }
}


texts: Parsing command input with simple bimaps

texts:
I've been playing with a simple toyrobot exercise to brush up some of my forgotten language skills and was wondering if there was a nicer way to implement my main command parsing loop.  I think the use of the two maps and the nested ternary operator is readable but would be interested in seeing other approaches.

#include "toyrobot.hpp"
#include <iostream>
#include <regex>
#include <string>
#include <map>

int main () {
  using namespace std;

  map<string,int> dirtoi = {{"NORTH", 0}, {"EAST", 1}, {"SOUTH", 2}, {"WEST", 3}};
  map<int,string> itodir = {{0, "NORTH"}, {1, "EAST"}, {2, "SOUTH"}, {3, "WEST"}};
  regex place("^PLACE (\\d),(\\d),(NORTH|EAST|SOUTH|WEST)$");

  Robot robot = Robot();
  Option<Table> table = Some(Table(Point(0,0),Point(4,4)));

  smatch m;
  string l;
  while (getline(cin, l))
  {
        l == "MOVE" ? robot.move() :
        l == "LEFT" ? robot.left() :
        l == "RIGHT" ? robot.right() :
        l == "REPORT" ? robot.report(itodir) :
        regex_match (l,m,place) ? robot.place(Point(stoi(m[1]), stoi(m[2]))
                                            , dirtoi.at(m[3])/2.0, table) :
    (void)0;
  }
}


texts:
This is one of my first projects, just a quick hobby thing for fun.

#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
using namespace std::this_thread;
using std::chrono::system_clock;

int random();

int main()
{
    cout << "Choose a JonTron episode!" << endl;
    string JonTron;
    getline(cin,JonTron);
    cout << "You chose " << JonTron << "." << endl;
    if (JonTron == "Aquaman")
        cout << "What's this blue pants? What-- what's this blue pants?" << endl;
else if (JonTron == "Anti-Drug Games")
    cout << "Too late, talking leg!" << endl;
else if (JonTron == "Banjo-Kazooie")
    cout << "CAAAAAAAAAAAAARS??? CARS?!?!?!" << endl;
else if (JonTron == "California Games")
    {cout << "SWOOD THIS! SWOOD THAT! What the FUCK does SWOOD mean?!?!?!" << endl;
    sleep_for(milliseconds(1000));
    cout << "I used to say it all the time in Cali! Grommet this, grommet that!";
    }
else if (JonTron == "Nightshade")
    {
    cout << "Congratulations! You've just won the Jef and Paul Award for Excellence in Shopping Centers!"<< endl;
    sleep_for(milliseconds(3000));
    cout << "Actually, the crowbar snaps in two." << endl;
    sleep_for(milliseconds(3000));
    cout << "Just kidding." << endl;
    sleep_for(milliseconds(5000));
    cout << "Fool me once, I'm mad." << endl;
    sleep_for(milliseconds(5000));
    cout << "Fool me twice, how could you?" << endl;
    sleep_for(milliseconds(5000));
    cout << "Fool me three times, you're officially that guy, okay--" << endl;
    sleep_for(milliseconds(3000));
    cout << "You know the one, you go to a bar, and he's like," << endl;
    sleep_for(milliseconds(3000));
    cout << "'This suit is ehh, official, it's a Giorgio Armani, actually, my dad knows him'," << endl;
    sleep_for(milliseconds(3000));
    cout << "FUCK YOU!" << endl;
    sleep_for(milliseconds(1000));
    cout << "I AIIIIIIIIIN'T HAVIN' THAT SHIT!!" << endl;
    }
else if (JonTron == "The Skateboard Kid")
    cout << "You just wanna hang up somebody's coat, and the couch falls out!" << endl;
else if (JonTron == "The Zoo Race")
    cout << "What'd they program this in, C--??" << endl;
    else
        cout << "What the fuuuuuck?" << endl;
cout << "You done now? We done? (Press any key [and then hit enter, duy] to be done.)" << endl;
float fuckingdummyvar;
cin >> fuckingdummyvar;
}

My current main concern is the very large block of if-elseif-else. To put things concisely, is there any less gigantically ugly way to do this?


texts: jQuery slideshow with connected links and the ability to pause/resume when hovered

texts:
Update: Here is Take 2.

I want a slideshow with three primary pieces of functionality:

Has text links that act as bullet-points and can jump directly to a slide when clicked.
Pauses when a slide or link is moused over.
Resumes resumes playing from the currently active slide if the user clicks a link.

This is what I came up with. Thanks for your feedback.

$(function() {
  var slideCount = $("#carousel-slides > img").length
  var slideToActivate = 1
  var viewingLength = 2000
  var loop

  automateTheCarousel()

  /* === events handlers === */
  $("#carousel-nav").on("click", "a", function() {
    slideToActivate = $(this).data("linked-image")
    changeCarouselSlide()
  })

  $("#carousel-slides, #carousel-nav").hover(stopTheCarousel, automateTheCarousel)

  /* === functions === */
  function automateTheCarousel() {
    loop = setInterval(goToNextCarouselSlide, viewingLength)
  }

  function stopTheCarousel() {
    clearInterval(loop)
  }

  function goToNextCarouselSlide() {
    slideToActivate++
    if (slideToActivate > slideCount) {
      slideToActivate = 1
    }
    changeCarouselSlide()
  }

  function changeCarouselSlide() {
    // Deactivate everything.
    $("#carousel-slides img").hide()
    $("#carousel-nav a").css({
      "font-weight": "normal"
    })

    // Activate
    $("#" + slideToActivate).show()
    $("a[data-linked-image=" + slideToActivate + "]").css({
      "font-weight": "bold"
    })
  }

});
#carousel-slides {
  float: left;
  width: 50%;
}
#carousel-slides img {
  height: 200px;
  width: 200px;
  display: block;
  margin: 0 auto;
}
#carousel-nav {
  float: right;
  width: 50%;
  text-align: left;
}

  These are the tests!!!

  Test 1

  Test 2

  Test 3

And here is some more text.

One small note: the inline styling is there to visually set the first slide as "active" when the page loads. I feel like there's a better way, though.


texts: Setting bgcolor in Ruby. What's the proper way to do it?

texts:
<p style="background-color:#<%= debate.bg_color %>;" >

be_color is a method of Debate that returns a string like 45FFFF.

Although it does what I want, this seems like a tremendously bad idea. What would be a better way to accomplish this? (I'm very new to both Ruby and Rails. And new-ish to web development in general.)