texts: Deck of cards program using a card value map

texts:
Previous review of this project: Nested Deck class design and implementation

My program finally meets all of my expectations to the best of my ability, but I'd still like another review.  Please give as many critiques as you can.  I will then implement this with future games that I have in mind.

CardValuesMap.h

#ifndef CARDVALUESMAP_H
#define CARDVALUESMAP_H

std::map<char, unsigned> retrieveMap()
{
    std::map<char, unsigned> values;

    values['A'] = 1;
    values['2'] = 2;
    values['3'] = 3;
    values['4'] = 4;
    values['5'] = 5;
    values['6'] = 6;
    values['7'] = 7;
    values['8'] = 8;
    values['9'] = 9;
    values['T'] = 10;
    values['J'] = 11;
    values['Q'] = 12;
    values['K'] = 13;

    return values;
}

#endif

Deck.h

#ifndef DECK_H
#define DECK_H

#include <iostream>
#include <array>
#include <map>
#include <string>

class Deck;

class Card
{
private:
    friend class Deck;
    unsigned value;
    char rank;
    char suit;
    Card::Card(unsigned v, char r, char s) : value(v), rank(r), suit(s) {}

public:
    Card::Card() : value(0), rank(' '), suit(' ') {}
    bool operator<(const Card &rhs) const {return (value < rhs.value);}
    bool operator>(const Card &rhs) const {return (value > rhs.value);}
    bool operator==(const Card &rhs) const {return (suit == rhs.suit);}
    bool operator!=(const Card &rhs) const {return (suit != rhs.suit);}
    friend std::ostream& operator<<(std::ostream &out, const Card &aCard)
        {return out << '[' << aCard.rank << aCard.suit << ']';}
};

class Deck
{
private:
    static const unsigned MAX_SIZE = 52;
    static const std::map<char, unsigned> values;
    static const std::string SUITS;
    std::array<Card, MAX_SIZE> cards;
    int topCardPos;

public:
    Deck();
    void shuffle();
    Card deal();
    unsigned size() const {return topCardPos+1;}
    unsigned empty() const {return topCardPos == -1;}
    friend std::ostream& operator<<(std::ostream &out, const Deck &aDeck);
};

#endif

Deck.cpp

#include "Deck.h"
#include "CardValuesMap.h"
#include <algorithm>

const std::map<char, unsigned> Deck::values = retrieveMap();
const std::string Deck::SUITS = "HDCS";

Deck::Deck() : topCardPos(-1)
{
    for (auto valueIter = values.cbegin(); valueIter != values.cend(); ++valueIter)
    {
        for (auto suitIter = SUITS.cbegin(); suitIter != SUITS.cend(); ++suitIter)
        {
            topCardPos++;
            cards[topCardPos] = Card(valueIter->second, valueIter->first, *suitIter);
        }
    }

    shuffle();
}

void Deck::shuffle()
{
    topCardPos = MAX_SIZE-1;
    std::random_shuffle(&cards.front(), &cards.back()+1);
}

Card Deck::deal()
{
    if (empty())
    {
        std::cerr << "\nDECK IS EMPTY -- RESHUFFLING NOW\n";
        shuffle();
    }

    topCardPos--;
    return cards[topCardPos+1];
}

std::ostream& operator<<(std::ostream &out, const Deck &aDeck)
{
    for (int i = aDeck.size()-1; i > -1; --i)
    {
        out << "\n" << aDeck.cards[i];
    }

    return out;
}


texts: Extract data from one column of SQL Server table

texts:
I have an SQL Server table from which I want to extract data from one column (DD) and return as multiple columns.

The data is in NVARCHAR and looks like:

  ;HF:GN;HM:GTN;HN:GN;PN:AN;PVD:GO;PVR:1.1;BN:AN;BVD:GO;BV:2.3;

There is less to be changed in the way this data is structured.

I have to extract all of the data in ... and between : and ; and have to return as individual columns. I tried with the following query:

SELECT DataID
    ,SUBSTRING(DD,CHARINDEX(';HF:',DD) + LEN(';HF:'),CHARINDEX(';HM:',DD) - (CHARINDEX(';HF:',DD) + LEN(';HF:'))) as HF
    ,SUBSTRING(DD,CHARINDEX(';HM:',DD) + LEN(';HM:'),CHARINDEX(';HN:',DD) - (CHARINDEX(';HM:',DD) + LEN(';HM:'))) as HM
    ,SUBSTRING(DD,CHARINDEX(';HN:',DD) + LEN(';HN:'),CHARINDEX(';PN:',DD) - (CHARINDEX(';HN:',DD) + LEN(';HN:'))) as HN
    ,SUBSTRING(DD,CHARINDEX(';PN:',DD) + LEN(';PN:'),CHARINDEX(';PVD:',DD) - (CHARINDEX(';PN:',DD) + LEN(';PN:'))) as PN
    ,SUBSTRING(DD,CHARINDEX(';PVD:',DD) + LEN(';PVD:'),CHARINDEX(';PVR:',DD) - (CHARINDEX(';PVD:',DD) + LEN(';PVD:'))) as PVD
    ,SUBSTRING(DD,CHARINDEX(';PVR:',DD) + LEN(';PVR:'),CHARINDEX(';BN:',DD) - (CHARINDEX(';PVR:',DD) + LEN(';PVR:'))) as PVR
    ,SUBSTRING(DD,CHARINDEX(';BN:',DD) + LEN(';BN:'),CHARINDEX(';BVD:',DD) - (CHARINDEX(';BN:',DD) + LEN(';BN:'))) as BN
    ,SUBSTRING(DD,CHARINDEX(';BVD:',DD) + LEN(';BVD:'),CHARINDEX(';BVR:',DD) - (CHARINDEX(';BVD:',DD) + LEN(';BVD:'))) as BVD
    ,SUBSTRING(DD,CHARINDEX(';BVR:',DD) + LEN(';BVR:'),LEN(DD) - (CHARINDEX(';BVR:',DD) + LEN(';BVR:'))) as BVR
FROM DataTable
WHERE DD is not null

I think I'll have to generate the query at run-time from a list of column names or may have hard-coded query as the structure of the data and the required columns is not likely to change.

Given that, is there a better approach to optimize this query? May be by using Regular Expressions or any other approach?

Edit:

Is there a better approach using C# Code-behind? This eventually is being used for an ASP.Net Web Application.


texts: Elegantly avoid columns containing NaNs?

texts:
The next bit of code does exactly what i want it to do, but it is 'rather' unelegant and unpythonic, so the question is quite simple: how can this code be changed into something more elegant

import numpy
from scipy.stats import nanmean
A = [[1, numpy.nan, 2],[2,3,4], [2,3,4], [numpy.nan, 5, 5]]
A1 = numpy.array(A)
print A1

def dosomething(d2):
    a0 = d2[0, :]
    a1 = d2[1, :]
    a2 = d2[2, :]
    dnan = ~numpy.isnan(a0+a1+a2)
    a01 = (a0-numpy.mean(a0[dnan]))/numpy.std(a0[dnan])
    a11 = (a1-numpy.mean(a1[dnan]))/numpy.std(a1[dnan])
    a21 = (a2-numpy.mean(a2[dnan]))/numpy.std(a2[dnan])
    l = nanmean(numpy.array([a01,a11,a21]), axis=0)
    return l

print dosomething(A1)

[[  1.  nan   2.]
[  2.   3.   4.]
[  2.   3.   4.]
[ nan   5.   5.]]

[-1.  0.  1.]

Edit: i simplified it a bit more


texts: Order loaded modules by amount of functions

texts:
I am trying to solve some exercises from the "Programming Erlang" book.

One of them is "Write a function to determine which module exports the most functions"

This is my solution:

-module(module_info).
-export([modules_ordered_by_amount_of_functions/0]).

modules_ordered_by_amount_of_functions() ->
  Modules = loaded_modules_with_functions(),
  SortedModules = lists:sort(fun compare_functions_length/2, Modules),
  lists:map(fun extract_amount_of_functions/1, SortedModules).

loaded_modules_with_functions() ->
  LoadedModules = code:all_loaded(),
  LoadedModuleNames = lists:map(fun extract_module_name/1, LoadedModules),
  lists:map(fun extract_functions_from_module/1, LoadedModuleNames).

extract_module_name({ModuleName, _}) -> ModuleName.

extract_functions_from_module(ModuleName) ->
  [_, {exports, Functions} | _] = ModuleName:module_info(),
  {ModuleName, Functions}.

compare_functions_length ({_, FunctionsA}, {_, FunctionsB}) ->
  length(FunctionsA) >= length(FunctionsB).

extract_amount_of_functions ({ModuleName, Functions}) ->
  {ModuleName, length(Functions)}.

It doesn't really feel elegant to me.


texts: Detecting arrays with enough entries in common

texts:
I have made a function called testing. This function tests whether five numbers from each sub-array of $source are included in $dataArray sub-arrays, at least $limit times. If so, it returns the source sub-array as a string; else it returns "x". Please see or try the example below if this description isn't clear.

And now it comes: this function works properly but with large quantity of sub-arrays in $sourceArray it is relatively slow (13 mins for 100000 tests on i7-7700K, PHP/7.1.4).

Is there any way to make this function more effective and quicker? Is there any noticeable bad construction / leak which may have an immediate impact on performance?

<?php

$dataArray=array(array(8,25,32,33,37,43),array(6,10,16,32,33,44),array(18,33,36,37,41,46),array(3,4,20,29,31,43),array(2,9,13,15,19,30),array(14,21,22,29,44,49),array(3,7,9,24,44,49),array(4,6,18,35,45,48));
// and so on - circa 4000 sub-arrays

$sourceArray=array(array(3,4,6,14,16,21,22,25,26,31,32,34,41,45,47,49),array(5,8,11,15,16,18,25,26,32),array(1,2,6,16,17,18,19,22,32,33,40,44,49),array(5,8,11,15,16,18,25,26,32),array(4,12,15,16,20,23,30,37,41,44));
// and so on - 10M+ sub-arrays (variable quantity)

function testing($dataArray, $source, $limit) {

$guessedArray = array();
foreach ($dataArray as $data) {
    $counter = 0;
    foreach ($source as $number) {
        if (in_array($number, $data)) {
            $counter++;
        }
    }
    array_push($guessedArray, $counter);
}

$guessedArray = array_count_values($guessedArray);
ksort($guessedArray);

if ($guessedArray[5] >= $limit) {
    return implode("-", $source);
  } else {return "x";}
}

foreach ($sourceArray as $oneArray) { // just example but $sourceArray's sub-arrays must be processed one by one
$result = testing($dataArray, $oneArray, 1);
echo "$result<br />";
}

/*
Result:
x
x
1-2-6-16-17-18-19-22-32-33-40-44-49
x
x

-> because only the third sub-array in $sourceArray contains five numbers located in $dataArray's sub-arrays for at least $limit times
(in this example $limit = 1)
*/

?>


texts: How can I make my Merge Sort Code In C more secure, effective and efficient

texts:
I have been implementing the merge-sort algorithm for sorting the data for a long time, each time I use the following source code for implementation.
By secure, I mean, taking care of memory management, loopholes etc.

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
void mergesort(int*,int,int);
void mergeSequence(int*,int,int,int); //Merge the two arrays
void displaySequence(int*);
int n;
int main()
{
    int t,test;
    int*num=NULL;
    int i;
    printf("Enter the number of test cases\n", test);
    scanf("%d", &test);
    assert(test>0);
    for(t=0;t<test;t++)
    {
        printf("Enter the size of the sequence\n", n);
        scanf("%d", &n);
        assert(n>0);
        num=calloc(sizeof(int),n);
        assert(num);
        printf("Enter the sequence\n");
        for(i=0;i<n;i++)
            scanf("%d", (num+i));
        printf("Sequence before sorting\n");
        displaySequence(num);
        mergeSort(num,0,(n-1));
        printf("Sequence after sorting\n");
        display(num);
        free(num);
    }
    return 0;
}
void displaySequence(int*num)
{
    int i;
    for(i=0;i<n;i++)
        printf("%d ", num[i]);
    printf("\n");
}
void mergeSort(int*num,int start,int end)
{
    int mid;
    mid=start+((end-start)/2);
    printf("Mid->%d\n", mid);
    if(start<end)
    {
        mergeSort(num,start,mid);
        mergeSort(num,(mid+1),end);
        mergeSequence(num,start,mid,end);
    }

}
void mergeSequence(int*num,int start,int mid,int end)
{
    int n1,n2;
    int i,j,k;
    n1=(mid-start)+1;
    n2=(end-mid);
    printf("N1->%d\nN2->%d\n", n1,n2);
    int left[n1];
    int right[n2];
    for(i=0;i<n1;i++)
        left[i]=num[start+i];
    for(i=0;i<n1;i++)
        printf("%d ", left[i]);
    printf("\n");
    for(j=0;j<n2;j++)
        right[j]=num[(mid+1)+j];
    for(j=0;j<n2;j++)
        printf("%d ", right[j]);
    printf("\n");
    //Now I have two arrays, and I can now merge them
    k=start;
    i=0;
    j=0;
    while((k<=end))
    {
        if(i==n1)
        {
            num[k]=right[j];
            j++;
        }
        else if(j==n2)
        {
            num[k]=left[i];
            i++;
        }
        else if(left[i]<=right[j])
        {
            num[k]=right[j];
            j=j+1;
        }
        else
        {
            num[k]=left[i];
            i=i+1;
        }
        k++;
    }
    displaySequence(num);
}


texts: Class in a DLL to extract data from a file via many accessors

texts:
I'm making a class that takes a path to a text file as an argument in its constructor, and then parses the text file and pulls out a lot of data that it stores as private members. Most of these members are vectors of ints, floats, and strings.

The class will be used by different versions of VS, so my understanding is that I need to be careful about exporting templates like the STL containers (including string). I also assume I need to be careful about passing templates into the library. Therefore, everything going into or out of the public interface is kept as a primitive type.

//header
class FileLoader
{
public:
    FileLoader(const char* path);

    int GetIterationCount();
    const char* GetName();
    int GetID();

    int GetPathValue(int iteration);
    int GetAttemptsMadeCount(int iteration);
    float GetStartTime(int iteration);
    float GetEndTime(int iteration);
    const char* GetLargestContributer(int iteration);

private:
    int iterationCount;
    std::string GetName;
    int ID;

    std::vector<int> pathValue;
    std::vector<int> attemptsMadeCount;
    std::vector<float> startTime;
    std::vector<float> endTime;
    std::vector<std::string> largestContributer;
};

//associated cpp
int FileLoader::GetPathValue(int iteration)
{
    return pathValue.at(iteration);
}
const char* GetLargestContributer(int iteration)
{
    return largestContributer.at(iteration).c_str();
}
 //similar structure for other accessors

There's something like 15 data items, some are vectors and some are just single items.

This really clutters up the public interface, but I don't see a good way around it. I considered adding an enum at the top:

enum class DataTypes
{
    PathValue;
    AttemptsMadeCount;
    StartTime;
    EndTime;
    LargestContributer;
};

And then I could just have a single function for results:

int GetResults(DataTypes::PathValue, int iteration);

And grab the appropriate underlying data with a switch. However, I don't think there's any way that'll work because the return types are different for different results. The ints need to be ints because they're the type of things people will want to do comparison operations on.

Another thought was to have a results struct that contained all the different data items for a given iteration. Then the interface is just a function that takes an iteration number and spits out the struct, and the user can choose which data item they care about.

That's the most promising to me, but the normal user will probably be more interested in all the iterations for a given data item at once. As I was typing this I was concerned about memory, since getting all the iterations for one item would mean getting it for all or most of the others. This is many hundreds of megabytes of data so that might not be trivial. However, it occurs to me that my function could populate the struct with const references to the underlying data.

Is that being too inefficient just for the sake of prettiness? It does work fine now, but I figure if there's a better way to do it I'd learn something in the process.


texts:
I wrote a non-blocking MySQL interface for java (wrapped around the standard mysql java connector).

I think the code to use it looks a bit ugly however...

db.rawQuery(queries.someAlreadyPreparedStatement, (new Callback(){
    public void result(ResultSet result){
        while (result.next()) {
            //Handle each row from the result and do any processing
    }
}));

How could this be improved? Is this as good as it gets?


texts:
I'm having trouble figuring out the best approach with DI. After doing more research, Mark Seeman recommends using the Composition Root approach. In my example, I am using XML configuration to design my mappings which allows me to drop any new dll that implements an interface without having to perform a build on the whole solution. If I use a composition root, doesn't it become a violation of Liskov's principle since I have to manually make changes and then perform a rebuild?

Here is a link to my GitHub project

Interface Shared By all Projects

namespace UnityRnD.Core
{
    public interface IGreeting
    {
        string GetGreeting();
    }
}

Main Application

namespace UnityRnD.Application
{
    class Program
    {
        private static void Main(string[] args)
        {

            var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unitySingleNamed");
            IUnityContainer container = new UnityContainer();
            container.LoadConfiguration(section);

            var letsTalk = container.Resolve<IGreeting>("tom");
            Console.WriteLine(letsTalk.GetGreeting());
        }
    }
}

The Plan

The plan is to create a bunch of projects that represent a Line of Business. Each project will have a class that implements IGreeting. I can then drop that library into the bin and add a Unity config setting to point to that project. On the resolve where it says "tom" this can become a variable which will remove that hard reference to the string "tom."

Stacey and Tom projects

namespace UnityRnD.Tom
{
    public class Greetings : IGreeting
    {
        public string GetGreeting()
        {
            return "Hi, my name is Tom.";
        }
    }
}

Michael Project
notice the class name changes.

namespace UnityRnD.Michael
{
    public class ChattyKathy : IGreeting
    {
        public string GetGreeting()
        {
            return "Hi I'm Mike and I like pizza. Lets talk about pizza for a moment.";
        }
    }
}

I'm looking for help on whether to create a new project for a Composition Root to hold all the references.  Does the main application need hard references to all of them, or does using the XML configuration suffice?


texts:
I have implemented a hash table. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.

class Hashtable:
    def __init__(self,size):
        self.size = size
        self.mainList = [[] for i in range(0,1)for j in range(self.size)]
    def index(self,key):
        #To get the index number.
        asciiValue = 0
        for i in key:
            asciiValue = asciiValue + ord(i)
        index = asciiValue % self.size
        return index
    def put(self,key,value):
        #To add value to the list.
        index = self.index(key)
        self.mainList[index].append((key,value))
    def get(self,key):
        #To get value from the list
        index = self.index(key)
        for i in range(0,len(self.mainList[index])):
            if self.mainList[index][i][0] == key:
                return self.mainList[index][i][1]
        return "This key cannot be found."


texts: Searching for a pattern in a list of tuples

texts:
I have written some code to search a for a pattern in a list of tuples.

It works, but I am sure that it can be improved. Any feedback or ideas would be greatly appreciated.

The list of tuples I am searching in looks like this:

  x = [('A', True), ('B', True), ('C', False), ('D', False),
       ('X', False), ('E', True), ('F', True), ('G', True)]

I want to find X and then also grab all the values in the tuple adjacent to X that have a value of true.

So the expected output would be:

  X E F G

For:

  y = [('X', True), ('1', True), ('2', True), ('3', True), ('4', False), ('5', True)]

The expected output would be:

  X 1 2 3

For:

  z = [('Dog', True), ('Cow', False), ('Shark', True), ('Cat', True), ('X', False)]

The expected output would be:

  Shark Cat X

For:

  z = [('C', True), ('X', False), ('D', True), ('C', False), ('S', True)]

The expected output would be:

  C X D

This is my code:

test = [('A', False), ('B', False), ('C', True), ('D', True),
     ('E', True), ('X', False), ('G', True), ('H', False)]

def find_x(x):
    for item in x:
        if item[0] == 'X':
            index = x.index(item)
            return(index)
    return(None)

def look_around(x, index):
    left = 0
    right = len(x)-1
    found_left = False
    found_right = False

    #look left:
    if index != 0:
        for i in range(index, -1, -1):
            if x[i][1] == True:
                left = i
                found_left = True
            if x[i][1] == False and i != index:
                break

   #look right
    if index != len(x)-1:
        for i in range(index, len(x), +1):
            if x[i][1] == True:
                right = i
                found_right = True
            if x[i][1] == False and i != index:
                break

    if found_left and found_right:
        return(left, right)
    elif found_left and not found_right:
        return(left, index)
    elif not found_left and found_right:
        return(index, right)
    else:
        return (index, index)

index_of_x = find_x(test)
if index_of_x != None:
    left, right = look_around(test, index_of_x)
    print "match:"
    for i in range (left, right+1, +1):
        print test[i][0], #comma prints everything on same line


texts:
Is there something terribly wrong with this implementation?

template <class T>
constexpr inline std::size_t hash_combine(T const& v,
  std::size_t const seed = {}) noexcept
{
  return seed ^ (std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
}

template <typename T> struct hash;

template <typename ...T>
struct hash<std::tuple<T...>>
{
  template <typename A1, typename ...A, std::size_t ...I>
  static auto apply_tuple(std::tuple<A1, A...> const& t,
    std::index_sequence<I...>) noexcept
  {
    if constexpr(sizeof...(A))
    {
      return hash_combine(std::get<0>(t),
        hash<std::tuple<A const&...>>()({std::get<I + 1>(t)...})
      );
    }
    else
    {
      return std::hash<std::remove_cv_t<std::remove_reference_t<A1>>>()(
        std::get<0>(t));
    }
  }

  auto operator()(std::tuple<T...> const& t) const noexcept
  {
    return apply_tuple(t,
      std::make_index_sequence<sizeof...(T) - 1>()
    );
  }
};

EDIT: This is better, I think:

template <typename ...T>
struct hash<std::tuple<T...>>
{
  template <std::size_t ...I>
  static auto apply_tuple(std::tuple<T...> const& t,
    std::index_sequence<I...>)
  {
    std::size_t seed{};

    return ((seed = hash_combine(std::get<I>(t), seed)), ...);
  }

  auto operator()(std::tuple<T...> const& t) const
  {
    return apply_tuple(t, std::make_index_sequence<sizeof...(T)>());
  }
};


texts: Concatenating CSV filenames into a single file

texts:
I've created a PHP script which take an array of filenames as a comma-separated parameter and concatenates them, serving them as one, single JavaScript file.

I've also built a caching mechanism into it - each time, it checks if any of the individual JS files have been updated and, if one or more of them has, it updates the cache and serves the new output. Otherwise, it simply loads the relevant cached file.

<?php
    $scripts_to_concatenate = $_GET['scripts'];
    $scripts_array = explode(',', $scripts_to_concatenate);
    $cached_script = '/public_html/assets/scripts/cache/' . str_replace('.js', '', str_replace(',', '_', $scripts_to_concatenate)) . '.js.cache';
    $cache_expired = false;
    if (file_exists($cached_script)) {
        foreach ($scripts_array as $script) {
                if (filemtime($script) > filemtime($cached_script)) {
                    $cache_expired = true;
                }
        }
    } else {
        $cache_expired = true;
    }
    if ($cache_expired) {
        foreach ($scripts_array as $script) {
            $script = '/public_html/assets/scripts/' . $script;
            if (file_exists($script)) {
                $output = $output . @file_get_contents($script);
            }
        }
        file_put_contents($cached_script, $output);
    } else {
        $output = @file_get_contents($cached_script);
    }
    echo $output;

Is anyone able to suggest any ways for me to improve this code, to make it more efficient or more fool-proof?

UPDATE: I've incorporated janos's recommendations into my code (original, unoptimised code above). Does anyone have any other suggestions?


texts: Comparing two vectors of arbitrary size, block by block

texts:
I am trying to compare two vectors which are of size of multiple of 4. Each vector block has a unique number it e.g {0,0,0,0}, {0,0,0,1}, {0,0,0,2} or {0,0,0,0,0,0,0,1,0,0,0,2} and {0,0,0,2,0,0,0,1} so on. I first divide the vector in block of 4 and than compare it and save the block which is not present in another vector into a global vector. I wrote a small function which do the job but often shows segmentation error.

void comparing_vectors_by_block(std::vector<int> vector_A, std::vector<int>
vector_B)
{
int blockSize = 4;
std::vector<int>::iterator start_of_A = vector_A.begin();
std::vector<int>::iterator start_of_B = vector_B.begin();

std::vector<int> subList_A;
std::vector<int> subList_B;
std::cout << "size of the vector_A: " << vector_A.size() << std::endl;
std::cout << "size of the vector_B: " << vector_B.size() << std::endl;
for (auto i = 0; i < vector_A.size() / blockSize; i++)
{
    subList_A.assign(start_of_A, start_of_A + blockSize);
    for (auto i = 0; i < vector_B.size() / blockSize; i++)
    {
        subList_B.assign(start_of_B, start_of_B + blockSize);
        if (subList_A != subList_B)
        {

            hold_result.insert(hold_result.begin(), start_of_B, start_of_B + blockSize);
            start_of_B += blockSize;
        }
        else
        {
            start_of_B += blockSize;
            std::cout << "both vectors are not equal: " << std::endl;
        }
    }
    start_of_A += blockSize;
}


texts: MySQLi script to print the name of a user

texts:
I made my first script of MySQLi. I have just learnt it from 3rd party website. So, I am not sure I am using functions which are not deprecated or outdated. I should start to practice good scripts to access databases. So, I have posted here. Any mistake you see, please point it out.

<?php

include "functions.php";

$a = checkLogin();

if($a==1) {
    $id = $_COOKIE['id'];

    include "databaseConnector.php";

    $query = $mysqli->query("SELECT * FROM users WHERE id = '$id'") or die($mysqli->error.__LINE__);

    if($query->num_rows > 0) {
        while($row = $query->fetch_assoc()) {
?>
            <?php echo stripslashes($row['firstname'])." ".stripslashes($row['lastname']); ?>
<?php
        }
    }
    else {
        return false;
    }
}
else {
    redirectIndex();
}

?>


texts:
There is a simple movement CAKeyframeAnimation,  what needs is that I can cancel and restart the animation freely.
The key point of the following code, is that I use CATransaction.flush()
I update to the render tree manually.

If not, Flush is typically called automatically at the end of the current runloop.
Then the animation of my need behaves weirdly, not as expected.

class ViewController: UIViewController {
    let red = Red(frame: CGRect(x: 200, y: 200, width: 100, height: 100))

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(red)
    }

    // storyboard , button target action
    @IBAction func startAnima(_ sender: UIButton) {
        red.stopAnima()
        CATransaction.flush()
        red.startAnimating()
    }
}

class Red: UIView{
    var isAnimating = false

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.red
    }

    public func startAnimating() {
         if isAnimating == false {
             isAnimating = true
             animateForward()
         }
     }

     public func stopAnima() {
         if isAnimating{
             isAnimating = false
             stopAnimating()
         }
     }
}

extension UIView{
    func animateForward(){
        let animation = CAKeyframeAnimation()
        animation.isRemovedOnCompletion = true
        animation.keyPath = "position.y"
        animation.values = [0, 40, 40, 0]
        animation.keyTimes = [0, 0.3, 0.7, 1]
        animation.duration = 1
        animation.isAdditive = true
        layer.add(animation, forKey: nil)
    }

    func stopAnimating(){
        layer.removeAllAnimations()
    }
}

I have an other stupid method, using two views to simulate the needed animation.
The two demos are here
The above is in the second release.
The stupid is in the first release.
I want to know how to improve it


texts: Espresso tests that check if Snackbar is displayed and if there is an internet connection

texts:
I have recently began writing tests for Android using the espresso library.
Here I have three tests.

The first test is to check if a snackbar appears when searching with blank text.
The second is a search for a restaraunt not in the database.
Finally I have a test that checks if there is an internet connection.
Can anyone verify that my tests are doing what I intend them to do and if there is anything I am missing or doing wrong?

    public class MainScreenTest {

    //Rules are interceptors which are executed for each test method
    //and will run before any set up code in the @Before method
    @Rule
   public ActivityTestRule<MainScreen> mainScreenActivityTestRule =
            new ActivityTestRule<MainScreen>(MainScreen.class);

    @Test
    public void testSearchWithBlankText() throws Exception{
        Espresso.onView(withId(R.id.searchEditText)).perform(typeText(""),pressImeActionButton());
        Espresso.onView(withText(R.string.invalidSearch))
                .check(matches(isDisplayed()));

    }

    @Test
    public void testSearchWithInvalidRestaurant() throws Exception{
        Espresso.onView(withId(R.id.searchEditText))
                .perform(typeText("Hoffman"),pressImeActionButton());
        Espresso.onView(withId(R.id.noResultsTV)).check(matches(withText("No results, try another restaurant")));
    }

    @Test
    public void testWhenInternetIsAvailable() throws Exception{
        Context context = mainScreenActivityTestRule.getActivity().getBaseContext();
        ConnectivityManager cm = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isConnected = cm.getActiveNetworkInfo().isConnectedOrConnecting();
        Assert.assertEquals(true, isConnected);
    }

}


texts: Shortest regex search and sum for integers

texts:
Given a text file including different text and integer numbers (text.txt), what's the shortest way of getting the sum of all the numbers out if it? I have:

import re

f = open('text.txt', 'r')
result = 0
for line in f.readlines():
    for value in re.findall('[0-9]+', line):
        result += int(value)
f.close()
print(result)

Which works, but I would like to understand what are the possibilities to make it shorter?


texts: Finding the longest common substring of multiple strings in Haskell

texts:
The task is to find the longest common substring of a multitude of long strings. I'm trying to find the best algorithm that wouldn't use syntax trees/arrays (as I don't know anything about them yet).

The idea was to use binary search to find the length of the desired substring, instead of simply trying n, then (n - 1) etc.

My code looks like this:

-- find all the substrings of length n
ngrams :: Int -> String -> [String]
ngrams n s | n > length s = []
           | otherwise    = take n s : ngrams n (drop 1 s)

-- find the longest common substring of multiple strings
longestCommonSubstring :: [String] -> String
longestCommonSubstring xs = go 0 $ length (head xs) + 1
 where
  -- find a substring of a given length n that is common to all strings
  commonSubstrings n = foldr1 intersect (map (ngrams n) xs)
  go l r
    -- if the binary search ended, pick one common substring
    | r - l == 1 = head $ commonSubstrings l
    | otherwise
    = case commonSubstrings m of
      [] -> go l m    -- the length is too big, try a smaller one
      _  -> go m r    -- try longer length to find longer substring
   where
    m = (l + r) `div` 2    -- the middle point

It runs at around 3s for my dataset (~100 strings of length ~1000), which seems slow to me. Is there any way to clean up and quicken the code? And is there a better way to approach this problem (apart from the syntax trees) in general?


texts: Searching through a contact list for given criteria

texts:
I have been staring at this code for awhile now and I am thinking there is a way to optimize it (namely the if-else statement with the for-loops).

Additionally, this needs to be done with an array list as that is my assignment requirement. I have all my code working, and it is not due for a few days, so I am looking for ways to improve it while extending my learning beyond the classroom.

The numberOfContacts variable is fed into the method from the main method, which gets the count from another method that reads through a text file to get the number of contacts.

/**
 * search method searches through the contact list for a given criteria
 * and displays all results.
 * @param searchString is type String.
 * @param type is type String.
 * @param numberOfContacts is type int.
 * @param contacts is type Person[].
 */
public static void search(String searchString, String type, int numberOfContacts, Person[] contacts) {
    // Initialize variables for results
    int found = 0;
    int[] results = new int[numberOfContacts];

    // Determine the type of search
    if (type.equals("name")) {
        // Search by name
        for (int x = 0; x < numberOfContacts; x++) {
            if (contacts[x].getName().contains(searchString)) {
                results[found] = x;
                found++;
            }
        }
    } else {
        // Search by phone
        for (int x = 0; x < numberOfContacts; x++) {
            if (contacts[x].getPhone().contains(searchString)) {
                results[found] = x;
                found++;
            }
        }
    }

    // Display the search results
    System.out.println("\n\t**************");
    System.out.println("\tSearch Results");
    System.out.println("\t**************");
    System.out.println("Found " + found + " results containing \"" + searchString + "\":");
    System.out.println();

    if (found > 0) {
        for (int x = 0; x < found; x++) {
            System.out.println(contacts[results[x]].getName() + "\t" + contacts[results[x]].getPhone());
        }
    }

    System.out.println("\n\n\n");
}


texts:
I work with the Oracle JGeometry method which returns (or takes as method argument) 2D segments as double array (x1,y1,x2,y2 ... xn,yn). I need to extend this array to contain 3D segments as double array (x1,y1,z1,x2,y2,z2 ... xn,yn,zn) by default Z value or reduce to 2D (by removing of all Z coordinate). I wrote simple utility methods for making this. Is there any easier or smarter way to do this?
The conversion from 2D to 3D:
public static double[] to3D(double z, double[] inputArray) {
    List<Double> convertedItems = new ArrayList<>();
    for (int i = 0; i < inputArray.length; i++) {
        convertedItems.add(inputArray[i]);
        if ((i + 1) % 2 == 0) {
            convertedItems.add(z);
        }
    }
    return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}

The conversion from 3D to 2D:
public static double[] to2D(double[] inputArray) {
    List<Double> convertedItems = new ArrayList<>();
    for (int i = 0; i < inputArray.length; i++) {
       if ((i + 1) % 3 == 0) {
           continue;
       }
       convertedItems.add(inputArray[i]);
    }
    return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}


texts: Limiting the maximum amount of goroutines run simultaneously

texts:
Here is my code which helps me to contol the maximum amount of goroutines run simultaneously.
In example below maximum is 5.

var wg sync.WaitGroup
// Create bufferized channel with size 5
goroutines := make(chan struct{}, 5)
// Read data from input channel
for data := range input {
    // 1 struct{}{} - 1 goroutine
    goroutines <- struct{}{}
    wg.Add(1)
    go func(data string, goroutines <-chan struct{}, results chan<- result, wg *sync.WaitGroup) {
        // Process data
        results <- process(data)
        // Read from "goroutines" channel to free space for new goroutine
        <-goroutines
        wg.Done()
    }(data, goroutines, results, &wg)
}

wg.Wait()
close(goroutines)

Is there a better way to control the maximum amount of goroutines?How can I improve my code?


texts:
I am trying to map a complex type to Json and store the info as Json in the DB using EF6 Code First.

Here's what I have for now:

The complex type

namespace EFTests.Data
{
    public class CalibrationMeasureResults
    {
        public CalibrationMeasureResults(int cycle, double input, double
actualOutputSignal, double nominalOutputSignal)
        {
            Cycle = cycle;
            Input = input;
            ActualOutputSignal = actualOutputSignal;
            NominalOutputSignal = nominalOutputSignal;
            SignalDeviation = actualOutputSignal - nominalOutputSignal;
            SignalDeviationPercent = Math.Abs(SignalDeviation / 16);
        }

        public int Cycle { get; set; }
        public double Input { get; set; }
        public double ActualOutputSignal { get; set; }
        public double NominalOutputSignal { get; set; }
        public double SignalDeviation { get; }
        public double SignalDeviationPercent { get; }
    }
}

The entity

namespace EFTests.Data.Entities
{
    public class Calibration
    {
        internal string _MeasureResults { get; set; }

        public int Id { get; set; }

        public List<CalibrationMeasureResults> MeasureResults
        {
            get => _MeasureResults == null ? null : JsonConvert.DeserializeObject<List<CalibrationMeasureResults>>(_MeasureResults);
            set => _MeasureResults = JsonConvert.SerializeObject(value);
        }
    }
}

and then via Fluent-API

modelBuilder.Entity<Calibration>()
            .Property(c => c._MeasureResults).HasColumnName("MeasureResults");

modelBuilder.Entity<Calibration>().Ignore(c => c.MeasureResults);

Is this a good way of doing it? Or am I overlooking something?


texts: Reg expression for finding expression in sentence

texts:
I have a regular expression that match the string that contains the word "duration", followed by a < or > operator and then a number. Here is the expression:

duration\s*(<|>)\s*([0-9]+)

Is there any way I can make this expression better?


texts:
I've created the following trigger to force two columns (date_edited and date_deleted) to have the CURRENT_TIMESTAMP every time an UPDATE request is made.

BEGIN
    # DATE_EDITED
    SET NEW.date_edited = CURRENT_TIMESTAMP;

    # DATE_DELETED
    IF ((OLD.deleted = 0 OR OLD.deleted = 'NULL' OR ISNULL(OLD.deleted) = TRUE) AND NEW.deleted = 1) THEN
        SET NEW.date_deleted = CURRENT_TIMESTAMP;

    ELSEIF (NEW.deleted = 0 OR NEW.deleted = 'NULL' OR ISNULL(NEW.deleted) = TRUE) THEN
        SET NEW.date_deleted = NULL;

    END IF;
END

I'm looking to optimize the IF conditions so that it doesn't need so many OR operators to validate if a column value is null.
Something like:

BEGIN
    # DATE_EDITED
    SET NEW.date_edited = CURRENT_TIMESTAMP;

    # DATE_DELETED
    IF (!OLD.deleted AND NEW.deleted = 1) THEN
        SET NEW.date_deleted = CURRENT_TIMESTAMP;

    ELSEIF (!NEW.deleted) THEN
        SET NEW.date_deleted = NULL;

    END IF;
END

Is it possible to achieve?


texts:
I'm working on a project where I have to prompt a user a enter several dates. This is the code I came up with for prompting the user for the day, month, and year.

Console.WriteLine("Day: ");
var dateDay = Console.ReadLine();
var dateDayInt = Convert.ToInt32(dateDay);

Console.WriteLine("Month: ");
var dateMonth = Console.ReadLine();
var dateMonthInt = Convert.ToInt32(dateMonth);

Console.WriteLine("Year: ");
var dateYear = Console.ReadLine();
var dateyearInt = Convert.ToInt32(dateYear);

DateTime myDate = new DateTime(dateYearInt, dateMonthInt, dateDayInt, 00, 00, 00, 000);

I'm using this date in a method, so it needs to be in this format.

As you can see, it's a ton of repetitive code. If I even add one or two more dates, my project will become very cluttered. Let's say I need to get 20 dates. Is there an easier way to do this, like only having one prompt per date?


texts:
I have a function that will take an image and then return that image in 8-bit color. Almost all of the code was taken from MSDN.

The code is quite short compared to all of the other methods I've seen for converting an image to 8-bit color. I'm just curious as to if this is the most efficient method?

private static Image ImageTo8bpp(Image image)
{
    var bitmap = new Bitmap(image);
    var imageCodecInfo = GetEncoderInfo("image/tiff");
    var encoder = Encoder.ColorDepth;
    var encoderParameters = new EncoderParameters(1);
    var encoderParameter = new EncoderParameter(encoder, 8L);
    encoderParameters.Param[0] = encoderParameter;
    var memoryStream = new MemoryStream();
    bitmap.Save(memoryStream, imageCodecInfo, encoderParameters);
    return Image.FromStream(memoryStream);
}

private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
    var imageEncoders = ImageCodecInfo.GetImageEncoders();
    return imageEncoders.FirstOrDefault(t => t.MimeType == mimeType);
}


texts: Validating search parameters in an Angular $scope

texts:
I am using the following function to make a specific filter passing the $scope.searchParams in this way:

<tbody ng-repeat="user in users | customFilter:searchParams "> ...

$scope.updateSearch = function() {

    var searchParams = {},
      loginArr = [],
      nameArr = [],
      statusArr = [],
      accountsArr = [],
      profileArr = [];

    if($scope.search.name !== undefined && /\S/.test($scope.search.name)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      nameArr.push($scope.search.name);
      searchParams['name'] = nameArr;
    }
    if($scope.search.login !== undefined && /\S/.test($scope.search.login)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      loginArr.push($scope.search.login);
      searchParams['login'] = loginArr;
    }
    if($scope.search.status !== undefined && /\S/.test($scope.search.status)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      statusArr.push($scope.search.status);
      searchParams['merchant.status'] = statusArr;
    }
    if($scope.search.accounts !== undefined && /\S/.test($scope.search.accounts)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      accountsArr.push($scope.search.accounts);
      //accountsArr.push('500092');
      searchParams['merchant.accounts'] = accountsArr;
    }
    if($scope.search.profiles !== undefined && /\S/.test($scope.search.profiles)){
      //$scope.tags.push({ text: 'Nombre: ' + $scope.name });
      accountsArr.push($scope.search.profiles);
      searchParams['merchant.accounts'] = accountsArr;
    }
    $scope.searchParams = searchParams;
  };

In this case I have to filter based on 5 fields ('login','name','status','account' and 'profile'). This is not optimum if I need 10 or more fields to filter. How can I do this more generic?


texts:
I decided to dive into the world of functional programming since my programming so far has been mostly in C/C++, Java, and Python. I've gone through a couple Haskell tutorials and played around in GHCi so I decided to try my first real program. I decided to try one of the easier problems on Kattis.com, Transit Woes. You can get the full problem description here.

Essentially you are given a list of times that it takes to walk between bus stops, the transit times on the buses, and the intervals at which the buses come to the stops and you need to calculate the total travel time. It was really hard for me to get into a FP mindset, and I kept thinking how easy it would be if I could just write a for loop but I finally got it. I just wanted to get some advice on good FP coding practices, and what kinds of things I should stop doing or start doing so I can get into good habits from the beginning.

import System.IO
import Control.Monad

main = do
    lines <- replicateM 4 getLine
    let inputs = (map . map) read (map words lines) :: [[Integer]]
    let a = inputs !! 0 !! 0 + inputs !! 1 !! 0
    let b = zipWith (+) (tail $ inputs !! 1) (inputs !! 2)
    let c = inputs !! 3
    let finalTime = calcTime a b c
    putStrLn $ resultStr finalTime (inputs !! 0 !! 1)

calcTime :: Integer -> [Integer] -> [Integer] -> Integer
calcTime current travel intervals
        | length travel == 0 = current
        | otherwise = calcTime (firstStop + head travel) (tail travel) (tail intervals)
        where firstStop = head [n*i | n <- [1..], n*i >= current]
              i = head intervals

resultStr :: Integer -> Integer -> String
resultStr a b
        | a <= b = "yes"
        | otherwise = "no"


texts:
I have a WCF service in which I am reading and adding some records to a .xml file.  I load the .xml document in the constructor and use it in all the methods and save when it's updated.

I want to know if this is the correct way of using it.  I have seen code around where people load the xDocument only when it's required.  If I try that, will it affect performance of individual method calls in cases of big .xml files?

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MyService : IMyService
{
    private readonly string mSchemaPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data",
        "schema_0.1.xsd");
    private readonly string mXmlPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data",
        "MyDataRecords.xml");

    private XDocument mXDocument;

    public MyService()
    {
        try
        {
            //load xml document
            mXDocument = XDocument.Load(mXmlPath);

            if (mXDocument == null)
            {
                throw new Exception("Null returned while reading xml file");
            }
        }
        catch (Exception e)
        {
           //my exception management code
        }
    }

    public List<MyDataRecords> GetAllRecords()
    {
        ////fetch records from xDocument

       mXDocument.Save();
    }
    public void AddRecord(MyRecord record)
    {
        ////add record

       mXDocument.Save();
    }


texts:
I'm creating a simple registration form, but stuck somewhere. I want to use token variable in new user() scope, but if I put new user() part outside of crypto, I can't access it.

Right now it works as expected, but is incomplete. I wonder whether there's another way to achieve this without putting everything inside each other. I need to access hash, so I put new user() inside bcrypt.hash. I also need to access buf, so I put it inside bcrypt, too.

Should I restructure my code (if yes, please help me a little) or is it "okay" as it is? Everything is kinda chained right now, is that normal?

var newUser = req.body;

bcrypt.genSalt(10, function (err, salt) {
    bcrypt.hash(newUser.password1, salt, function (err, hash) {

        crypto.randomBytes(48, function (ex, buf) {
            var token = buf.toString('hex');

            new user({
                email: newUser.email,
                username: newUser.username,
                password_hash: hash,
                image_id: 1,
                confirmation_code: token

            }).save().then(function (data) {
                // do stuff
                console.log(data.toJSON());
            });
        });
    });
});


texts:
One year ago, I asked for a review of Simple Linux upgrade script in Bash.

Conditions are slightly changed, and/or more accurate:

Code readability for the code user, making it simple to adjust the script's behavior
Output readability for the script user, supposing it will run always in interactive form (this is sort of contradicting the original post)
Colored headings describing what exactly is the script doing
Attempt to correct things; well this one is hard to make, but let's suppose the two initial commands will do the trick
Clean-up old packages after successful update

I hereby add:

It must be a portable POSIX shell script
It must have a clear typed-in header for users to distinguish between different computers, if running this script on several machines. It could be a hostname, but I decided otherwise for personal purposes (I myself run it on 3 machines in sequence with SSH public key authentication)
It must, in the end, check if the Linux it is running on, is Mint. If so, it needs to offer a kernel upgrade (I chose the safest way through MintUpdate) - ask if the user wants to run it
I want it to pass ShellCheck.net without any warning

#!/bin/sh

red="\\033[1;31m"
green="\\033[1;32m"
yellow="\\033[1;33m"
blue="\\033[1;34m"
nocolor="\\033[0m"

print_newline()
{
    printf "\\n"
}

show_success()
{
    echo "${green}Success.${nocolor}"
    print_newline
}

show_error_and_exit()
{
    echo "${red}An error occured.${nocolor}"
    print_newline
    exit "$1"
}

error_handler()
{
    if [ "$1" -ne 0 ]
    then
        show_error_and_exit "$2"
    else
        show_success
    fi
}

ask_for_sudo_password()
{
    sudo sh -c ":"
}

is_it_linux_mint()
{
    return $(grep -i mint /etc/lsb-release > /dev/null 2>&1)
}

print_newline

echo "${blue}--------------------${nocolor}"
echo "${blue}Vlasta - Laptop Mint${nocolor}"
echo "${blue}--------------------${nocolor}"

print_newline

echo "${green}Step 0: enter password${nocolor}"

# in order to print information AFTER sudo password has been provided
ask_for_sudo_password

error_handler "$?" 1

echo "${green}Step 1: configure packages${nocolor}"
echo "${yellow}dpkg --configure -a${nocolor}"

sudo dpkg --configure -a

error_handler "$?" 2

echo "${green}Step 2: fix broken dependencies${nocolor}"
echo "${yellow}apt-get install --fix-broken${nocolor}"

sudo apt-get install --fix-broken

error_handler "$?" 3

echo "${green}Step 3: update cache${nocolor}"
echo "${yellow}apt-get update${nocolor}"

sudo apt-get update

error_handler "$?" 4

echo "${green}Step 4: upgrade packages${nocolor}"
echo "${yellow}apt-get upgrade${nocolor}"

sudo apt-get upgrade

error_handler "$?" 5

echo "${green}Step 5: upgrade packages with possible removals${nocolor}"
echo "${yellow}apt-get dist-upgrade${nocolor}"

sudo apt-get dist-upgrade

error_handler "$?" 6

echo "${green}Step 6: remove unused packages${nocolor}"
echo "${yellow}apt-get --purge autoremove${nocolor}"

sudo apt-get --purge autoremove

error_handler "$?" 7

echo "${green}Step 7: clean up${nocolor}"
echo "${yellow}apt-get autoclean${nocolor}"

sudo apt-get autoclean

error_handler "$?" 8

if is_it_linux_mint
then

    while true
    do
        echo "Do you want to check for kernel upgrade via MintUpdate?"
        read -r answer
        case "$answer" in
            [Yy]) :   ; break;;
            [Nn]) exit; break;;
               *) echo "Please answer Y or N.";;
        esac
    done

    echo "${green}Step 8: Linux Mint kernel upgrade${nocolor}"
    echo "${yellow}mintupdate${nocolor}"

    sudo /usr/bin/python3 /usr/lib/linuxmint/mintUpdate/mintUpdate.py show

fi


texts:
I need advise on how to improve the following code for this exercise.

I need to write a function which receives 2 arguments:

Data records ///example: "id,first,last,email\n" + "555,John,Doe,jd@gmail.com\n" + "666,Jason,scott,js@gmail.com\n" + ............
Parameter // example: "email"

I need to return a function which searches the records for the value sent by the user;

Example:

var search = init(
"id,first,last,email\n" +
"555,John,Doe,jd@gmail.com\n" +
"666,Jason,scott,js@gmail.com\n",
"email");

search("js@gmail.com"); /// -> {"id":"666","first":"Jason","last":"scott", "email":"js@gmail.com"}

My code so far:

   function init(text, key) {
    var arr = text.split('\n'); /// convert text to array
    var keyIndex = arr[0].split(',').indexOf(key); /// returns 3

    return function (value) {
        for (var i = 1; i < arr.length; i++) {
            var dataLine = arr[i].split(','); /// "666,Jason,scott,js@gmail.com\n" to array
            if (dataLine[keyIndex] === value) { /// found match between value and id
                return convertToObject(arr[0].split(','), dataLine);
            }
        }
        return "not found";
    }
}

function convertToObject(indexLine, dataLine) {
    /// creates an object from 2 lines: {email: "js@gmail.com",first: "Jason", id: "666", last: "scott"}
    var obj = {};
    var result = "";
    for (var j = 0; j < dataLine.length; j++) {
        obj[indexLine[j]] = dataLine[j];
    }
    return JSON.stringify(obj); /// String format;
}

Although my code works, I would appreciate any insights -

Is there a way to optimize this search? is it right to convert every line of data to array on every loop iteration?


texts:
Dears
I have following component
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { filterTransactionsByDates } from 'Utils/functions';
import {ReactComponent as BilanceIcon} from 'assets/icons/balanceDashboardIcon.svg';
import { ReactComponent as IncomeIcon } from 'assets/icons/incomeDashboardIcon.svg';
import { ReactComponent as SavingsIcon } from 'assets/icons/savingsDashboardIcon.svg';
import { ReactComponent as ExpensesIcon } from 'assets/icons/expensesDashboardIcon.svg';

import SingleSummaryField from 'components/UI/SingleSummaryField'

const Wrapper = styled.div`
    width: 96%;
    height: 100%;
    display: flex;
    flex-flow: column;
    gap: 21px;
`

const Row = styled.div`
    display: flex;
    flex-flow: row;
    gap: 21px;
`

const BudgetSummary = ({ budgetSummary }) => {
  const {expensesSum, incomesSum, balance} = budgetSummary;
  return (
    <Wrapper>
      <Row>
        <SingleSummaryField amount={balance} name="Balance">
          <BilanceIcon />
        </SingleSummaryField>
        <SingleSummaryField amount={incomesSum} name="Income">
          <IncomeIcon />
        </SingleSummaryField>
      </Row>
      <Row>
        <SingleSummaryField amount={1000} name="Savings">
          <SavingsIcon />
        </SingleSummaryField>
        <SingleSummaryField amount={0 - expensesSum} name="Expenses">
          <ExpensesIcon />
        </SingleSummaryField>
      </Row>
    </Wrapper>
  );
};

BudgetSummary.propTypes = {
  budgetSummary: PropTypes.shape({
    expensesSum: PropTypes.number.isRequired,
    incomesSum: PropTypes.number.isRequired,
    balance: PropTypes.number.isRequired,
  }),
};

const getBudgetSummary = createSelector(
  (state) => state.expenses.expenses,
  (state) => state.incomes.incomes,
  (state) => state.datesRange.datesRange,
  (expenses, incomes, datesRange) => {
    const filteredExpenses = filterTransactionsByDates(expenses, datesRange);
    const filteredIncomes = filterTransactionsByDates(incomes, datesRange);

    const expensesSum = filteredExpenses.reduce((sum, currentTransaction) => {
      return sum + currentTransaction.amount;
    },0);

    const incomesSum = filteredIncomes.reduce((sum, currentTransaction) => {
      return sum + currentTransaction.amount;
    }, 0);

    const balance = incomesSum - expensesSum;

    return {
      expensesSum: expensesSum,
      incomesSum: incomesSum,
      balance: balance,
    };
  }
)

const mapState = (state) => {
  return {
    budgetSummary: getBudgetSummary(state)
  }
}

export default connect(mapState)(BudgetSummary);

What do you think about providing data
to the component ? Do you think that method which is being used right now is fine or it would be better to separate the logic to some kind of container component or maybe shall I create separate component which will handle only js operations on data ?


texts: Google Code Jam Google String problem: a sequence resulting from bit flips and reversals

texts:
I'm currently having a go at some past Google Code Jam problems to help me practice my programming skills.

One of these problems is Problem A ("Googol String") from Round A APAC Test 2016. Here is the problem for reference (you can find the details via the link):

  Problem

  A "0/1 string" is a string in which every character is either 0 or 1. There are two operations that can be performed on a 0/1 string:

  switch: Every 0 becomes 1 and every 1 becomes 0. For example, "100" becomes "011".
  reverse: The string is reversed. For example, "100" becomes "001".

  Consider this infinite sequence of 0/1 strings:

  S0 = ""

  S1 = "0"

  S2 = "001"

  S3 = "0010011"

  S4 = "001001100011011"

  ...

  SN = SN-1 + "0" + switch(reverse(SN-1)).

  You need to figure out the Kth character of Sgoogol, where googol = 10100.

  Input

  The first line of the input gives the number of test cases, T. Each of the next T lines contains a number K.

  Output

  For each test case, output one line containing "Case #x: y", where x is the test case number (starting from 1) and y is the Kth character of Sgoogol.

After an hour (probably too long to spend on one problem, but it's practice!), I developed a solution.

Here it is:

def switch(num):
    newnum = ""
    for char in num:
        newnum += ("1" if char == "0" else "0")
    return newnum

def reverse(num):
    newnum = ""
    for i in range(len(num)-1, -1, -1):
        newnum += num[i]
    return newnum

def find(digits):
    googol = (10**100)
    s = ["", ""]

    for n in range(1, googol + 1):
        s[1] = s[0] + "0" + switch(reverse(s[0]))

        if len(s[1]) >= digits:
            return s[1]

        s[0] = s[1]

r_fname = "A-small-practice.in"
w_fname = "output-small.txt"

with open(r_fname, "r") as file:
    contents = file.readlines()

with open(w_fname, "w+") as file:
    t = int(contents[0].strip("\n"))

    for case in range(1, t+1):
        k = int(contents[case])
        print("Case {0}: finding the {1}th digit".format(str(case), str(k)))

        string = find(k)
        solution = string[k-1]

        print("Case #{0}: {1}".format(str(case), solution))
        file.write("Case #{0}: {1}\n".format(str(case), solution))

The above can successfully generate an output for the small input file, but the main issue I am having is that it runs far too slow for the large input file (almost as if not running at all).

I have already tried to improve the code a little - I thought adding the line:

s[0] = s[1]

in the for loop would mean that the list will always only consist of two items, reducing memory allocation.

My other fear is that I have coded too much for something that could be written in a more concise way (I'm not sure about this one).


texts:
private static boolean trovato , ok = false;

public static void main(String args[]) throws IOException {

HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

String line;
line = stdin.readLine();
String a = "a" ;
String ii = "i" ;
String s = "s" ;
int cont = 0 ;

while (!line.equals("<END>")) {

String stringa = "";
String elemento = "" ;

if (line.startsWith(ii)) {
map = new HashMap<String, HashSet<String>>();
}
else if (line.startsWith(a)) {
String[] letteraPerLettera = line.split("");

for (int i = 0  ; i < letteraPerLettera.length - 2; i++) {

if (!letteraPerLettera[i].equals(" ")) {

if (ok)
{
element = line.substring(2,i-2) ;

trovato  = true ;
ok = false ;
}

if (trovato )
{
stringa+=letteraPerLettera[i];
if (map.containsKey(stringa)) {
map.get(stringa).add(elemento);
} else
{
HashSet <String> hs = new HashSet<String> () ;
map.put(stringa, hs );
map.get(stringa).add(elemento);
}
}

}

else {

cont ++ ;

if (cont == 2)

ok = true ;

stringa = "";

}

}

}

else if (line.startsWith(s)) {
String subtag = line.substring(2,line.length()-3);
if (map.containsKey(subtag)) {

System.out.println(map.get(subtag).size());
} else {
System.out.println("missing");
}
}

cont = 0 ;
trovato = false ;
line = stdin.readLine();
}
stdin.close();
}

My code has an input like this:

i3
a Duna automobile Deserto -1
a Nissan auto automobile -1
s aut -1

i2
a Pesca Sport Frutta -1
s sport -1

END

i = 3 means that there are 3 lines.
"a" means that I'm adding an element (first occurrence after "a") and the other words after the element are my "tags".
"s" means that I have to find the tags that have as substring the word "aut" for the first block and "sport" for the second block.

At the end the output is like this:

￼2
1

"2" means I have two elements "duna" & "nissan" that have tags (auto, automobile, auto) that start with the word "aut".
"1" means I have the element "pesca" that has tag (sport) that starts with the sub-tag "sport".

With END, the program is finished.


texts:
I am solving interview questions from here.

  Problem : Given an integer n, generate the nth count and say sequence.
  The count-and-say sequence is the sequence of integers beginning as follows:  1, 11, 21, 1211, 111221, ...

  1 is read off as one 1 or 11.

  11 is read off as two 1s or 21.

  21 is read off as one 2, then one 1 or 1211.

  Note : The sequence of integers will be represented as a string.

  Example: if n = 2, the sequence is 11.

How should I further optimize my solution?

def count_and_say(num):
        string = '11'
        cnt = 0
        new_string = []
        if num == 1:
            return "1"
        while num != 2:
            cnt += 1
            for i in range(len(string)):
                if i+1 != len(string):
                    if string[i] == string[i+1]:
                        cnt += 1
                    else:
                        new_string.append(str(cnt)+string[i])
                        cnt = 1
                else:
                    new_string.append(str(cnt)+string[i])
            cnt = 0
            num -= 1
            string = ''.join(new_string)
            new_string = []
        return string


texts:
Simulate a tic-tac-toe game

Requirements

A player is picked at random as a first player.
The two players plays tic tac toe game.
The game ends when the board is full or either one of the player wins.
Return the board status and result after end of the game.

  Player Class

class Player:
    def __init__(self, name, symbol):
        self.name = name
        self.symbol = symbol

    def pick_available_grid(self, available_position):
        random_index = random.choice(available_position.keys())
        return random_index

  Board Class

class Board:
    def __init__(self):
        self.grid = [None]*9
        self.available_position = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}

    def update_board(self, index, symbol):
        self.grid[index-1] = symbol
        del self.available_position[index]

    def check_if_board_full(self):
        len(self.available_position) == 0

    def check_for_win_condition(self,symbol):
        if (self.grid[0]==symbol and self.grid[1]==symbol and self.grid[2]==symbol):
            return True
        if (self.grid[3]==symbol and self.grid[4]==symbol and self.grid[5]==symbol):
            return True
        if (self.grid[6]==symbol and self.grid[7]==symbol and self.grid[8]==symbol):
            return True

        #vertical grid check
        if (self.grid[0]==symbol and self.grid[3]==symbol and self.grid[6]==symbol):
            return True
        if (self.grid[1]==symbol and self.grid[4]==symbol and self.grid[7]==symbol):
            return True
        if (self.grid[2]==symbol and self.grid[5]==symbol and self.grid[8]==symbol):
            return True

        #diagonal grid check
        if (self.grid[0]==symbol and self.grid[4]==symbol and self.grid[8]==symbol):
            return True
        if (self.grid[2]==symbol and self.grid[4]==symbol and self.grid[6]==symbol):
            return True

  Game Class

class Game:
    global SYMBOL
    SYMBOL = ['X', 'O']

    def __init__(self):
        self.board = Board()
        self.players = []
        self.result = None

    def set_players(self):
        player1 = Player('akanksha', SYMBOL[0])
        player2 = Player('akanksha', SYMBOL[1])
        self.players.append(player1)
        self.players.append(player2)

    def set_current_player(self, current_player=None):
        current_player = self.players[1] if current_player == self.players[0] else self.players[0]
        return current_player

    def set_result(self):
        if self.board.check_for_win_condition(self.players[0].symbol):
            self.result = self.players[0]
        elif self.board.check_for_win_condition(self.players[1].symbol):
            self.result = self.players[1]
        elif self.board.check_if_board_full():
            self.result = 'Draw'
        return self.result

    def play_game(self):
        current_player = self.set_current_player()
        while(not self.set_result()):
            available_position = self.board.available_position
            grid_position = current_player.pick_available_grid(available_position)
            self.board.update_board(grid_position, current_player.symbol)
            current_player = self.set_current_player(current_player)

    def end_game(self):
        print(self.board.grid)
        if self.result == 'Draw':
            print('This game is a draw')
        else:
            print('player', self.result.name, "with symbol", self.result.symbol, "wins")

    def start_game(self):
        self.set_players()
        self.play_game()
        self.set_result()
        self.end_game()

  Main Program

class MainProgram:
    def main():
        print("Welcome to TicTacToe Game")
        game = Game()
        game.start_game()

    main()

I am new to oops, how can I improve this?

Questions:

Should I create a separate class for symbol?
Should check_for_win_condition be included in Game instead of Board class?
Should self.available_position be used or it should be method which computes available cells from grid


texts: Python CLI-Parser improvement for "one of those options"

texts:
I was wondering if there was a better way to implement my cli parser.

For context:
I need to pass to my script either a file in one of two formats or two files in a specific format.

It may be easier to understand like this:

file.ext1 OR file.ext2 OR (file_1.ext2 AND file_2.ext2)

I've used python argparse add_mutually_exclusive_group successfully and it looks like this:

import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
    "--ext1",
    type    = __existant_file,
    metavar = "FILE",
    help    = "input file (format ext1)"
)
group.add_argument(
    "--ext2",
    type    = __existant_file,
    metavar = "FILE",
    help    = "input file (format ext2)"
)
group.add_argument(
    "--paired",
    nargs   = 2,
    type    = __existant_file,
    metavar = ("MATE_1", "MATE_2"),
    help    = "input file (two files format ext2)"
)

args = parser.parse_args()
print(args)

if args.ext1 is not None:
  file = args.ext1
elif args.ext2 is not None:
  file = args2.ext2
else:
  file = args.paired[0]
  file2 = args.paired[1]

Which is used as:

python script.py --ext1 file
OR
python script.py --ext2 file
OR
python script.py --paired file_1 file_2

Which is working but not really smooth. Do you have any lead of how I can improve the CLI parser ?


texts: Random timestamp within last 3 relative years

texts:
I'm trying to generate a random time between now and 3 years ago. To my knowledge, Go doesn't have a random(min,max) feature in either math/rand or crypto/rand where min > 0. To naively combat that, I generate a slice containing every time stamp within the relative now and 3 years ago, and then select the index at random with rand.Intn(len(timeRange)), because I am guaranteed to get a random index between 0 and len(timeRange). It works just fine, and I get a Unix time stamp sometime between now and 3 years ago. However, I want to generate just one timestamp, not ~94m of them and then randomly picking one...it's egregiously slow.

Here is the code:

package main

import (
    "time"
    "math/rand"
    "fmt"
)

func randomTimestamp() time.Time {
    now := time.Now().Unix()
    threeYearsAgo := int64(now - 94608000)
    timeRange := make([]int64,1)
    for i := threeYearsAgo; i < now; i++ {
        timeRange = append(timeRange, i)
    }
    randomTime := rand.Intn(len(timeRange))

    randomNow := time.Unix(timeRange[randomTime], 0)

    return randomNow
}

func main() {
    for i := 0; i < 25; i++ {
        fmt.Println(randomTimestamp().Format(time.RFC3339))
    }
}

How can I optimise randomTimestamp() so it doesn't have to calculate every second over the last 3 years, but it randomly picks one between now and 3 years ago?


texts: Preventing numbers from showing up in scientific notation

texts:
We have a StreamBuffer class which is not inherited from std::ios_base (or some of it's derivatives such as std::ostream) so that I can use std::fixed operations and I am trying to prevent number showing up in scientific notations. With my below code some numbers are getting shown in scientific notations. We want to avoid doing any allocations so that's why we implemented StreamBuffer class because of performance reason.

T value = 0;

template<typename U> void process(U& buf, DataOption holder) const {
    if (holder == DataOption::TYPES) {
        switch (type_) {
        case teck::PROC_FLOAT:
            buf << "{\"float\":" << value << "}";
            break;
        case teck::PROC_DOUBLE:
            buf << "{\"double\":" << value << "}";
            break;
        default:
            buf << "{\"" << type_ << "\":" << value << "}";
        }
    }
}

This is the way it is being called:

void HolderProcess::dump(std::ostream& os, DataOption holder) const
{
    process<std::ostream>(os, holder);
}

void HolderProcess::dump(StreamBuffer& buffer, DataOption holder) const
{
    process<StreamBuffer>(buffer, holder);
}

I came up with this solution to avoid number (here value is coming in exponent form and I want to have a fixed number for that value) getting converted to scientific notation, but it uses string and it will do some allocations, which is not performance-efficient.

template <typename T> string str(T number)
{
   std::ostringstream ss;
   ss << std::fixed << number;
   return ss.str();
}

And then I can call above template method from my above each case block. This, however, will most certainly allocate more memory. Is there any better way to solve this problem which is optimized, efficient and doesn't do any allocations?


texts:
I have created the following code:

class Club(object):
    def __init__(self, name, points=1000):
        self.name = name
        self.points = points

    def __eq__(self, other):
        return self.name == other.name

    def __gt__(self, other):
        return self.points > other.points

    def compute_points(self, opponent, is_home, result):
        rating_diff = self.points - opponent.points + (100 if is_home else -100)
        expected = 1 / (1 + 10**(-rating_diff/400))
        return 32 * (result-expected)

def play_match(home, away, result):
    home_change = int(home.compute_points(away, True, result))
    away_change = int(away.compute_points(home, False, 1-result))
    home.points += home_change
    away.points += away_change

def club_index(club_to_find, clubs):
    index = 0
    while index < len(clubs):
        club = clubs[index]
        if club.name == club_to_find:
            return index
        index += 1
    return -1

def main():
    clubs = []
    with open("matches.txt") as file:
        matches = file.readlines()

    for match in matches:
        (home_str, away_str, result) = match.split(" ")

        index = club_index(home_str, clubs)
        if index == -1:
            home = Club(home_str)
            clubs.append(home)
        else:
            home = clubs[index]

        index = club_index(away_str, clubs)
        if index == -1:
            away = Club(away_str)
            clubs.append(away)
        else:
            away = clubs[index]

        play_match(home, away, float(result))

    clubs = sorted(clubs)
    clubs.reverse()
    with open("ranking.txt", "w") as file:
        for club in clubs:
            file.write(club.name + ": " + str(club.points) + "\n")

if __name__ == "__main__":
    main()

which takes a file containing match results, and creates a file containing a ranking based on the Elo Ranking System. However, I feel like my main() method could've been implemented in a better way, so I came here to see for some pointers as to how I can better implement it or pick up any other good practices.

EDIT: Here's an example of the input file:

Swansea ManUtd 0
WestHam Cardiff 1
WestBrom Southampton 0
Sunderland Fulham 0
Norwich Everton 0.5
Arsenal AstonVilla 0
Liverpool Stoke 1
Chelsea Hull 1


texts:
I'm making a family tree. The following script allows the user to expand branches of the tree. It works fine, but there must be a better way.

You can see it working here.

$(function(){
    $('.oc').prepend('')
    $("ul[id|=Nested]").hide();
    $("a[id|=trigger_Nested]").click(function() {
        var text = $(this).siblings("ul");
        if (text.is(':hidden')) {
            text.slideDown("fast");
            $(this).next("span").html('');
        } else {
            text.slideUp("fast");
            $(this).next("span").html('');
        }

        return false;
    });
});


texts:
I have two projects, a native C++ DLL (pinvokelib.dll), and a C# console application (pinvoketest.exe) which calls the DLL. I'm curious if the way I do P/Invoke is considered best practice.

Here is my C++ code:

extern "C" __declspec(dllexport) int test(int val);

int test(int val)
{
    return val * 2;
}

And my C#:

using System;
using System.Runtime.InteropServices;

namespace pinvoketest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(test(42));
            Console.ReadLine();
        }

        [DllImport("pinvokelib.dll", CallingConvention=CallingConvention.Cdecl)]
        static extern int test(int val);
    }
}

I'm using Visual Studio 2012 Express to compile both.

Is there any way that the code can be improved? Is there something redundant? I'm especially unsure about the first line of the C++ code, since I don't understand everything about it very well.


texts: Simple Question about Numeric Operations

texts:
I have a question that may be easily answered, but the answer evades me.  In regards to numeric operations, how come when I code this:

double celsius = 30;
double fahrenheit = (celsius + 32.0) / (5/9);

I get an answer:

fahrenheit = infinity;

But, when I code this:

double fahrenheit = (celsius + 32.0) / (5.0/9);  // with a decimal place after 5 or 9

The answer comes out correctly as 111.6?

Shouldn't the (5/9) automatically become a double without the decimal, or am I incorrect?


texts: Using nullable properties in a base class for record selection in Table per Hierarchy

texts:
I want to be able to list every Transaction associated with a Client in date order.

Transaction has 2 sub-types: PaymentTransaction and ChargeTransaction.

The key difference between them is:

PaymentTransaction should be associated directly with a Client.
ChargeTransaction is associated with a Proposal, which in turn is associated with a Client.

public abstract class Transaction
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public DateTime Time { get; set; }
}

public class PaymentTransaction : Transaction
{
    public int ClientId { get; set; }
    public Client Client { get; set; }
}

public class ChargeTransaction : Transaction
{
    public int ProposalId { get; set; }
    public Proposal Proposal { get; set; }
}

public class Client
{
    public int Id { get; set; }
    public ICollection<Proposal> Proposals { get; set; }
    public ICollection<PaymentTransaction> Payments { get; set; }
}

public class Proposal
{
    public int Id { get; set; }
    public int ClientId { get; set; }
    public Client Client { get; set; }
    public ICollection<ChargeTransaction> Charge { get; set; }
}

There will be 1000s of records for each Client. So I need to page the results.

I don't want to have to blend the results from 2 Db tables, so I have used Table per Hierarchy pattern:

public DbSet<Transaction> Transactions { get; set; }
public DbSet<PaymentTransaction> PaymentTransactions { get; set; }
public DbSet<ChargeTransaction> ChargeTransactions { get; set; }

My problem is retrieving the results for a specific ClientId. For db.ChargeTransactions I would use x => x.Proposal.ClientId. And for db.PaymentTransactions I would use x => x.ClientId. But for db.Transactions I cannot use either of these.

My Solution

I have put the Proposal and Client properties directly on the Transaction model and made them nullable.

I'm not convinced this is a good solution, but I don't know a better way. That is why I'm asking this question.

Can you suggest any improvements on this? Or a better approach?

public abstract class Transaction
{
    public int Id { get; set; }
    public decimal Amount { get; set; }
    public DateTime Time { get; set; }
    public int? ClientId { get; set; }
    public virtual Client Client { get; set; }
    public int? ProposalId { get; set; }
    public virtual Proposal Proposal { get; set; }
}

public class PaymentTransaction : Transaction
{

}

public class ChargeTransaction : Transaction
{

}

This means I can do:

db.Transactions.Where(x => x.ClientId == clientId || x.Proposal.ClientId == clientId)


texts: Beginner's level hovering effect on anchors

texts:
After a few trials I've written this code where the border of a link expands:

a {
  position: relative;
  text-decoration: none;
margin:0;
}

a::after{
  content: "";
  position: absolute;
//relative to a
  bottom:0;
  left:0;
  width:0%;
  transition: 0.3s width ease-out;
}
a:hover::after {
  width:100%;
  border: 1px solid black;
}
LINKLINKLINK

Would you suggest any beginner-level improvement of the code?
Or any exercise or variant of it?


texts: Variable length string validation against whitelisted characters

texts:
I need to validate a variable length string against some white-listed characters. The algorithm that I have works but I have a sneaking suspicion that there is a more elegant solution. The code below hasn't been identified as a bottleneck so ease of maintenance is preferred over a clever but confusing implementation.

private static readonly Regex ReferralCodeValidator = new Regex(
   @"[ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789]",
   RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

private const int MinLength = 3;

private const int MaxLength = 8;

public static bool IsValidReferralCode(this string code)
{
   if (string.IsNullOrWhiteSpace(code))
   {
       return false;
   }

   if (code.Length < MinLength || code.Length > MaxLength)
   {
       return false;
   }

   // Variable for clarity and easier regex troubleshooting
   var strippedCode = ReferralCodeValidator.Replace(code, string.Empty);
   return strippedCode == string.Empty;
}

I also have the following NUnit tests to validate/exercise the solution:

[Test]
[TestCase("AARPeVER", true)]
[TestCase("1234EVE", true)]
[TestCase(null, false)]
[TestCase("AARP", true)]
[TestCase("AA", false)]
[TestCase("AAr", true)]
[TestCase("123456789", false)]
[TestCase("AARP0", false, Description = "Zero isn't allowed.")]
[TestCase("AARPO", true, Description = "The letter O is allowed.")]
[TestCase("", false)]
[TestCase("  ", false)]
[TestCase("AAR ", false)]
[TestCase("AAR\n", false)]
[TestCase("Ever||12", false)]
public void IsValidReferralCode(string input, bool success)
{
    Assert.AreEqual(success, input.IsValidReferralCode());
}


texts: Find first non-repetitive character in a string

texts:
The original task was to find the first non-repetitive character in a string.

Every now and then I read questions here on Code Review and try answering them myself, and as such I stumbled upon this one.

Now, I have two solutions:

The first one:

struct ch {
    int num;
    char c;
} characters[127];

char find_first_non_repetitive(char *string)
{
    int i = 0;

    for(i = 0; i < strlen(string); i++) {
        characters[string[i]].num++;
        characters[string[i]].c = string[i];
    }

    int index = characters[string[0]].num;
    char c = characters[string[0]].c;

    for(i = 1; i < 127; i++)
    {
        if(characters[i].num != 0 && first > characters[i].num)
        {
            first = characters[i].num;
            c = characters[i].c;
        }
    }

    return c;
}

About this one, if using C# instead of C, my idea was to replace struct with an ArrayList<int>.

The second one:

char find_first_non_repetitive(char *string)
{
    const int NUM_CHARACTERS = 127;

    int i = 0, cha[NUM_CHARACTERS];

    for(i = 0; i < NUM_CHARACTERS; i++) cha[i] = 0;

    for(i = 0; i < strlen(string); i++) cha[string[i]]++;

    int index = cha[string[0]];
    char c = string[0];

    for(i = 1; i < strlen(string); i++)
    {
        if(index > cha[string[i]])
        {
            index = cha[string[i]];
            c = string[i];
        }
    }

    return c;
}

Which one is more efficient, and is there an even more efficient way?


texts: Ruby on Rails - Creating many models associated with another one

texts:
So I have the following models:

class Poll < ApplicationRecord
    validates :title, presence: true, allow_blank: false
    validates :options, presence: true

    has_many :options, dependent: :destroy
end

class Option < ApplicationRecord
    validates :title, presence: true, allow_blank: false

    belongs_to :poll
end

And given the following data:

{
    title: "My poll",
    options: [
        {title: "Option 1"},
        {title: "Option 2"},
        {title: "Option 3"},
    ]
}

I would like to create a poll with 3 options.

This is my solution:

    # POST /polls
    def create
        @poll = Poll.new(poll_params)

        params[:options].each do |option|
            @poll.options.new option.permit(:title)
        end

        if @poll.save
            render json: @poll, status: :created, location: @poll
        else
            render json: @poll.errors.full_messages, status: :unprocessable_entity
        end
    end


texts:
I am creating an mapeditor web application like tiled

My ng-repeat looks like this:

It happens to be verry slow rendering and editing when using maps bigger than 50 by 50 tiles.

This means you will have 50 x 50 = 2500 * 2(layers) = 5,000 tiles/divs. And more if there are more bottom images or top images stacked.

Things I tried:

Replacing {{bind}} with ng-* attributes
Using current scope variables x or y instead of the $scope variable mapDisplayerImages[y] and [y][x].

Are there more things I can do to optimize the mapeditor?


texts:
I have a CSV file, call it csv_file. It has the following content:

Username, Password
name1, pass1
name2, pass2
...

I also have a dictionary, call it mydict. It has the following content:

mydict = {
    "name2" : "pass2",
    "name3" : "pass3"
     ...
}

I want to update my CSV file to now include name3, pass3, since those aren't in the CSV file but they are in the dictionary.

What's the most efficient, pythonic way of doing this?

Right now, here's what I have, but I don't think it's very efficient:

with open(csv_file, 'rb') as infile, open(new_csv_file, 'wb') as outfile:

     r = csv.DictReader(infile)
     w = csv.DictWriter(outfile, r.fieldnames)
     w.writeheader()

     temp_dict = {row['Username'] : row['Password'] for row in r}

     for k in mydict:
          if k.key not in temp_dict:
               temp_dict[k] = mydict[k]

     for value in temp_dict:
          w.writerow({'Username' : value, 'Password' : temp_dict[value]})

I'm sure there's something I can do to make this better. Any suggestions?


texts:
Can someone please review the code and suggest any improvements / changes? Note that this method works but wanted to see if there is a better way for self learning purpose JavaScript/jQuery.
Example
https://jsfiddle.net/tjmcdevitt/Lx0vnb89/4/
var AppType = [
    ['All'],
    ['API'],
    ['AWS'],
    ['Web']
];

    $.each(AppType, function (index, AppType) {
        var option = $('<option></option>').attr("value", AppType).text(AppType);
        $("#ddlApplicationType").append(option);
    });


texts:
Working with PyTorch tensors, I need to split the batch of items by its flags, so the items in x_batch_one and x_batch_two are lists of pairs that have the same flags.

def pairs_by_flags(self, x_batch, y_batch, max_flag):
#split x_batch on pairs

    sizes = (x_batch.size(0)//2, *x_batch.size()[1:] )

    items_pos = torch.zeros((max_flag,), dtype = torch.long, device = x_batch.device)

    x_batch_one = torch.zeros(sizes, device = x_batch.device)
    x_batch_one_pos = 0
    x_batch_two = torch.zeros(sizes, device = x_batch.device)

    for index, flag in enumerate(y_batch):
        x_item = x_batch[index]
        i_flag = items_pos[flag]
        if i_flag:
            x_batch_two[i_flag-1] = x_item
            items_pos[flag] = 0
        else:
            x_batch_one[x_batch_one_pos] = x_item
            x_batch_one_pos+=1
            items_pos[flag] = x_batch_one_pos

    return x_batch_one, x_batch_two

Here is a simple example with single digits:

from torch_helper.myt import thelp
import torch

arr = torch.tensor([2,7,6,2,7,3,2,8,8,6,2,3])

arr1, arr2 =   thelp.pairs_by_flags(arr, arr, 9)

print(arr1)

print(arr2)

Output:

tensor([2., 7., 6., 3., 2., 8.])
tensor([2., 7., 6., 3., 2., 8.])

But after making this naive solution I wonder if it could be improved, perhaps eliminating the loop using some tensor [:,,,:,,,:] magic.


texts: Script which migrates files to secondary storage and symlinks them

texts:
I wrote this code to clean up some of the space on our file server. We've got 15 years of legacy data that nobody accesses or changes or cares about that we have to keep regardless. I'd rather have it not sitting on our main file server so that I don't have to add an additional TB to it annually. This script goes through the file structure, finds files that haven't been touched in 4 years and copies them to slower storage, then replaces the source file with a symlink.

I'm new to PowerShell, so any pointers regarding style or a better way to do things would be nice. I know that my way of bracing things is wrong and that closing curly braces should be indented one less level, but I don't care and find this easier to deal with.

param(
    [string]$Dir = "",
    [string]$ArchiveDrive = ""
    )

if ($ArchiveDrive -eq ""){
    $hostname = hostname
    $ArchiveDrive = "\\Archives\"+$hostname+"\"+$Dir[0]+"\"
    }

import-module PSCX
import-module new-symlink

$FileList = @()

$SourceDrive = $dir[0] + ":\"

$date = Get-Date -Format yyyy-MM-dd
$ErrLog = "C:\ErrorLog $date.txt"
$DelLog = "C:\DelLog $date.txt"
$PathWarning = "C:\_PROBLEMS DETECTED.txt"

function BuildLists($dir){
    $FileList = @()
    $DirList = (dir $dir -recurse)
    foreach ($item in $DirList){
        if ( ((get-date).Subtract($item.LastWriteTime).Days-gt 1460) -eq $True) {

            $FileList += $item
            }
        #else {write-host "$item is modified recently"}
        }
    return $FileList
    }

function CheckPathLength($file){
    if ($File.FullName.Length -ge 220){
        copy $PathWarning $File.DirectoryName}
    }

function ArchiveFile($SourceFile){
    $DestFile = ($SourceFile.fullname.replace($SourceDrive, $ArchiveDrive))
    $DestDir = ($SourceFile.DirectoryName.replace($SourceDrive, $ArchiveDrive))
    mkdir -Path $DestDir 2>$ErrLog
    copy $SourceFile.FullName $DestFile
    }

function HashCheckFile($SourceFile){
    $DestFile = $SourceFile.FullName.replace($SourceDrive, $ArchiveDrive)
    $SourceHash = get-hash($SourceFile.fullname)
    $DestHash = get-hash("$DestFile")
    return $SourceHash.HashString -eq $DestHash.HashString
    }

function DeleteFIle($File){
    del $file.fullname
    }

function LinkFile($Sourcefile){
    $SourceFilePath = $Sourcefile.fullname
    $DestFile = ($sourcefilepath.replace($SourceDrive, $ArchiveDrive))
    New-Symlink -path $DestFile $SourceFile.fullname -file 1>$errlog
    }

function CheckPathLength($file){
    if ($File.FullName.Length -ge 220){
        copy $PathWarning $File.DirectoryName}
    }

function ReplicateFile($file){
    if ($file.Attributes -eq "Directory"){continue}
    ArchiveFile($File)
    if (HashCheckFile($File)){
        DeleteFile($File)
        LinkFile($File)
        }
    }

function Archive($FileList){
    foreach ($File in $FileList){
        CheckPathLength($file)
        ReplicateFile($File)
        }
    }

function RunArchiving($dir){
    $FileList = BuildLists($dir)
    Archive($FileList)
    }

function UnArchive(){}

RunArchiving($dir)


texts: Modified Fibonacci method implementation - dynamic programming

texts:
I found this question on Hackerrank in dynamic programming:

  Define a modified Fibonacci sequence as:
  $$t_{n+2} = t_n  + t_{n+1}^2$$

  Given three integers, \$t_1\$, \$t_2\$, and \$n\$, compute and print
  term \$t_n\$of a modified Fibonacci sequence.

Could this efficiency be improved?

t1,t2,n = map(int, raw_input().split(" "))
array =[]
array = array+[t1, t2]
for i in range(2,n):
   ele = array[i-2] + array[i-1]*array[i-1]
   array.append(ele)
print array[n-1]


texts:
An array is bitonic if it is composed of an increasing sequence of integers followed immediately by a decreasing sequence of integers. Write a program that, given a bitonic array of N distinct integer values, determines whether a given integer is in the array.

I have divided the problem in two sub-problems:

Find the maximum.
Do the binary search on left and right half.

Here is the complete solution:

def bin_search(ary, elem, low, high):
    """ Search element in array of ascending order."""
    # Gaurd clause, if element is not in array,
    if low > high:
        return None
    mid = low + (high - low) / 2
    if (ary[mid] < elem):
        return bin_search(ary, elem, mid + 1, high)
    elif (ary[mid] > elem):
        return bin_search(ary, elem, low, mid - 1)
    else:
        return mid

def bin_search_reverse(ary, elem, low, high):
    """ Search element in array of descending order."""
    # Gaurd clause, if element is not in array,
    if low > high:
        return None
    mid = low + (high - low) / 2
    if (ary[mid] > elem):
        return bin_search_reverse(ary, elem, mid + 1, high)
    elif (ary[mid] < elem):
        return bin_search_reverse(ary, elem, low, mid - 1)
    else:
        return mid

def find_max_bitonic(ary):
    def recurse(low, high):
        mid = low + (high - low) / 2
        # Handle base cases first.
        if (high - low == 1):
            return high

        if (ary[mid] < ary[mid+1]):
            return recurse(mid, high) # Go right.
        else:
            return recurse(low, mid)
    return recurse(0, len(ary) - 1)

def search(ary, elem):
    maximum = find_max_bitonic(ary)
    if (ary[maximum] == elem):
        return maximum
    left = bin_search(ary, elem, 0, maximum - 1)
    right = bin_search_reverse(ary, elem, maximum + 1, len(ary) - 1)
    return left or right

ary = (5, 15, 25, 35, 40, 45, 20, 10, 2)
print search(ary, 20)

I think there is a scope of lot of improvements. I personally think writing two separate methods for binary search can be avoided but don't know if there is any elegant alternative.

Running time

\$log_{2}O(N)\$(Finding maximum) + 2\$log_{2}O(N)\$(Binary search) = \$3log_{2}O(N)\$


texts: Bookmarklet for selecting code snippets on Code Review

texts:
The following code will add to each code block a 'Select Code' button that will select the code belonging to that block. Please review for maintainability.

In order to use this, visit http://codereviewcommunity.github.io/CodeReviewBookmarklet/

javascript: if ($('button').length === 0) {
  /* Stack Exchange does not do buttons, this does */
  $(".prettyprint").each( function()
  {
    /* Thank you http://stackoverflow.com/a/2838358/7602 */
    function selectCode(el, win)
    {
      win = win || window;
      var doc = win.document, sel, range;
      if (win.getSelection && doc.createRange)
      {
        sel = win.getSelection();
        range = doc.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
      }
      else if (doc.body.createTextRange)
      {
        range = doc.body.createTextRange();
        range.moveToElementText(el);
        range.select();
      }
    }

    var buttonText  = 'Select Code',
        length      = buttonText.length,
        codeBlock   = this,
        $link       = $('<button type="button">' + buttonText + '</button><br>').click(function()
        {
          console.log( $(codeBlock).text().substring( length ) );
          selectCode(codeBlock);
        });
    $(codeBlock).prepend( $link );
  });
}

I have tested this on FF and Chrome and it works for me.


texts: Print all permutations from a given list of strings such that each set of strings is completely unique

texts:
Problem : Given a list of strings, some of which may be anagrams amongst themselves, print the permutations which can be so constructed so that each permutation has set of strings which is completely unique.

input :  “asda”, “daas”, “dand”, “nadd”

output :  {“asda”, “dand”}, {“daas”, “dand”}, {“asda”, “nadd”}, {“daas”, “nadd”}

input  :  “laptop”, “toplap”, “loptap”, “mouse”

output :  {“laptop”, “mouse”}, {“toplap”, “mouse”}, {“loptap”, “mouse”}

Code :

def is_anagram(value_1, value_2):
    """checks whether the two given strings are anagrams """
    if sorted(value_1) == sorted(value_2):
        return True

def random_set(input_value):
    """returns the set of strings which are completely unique"""
    if len(input_value) <= 2:
        output = input_value
    else:
        output = []
        for i in range(len(input_value)):
            for j in range(len(input_value)):
                if not is_anagram(input_value[i], input_value[j]):
                    output.append( {input_value[i], input_value[j]})

    return output

print random_set(["asda", "daas" , "dand" , "nadd"])
print random_set(["laptop", "toplap", "loptap", "mouse"])

Though the code gives the correct output but it makes duplicate copy of the sets. How can i remove this flaw?


texts: Google People PHP best practise to get OOP

texts:
I need to log in users to web app in Javascript and PHP. So I have Javascript interface which send me accessToken to PHP which stores users data to DB and log user in. But the result code does not look like OOP but like a peace of garbage. May be I dont know how to write that code, so the question is if this peace of PHP code is ok or if it is possible to rewrite it to real OOP. Cause OOP exists because of people who use the code. It should make sense for humans. It seems this make sense only for authors of the code.
$code = $_POST['code'];

try
{
    $client = new Google_Client();
    $client->setAuthConfig(__DIR__ . '/../model/JsonData/GoogleCredentials.json');
    $client->setRedirectUri( self::REDIRECT_URI );

    $accessToken = $client->fetchAccessTokenWithAuthCode( $code );

    $client->setAccessToken( $accessToken );

    $peopleService = new \Google_Service_PeopleService( $client );
    $me = $peopleService->people->get('people/me', ['personFields' => 'emailAddresses,names,metadata,coverPhotos']);  // This is extra feature which does not accept spaces....

}
catch ( \Exception $e )
{
    Debugger::log( $e );
    $this->sendJson( array( 'errCode' => 1, 'error' => 'Log in fails.' ) );
}

/** @var \Google_Service_PeopleService_EmailAddress $email */
foreach ( $me->getEmailAddresses() as $email )
{
    if ( $email->getMetadata()->getPrimary() ) $user_email = $email->value;  // Oh really? I want to log in user....
}
/** @var \Google_Service_PeopleService_Name $name */
foreach ( $me->getNames() as $name )
{
    if ( $email->getMetadata()->getPrimary() ) $user_name = $name->displayName;
}

if ( ! isset( $user_email ) ) $this->sendJson( array( 'errCode' => 0, 'error' => 'Email is required.' ) );
if ( ! isset( $user_name ) ) $this->sendJson( array( 'errCode' => 0, 'error' => 'Name is required' ) );

// Hello ID is missing. How to uniquely identify user?

May be I am wrong but is it possible to write it better way to get relevant data for log in? Where is ID which can uniquely identify user?
Look at this JS interface. This looks like OOP https://developers.google.com/identity/sign-in/web/people


texts:
I am practicing the SOLID principles and my first step was taking a dive into dependency injection(DI), so I created a class, a container for all DIs. It works, but I'm just not entirely sure if this is how I should go about doing it, although to me it seems fine.

interface ContainerInterface
{
    public function set($name, callable $value);
    public function get($name);
}

class DI implements ContainerInterface
{

    protected $services;

    public function set($name, callable $value)
    {
        $this->services[$name] = $value();
    }

    public function get($name)
    {
        return $this->services[$name];
    }

}

That covers the DI class, now I'll set an example of how I could use it:

$di = new DI();

$di->set('database', function() {
    return new Database();
});

$di->set('pagination', function() use ($di) {
    return new Pagination(DatabaseInterface $di->get('database'));
});

$application = new Application(ContainerInterface $di);

In the last line, I just injected the container and now I can access all the DIs.


texts: Optimizing PHP script fetching entire HTML pages

texts:
The following script should get links which are stored in a text file (line by line), then put them into an array and finally scan each links' source code for a certain line. If this line is found, it will be pasted into a CSV file.

It works fine so far, but it takes ages to finish, since each link is 'opened' and the complete source code for that link is scanned for this specific line.

I'm looking for ideas on how to optimize the code to run faster.

Here is my code:

$filename = "products.txt";
$writecsv = "notavailable.csv";
global $products;

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/abCk.txt");
curl_setopt($ch, CURLOPT_URL,"https://www.websitegoeshere.com");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Login=USERNAME&Password=PASSWORD");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/abCk.txt");

// Open the file
$fp = @fopen($filename, 'r') or die("products.txt not found");

// Add each line to an array
if ($fp) {
   $products = explode("\n", fread($fp, filesize($filename)));
}

fclose($fp);

$fpcsv = fopen($writecsv, 'w') or die("notavailable.csv not found");

foreach($products as $key => $val) {
    curl_setopt($ch, CURLOPT_URL,$val);
    $buf2 = curl_exec ($ch);
    $html = htmlentities($buf2);
    if (strpos($html, "/extension/silver.project/design/sc_base/images/available_yes.gif") !== false) {
        fputcsv($fpcsv, "available");
    } else {
        fputcsv($fpcsv, "not available");
    }
}

fclose($fpcsv);

curl_close ($ch);
echo "csv written successfully."

Any help is really welcomed. Thanks in advance!