texts: shared_ptr basic implementation for non array types

texts:
This is an implementation to simulate the basic functionality of c++ shared_ptr.
This doesn't provide features like custom deleter and make_shared().

I would really appreciate any feedback to improve the below code, any other api's that I should be providing etc.

#ifndef SHARED_PTR_H_
#define SHARED_PTR_H_

#include <utility>

namespace kapil {
  template <typename T>
  class shared_ptr {
    private:
      T* ptr_;   // data pointer
      int* ref_count_;  // reference count pointer

      void decrement_ref_count_and_delete_if_needed() {
        if (ref_count_) {
          --(*ref_count_);
            if (*ref_count_ == 0) {
              delete ptr_;
              delete ref_count_;
              ptr_ = nullptr;
              ref_count_ = nullptr;
            }
        }
      }

    public:
      constexpr shared_ptr() noexcept : ptr_{nullptr}, ref_count_{nullptr} {}

      constexpr explicit shared_ptr(T* ptr) {                  // constructor
        ptr_ = ptr;
        ref_count_ = new int{1};
      }

      shared_ptr(const shared_ptr& other) noexcept { // copy constructor
        ptr_ = other.ptr_;
        ref_count_ = other.ref_count_;
        if (ref_count_ != nullptr) {
          ++(*ref_count_);
        }
      }

      shared_ptr(shared_ptr&& other) noexcept {  // move constructor
        ptr_ = other.ptr_;
        ref_count_ = other.ref_count_;
        other.ptr_ = nullptr;
        other.ref_count_ = nullptr;
      }

      ~shared_ptr() noexcept {             // destructor
        decrement_ref_count_and_delete_if_needed();
      }

      shared_ptr& operator = (const shared_ptr& other) noexcept {   // assignent operator
        if (this != &other) {
          decrement_ref_count_and_delete_if_needed();
          ptr_ = other.ptr_;
          ref_count_ = other.ref_count_;
          if (ref_count_) {
            ++(*ref_count_);
          }
        }
        return *this;
      }

      shared_ptr& operator = (shared_ptr&& other) noexcept {   // move assignment operator
        *this = other;
      }

      T* get() const noexcept {
        return ptr_;
      }

      void reset() noexcept {
        decrement_ref_count_and_delete_if_needed();
      }

      void reset(T* ptr) {
        decrement_ref_count_and_delete_if_needed();
        ptr_ = ptr;
        if (!ref_count_) {
          ref_count_ = new int{1};
        }
        *ref_count_ = 1;
      }

      int use_count() const noexcept {
        return *ref_count_;
      }

      void swap (shared_ptr& other) {
        std::swap(ptr_, other.ptr_);
        std::swap(ref_count_, other.ref_count_);
      }

      T& operator * () const {
        return *ptr_;
      }

      T* operator -> () const noexcept {
        return ptr_;
      }

      explicit operator bool() const noexcept {
        return (ptr_ != nullptr);
      }

      friend bool operator == (const shared_ptr& lhs, const shared_ptr& rhs) noexcept {
        return (lhs.ptr_ == rhs.ptr_);
      }

      friend bool operator != (const shared_ptr& lhs, const shared_ptr& rhs) noexcept {
        return !(lhs == rhs);
      }
  }; // class shared_ptr

  template <typename T>
  void swap(shared_ptr<T>& lhs, shared_ptr<T>& rhs) {   // swap function in namespace to facilitate ADL
    lhs.swap(rhs);
  }
} // namespace kapil

#endif


texts: Possible solutions to remove the use of a Hashtable

texts:
While this is working very well for storing setting variables for my applications, I've been using it for a number of years and really feel there is something better. I'm perhaps just looking to use some newer functions from the framework.

    public string Value { get; set; }
    public string Name { get; set; }
    public string Notes { get; set; }

    /// <summary>
    /// Gets the selected setting from cache if it exists,
    ///     else returns the supplied default value
    /// </summary>
    /// <param name="settingName"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static string GetCacheSetting(string settingName, string defaultValue)
    {
        return LoadSettings().Contains(settingName) ? Convert.ToString(LoadSettings()[settingName]) : defaultValue;
    }

    /// <summary>
    /// Returns the selected setting value from cache.
    /// If cache is null then rebuild the cache.
    /// </summary>
    /// <returns></returns>
    public static Hashtable LoadSettings()
    {
        Hashtable h;
        h = (Hashtable)HttpRuntime.Cache["SiteSettings"];

        if (h == null)
        {
            h = new Hashtable();

            DataAccess da = new DataAccess(); //My DAL

            foreach (DataRow row in da.GetSiteSettings().Tables[0].Rows)
            {
                Settings oSetting = new Settings();
                oSetting.SettingsInitFromRow(row);
                h.Add(oSetting.Name, oSetting.Value);
            }

            HttpRuntime.Cache.Insert("SiteSettings",
                                    h,
                                    null,
                                    DateTime.Now.AddMinutes(120),
                                    Cache.NoSlidingExpiration);
        }

        return h;
    }

    /// <summary>
    /// Sets the values for the cache items
    /// </summary>
    /// <param name="row"></param>
    private void SettingsInitFromRow(DataRow row)
    {
        this.Name = (string)row["Name"];
        this.Value = (string)row["Value"];
    }

The settings are stored in the database and created at install time/modified as needed. At most I have 20 to 30 setting values in the database. I'm using a Hashtable stored in cache to get my values to remove the need to access the database 2, 3, or more times on every page load just for settings in addition to the rest of the times for page content. Doing this was the last time I majorly changed it maybe 3 years ago.

Any ideas?


texts:
Problem statement:

  Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily, a service lane runs parallel to the highway. The length of the highway and the service lane is N units. The service lane consists of N segments of unit length, where each segment can have different widths.

  Calvin can enter into and exit from any segment. Let's call the entry segment as index i and the exit segment as index j. Assume that the exit segment lies after the entry segment(j>i) and i ≥ 0. Calvin has to pass through all segments from index i to indexj (both inclusive).

  Calvin has three types of vehicles - bike, car and truck, represented by 1, 2 and 3 respectively. These numbers also denote the width of the vehicle. We are given an array width[] of length N, where width[k] represents the width of kth segment of our service lane. It is guaranteed that while servicing he can pass through at most 1000 segments, including entry and exit segments.

  If width[k] is 1, only the bike can pass through kth segment.
  If width[k] is 2, the bike and car can pass through kth segment.
  If width[k] is 3, any of the bike, car or truck can pass through kth segment.

  Given the entry and exit point of Calvin's vehicle in the service lane, output the type of largest vehicle which can pass through the service lane (including the entry & exit segment)

  Input Format

  The first line of input contains two integers - N & T, where N is the length of the freeway, and T is the number of test cases. The next line has N space separated integers which represents the width array.

  T test cases follow. Each test case contains two integers - i & j, where i is the index of segment through which Calvin enters the service lane and j is the index of the lane segment where he exits.

  Output Format

  For each test case, print the number that represents the largest vehicle type that can pass through the service lane.

  Note:
  Calvin has to pass through all segments from index i to index j (both inclusive).

  Constraints:

  2 <= N <= 100000

  1 <= T <= 1000

  0 <= i < j < N

  2 <= j-i+1 <= min(N,1000)

  1 <= width[k] <= 3, where 0 <= k < N

Solution:

N, T = map(int, input().split())
widths = list(map(int, input().split()))
for _ in range(T):
    i, j = map(int, input().split())
    vehicle = 3
    for x in range(i, j+1):
        width = widths[x]
        if width == 1:
            vehicle = 1 # Only a bike can pass
            break
        elif width == 2:
            vehicle = 2 # Only a car or bike can pass
    print(vehicle)

I'm looking for any way to make this shorter, simpler or more Pythonic.


texts:
Since I'm learning F# along with functional programming, I managed to implement the rules for Conway's Game of Life. I'm not sure if I can improve some of its parts, though. For example, the neighbours function does an ugly range testing, but I can't think of anything simpler.

module Game

open System

type Cell =
    | Alive
    | Dead

let amount_neighbours (board: Cell[,]) (pos: int * int) =
    let range (n: int) (limit: int) =
        let min = if n < 1 then 0 else n - 1
        let max = if n > (limit - 2) then (limit - 1) else n + 1
        [min .. max]

    let x_range = range (fst pos) (Array2D.length1 board)
    let y_range = range (snd pos) (Array2D.length2 board)

    List.sum [for x in x_range ->
        List.sum [for y in y_range -> if board.[x, y] = Alive && (x, y) <> pos then 1 else 0]]

let lifecycle (board: Cell[,]) =
    Array2D.init (Array2D.length1 board) (Array2D.length2 board) (fun i j ->
        let neighbours = amount_neighbours board (i, j)
        match neighbours with
            | 2 -> board.[i, j]
            | 3 -> Alive
            | _ -> Dead)

let rec process_game (board: Cell[,]) (n: int) =
    match n with
        | x when x > 0 ->
            printfn "Iteration"
            printfn "%A" board
            process_game (lifecycle board) (n - 1)
        | _ -> 0

[<EntryPoint>]
let main args =
    let board = Array2D.init 5 5 (fun i j -> if i = 2 && j > 0 && j < 4 then Alive else Dead)
    ignore (process_game board 4)
    0


texts:
I'm looking for a more consise way to sort a block of objects. Where you can sort a block of blocks based on the numeric position of the values to compare, there's no such shorthand for comparing objects by a given field:

test-data: reduce [
    object [name: "A" value: 1]
    object [name: "B" value: 3]
    object [name: "C" value: 2]
]

One solution would be to extend the native SORT function to accept a WORD! argument corresponding to the object field. However, that would require an update to the language and might take a little while to be accepted.

I've sketched out the following SORT-BY function that would take either a word (for the object field) or a block (an expression that is applied to the object):

sort-by: func [series [block!] comparator [block! word!]][
    forskip series 2 [
        insert series either word? comparator [
            all [
                in series/1 :comparator
                get in series/1 :comparator
            ]
        ][
            use [object] compose [
                object: first series
                (comparator)
            ]
        ]
    ]

    sort/skip series 2

    head forall series [remove series]
]

It's not ideal—it iterates through the block pulling the respective value from each object and adding it to the block; sorts the block; and removes the value again.

sort-by test-data 'value
sort-by test-data 'name
sort-by test-data [object/value]
sort-by test-data [sine 50 * object/value]

Any thoughts on the approach, particularly economy? Or even the need for such a function...

Obviously is lacking a descending/ascending switch—implied in future revision.


texts: Recursively moving every lowercase 'x' in a string to the end

texts:
Given a string, compute recursively a new string where all the
  lowercase 'x' chars have been moved to the end of the string.

endX("xxre") → "rexx"
endX("xxhixx") → "hixxxx"
endX("xhixhix") → "hihixxx"

Here's the initial idea I've had:

public String endX(String str) {
  ArrayList<Character> track = new ArrayList<Character>();
  return end(str,"",0,track);
}

public String end(String str,String res,int index,ArrayList<Character> track)
{
  if(index==str.length() && track.size()==0)
  {
    return res;
  }
  else if(index==str.length() && track.size()!=0)
  {

    return end(str,res+String.valueOf(track.remove(0)),index,track);
  }
  else if(str.charAt(index)=='x')
  {
    track.add(str.charAt(index));
    return end(str,res,index+1,track);
  }
  else
  {
    return end(str,res+str.charAt(index),index+1,track);
  }

}

I insisted on now using Java substring builtin functions since its complexity is \$O(n)\$. The above solution takes \$O(n)\$ time and \$O(n)+O(n)\$ space complexity.

How I can I optimize my solution further in terms of space and time complexity and total number of variables?


texts: Haskell Servant - login endpoint with two error states

texts:
Here is one a handler for dealing with logins, I've recently refactored it to try and make dealing with the different error cases a bit more elegant, though I still think there is room for improvement:

import Config
import Control.Monad.Reader
import Data.Aeson
import Data.Aeson.Types
import Data.Bifunctor (bimap)
import Data.Char
import Data.List as List
import Data.Text.Lazy
import Data.Text.Lazy.Encoding
import Database.Persist
import Database.Persist.Postgresql
import GHC.Generics
import Servant
import Servant.Auth.Server
import Types (Account(..))
import Queries

type Route = "login" :> ReqBody '[JSON] Credentials :> Post '[JSON] LoginAttempt

instance FromJWT (Key Account)
instance ToJWT (Key Account)

data Credentials = Credentials
    { loginEmail :: String
    , loginPass  :: String
    } deriving (Eq, Show, Read, Generic)

instance FromJSON Credentials

instance ToJSON Credentials where
    toJSON creds =
        object
            [ "account" .= loginEmail creds
            ]

data LoginAttempt
    = Ok { authToken :: Text }
    | AuthenticationErr
    | TokenGenerationErr
    deriving (Generic)

instance ToJSON LoginAttempt where
    toJSON (Ok token) =
        object [ "token" .= token ]
    toJSON AuthenticationErr =
        object [ "error" .= ("Invalid username or password" :: Text) ]
    toJSON TokenGenerationErr =
        object [ "error" .= ("Error generating token" :: Text) ]

action :: Config -> JWTSettings -> Credentials -> Handler LoginAttempt
action config jwt (Credentials email pass) = do
  login <- runSqlPool (Queries.validateAccount email pass) $ getPool config
  result <- either (const $ return AuthenticationErr) generateToken login
  case result of
    AuthenticationErr -> throwError $ err401 { errBody = encode . toJSON $ result }
    TokenGenerationErr -> throwError $ err500 { errBody = encode . toJSON $ result }
    _ -> return result
  where
    generateToken :: Key Account -> Handler LoginAttempt
    generateToken k = do
      token <- liftIO $ makeJWT k jwt Nothing
      pure $ either (const TokenGenerationErr) (Ok . decodeUtf8) token


texts: Rolling median function (Daily Coding Problem 377)

texts:
Given an array of numbers arr and a window of size k, print out the
  median of each window of size k starting from the left and moving
  right by one position each time.

  For example, given the following array and k = 3:

  [-1, 5, 13, 8, 2, 3, 3, 1]

  Your function should print out the
  following:

  5 <- median of [-1, 5, 13]
  8 <- median of [5, 13, 8]
  8 <- median of [13, 8, 2]
  3 <- median of [8, 2, 3]
  3 <- median of [2, 3, 3]
  3 <- median of [3, 3, 1]

  Recall that the median of an even-sized list is the average of the two middle
  numbers.

Is there any improvement possible in this implementation?

    #include <iostream>
    #include <vector>
    #include <array>
    #include <algorithm>

    template <typename T>
    struct range
    {
        auto begin()const {return  a; }
        auto end()const {return b;}

        T a,b;
    };

    range<const int*>make_range(const int* begin, const int* end)
    {
        return {begin, end};
    }

    range<const int *> make_window(const std::vector<int>& vec, size_t start, size_t end)
    {
        return make_range(vec.data() + start, vec.data() + end);
    }

    int median(int arr[], size_t N)
    {
        //sort the array
        std::sort(arr, arr + N);
        if(N % 2 == 0)
            return (arr[N/2 - 1] + arr[N/2])/2;
        return arr[N/2];
    }

     int main(){
        const auto window_length = 3;
        std::vector<int> input{-1, 5, 13, 8, 2, 3, 3, 1};
        const auto end_length = input.size() - window_length;
        std::array<int, window_length> arr{};

    for(size_t i(0); i < end_length; i++)
    {
        int counter (0);
        const auto window = make_window(input, i, i + window_length);
        for(const auto& value : window)
        {
            std::cout << value << ' ';
            arr[counter++] = value;
        }
        int result = median(arr.data(), arr.size());
        counter = 0;
        std::cout << "\nmedian " << result << '\n';
        std::cout << '\n';
    }

    return EXIT_SUCCESS;
   }


texts: Optimising String split into chunks of fixed size

texts:
I am looking to optimise my solution of the 'SMS problem', i.e splitting a String into chunks of the same size without splitting words.

I did a recursion and am looking for ways to optimise that code, or a more efficient algorithm.
In my solution spaces are left at the beginning of each chunk, this is voluntary.

Here is the code:

var exampleTxt = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`;

function getIndexOfLastSpace(msg, nthChar) {
  var curMsg = msg.substring(0, nthChar);
  console.log(curMsg.lastIndexOf(" "));
  return curMsg.lastIndexOf(" ");
}

function getMessagesNumber (msg) {

  if (msg.length < 1) {
    return 0;
  } else if (msg.length > 1 & msg.length < 153) {
    return 1;
  } else {

    var messages = [];

    while (msg.length > 0) {
      var chunk;
      // Last message
      if (msg.length <= 153) {
        chunk = msg;
      } else {
        var lastSpaceIndex = getIndexOfLastSpace(msg, 153);
        chunk = msg.substring(0, lastSpaceIndex);
      }
      messages.push(chunk);
      msg = msg.replace(chunk, '');
    }
    return messages.length;
  }
}

console.log(getMessagesNumber(exampleTxt));

Also am I write in thinking that the complexity of this algorithm is O(n) ?


texts: Writing a program to read a maximum of 99 elements in an iteration from a list

texts:
I want to read a list of elements and pass a maximum of 99 elements to a function for some logical operations.

I have tried this with an array as an example and this code was successful in achieving my purpose.

I just want someone to review it and help optimize it.

/**
 */
package com.review.code.java;

/**
 * i>   Read a List Input,
 * ii>  Call a Function with maximum of 99 elements in one iteration Eg:(0..98; 99..198; 199..297; .....)
 *
 *
 */
public class OptimizeReadingList {

    public static int list_size=107;//252,543,... etc. - Input List Size

    public static int a[] = new int[list_size];

    public static void main(String[] args) {

        int read_max_size = 99;
        int input_list_size = list_size;

        // Add Elements to the Array
        for(int j =0;j<input_list_size;j++){
            a[j]=j+1;
        }

        // Print all the Elements in the List
        for(int j =0;j<input_list_size;j++){
            System.out.print(a[j]+",");
        }

        System.out.println("\n Print only a max of 99 elements in one iteration using the printElements method");

        // Should Call a function printElements with start_index and end_index
        for(int i = 0,ele = (read_max_size-1); i<input_list_size ; ){

            printElements(i,ele);

            // Increment Operations for the next elements(maybe another 99 or less than 99)
            i=(ele+1);
            if((ele+read_max_size > input_list_size)){
                ele=input_list_size;
            }else{
                ele=ele+ele;
            }
        }

    }

    // Consider that this method can read only a maximum of 99 elements in range.
    private static void printElements(int i, int ele) {
        for(int j = i;j<ele;j++){
            System.out.print(a[j]+",");
        }
        System.out.println("\n");
    }

}


texts: Listing all directories, sub directories and files starting from the root

texts:
I have to deploy this code that will list all the directories, sub directories and files in it starting from the root. The code works but I am not sure if this is the correct way to list. It should not fail, though.

Also, in despite not allowing directories with the name . and .., they get printed. Why is that?

<?php

# Snippet that lists all the directories,sub directories and files under that directory
# recursive function

function directory_f_lister($root) {
    $dir_list = scandir($root);
    for($var=0;$var<count($dir_list);$var++) {
        if(is_readable($root.$dir_list[$var])) {
            if(is_dir($root.$dir_list[$var])) {
                if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
                echo "
Name of directory $dir_list[$var]
";
                echo "
";
                $dh = opendir($root.$dir_list[$var]);
                while(($name = readdir($dh)) !== false) {
                    if(is_dir($root.$dir_list[$var].$name)) {
                        if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
                        echo "Name of directory :  $name ";
                        echo "
";
                        directory_f_lister($root.$dir_list[$var].$name);
                    }else {
                        echo $name;
                        echo "
";
                    }
                }
            }
        }
    }
}

directory_f_lister(DIRECTORY_SEPARATOR);
#end


texts:
I have written the following code, and so far in all my tests it seems as if I have written a working Mutex for my 4 Threads, but I would like to get someone else's opinion on the validity of my solution.

typedef struct Mutex{
    int turn;
    int * waiting;
    int num_processes;
} Mutex;

void enterLock(Mutex * lock, int id){
    int i;
    for(i = 0; i < lock->num_processes; i++){
        lock->waiting[id] = 1;
        if (i != id && lock->waiting[i])
            i = -1;
        lock->waiting[id] = 0;
    }
    printf("ID %d Entered\n",id);
}

void leaveLock(Mutex * lock, int id){
    printf("ID %d Left\n",id);
    lock->waiting[id] = 0;
}


texts:
Previous iteration.

You know, I think this is the fastest I've ever pushed out an update to anything. This is Version 2 of my Brainf**k to Ruby converter, and the generated code looks... Well, like Brainf**k, converted directly to Ruby, with no attempt at making it more readable.

I'm looking for any tips on making things more idiomatic, both in the generator and generated code. The nest if/cases really bug me, but I'm not quite sure how to get rid of them, especially since just two characters are blindly replaced. I'd also like advice on making it run faster.

bf_to_ruby.rb

input_file, output_file = ARGV
code = IO.read(input_file).tr('^+-<>.,[]', '')

open(output_file, File::CREAT | File::WRONLY) do |output|
  output.puts <<-END.gsub(/^[ \t]*\||\s*#@.*$/, '')
    |#!/usr/bin/env ruby
    |class Mem < Hash #@ `Hash` because it's more memory-efficient and allows negative values.
    |  def initialize; super(0); end
    |  def []=(i, val); super(i, val & 255); end
    |end
    |data = Mem.new
    |pointer = 0
  END
  indent_level = 0
  code.scan(/(\++)|(\-+)|(<+)|(>+)|([.,\[\]])/)
      .map do |string|
        if string[0]
          next "#{'  ' * indent_level}data[pointer] += #{string[0].length}"
        elsif string[1]
          next "#{'  ' * indent_level}data[pointer] -= #{string[1].length}"
        elsif string[2]
          next "#{'  ' * indent_level}pointer -= #{string[2].length}"
        elsif string[3]
          next "#{'  ' * indent_level}pointer += #{string[3].length}"
        elsif string[4]
          case string[4]
            when '['
              ret = "#{'  ' * indent_level}until data[pointer] == 0"
              indent_level += 1
              next ret #Split it so that it's clear that indent is increased *after* the line
            when ']'
              indent_level -= 1
              next "#{'  ' * indent_level}end"
            when ','
              next "#{'  ' * indent_level}data[pointer] = $stdin.readbyte"
            when '.'
              next "#{'  ' * indent_level}putc data[pointer]"
          end
        end
      end.each { |line| output.puts(line) }
end

Demo

Input:

++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.

Output:

#!/usr/bin/env ruby
class Mem < Hash
  def initialize; super(0); end
  def []=(i, val); super(i, val & 255); end
end
data = Mem.new
pointer = 0
data[pointer] += 8
until data[pointer] == 0
  pointer += 1
  data[pointer] += 4
  until data[pointer] == 0
    pointer += 1
    data[pointer] += 2
    pointer += 1
    data[pointer] += 3
    pointer += 1
    data[pointer] += 3
    pointer += 1
    data[pointer] += 1
    pointer -= 4
    data[pointer] -= 1
  end
  pointer += 1
  data[pointer] += 1
  pointer += 1
  data[pointer] += 1
  pointer += 1
  data[pointer] -= 1
  pointer += 2
  data[pointer] += 1
  until data[pointer] == 0
    pointer -= 1
  end
  pointer -= 1
  data[pointer] -= 1
end
pointer += 2
putc data[pointer]
pointer += 1
data[pointer] -= 3
putc data[pointer]
data[pointer] += 7
putc data[pointer]
putc data[pointer]
data[pointer] += 3
putc data[pointer]
pointer += 2
putc data[pointer]
pointer -= 1
data[pointer] -= 1
putc data[pointer]
pointer -= 1
putc data[pointer]
data[pointer] += 3
putc data[pointer]
data[pointer] -= 6
putc data[pointer]
data[pointer] -= 8
putc data[pointer]
pointer += 2
data[pointer] += 1
putc data[pointer]
pointer += 1
data[pointer] += 2
putc data[pointer]

You'll notice that the generated code is nearly the same as the last version's generated code, but with a lot of duplicate lines merged and indenting.


texts:
Any suggestions on better way to remove the last word from a string?

$words = str_word_count($text, 1);
$lastWord = array_pop($words);
$textWithoutLastWord = implode(" ", $words);

or

$lastSpacePosition = strrpos($text," ");
$textWithoutLastWord =substr($text,0,$lastSpacePosition);


texts: C++ vs D - Algorithm Optimization/Conversion (Using vectors/arrays)

texts:
OK, I've been playing with D for a while (and been in love with its expressive power and simplicity, to be honest). However, since I'm still new to D, I'm facing a few issues.

Let's take the following example. All the following program does is to take numbers in the 0..10000000 (fairly big one, for benchmarking purposes) and for each one of them return a vector/array with the positions of bits set (in binary).

E.g.

4 = 100(2) => [ 2 ]
5 = 101(2) => [ 0, 2 ]
6 = 110(2) => [ 1, 2 ]
7 = 111(2) => [ 0, 1, 2]

And so on...

Now here's my C++ code (no vector reserve etc being used) :

// bits.cpp

#include <vector>
#include <iostream>
#include "math.h"

using namespace std;

vector<unsigned int> bitsSet(unsigned long long bitboard)
{
    unsigned int n;
    vector<unsigned int> res;

    for (n = 0; bitboard != 0; n++, bitboard &= (bitboard - 1))
    {
        res.push_back(log2(bitboard & ~(bitboard-1)));
    }

    return res;
}

int main()
{
    for (int k=0; k<10000000; k++)
    {
        vector<unsigned int> res = bitsSet(k);
    }

    return 0;
}

And here's my D code :

// bits.d

import std.stdio;
import std.math;

int[] bitsSet(ulong bitboard)
{
    int[] res;

    for (int n=0; bitboard!=0; n++, bitboard&=(bitboard-1))
        res ~= cast(int)log2(bitboard & ~(bitboard-1));

    return res;
}

void main(string[] args)
{
    for (ulong k=0; k<10000000; k++)
    {
        int[] bits = bitsSet(k);
    }
}

Now, given that the 2 pieces of code are compiled with g++ bits.cpp -o cbits (or clang++ bits.cpp -o cbits) and dmd bits.d -ofdbits, respectively, these are my benchmark results, using time (on Mac OS X 10.8.2) :

For C++ :

time ./cbits

real    0m19.742s
user    0m19.722s
sys 0m0.012s

For D :

time ./dbits

real    0m14.914s
user    0m14.891s
sys 0m0.017s

This looks OK. (with D being - for me - noticeably faster).

NOTE :

Now, if I try to use something like res.reserve(64); in my C++ bitsSet function, though, time drops to around 7s.... which IS significantly faster. Tried something like res.length = 64; (in my D code), time dropped to around 11s (though slower than C++), but I'm not sure if the result is the same...

What further optimizations would you suggest for my D code, so that it's at least as fast as my C++ code?

Results with Compiler Optimization flags :

With clang++ bits.cpp -O3 -o cbits

time ./cbits

real    0m8.994s
user    0m8.986s
sys 0m0.006s

With dmd bits.d -O -release -inline -m64 -ofdbits

time ./bitsd

real    0m14.083s
user    0m14.034s
sys 0m0.014s

Which looks pretty amazing (or bizarre). Clang managed to go from 19 to 8 seconds, while D optimization did nothing???

EDIT : So, is there no hope that my D code will run as fast as it's C++ counterpart?


texts:
I have created a simple custom logger to print the error log and save it to a file with specific location.

package logger

import (
    "log"
    "os"
)

var trace *log.Logger
var filePathVar string
var fileNameVar string
var prefixVar string

// use this function first before calling others.
func InitLogger(prefix, filePath, fileName string) {
    setPrefix(prefix)
    createLogFile(prefix, filePath, fileName)
    filePathVar = filePath
    fileNameVar = fileName
    prefixVar = prefix
}

func setPrefix(prefix string) {
    trace = log.New(os.Stderr,
        prefix,
        log.Ldate|log.Ltime|log.Lshortfile)

}

func createLogFile(prefix, filePath, fileName string) (*os.File, error) {
    setPrefix(prefix)
    f, err := os.OpenFile(filePath+fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
    if err != nil {
        // error file is not created
        err = os.MkdirAll(filePath, os.ModePerm)
        if err != nil {
            trace.Println(err)
            return nil, err
        }
        createLogFile(prefix, filePath, fileName)
    }

    return f, nil
}

// use this PrintLog use print the error on the terminal without exitting apps.
func PrintLog(errorLog string) {
    //assign to global variable
    if filePathVar == "" || fileNameVar == "" || prefixVar == "" {
        trace.Fatalln("Error file path and Name empty prefix Cannot be Empty")
    }

    f, err := createLogFile(prefixVar, filePathVar, fileNameVar)
    if err != nil {
        trace.Fatalln(err)
        return
    }
    trace.Println(errorLog)
    // save the log out put to file
    trace.SetOutput(f)
    trace.Println(errorLog, err)
}

// use this Fatal log to exit the application whenever got error.
func FatalLog(errorLog string) {
    //assign to global variable
    if filePathVar == "" || fileNameVar == "" || prefixVar == "" {
        trace.Fatalln("Error file path and Name empty")
    }

    f, err := createLogFile(prefixVar, filePathVar, fileNameVar)
    if err != nil {
        trace.Fatalln(err)
        return
    }
    trace.Println(errorLog)
    // save the log out put to file
    trace.SetOutput(f)
    trace.Fatalln(errorLog, err)
}

To use this package I must call the InitLogger function first

logger.InitLogger("Prefix Logger","./filpath/","filename.txt")

And then after that I can choose to print the error using either PrintLog or FatalLog.

The PrintLog function is used when we wanted to print the log without having crashing or closing the app os.Exit. The FatalLog the same as PrintLog but will crash the app or call os.Exit.

Any idea what can be improved here? source code


texts: Replacing DataContract serialization with Binary one in Azure Service Fabric

texts:
Azure Service Fabric uses DataContract serialization, which is a total disaster – it violates LSP (wiki) - see all those KnownTypeAttribute things, making framework development basically impossible.

I made the following class be a parent of all ValueObject to convince Service Fabric actually consume Binary serialization when it thinks about Data Contract one:

[DataContract]
[Serializable]
[JsonObject(MemberSerialization.OptOut)]
public abstract class SerializableObject
{
    [DataMember]
    [JsonIgnore]
    byte[] State { get; set; }
    static object Recursive { get; } = new object();

    [OnSerializing()]
    void OnSerializing(StreamingContext context)
    {
        if (context.Context == Recursive)
            return;

        var formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Other, Recursive));
        using (var stream = new MemoryStream())
        {
            formatter.Serialize(stream, this);
            State = stream.ToArray();
        }
    }

    [OnDeserialized()]
    void OnDeserialized(StreamingContext ctxt)
    {
        if (State == null)
            return;

        var formatter = new BinaryFormatter();
        using (var stream = new MemoryStream(State))
            Assign(formatter.Deserialize(stream));
    }

    void Assign(object obj)
    {
        foreach (var property in GetType()
            .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Where(p => p.CanRead && p.CanWrite))
            property.SetValue(this, property.GetValue(obj));
    }
}

So, actual objects could be something like this:

[DataContract]
[Serializable]
public class PacketRecieved : SerializableObject
{
    public PacketRecieved(DeviceId deviceId, InboundPacket packet)
    {
        DeviceId = deviceId;
        Packet = packet;
    }

    public DeviceId DeviceId { get; private set; }
    public InboundPacket Packet { get; private set; }
}


texts: Merging three CSV files with a primary key

texts:
This is my first time coding in my life. I don't really know much about coding. I googled whatever I need and combined them all together. It works great, but want to know if there is any improvement needed. Is there a better language to write in?

import os, csv, re, time
from datetime import date, timedelta

SendIDs =[]
BouncedEAes=[]
SubKeys=[]
MerchantIDs=[]
EventDates=[]
BounceCategories=[]
BounceReasones=[]
#SendTimes=[] #To find the most recent date that a welcome email was sent.
BounceDate=0

f = open("SendJobs.csv") #To get Send IDs and dates for Welcome emails
for row in csv.reader(f):
    if "Welcome" in row[7]:
        SendIDs.append(row[1])
        # SendTimes.append(
        #   time.strftime("%Y%m%d",
        #       time.strptime(row[5],"%m/%d/%Y  %H:%M:%S %p")))
f.close()

# if not os.path.exists('SendIDs.csv'):
#   open('SendIDs.csv', 'w').close()

# f = open("SendIDs.csv")
# for row in csv.reader(f):
#   SendIDs.append(row[0])

# UniqSendIDs = {}.fromkeys(SendIDs).keys()
# f.close()

# f = open("SendIDs.csv","w")
# with f as output:
#   writer = csv.writer(output, lineterminator='\n')
#   for item in UniqSendIDs:
#       writer.writerow([item])
# f.close()

f = open('Bounces.csv')
for row in csv.reader(f):
    for item in SendIDs: #OR UniqSendIDs
        if item == row[1]:
            SubKeys.append(row[2])
            BouncedEAes.append(row[3])
            BounceCategories.append(row[8])
            BounceReasones.append(row[10])
            #EventDate: Only need bounce date, NO time required.
            BounceDate = time.strptime(row[6],"%m/%d/%Y  %H:%M:%S %p")
            BounceDate = time.strftime("%m/%d/%Y", BounceDate)
            EventDates.append(BounceDate)
f.close()

f = open('Attributes.csv')
for row in csv.reader(f):
    for item in BouncedEAes:
        if item == row[2]:
            MerchantIDs.append(row[4])
f.close()

SubKeys.insert(0,"SubscriberKey")
BouncedEAes.insert(0,"EmailAddress")
MerchantIDs.insert(0,"Merchant_Number")
EventDates.insert(0,"EventDate")
BounceCategories.insert(0,"BounceCategory")
BounceReasones.insert(0,"BounceReason")

new_data=[[SubKeys[i],BouncedEAes[i], MerchantIDs[i], EventDates[i], BounceCategories[i], BounceReasones[i]] for i in range(len(BouncedEAes))]

# if len(SendTimes)==0:
#   yesterday = date.today() - timedelta(1)
#   SendTimes.append("NoWelcomeEmailsSent_"+yesterday.strftime("%Y%m%d"))

# if len(BouncedEAes)==1:
#   SendTimes.append("NoBouncedEmails_"+SendTimes[-1])

# FILENAME FORMAT: Welcome-Cadence-#2-RESULT-YYYYMMDD
# YYYYMMDD: One day before the day the file was received.

yesterday = date.today() - timedelta(1)

f=open("Welcome-"+yesterday.strftime('%Y%m%d')+".csv","wb")
output=csv.writer(f)

for row in new_data:
    output.writerow(row)
f.close()

"""
ERROR MESSAGES
"""

#new_data=[[SubKeys[i],BouncedEAes[i], MerchantIDs[i], EventDates[i], BounceCategories[i], BounceReasones[i]] for i in range(len(BouncedEAes))]
#IndexError: list index out of range

"""
Check Attributes.csv
"""


texts: Compute the minimum distance between two points in a 2-D plane

texts:
I have tried to calculate the minimum distance between the two points in a 2D plane. I have used the divide and conquer strategy to attain the complexity of n logn. The steps that I did are:

Recursively sort a list in X plane and compute the minimum difference between the coordinates sorted by X plane.
Recursively sort a list in Y plane compute the minimum difference between the coordinates sorted by Y plane.
Compute the min of the two from the above steps
It will be the result

Here is my code:

var points = [
  [1, 6],
  [1, 1],
  [2, 1],
  [1.5, 1]
];

var smallestDifference;

function mergeSort(arr, dimension = 'x') {
  if (arr.length == 1)
    return arr;

  if (arr.length > 1) {
    let breakpoint = Math.ceil((arr.length / 2));
    // Left list starts with 0, breakpoint-1
    let leftList = arr.slice(0, breakpoint);
    // Right list starts with breakpoint, length-1
    let rightList = arr.slice(breakpoint, arr.length);

    // Make a recursive call
    leftList = mergeSort(leftList, dimension);
    rightList = mergeSort(rightList, dimension);

    var a = merge(leftList, rightList, dimension);
    return a;
  }
}

function merge(leftList, rightList, dimension) {
  let result = [];
  let dimensionIndex;
  if ('x' == dimension) {
    dimensionIndex = 0;
  } else if ('y' == dimension) {
    dimensionIndex = 1;
  }
  while (leftList.length && rightList.length) {
    // Sorting the x/y coordinates
    if (leftList[0][dimensionIndex] <= rightList[0][dimensionIndex]) {
      result.push(leftList.shift());
    } else {
      result.push(rightList.shift());
    }
  }

  while (leftList.length)
    result.push(leftList.shift());

  while (rightList.length)
    result.push(rightList.shift());

  // Compute the distance using the distance formula
  let difference = Math.sqrt(Math.pow(result[1][0] - result[0][0], 2) + Math.pow(result[1][1] - result[0][1], 2));
  if (smallestDifference) {
    if (difference < smallestDifference)
      smallestDifference = difference;
  } else {
    smallestDifference = difference;
  }
  return result;
}

var resultX = mergeSort(points, 'x');
var resultY = mergeSort(points, 'y');

document.write(`Minimum distance between two points: ${smallestDifference}`);

With the inputs that I have tried, I have found the results to be correct. But is this the good/best way to approach this? If this solution were to be improved what changes would be made?


texts: Implementation of Counting Sort using C++

texts:
Please review my code. If any improvement needed please point out. I have used std::map. Is there any better alternative?

#include <bits/stdc++.h>

class count_sort
{
  std::map<int, int> m;
  std::map<int, int>::iterator it;

public:

  void counting_sort(std::vector<int>& a){
   for(int i=0; i<a.size(); i++)
   {
    m[a[i]]++;
   }
  }

  void display()
  {
    it = m.begin();
    while(it != m.end())
    {
      for(int i = 0; i < it->second; i++)
      {
        std::cout<<it->first<<" ";
      }
     it++;
   }
   std::cout<<"\n";
  }
};

int main()
{
    count_sort c1;
    std::vector<int>v {2,5,3,0,2,3,0,3};
    std::cout<<"The entered values are \n";
    for(int i = 0; i < v.size(); i++)
    {
      std::cout<<v[i]<<" ";
    }
    std::cout<<"\n";
    c1.counting_sort(v);
    std::cout<<"The sorted values \n";
    c1.display();
}

It says add more details. I don't know what to add.


texts: Python - Do I need a class or are these functions okay?

texts:
I'm fairly new to Python but had to start using it and for reasons I have to use 2.7, which is why I am using that syntax. I have this function which gets data from a file, if it exists, and then gets passed onto other functions to perform SQL queries etc. The script is only intended to work for the directory it is running in, hence the os.getcwd()
This static data is the only data that gets looked up then returned and referenced by other functions. It works as it is but would you say for professionalism and understanding python better that a class would be better here or a restructure in someway? I am of course only posting a snippet.
    currentdirectory = os.getcwd()
    versionf = "version.ini"
    verfile = os.path.join(currentdirectory, versionf)

    def main():
       get_local_details()
       push_app(application, version)
       do_something(app_name_version)

    def get_local_details():
        if os.path.isfile(verfile):
            def get_app_name():
                try:
                    global application
                    application = subprocess.check_output(['grep', 'application', verfile]).strip('\n')
                    application = application.rsplit('=')[1]
                    return application
                except:
                    print "Application missing from version.ini"
             def version_number():
                try:
                    global version
                    version = subprocess.check_output(['grep', 'version', verfile]).strip('\n')
                    version = version.rsplit('=')[1]
                    return version
                except:
                    print "version missing from version.ini"
            get_app_name()
            version_number()
            def app_name_version(application, version)
                try:
                    global applicationver
                    applicationver = application + "." + version
                    return applicationver
                except:
                    print "error here"
            app_name_version(application, version)
        else:
            print "File does not exist."

main()

contents of ini file are
application=testapp
version=1.0

do_something is a function that contains a SQL query that uses the app_name_version as the WHERE statement.
Is it even possible to use a function within a class to define the attributes?


texts: CMS for allowing users to delete or edit a post

texts:
I have been working on a personal CMS for a site I've been running, and right now I'm working on a page that lists all entries, or posts from a database. I have given the user, with checkboxes and a drop down menu, the option to either delete or edit a post.

    //query database
    $query = mysql_query("SELECT * FROM userPosts");

    //turn query results into an array
    while($rows = mysql_fetch_array($query)) :

    //List all posts in a table (other table markup not shown).
    $posts = $rows['userTexts'];
    $id = $rows['ID'];
    echo "
\n" . $id . "	\n" . $posts . "	\n<input type='checkbox' name='chkBox' value='chk[". $id . "]'>	\n
\n";
endwhile

This part is not the problem, but I figure it is necessary for the question. Is there a way to make this code cleaner, without so many if statements?

$chkWhat = $_REQUEST["chkBox"];
$options = $_REQUEST["options"];

if(isset($_REQUEST["submit"])) {
    if($chkWhat != "chk[" .$id . "]") {
        echo "
Please select a post.
";
    } else {
        if( //more than one check box is checked but I still have to figure this...) {
            echo "
For now, please just select 1 post you would like to edit.
";
        } else {
            //edit your post
            echo "You will edit your post";
        }
        if($options == "delete") {
            //delete your post(s) here
            echo "You will delete your post(s)";
        }
    }
}

Sorry about the second if statement there, but I am still researching that.


texts:
I would like a review for this simple recursive algorithm which returns the largest int in an array of integers. I would like feedback on the transfer of state via the third parameter specifically. Please also note 2 things:

It must be recursive
This is not for production usage, but rather recursion practice

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

int max_val(int arr[], int length, int curr_max)
{
    if(length <= 0)
        return curr_max;

    if(curr_max < *arr)
    {
        curr_max = *arr;
    }
    arr++;
    return max_val(arr,length-1,curr_max);
}

int main()
{
    int arr[] = {2,73,39,5,8,62,9};
    printf("Max: %d\n", max_val(arr,7,0));
    return EXIT_SUCCESS;
}


texts: A simple command line linear interpolator in C

texts:
I'm trying to become more familiar with C (been working through the MIT Practical Programming in C course and K&R) so decided to write a simple command-line linear interpolator. You can feed it a vector (where missing values are represented by 0n) and it should print an interpolated vector. Any comments on style etc are much appreciated.

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

#define NULLA "0n"
#define NULLF -1000
#define MAXLEN 1000

int main(int argc, char * argv[])
{

    if(argc < 2)
    {
        printf("missing vector for interpolation\n");
        return 1;
    }

    if(argc - 1 > MAXLEN)
    {
        printf("vector is too long\n");
        return 2;
    }

    float start, end, delta; //bound values and change for interpolation
    int num_nulls = 0; //number of nulls in a given interpolation range

    float filled[MAXLEN]; //vector where we will put our values

    int i, j; //indices, for argv[] and filled[] vectors, correspondingly

    //we want all values in filled to be initalized to zero, to avoid junk vals
    for(j = 0; j < MAXLEN; j++)
        filled[j] = 0.;

    //let's go through any initial nulls, which just get put back in
    //to the vector, since we can't interpolate (no starting/ending values yet)
    for(i = 1, j = 0; i < argc && strcmp(argv[i], NULLA) == 0; i++)
       filled[j++] = NULLF;

    //the meat of the interpolations take places in the remaing parts
    //of the vector
    for( ; i < argc; i++)
    {
        if(strcmp(argv[i], NULLA) != 0 && num_nulls == 0)
        {
            start = atof(argv[i]);
            filled[j++] = start;
        }
        else if(strcmp(argv[i], NULLA) != 0 && num_nulls > 0)
        {
            end = atof(argv[i]);
            delta = (end - start) / (1 + num_nulls);
            while(num_nulls-- > 0)
            {
                start+=delta;
                filled[j++] = start;
            }
            filled[j++] = end;
            start = end; //we should be ready for another interpolation
            num_nulls = 0;
        }
        else
            num_nulls++;
   }

    //add in any trailing nulls, since interpolation can't be performed
    while(num_nulls-- > 0)
        filled[j++] = NULLF;

    for(i = 0; i < j; i++)
    {
        if(filled[i] != NULLF)
            printf("%.2f ", filled[i]);
        else
            printf("%s ", NULLA);
    }
    putchar('\n');

    return 0;
}


texts: Associating a lock/mutex with the data it protects

texts:
I've recently come across some areas of code in our solution that have a few thread-safety problems.  Thread-safety is a minefield at best so I thought I'd have an attempt at writing a few little utility classes that would make it easier to write safe multi-threaded code.
The general idea is to link a resource with the lock(s) that protect it.  If the resource is accessed outside of all of it's locks then a runtime exception is thrown.

Imagine a developer had written the following (example) caching object but had forgotten to take the _imageLock when clearing the cache.

Using the traditional .net locking mechanism (of just locking on an Object) we might corrupt the Dictionary if two threads call Add() and ClearCache() at the same time.

Using these utility classes, Padlock and Protected<T>, will instead throw an exception in the ClearCache() method because the Protected<T> object is being accessed outside of it's lock. This exception should surface during the developers normal testing procedure, before the code is even checked in.

public class SomeThreadSafeCache
{
    Padlock _imageLock = new Padlock();
    Protected<Dictionary<string, byte[]>> _imageCache;

    public SomeThreadSafeCache()
    {
        //The variable _imageCache is associate with the _imageLock Padlock
        //i.e. _imageCache is only available when we're locking on _imageLock.
        _imageCache = new Protected<Dictionary<string, byte[]>>(
            new Dictionary<string, byte[]>(),
            _imageLock);
    }

    public void AddImage(string key, byte[] data)
    {
        using (_imageLock.Lock())
        {
            _imageCache.Value.Add(key, data);
        }
    }

    public void ClearCache()
    {
        //Throws an exception because the protected
        //resource is accessed outside of it's lock.
        _imageCache.Value.Clear();
    }
}

(I know that .net now comes with Concurrent collections which make my example pointless but the general idea of linking a resource with it's lock is what I'm trying to get at)

The Protected<T> class is able to be associated with as many Padlocks as you might want.

public class SomeOtherThreadSafeObject
{
    Padlock _lock1 = new Padlock();
    Padlock _lock2 = new Padlock();

    Protected<int> _i;

    public SomeOtherThreadSafeObject()
    {
        _i = new Protected<int>(0, _lock1, _lock2);
    }

    public void IncrementI()
    {
        using (_lock1.Lock())
        {
            using (_lock2.Lock())
            {
                _i.Value++;
            }
        }
    }
}

(A trivial example for illustrative purposes only, the Interlocked.Increment function would do a better job.)

If either _lock1 or _lock2 is not taken then

_i.Value++

will throw an exception stating that the object is not fully locked.

Enforcing the order in which the locks are taken are outside the scope of the utility classes.  I'm also trying to avoid the old ICollection.SyncRoot pattern by not allowing

Protected<T>.Padlock.Lock()

The locking policy itself should be up to the implementors of the class.  All Protected<T> is interested is in is knowing if it's fully protected before allowing access to it's internal value.

What I'm asking for a review of is the general approach/idea. Does this seem like a sensible system?  Are there any glaring problems with it that I've not thought of?  If anyone wants to see the actual implementation code then I can post it on Github (or somewhere similar).

(I'm aware that this abuses the IDisposable/Using pattern but for added thread-safety I think it will be worth it for us).


texts: Overlaping sections using Bootstrap and CSS

texts:
I'm currently converting a PSD to a web template and attempting to overlap content and I'm running into a issue with the 3rd section because there is  more padding than the first overlap and using the CSS style background-color covers wherever there is a block element but if there isn't anything in the pace a image takes priority.

I have a link to the github page where it is live in it's current state

The phone image is above the background color of the next section, I've tried using z-index but it still seems to take priority over the next section. Does anyone know a css trick or the proper method to do this overlap like in the previous section I've overlapped the content.

Here is some of the HTML code

DESIGN

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A amet assume consequatur deleniti eligendi eos, expedita fugit maxime, natus nostrumas officia officiis quisquam quos repellendus verit verodasdfudgera voluptate. Nihil, perspiciatis puth.

                    <button class="button" type="submit">GET STARTED</button>

01/05

                     &nbsp; &nbsp;

OUR COMMUNITY

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

The CSS

/* ================== SECOND SECTION =================== */

.second-section {
    background-color: #FFF;
    margin-top: -300px;
}
.second-section .content {
    background-color: #FFF;
    padding-top: 150px;
}

.second-section h3 {
    word-spacing: 5px;
    letter-spacing: 2px;
    line-height: 1.25em;
    color: #16a085;
}

.second-section img {
    z-index: -10;
}

.second-section p {
    font-size: 1em;
    line-height: 2em;
}

.second-section p:last-of-type {
    padding-top: 50px;

}
.second-section i {
    font-size: 2em;
    font-weight: bold;
}

/* ===========================  THIRD SECTION =========================== */

.third-section {
    background-color: #f5f6f7;
    margin-top: -150px;
    padding-top: 150px;
    z-index: 10;
}
.third-section .content {
    background-color: #f5f6f7;
}

.content {
    background-color: #f5f6f7;

}

Essentially I'm just using margin to pull the next section up and overlap the previous section. If someone knows of a better way that's utilizing bootstrap or pure CSS that would be great but i've tried several different things.


texts: Find the non repeating number in the integer array

texts:
The program finds the non repeated number in a int array. I am using a count for the duplicates and making a Numcounts[] to store the count values. I am assuming the array is sorted. Then I can check the Numcounts[] for 1, and that would be the non-repeating number. The complexity is \$O(n^2)\$.

Can you tell me how to do the same thing using hashmaps? I haven't used hashmaps and I know the complexity can be reduced to \$O(n))\$ using them.

#include<stdafx.h>
#include<stdio.h>

int main()
{
    int n=6;
    int * Numcounts = new int[n];
    int count = 0;
    int a[6] = {1,1,1,2,2,3}; // sort the array before proceeding.Because in the else part count is set to zero.
    //If the array is unsorted then count will be reset in middle and will not retain the previous count.
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
            if(a[i]==a[j])
            {
                count = count+1;
                Numcounts[i] = count;
            }
            else{
                count = 0;
            }
        }
    }
}


texts: CRUD (database layer) for F# with TypeProviders

texts:
I am a newbie in F# and I am thinking about use F# in my next project.  The project will work the database and I need to store and retrieve instances of objects in the Db.

Could you please check my code and say if there is something that I can improve?

Here is a simple object:

namespace Entities

type Item(id : string, name : string) =
    member val ItemId = id with get, set
    member val ItemName = name with get, set

    new() = new Item()

Here is Database Layer:

namespace SqlController

open System
open System.Data
open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Microsoft.FSharp.Linq

open Entities

type dbSchema = SqlDataConnection<"Data Source=VM-WIN8\SQLEXPRESS;Initial Catalog=mobile;Integrated Security=SSPI;">

type SqlConnector() =

    // universal sql functions
    member private this.DeleteRowsFrom (table : Table<_>) rows =
        table.DeleteAllOnSubmit(rows)

    // map functions
    member private this.Item2Record (item : Item) =
        new dbSchema.ServiceTypes.ItemsTable(
            ItemId = item.ItemId,
            ItemName = item.ItemName)

    member private this.Record2Item (e : dbSchema.ServiceTypes.ItemsTable) =
        new Item(e.ItemId, e.ItemName)

    // ### Items

    // return all items
    member this.GetItems() =
        use db = dbSchema.GetDataContext()

        query {
            for row in db.ItemsTable do
            select row
        } |> Seq.map this.Record2Item |> Seq.toArray

    // return one item by item id
    member this.GetItemByItemId(itemId : string) =
        use db = dbSchema.GetDataContext()

        query {
            for rows in db.ItemsTable do
            where (rows.ItemId = itemId)
            select rows
        }
        |> (fun s ->
                if Seq.isEmpty s then
                    None
                else
                    s |> Seq.head |> this.Record2Item |> Some)

    // insert new item
    member this.InsertItem (item : Item) =
        use db = dbSchema.GetDataContext()
        item |> this.Item2Record |> db.ItemsTable.InsertOnSubmit

        try
            db.DataContext.SubmitChanges()
        with
            | exn -> printfn "Exception: \n%s" exn.Message

    // update item
    member this.UpdateItem (item : Item) =
        use db = dbSchema.GetDataContext()

        query {
            for rows in db.ItemsTable do
            where (rows.ItemId = item.ItemId)
            select rows
        }
        |> Seq.nth 0
        |> (fun e -> e.ItemName <- item.ItemName)

        try
            db.DataContext.SubmitChanges()
        with
            | exn -> printfn "Exception: \n%s" exn.Message

    // delete item by itemId
    member this.DeleteItemByItemId(itemId : string) =
        use db = dbSchema.GetDataContext()

        query {
            for rows in db.ItemsTable do
            where (rows.ItemId = itemId)
            select rows
        } |> this.DeleteRowsFrom db.ItemsTable

        try
            db.DataContext.SubmitChanges()
        with
            | exn -> printfn "Exception: \n%s" exn.Message

Here is some tests:

module Tests

open NUnit.Framework
open FsUnit

open Entities
open SqlController

[<TestFixture>]
type SqlControllerTest() =
    let sqlConnector = new SqlConnector();

    [<Test>]
    member x.SelectionAllTest() =
        let items = sqlConnector.GetItems()
        items.Length |> should equal 3

    [<Test>]
    member x.SelectById() =
        let item = sqlConnector.GetItemByItemId("20")
        if Option.isSome item then
            (Option.get item).ItemName |> should equal "two"

    [<Test>]
    member x.SelectNotExistingItem() =
        let item = sqlConnector.GetItemByItemId("xx")
        Option.isNone item |> should equal true


texts: C++ class for capturing broadcast window messages

texts:
In the Windows operating system, some system events are notified via broadcast window messages. DBT_DEVICEARRIVAL and DBT_DEVICEREMOVECOMPLETE are good examples of this. To receive and process these notifications, one need to have a window with an associated window procedure. Given a non-GUI application, this is a burden. So, I'm thinking about encapsulating a simple class for capturing broadcast window messages, and here it comes. The pack comes in one main class CWndMsgReceiver and two helper classes CDummyWndClass and CDummyWnd.

I hope to have my code reviewed, and get some comments and suggestions.

WndMsgReceiver.h

#pragma once
#include <atomic>
#include <thread>
#include <windows.h>

class CDummyWndClass {
public:
  explicit CDummyWndClass(WNDPROC wndproc);
  ~CDummyWndClass();
  operator PCWSTR() const;
private:
  ATOM atom_;
};

class CDummyWnd {
public:
  explicit CDummyWnd(WNDPROC wndproc);
  ~CDummyWnd();
  operator HWND() const;
private:
  CDummyWndClass wndcls_;
  HWND hwnd_;
};

class CWndMsgReceiver {
public:
  explicit CWndMsgReceiver(WNDPROC wndproc);
 ~CWndMsgReceiver();
  operator HWND() const;  // to use with RegisterDeviceNotification
private:
  static void MsgPump(WNDPROC wndproc, std::atomic<HWND>& hwnd);
  std::atomic<HWND> hwnd_;
  std::thread thrd_;
};

WndMsgReceiver.cpp

#include "WndMsgReceiver.h"
#include <cstring>
#include <functional>
#include <utility>

CDummyWndClass::CDummyWndClass(WNDPROC wndproc)
    : atom_(0) {
  HMODULE hmodule = 0;
  GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
                     GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                     (PCWSTR)wndproc, &hmodule);
  WNDCLASSW wndcls = {0, wndproc, 0, 0, (HINSTANCE)hmodule, 0, 0, 0, nullptr,
                      L"{F9F40031-F77E-4A5C-8A6C-30296B823C22}"};
  atom_ = RegisterClassW(&wndcls);
}

CDummyWndClass::~CDummyWndClass() {
  UnregisterClassW((PCWSTR)*this, 0);
}

CDummyWndClass::operator PCWSTR() const {
  PCWSTR p = nullptr;
  std::memcpy(&p, &atom_, sizeof(atom_));
  return p;
}

////////////////////////////////////////////////////////////////////////////////

CDummyWnd::CDummyWnd(WNDPROC wndproc)
    : wndcls_(wndproc)
    , hwnd_(CreateWindowW((PCWSTR)wndcls_, nullptr, 0, 0,
                          0, 0, 0, 0, 0, 0, nullptr)) {
}

CDummyWnd::~CDummyWnd() {
  DestroyWindow(hwnd_);
}

CDummyWnd::operator HWND() const {
  return hwnd_;
}

////////////////////////////////////////////////////////////////////////////////

CWndMsgReceiver::CWndMsgReceiver(WNDPROC wndproc)
    : hwnd_{}
    , thrd_(std::thread(MsgPump, wndproc, std::ref(hwnd_))) {
  do Sleep(0); while (!(HWND)hwnd_);
}

CWndMsgReceiver::~CWndMsgReceiver() {
  PostThreadMessageW(GetThreadId(thrd_.native_handle()), WM_QUIT, 0, 0);
  thrd_.join();
}

CWndMsgReceiver::operator HWND() const {
  return hwnd_;
}

void CWndMsgReceiver::MsgPump(WNDPROC wndproc, std::atomic<HWND>& hwnd) {
  CDummyWnd wnd(wndproc);
  hwnd = wnd;
  MSG msg = {};
  while (GetMessageW(&msg, 0, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessageW(&msg);
  }
}


texts: Simple Java program - Coding bat sumNumbers

texts:
The problem is stated as follows:

Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
sumNumbers("abc123xyz") → 123
sumNumbers("aa11b33") → 44
sumNumbers("7 11") → 18

Here's the program I wrote based on Character.isDigit(char) and Integer.parseInt(string).
public int sumNumbers(String str) {
  int sum = 0;
  for (int i = 0; i < str.length(); i++) {
      if (Character.isDigit(str.charAt(i))) {
          int count = 0;
          for (int j = i; j < str.length(); j++) {
              if (Character.isDigit(str.charAt(j))) count++;
              else break;
          }
          sum += Integer.parseInt(str.substring(i, i + count));
          i += count;
      }
  }
  return sum;
}

I'm not sure if I should make it more modular since it's pretty straightforward. I was wondering if I could do this without count. Also, I know it's nit-picky, but I want to know if the way I format my for loops and if else statements is good style. This is just a standalone program, so I'm not really concerned about the public/private issue.


texts:
This is for adding code into my table really easily, however it will be called 2000+ times per second, so I need to know if this is the most efficient code to add a row to the database.

<?php
$site = $_GET['url'];
$con=mysqli_connect("localhost","","","rocket_newsites");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"INSERT INTO `rocket_newsites`.`sites` (`id`, `url`) VALUES (NULL, '$site');");

mysqli_close($con);
exit();
?>


texts: Method that remove duplicates from a list of words in Java

texts:
Today, I took a coding challenge with this question:

Given a List of Strings, write a method removeDuplicates that removes duplicate words from the List and returns an ArrayList of all the unique words. The returned ArrayList should be lexically alphabetically.

One thing that I learned while doing this problem is a TreeSet. From my understanding it works like a set but adds elements in order.

From the code, I concluded that my time complexity would be O(n).
Can anyone offer suggestions or corrections?

public static ArrayList<String> removeDuplicates(List<String> input) {

    ArrayList<String> array = new ArrayList<String>();
    Set<String> noDups = new TreeSet<String>();

    if(input.isEmpty()){
        return array;
    }

    if(input.size() == 1){
        array.add(input.get(0));
        return array;
    }

    for(int i = 0; i < input.size(); i++){
            noDups.add(input.get(i));
    }

    return new ArrayList<String>(noDups);
}


texts: Implementing pthread barrier for Mac OS/X

texts:
I have written this little thingie to fix a problem of missing pthread_barrier_t in Mac OS/X pthreads. Are there any issues with this code?

The header:

#ifndef PTHREAD_BARRIER_H
#define PTHREAD_BARRIER_H

#include <pthread.h>

#ifdef __APPLE__

#ifdef __cplusplus
extern "C" {
#endif

#if !defined(PTHREAD_BARRIER_SERIAL_THREAD)
# define PTHREAD_BARRIER_SERIAL_THREAD  (1)
#endif

#if !defined(PTHREAD_PROCESS_PRIVATE)
# define PTHREAD_PROCESS_PRIVATE    (42)
#endif
#if !defined(PTHREAD_PROCESS_SHARED)
# define PTHREAD_PROCESS_SHARED     (43)
#endif

typedef struct {
} pthread_barrierattr_t;

typedef struct {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    unsigned int limit;
    unsigned int count;
    unsigned int phase;
} pthread_barrier_t;

int pthread_barrierattr_init(pthread_barrierattr_t *attr);
int pthread_barrierattr_destroy(pthread_barrierattr_t *attr);

int pthread_barrierattr_getpshared(const pthread_barrierattr_t *restrict attr,
                   int *restrict pshared);
int pthread_barrierattr_setpshared(pthread_barrierattr_t *attr,
                   int pshared);

int pthread_barrier_init(pthread_barrier_t *restrict barrier,
             const pthread_barrierattr_t *restrict attr,
             unsigned int count);
int pthread_barrier_destroy(pthread_barrier_t *barrier);

int pthread_barrier_wait(pthread_barrier_t *barrier);

#ifdef  __cplusplus
}
#endif

#endif /* __APPLE__ */

#endif /* PTHREAD_BARRIER_H */

The source file:

#include "pthread_barrier.h"

#include <errno.h>

#ifdef __APPLE__

#define __unused __attribute__((unused))

int
pthread_barrierattr_init(pthread_barrierattr_t *attr __unused)
{
    return 0;
}

int
pthread_barrierattr_destroy(pthread_barrierattr_t *attr __unused)
{
    return 0;
}

int
pthread_barrierattr_getpshared(const pthread_barrierattr_t *restrict attr __unused,
                   int *restrict pshared)
{
    *pshared = PTHREAD_PROCESS_PRIVATE;
    return 0;
}

int
pthread_barrierattr_setpshared(pthread_barrierattr_t *attr __unused,
                   int pshared)
{
    if (pshared != PTHREAD_PROCESS_PRIVATE) {
        errno = EINVAL;
        return -1;
    }
    return 0;
}

int
pthread_barrier_init(pthread_barrier_t *restrict barrier,
             const pthread_barrierattr_t *restrict attr __unused,
             unsigned count)
{
    if (count == 0) {
        errno = EINVAL;
        return -1;
    }

    if (pthread_mutex_init(&barrier->mutex, 0) < 0) {
        return -1;
    }
    if (pthread_cond_init(&barrier->cond, 0) < 0) {
        int errno_save = errno;
        pthread_mutex_destroy(&barrier->mutex);
        errno = errno_save;
        return -1;
    }

    barrier->limit = count;
    barrier->count = 0;
    barrier->phase = 0;

    return 0;
}

int
pthread_barrier_destroy(pthread_barrier_t *barrier)
{
    pthread_mutex_destroy(&barrier->mutex);
    pthread_cond_destroy(&barrier->cond);
    return 0;
}

int
pthread_barrier_wait(pthread_barrier_t *barrier)
{
    pthread_mutex_lock(&barrier->mutex);
    barrier->count++;
    if (barrier->count >= barrier->limit) {
        barrier->phase++;
        barrier->count = 0;
        pthread_cond_broadcast(&barrier->cond);
        pthread_mutex_unlock(&barrier->mutex);
        return PTHREAD_BARRIER_SERIAL_THREAD;
    } else {
        unsigned phase = barrier->phase;
        do
            pthread_cond_wait(&barrier->cond, &barrier->mutex);
        while (phase == barrier->phase);
        pthread_mutex_unlock(&barrier->mutex);
        return 0;
    }
}

#endif /* __APPLE__ */


texts:
I want to implement a random word generator that would not use Import statements. The solution is working for a *nix system. The solution does yield a random word, but please suggest:

How to make the function optimally/safely return words with a higher position in the list(e.g. now we're almost guaranteed to return an 'A' word)
How to get a word with min/max length instead of length
Should I break this into smaller functions?
How to make the code more readable/higher performance
Is there a better approach to this problem? How to tell which modules are better off imported instead of implemented from scratch(except for the built-ins)?

def generate_random_word(length=8):
    """
    Return a random string from /usr/share/dict/words on a *nix system
    """
    with open('/usr/share/dict/words', 'r') as words_file, open("/dev/random", 'rb') as random_file:
        random_words = words_file.read().split('\n')
        size_words = [x for x in random_words if len(x) == length]
        for _ in range(0, 100):
            while True:
                try:
                    random_word = size_words[(int.from_bytes(random_file.read(1), 'big'))]
                except IndexError:
                    continue
                break

    return random_word


texts: Check whether string of brackets are well-formed

texts:
The task

I asked similar questions here and here.

  Given a string of round, curly, and square open and closing brackets,
  return whether the brackets are balanced (well-formed).

  For example, given the string "([])", you should return true.

  Given the string "([)]" or "((()", you should return false.

My solution

...is inspired by @200_success' answer. I only made it more concise.

const isBracketBalanced = brc => {
  const braces = {
    "(": ")",
    "[": "]",
    "{": "}",
  }, expectCloseStack = [];

  const bracketIsBalanced = b => braces[b] ?
           expectCloseStack.push(braces[b]) :
           expectCloseStack.pop() === b;

  return [...brc]
    .every(bracketIsBalanced) &&
    !expectCloseStack.length;
};

console.log(isBracketBalanced("([])[]({})"));


texts:
I'm writing start/stop module for my application.
I have a class that manages application life cycle and I called it Work.
Work uses WorkState class that contains 4 states the application can be in, that's:

INITIALIZING (state between NOT_RUNNING and RUNNING)
RUNNING
FINALIZING (state between RUNNING and NOT_RUNNING)
NOT_RUNNING

The class also contains some useful methods to manage states.
Work uses QueryExecutor. QueryExecutor is just a subclass of ThreadPoolExecutor with overriden method afterExecute() that changes application state after performing a start/stop task. (e.g. changing state from INITIALIZING to RUNNING after performing a start operation).
MY VISION:
When a thread invoke the start()/stop() methods, the code mustn't allow other thread to interfere the process until it's done. Also, there's no way to perform the stop action when the system is not started and vice versa.
MY CONCERNS:

Should I change locking system to "fair"?
Will it work smoothly with 2 threads? (There's no possibility that the start()/stop() can be accessed at the same time by more than 2 threads)
Does the code have any bugs I can't see?
Any way to write it much simpler?

Work.java
public class Work {

    //public start() and stop() methods that can be accessed
    //from two threads:
    //- JavaFX main thread (user action)
    //- other thread (after all of the task are done)
    //
    //Those methods return a boolean that indicates if
    //the chosen action was performed properly
    //(just to show an alert to user)

    public static boolean start() {
        return processQuery(Query.START);
    }

    public static boolean stop() {
        return processQuery(Query.STOP);
    }

    //------Internals

    private static final QueryExecutor queryProcessor = new QueryExecutor(Work::unlockProcessing);
    private static final WorkState state = new WorkState();
    private static final Object lock = new Object();

    private static boolean processQuery(Query query) {
        synchronized (lock) {
            if (state.isInProperState(query)) {
                state.changeState(query);
                queryProcessor.execute(query == Query.START ? Work::startQuery : Work::stopQuery);
                return true;
            } else {
                return false;
            }
        }
    }

    private static void unlockProcessing() {
        synchronized (lock) {
            state.matureState();
        }
    }

    private static void startQuery() {
        // <SOME SYNCHRONOUS CODE>
    }

    private static void stopQuery() {
        // <SOME SYNCHRONOUS CODE>
    }

}

WorkState.java
public class WorkState {

    private State state = State.NOT_RUNNING;

    public void changeState(Query query) {
        state = query == Query.START ? State.INITIALIZING : State.FINALIZING;
    }

    public void matureState() {
        state = state == State.INITIALIZING ? State.RUNNING : State.NOT_RUNNING;
    }

    public boolean isInProperState(Query query) {
        return (state == State.RUNNING && query == Query.STOP)
                || (state == State.NOT_RUNNING && query == Query.START);
    }

    private enum State {
        INITIALIZING, RUNNING, FINALIZING, NOT_RUNNING;
    }

}

QueryExecutor.java
public class QueryExecutor extends ThreadPoolExecutor {

    private final Runnable unlockProcessingAfterExecute;

    public QueryExecutor(Runnable unlockProcessingAfterExecute) {
        super(1, 1, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
        this.unlockProcessingAfterExecute = unlockProcessingAfterExecute;
    }

    @Override
    protected void afterExecute(Runnable r,
                                Throwable t) {
        super.afterExecute(r, t);
        unlockProcessingAfterExecute.run();
    }

}

Query enum
public enum Query {
    START, STOP
}


texts:
I am learning Scala, coming from Java background. Here I have written a small prototype proof of concept program that is a part of concept base for a simple upcoming tutorial game. There are two game objects: a Cell and a Breed of cells (a 1d row). The operations are simple. One can create a breed with a number of cells. Each cell can mutate with a custom function chosen randomly from the available set. If the breed mutates, all of it's cells mutate. My question is the one common today - how Scala-ish is my code? How to improve? Coming from OOP, I have witnessed a very strange feeling while writing this code: it feels just like the internals of objects leak out from their ripped bodies just like in a real OOP thriller movie. But everyone suggests breaking the code into functions... so where is the balance?

package main
import scala.util.Random

object Breed extends App{

val rand:Random = new Random

//mutations
def mutF(f:Int => Int)(v:Int) : Int = {f(v)}

def mutFA(v:Int) : Int = mutF(x => x)(v)
def mutFB(v:Int) : Int = mutF(x => x + x)(v)
def mutFC(v:Int) : Int = mutF(x => x * x)(v)

val mutations : List[Int=>Int] = List(mutFA, mutFB, mutFC)

//constants (sources)
val emptyCellList : List[Cell] = List[Cell]()

//mutations manipulations
def nextMutation(f:Int=>Int) : Int=>Int = {
    val i = mutations.indexOf(f)
    if(i == mutations.length - 1) mutations(0)
    else mutations(i + 1)
}

def randomMutation : Int=>Int = {
    mutations(rand.nextInt(mutations.length))
}

//---CELL---
class Cell(f:Int=>Int, value:Int) {
    def mutate() = new Cell(nextMutation(f), f(value))
    override def toString = "[" + value + "]"
}

def cellsToString(l:List[Cell]) : String = {
    l match {
        case Nil => ""
        case y :: ys => y.toString + cellsToString(ys)
    }

}

//breeder
def createBreed(num:Int) : Breed = {

    def makeCell() : Cell = new Cell(randomMutation, rand.nextInt(10))

    def makeCells(acc:Int, cells:List[Cell]) : List[Cell] = {
        if(acc == 0) cells
        else makeCells(acc - 1, makeCell :: cells)
    }

    new Breed(0, makeCells(num, List[Cell]()))
}

def mutateBreed(gens:Int, breed:Breed) : Breed = {
    def mutate(acc:Int, b:Breed) : Breed = {
        if(acc == 0) b
        else {
            val mutated : Breed = b.mutate();
            println(b.output() + " ---> " + mutated.output())
            mutate(acc - 1, mutated)
        }
    }
    mutate(gens, breed)
}

//---BREED---
class Breed(generation:Int, cells:List[Cell]) {

    def mutateCells() : List[Cell] = {
        def f(l:List[Cell]) : List[Cell] = {
            l match {
                case Nil => Nil
                case x :: xs => x.mutate() :: f(xs)
            }
        }
        println("BREED: size=" + cells.length)
        f(cells)
    }

    def mutate() : Breed = new Breed(generation + 1, mutateCells)

    def output() : String = {
        "BREED: [" + generation + "] = " + cellsToString(cells)
    }
}

// /\/\/\/\/test/\/\/\/\
def test() {
    val breed = createBreed(10)
    mutateBreed(10, breed)
}

test
}


texts: Multi Selection Component (React + Hooks)

texts:
all.
This component is meant to take in an array of available options and provide the user an easy way to choose multiple options. Each time the selected options are changed/updated, those options are console logged.

I'm hoping that someone could provide any criticism on my current code. I want to make sure that the code is as simple and clean as it could be, while keeping all logic outside of the JSX.
Photo of component at bottom of post.

Thanks in advance!

const label = 'Select options';
const availableOptionsLabel = 'Available Types';
const selectedOptionsLabel = 'Selected Types';

export default function MultiSelection({options=['A', 'B', 'C']}) {
  const [availableOptions, setAvailableOptions] = useState([]);
  const [selectedOptions, setSelectedOptions] = useState([]);

  useEffect(() => {
    setAvailableOptions(options);
  }, []);

  useEffect(() => {
    console.log('Updated selection is: ', JSON.stringify(selectedOptions));
  }, [selectedOptions]);

  const row = (text, key, whichColumn, action) => {
    return(
      <div key={`${whichColumn}-button-row-${key}`} className='button-row-container' onClick={() => action(text)}>
        <IconButtonRow>
          <IconButton id='add' iconClass='icon-add'/>

{text}

        </IconButtonRow>

    )
  }

  const moveToAvailableOptions = clickedOption => {
    setAvailableOptions([...availableOptions, clickedOption]);
    let tempSelectedOptions = [...selectedOptions.filter(option => option !== clickedOption)];
    setSelectedOptions(tempSelectedOptions);
  }

  const moveToSelectedOptions = clickedOption => {
    setSelectedOptions([...selectedOptions, clickedOption]);
    let tempAvailableOptions = [...availableOptions.filter(option => option !== clickedOption)];
    setAvailableOptions(tempAvailableOptions);
  }

  return(

{label}

{availableOptionsLabel}

{selectedOptionsLabel}

          {availableOptions.map((option, key) => row(option, key, 'available', moveToSelectedOptions))}

          {selectedOptions.map((option, key) => row(option, key, 'selected', moveToAvailableOptions))}

  )
}


texts:
Suppose we have two sorted lists, and we want to find one element from the first, and the other element from the 2nd list, where the sum of the two elements equal to a given target. If there are multiple combinations, need to find all the combinations.

Any bugs, performance improvement ideas in terms of algorithm time complexity or code style advice is highly appreciated. My basic idea is to scan the first list from the beginning, and scan the second list from the end, a similar approach to how we resolve the 2-sum classic problem in one list.

def two_sum(list1, list2, target, result):
    i = 0
    j = len(list2) - 1
    while i < len(list1) and j >= 0:
        if list1[i] + list2[j] == target:
            result.append((list1[i], list2[j]))
            i += 1
            j -= 1
            while i < len(list1) and list1[i] == list1[i-1]:
                i += 1
            while j >= 0 and list2[j] == list2[j+1]:
                j -= 1
        elif list1[i] + list2[j] > target:
            j -= 1
        else:
            i += 1
if __name__ == "__main__":
    list1 = [1,3,5,7]
    list2 = [2,3,4,5]
    result = []
    two_sum(list1, list2, 6, result)
    print result


texts:
While quarantine I decided to look into the assembly language, as it's quite interesting to see how code works on the lower levels. To challenge myself I made a binary search algorithm. The OS is Windows.
I just code casually (in Python and C++, so I know about the concept of pointers), therefore I don't have that much experience.
I just wanted to put this on code review to know if this code style is acceptable or if I'm disregarding important conventions. So please critique and let me know.
bits 64

section .text
    global main
    extern printf
    extern ExitProcess

main:
    mov r12, list       ; load list into register
    mov r13, len >> 3   ; r13 holds the width of the search "sector"
    test r13, 1         ; test if the first search "sector" is even
    jz is_even          ; if not, it's set to an even number
    inc r13
    is_even:
    push r13            ; save width
    shl r13, 2          ; multiply index by 4 to get the width in bytes
    add r12, r13        ; move the pointer to the first search position
    pop r13             ; restore width

search:
    shr r13, 1          ; halve search "sector"
    push r13
    shl r13, 2          ; get width in bytes

    mov r14d, dword [r12]
    cmp r14d, dword [target] ;compare target to current search position
    je finish
    jl search_right
    jg search_left

search_left:
    sub r12, r13   ; move search position
    pop r13
    jmp search
search_right:
    add r12, r13   ; move search position
    pop r13
    jmp search

finish:
    lea rcx, [fmt]  ; set printf format
    mov rdx, r12    ; rdx is pointer to the target
    sub rdx, list   ; we want the index of the target, so we SUB the pointer to the first element
    shr rdx, 2      ; ints are 4-byte, so we have to devide the difference by 4

    sub rsp, 40     ; shadow space
    call printf
    add rsp, 40

    mov rax, 0
    call ExitProcess

section .data
    fmt db "%d", 10, 0     ; printf format string
    target dd 123          ; number we're looking for
    list dd 4, 123 ,2584, 4510, 8451, 6987, 12543
    len equ $ - list


texts: Filter function implementations using copy_if algorithm vs. for loop

texts:
I have the following method of some class, which also defines the method isAllowed:

auto filter(const auto& in)
{
    auto ret = decltype(in) {};
    for(auto x : in)
      if(isAllowed(x))
        ret.insert(x);
    return ret;
}

This is a clear case where copy_if could be used instead. I see two alternative versions:

auto filter(const auto& in)
{
    auto ret = decltype(in) {};
    copy_if(begin(in), end(in),
            inserter(ret, end(ret)),
            [this](auto i) {return this->isAllowed(i);});
    return ret;
}

or

auto filter(const auto& in)
{
    auto ret = decltype(in) {};
    copy_if(begin(in), end(in),
            inserter(ret, end(ret)),
            bind(&A::isAllowed, this, placeholders::_1));
    return ret;
}

Both seem much less obvious than the original, so I am inclined to keep the for loop. Is there a strong argument not to? (And is there a better way?)

Otherwise, I feel itchy because cases like this point to the limited usefulness of the algorithm tools, despite what best practices advise.

There are probably good arguments for choosing copy_if that are not being considered properly (performance?). This question is mainly after those, as the others seem more intuitive and easier to get.


texts: Three edittext boxes: suggestions to clean up code

texts:
I am a newbie at writing Android apps and using Java in general. I have went through most of the Android hello view tutorials but still seem to be lacking some understanding of the basics.  Here is a snippet of code I wrote for an app.  My goal was to have three edittext boxes for the user to input information.  I want the user to put information in two of the three boxes and when they hit the calculate button, it will calculate the third edittext value based on a specific equation.  Is there anyway that I can avoid initializing these 3 edittext objects in each of my methods within this class?  Any other suggestions for cleaning up or improving this code?

public class PlantPopulation extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        EditText seedSpacing = (EditText)
                findViewById(R.id.seedSpacing);
        EditText rowSpacing = (EditText)
                findViewById(R.id.rowSpacing);
        EditText population = (EditText)
                findViewById(R.id.population);

        seedSpacing.setText("");  //clear values
        rowSpacing.setText("");
        population.setText("");

    }

    //check how many boxes are empty
    public int checkifempty(String array[]) {

        int i = 0;
        for (String string : array) {
            if (string.equals("")) {
                i = i+1;
            }
        }
        return i;
    }

    //run the calculation
    public void calc(View v) {

        EditText seedSpacing = (EditText)
                findViewById(R.id.seedSpacing);
        EditText rowSpacing = (EditText)
                findViewById(R.id.rowSpacing);
        EditText population = (EditText)
                findViewById(R.id.population);

        String sS = seedSpacing.getText().toString();
        String rS = rowSpacing.getText().toString();
        String pop = population.getText().toString();

        String boxes[] = {sS,rS,pop};
        //determine which box is empty
        if (checkifempty(boxes) <2) {

            if (sS.equals("")) {
                double calc1=(43560*144)/new Double(rS)/
                        new Double(pop);
                calc1 = Math.floor(calc1 * 100 +.5)/100;
                seedSpacing.setText(Double.toString(calc1));
            } else if (rS.equals("")) {
                double calc2=(43560*144)/new Double(sS)/
                        new Double(pop);
                calc2 = Math.round(calc2);
                rowSpacing.setText(Double.toString(calc2));
            } else if (pop.equals(""))  {
                Double calc3=((43560*144)/new Double(rS)/
                        new Double(sS));
                Integer calc = calc3.intValue();
                //calc3 = Math.round(calc3);
                population.setText(calc.toString());
            } else {
                Toast.makeText(PlantPopulation.this,
                    "Leave one item blank.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(PlantPopulation.this,
                    "You must fill in two of the three boxes.", Toast.LENGTH_SHORT).show();
        }
    }
}


texts: Joining two KeyedTuple objects in SQLAlchemy

texts:
I have the following two queries:

res=session.query(t_marketing_mailing_stats_tbl).filter(
    t_marketing_mailing_stats_tbl.c.mailing_id==mid)

res_t=session.query(t_marketing_time_stat_tbl).filter(
    t_marketing_time_stat_tbl.c.mailing_id==mid)

try:
    return res.one() + res_t.one()
except NoResultFound as e:
    return None

res and res_t are both of type sqlalchemy.util._collections.KeyedTuple which support addition, however, the resulting object is a simple tuple, without keys.

I would like to have a combined result, so I did the following:

rv = {}
res=session.query(t_marketing_mailing_stats_tbl).filter(
    t_marketing_mailing_stats_tbl.c.mailing_id==mid)

res_t=session.query(t_marketing_time_stat_tbl).filter(
    t_marketing_time_stat_tbl.c.mailing_id==mid)

try:
    res =res.one()
    res_t = res_t.one()
    for k in res.keys():
        rv[k] = getattr(res, k)
    for k in res_t.keys():
        rv[k] = getattr(res_t, k)
except NoResultFound as e:
    return None

While this works, I suspect there is a built-in way, or a better way of achieving this with SQLAlchemy.


texts:
The site should be accessible only to signed-in users. I'm making sure I publish and enable data manipulation to only those, but I wanna make sure even the app structure won't be visible.

What I did was creating an autorun that checks for changes in signed-in user and reloads the router. The router takes care of redirecting if needed.

let first_time = false;
Tracker.autorun(() => {
    Meteor.userId();
    if(first_time)
        FlowRouter.reload();
    else
        first_time = true;
});

FlowRouter.route(States.home,{
    triggersEnter: [(context, redirect) => {
        if(!Meteor.userId())
            redirect(States.login);
    }],
    action(params,queryParams){
        BlazeLayout.render('SimpleLayout', { content: "App"});
    }
});

FlowRouter.route(States.login,{
    action(params,queryParams){
        BlazeLayout.render('SimpleLayout', { content: "Login"});
    }
});

Are there any flaws?


texts: how to rewrite sql query with subquery to find max element without using limit?

texts:
the question is here

 Return the name of the category that has the most films.

There are 2 databases - film_category:
film_id category_id last_update
1   6   2017-02-15 10:07:09-08
2   11  2017-02-15 10:07:09-08
3   6   2017-02-15 10:07:09-08
4   11  2017-02-15 10:07:09-08
5   8   2017-02-15 10:07:09-08

and category:
category_id      name         last_update
1                Action        2017-02-15 09:46:27-08
2                Animation     2017-02-15 09:46:27-08
3                Children      2017-02-15 09:46:27-08

I have made it work, but I feel there is a way to refactor without 'limit'
 select category.name from film_category inner join
 category on category.category_id = film_category.category_id
 group by category.name
 order by count(film_category.film_id) desc limit 1

I dont know how to write it without 'limit 1'
select category.name from film_category inner join
     category on category.category_id = film_category.category_id
     group by category.name
     having count(film_category.film_id) > (select max().... )


texts: Is this PHP email validation comprehensive and complete?

texts:
It might be a bit redundant, and I'm not experienced enough to wrap it all into one function. But,
I'm aiming for unicode email adresses and a quick loose but secure validation. How can I improve this?

note: I'm using PDO, so I'm mainly focusing on preventing HTML injection. Is this an issue ether way if I'm outputting user input in htmlspecialchars?

$email = "Bàt mâ'n@çupærman.dc";

function isValid($email) {
    return !preg_match('/[^ ]+@[^ ]+\.[^ ]{2,7}/', $email);
}

$encoded_email = htmlspecialchars($email, ENT_COMPAT, 'UTF-8');
if (isValid($email)) {
    echo $encoded_email. " is not valid!";
} else {
    if ($encoded_email===$email) {
    echo $encoded_email. " is valid!";
    } else {
        echo $encoded_email. " is not valid!";
    }
}


texts:
I am learning C and decided to make an implementation of Base64 encoding according to the info Wikipedia provides about it.

My main question is: should I declare the index_table array inside the get_base64_digit function like static char index_table[] = "blabla"?

A general code review would also be appreciated.

funcs.c

static char index_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static char get_index_digit(int x) {
    return index_table[x];
}

char get_base64_digit(const unsigned int base64, int digit_number){

    switch (digit_number){
            case 0:
                    return get_index_digit(base64 >> 18);
            case 1:
                    return get_index_digit((base64 >> 12) & 077);
            case 2:
                    return get_index_digit((base64 >> 6) & 077);
            case 3:
                    return get_index_digit(base64 & 077);
    }

    return '\0';
}

funcs.h

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

char get_base64_digit(unsigned int base64, int digit_number);

main.c

 #include "funcs.h"

int main(int argc, char* argv[]){

    char* text = argc == 2 ? argv[1] : '\0';

    unsigned final, temp;

    int text_len  = strlen(text);
    int remainder = text_len % 3;

    //Iterate over the input string, three characters at a time.
    for (int x = final = temp = 0; x < (remainder == 0 ? text_len : text_len - remainder); x += 3) {

            final = (text[x] << 16) | (text[x+1] << 8) | text[x+2];

            printf("%c%c%c%c",  get_base64_digit(final, 0), get_base64_digit(final, 1), get_base64_digit(final, 2), get_base64_digit(final, 3));

    }

    //Handle the last bytes in case text_len wasn't a multiple of 3
    if (remainder == 1) {
            final = text[text_len-1] << 16;
            printf("%c%c==\n", get_base64_digit(final, 0), get_base64_digit(final, 1));
    } else if (remainder == 2){
            final = (text[text_len-2] << 16) | (text[text_len-1] << 8);
            printf("%c%c%c=\n",  get_base64_digit(final, 0), get_base64_digit(final, 1), get_base64_digit(final, 2));
    } else
            return 0;

    return 0;
}


texts:
I'm writing tutorials for new programmers. The tutorials show programmers how to structure events.

I've attached the code for one of the tutorials. Can someone take a look at my code and let me know if you see any bugs or gotchas? The goal of the code is to

be extremely easy to read and short
show a clear separation of the publisher and listener
use custom arguments

You can test the code here.

using System;

// program that managers publisher and listener
public class Program
{
    // subscribe to event, raise event
    public static void Main()
    {
        // new publisher
        Publisher publisher = new Publisher();
        // new listener
        Listener listener = new Listener();
        // subscribe to event
        listener.Subscribe(publisher);
        // raise event
        publisher.RaiseEvent();
    }
}

// object with the event
public class Publisher
{
    // declare event handler
    public delegate void EventHandler(Object sender, RaiseArgs e);
    // declare event
    public static event EventHandler Event;
    // raise event, result: "hello"
    public void RaiseEvent()
    {
        RaiseArgs args = new RaiseArgs();
        args.Message = "hello";
        Event(this, args);
    }
}

// object that listens for the event
public class Listener
{
    // subscribe to event
    public void Subscribe(Publisher publisher)
    {
      Publisher.Event += HeardEvent;
    }

    static void HeardEvent(Object sender, RaiseArgs e)
    { Console.WriteLine(e.Message); }
}

// the arguments to use with an event
public class RaiseArgs : EventArgs
{
    public string Message { get; set; }
}


texts: Most efficient way to find spatial order from a list of tuples (Python)

texts:
I have a circle-growth algorithm (line-growth with closed links) where new points are added between existing points at each iteration.

The linkage information of each point is stored as a tuple in a list. That list is updated iteratively.

QUESTIONS:

What would be the most efficient way to return the spatial order of these points as a list ?
Do I need to compute the whole order at each iteration or is there a way to cumulatively insert the new points in a orderly manner into that list ?

All I could come up with is the following:

tuples = [(1, 4), (2, 5), (3, 6), (1, 6), (0, 7), (3, 7), (0, 8), (2, 8), (5, 9), (4, 9)]

starting_tuple = [e for e in tuples if e[0] == 0][0]
## note: 'starting_tuple' could be either (0, 7) or (0, 8), starting direction doesn't matter

order = [starting_tuple[0], starting_tuple[1]]
## order will always start from point 0

idx = tuples.index(starting_tuple)
## index of the starting tuple

def findNext():
    global idx
    for i, e in enumerate(tuples):
        if order[-1] in e and i != idx:
            ind = e.index(order[-1])
            c = 0 if ind == 1 else 1
            order.append(e[c])
            idx = tuples.index(e)

for i in range(len(tuples)/2):
    findNext()

print order

It is working but it is neither elegant (non pythonic) nor efficient.
It seems to me that a recursive algorithm may be more suitable but unfortunately I don't know how to implement such solution.

Also, please note that I'm using Python 2 and can only have access to full python packages (no numpy).

This question has also been posted on SO.