texts: Find how many inequalities can be simultaneously satisfied

texts:
Inequality
Given n inequalities about X, how many of them can hold at the same time at most?
The inequalities are in the following forms:

X < C

X <= C

X = C

X > C

X >= C

input

First line with an integer n.

Following n lines, each line with an inequality.

Data Limit:
1 ≤ N ≤ 50, 0 ≤ C ≤ 1000

output

One line with an integer, denoting the answer.

Sample Input
4
X = 1
X = 2
X = 3
X > 0

Sample Output
2

Here is my code:
#include <iostream>
#include <string>

#include <vector>

#include <map>
#include <set>

using namespace std;

int main() {
    //cout<<"请输入:"<<endl;
    int T;
    cin >> T;
    int count = T;

    vector<float> arrayOne(T, 0);
    vector<int> arrayTwo(T, 0);
    map<string, int> symbols = {
        pair<string, int>(">", 1),
        pair<string, int>(">=", 2),
        pair<string, int>("=", 3),
        pair<string, int>("<=", 4),
        pair<string, int>("<", 5)
    };

    while(T--)
    {
        string sOne;
        cin >> sOne;
        string sThree;
        cin >> sThree;
        arrayTwo[count-T-1] = symbols.find(sThree)->second;
        std::string sTwo;
        std::cin >> sTwo;
        float num = stof(sTwo);
        arrayOne[count-T-1] = num;
    }
    set<float> answerSet;
    for (float numPiece: arrayOne){
        answerSet.insert(numPiece-0.5);
        answerSet.insert(numPiece);
        answerSet.insert(numPiece+0.5);
    }
    int answer = 0;
    for (set<float>::iterator testNum=answerSet.begin(); testNum != answerSet.end(); ++testNum){
        //   cout<<*testNum;
        int passNum = 0;
        int i = 0;
        for (int numTwo: arrayTwo){
            switch (numTwo) {
                case 1:
                {
                    if (*testNum > arrayOne[i]) {
                        passNum += 1;
                    }
                }
                    break;
                case 2:
                {
                    if (*testNum >= arrayOne[i]) {
                        passNum += 1;
                    }
                }
                    break;
                case 3:
                {
                    if (*testNum == arrayOne[i]) {
                        passNum += 1;
                    }
                }
                    break;
                case 4:
                {
                    if (*testNum <= arrayOne[i]) {
                        passNum += 1;
                    }
                }
                    break;
                case 5:
                {
                    if (*testNum < arrayOne[i]) {
                        passNum += 1;
                    }
                }
                    break;
                default:
                    break;
            }
            i++;
        }
        answer = max(answer, passNum);
    }
    cout<<answer<<endl;
    return 0;
}

Very intuitive , just get all the boundary numbers, then find the max passes.
How to make it more efficient?


texts: Checking for one- or two-dimensional palindrome strings

texts:
I am new to Python and I would like some comments to the following code. It is for checking if a string is a palindrome (in one or two dimensions).

string_to_check = str(input("Please enter a phrase to check if it is palindrome: "))
string_to_check = string_to_check.upper() #transform the string to uppercase
list_to_check = string_to_check.split()
print ('The string to check is: \"{}" and has {} words'.format(string_to_check , number_of_words))

#two-dimension palindrome check - with two full lists

reversed_list_to_check = list(map(lambda x:x[::-1], list_to_check[::-1]))

if list_to_check == reversed_list_to_check :
    two_dimension_palindrome = True
    print ("The string %s is a two-dimension palindrome" %string_to_check)
else :
        #one-dimension palindrome check
    string_to_check = "".join(list_to_check) #string without spaces

    if string_to_check == string_to_check[::-1]:
        one_dimension_palindrome = True
        print ('%s is a one-dimension palindrome' % string_to_check)
    else:
        print ("Your string is not a palindrome")

Is this the Pythonic way?


texts:
I'm working through problems on this site.

The problem I'm currently doing is:

  Given an array having both positive and negative integers, your task
  is to complete the function maxLen which returns the length of maximum
  subarray with 0 sum. The function takes two arguments an array A and n
  where n is the size of the array A.

However the code is too slow to pass so I can't check if the solution is working correctly or not - (it works fine for the single test case that's provided)

Can anyone suggest how to improve the performance of this code?

from itertools import combinations

def maxLen(n, arr):
    for i in range(n, 0, -1):
        for combo in combinations(arr, i):
            if sum(combo) == 0:
                return len(combo)
    else:
        return 0


texts: Structuring code to do URL routing for Node.js

texts:
What would be the best (performance, memory wise) to achieve a clean way to create a class or some way to properly structure the code, that shares 2 variables (req, res) which have a decent object size.

And yes, for those who use Node.js it are the req and res variables, but it is irrelevant.

This is what I tried so far:

function Client(req, res){
  var self = this;

  self.req = req;
  self.res = res;

  route.call(self);
  handleRoute.call(self);
  handleRequestData.call(self);
}

function route(){
  var self = this;

  self.req.route = // ...
}

function handleAuth(){
  var self = this;

  self.req.auth = // ...
}

function handleRequestData(){
  var self = this;

  self.req.data = // ...
}

I am wondering if it could be improved, since I mentioned req and res are pretty decent objects with methods, properties. Since .call(self) you pass through the instance, would it be most effective way?

Also I don't like using "var self = this;" all the time, it is useless.

And btw, I don't want to use Coffeescript.

Solution 1. (fails because of the massive passing through req and res)

Lets assume we got to files 1. client.js

var Client = {
  route: function(req, res){},
  auth: function(req, res, callback){ callback(req, res); },
  getData: function(req, res, callback){ callback(req, res); } // async
}

file 2. main.js

var client = require('./client.js');

client.route(req, res); // fine because this is syncronous.

// This is where the problem is, massive passing through req and res parameters.
client.auth(req, res, function(req, res){
  client.getData(req, res, function(req, res){
    // Do something...
  });
});


texts:
Given a dot separated domain name, reverse the domain elements.

Example:

codereview.stackexchange.com -> com.stackexchange.codereview
google.com -> com.google

I just wanted some suggestions to improve my code. Or if you can suggest a better way, please do so.

package practice;

import java.util.Scanner;
import java.util.StringTokenizer;

public class ReverseDomainName
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the domain name to be reversed");
        String domain = sc.nextLine();
        sc.close();
        ReverseDomainName obj = new ReverseDomainName();
        String reversedDomainName = obj.reverseDomainNameString(domain);
        System.out.println("The reversed Domain Name = "+reversedDomainName);
    }

    public String reverseDomainNameString(String s)
    {
        String reverse1 = "",word ="" ;
        int i;

        StringTokenizer st = new StringTokenizer(s,".");
        int len = st.countTokens();

        /*
         * The check is performed so that instead of com.stackexchange.codereview.
         * we can get the proper com.stackexhange.codereview  so no
         * extra dot
         */

        word  = st.nextToken();
        reverse1 = word+reverse1;

        for(i=1;i<len;i++)
        {
            word = st.nextToken();
            reverse1 = word +"."+reverse1;

        }

        return reverse1;
    }

}


texts:
I wrote a simplified pig latin translator in APL and I would like some feedback on it, as I am not sure my implementation is neat enough.

The simplified pig latin translation follows the following rules, where only 'aeiouAEIOU' are considered vowels:

one-letter words have 'way' appended to them; e.g. 'I' becomes 'Iway'
2 or more letter words starting with a vowel have 'ay' appended to them; e.g. 'awesome' becomes 'awesomeay'
2 or more letter words starting with a consonant have the consonants in front of the first vowel moved to the back, and then 'ay' is appended; e.g. 'cool' becomes 'oolcay'

The problem statement (problem 3 of the second easy problem set) specified that input might be a scalar (i.e. a single character) or a (possibly empty) character vector.

This is the code I wrote:

PigLatin ← {
  ⍝ Monadic function expecting character scalar or character vector and returning character vector.
  ⍝ Translates an English sentence into Pig lating.
  ⍝ e.g. 'I always run fast' becomes 'Iway alwaysay unray astfay'.

  vowels ← 'aeiouAEIOU'
  words ← ' ' (≠⊆⊢) ,⍵
  ⍝ Rotate all words until a vowel is at the front.
  rotated ← {⍵ ⌽⍨ ¯1+⊃⍸ ⍵∊vowels}¨ words
  ⍝ Append a 'w' to words of length 1.
  suffixed ← (,∘'w')¨@(1∘=≢¨) rotated
  ⍝ Append 'ay ' to all words, join and drop last ' '.
  ¯1↓∊ (,∘'ay ')¨ suffixed
}

Questions

The basic idea is that I split the input sentence into words, apply the rules to each word and then join them together; this seems sensible, right? This feels like a very standard algorithm but I don't know if APL is suitable for another type of approach.
Following the idea outlined above, my first version had this final line ∊ {⍺' '⍵}/ (,∘'ay')¨ suffixed instead of the current ¯1↓ ∊(,∘'ay ')¨ suffixed; but this meant my code didn't work for empty inputs '' because it tried running {⍺' '⍵}/ on an empty vector and raised a DOMAIN ERROR. My workaround for this was appending 'ay ' to every word, instead of just 'ay' and then dropping the final extra ' ' with ¯1↓;

Is this a good way of handling the edge case ''?
Would it be better if I had a dfn guard for the '' case?
Would you handle it in a different way?

Is ≠⊆⊢ an idiom in APL to split the right vector on the left arguments? It even shows in the tooltip for the Partition ⊆ glyph.
Any further comments, suggestions, etc that don't necessarily address my questions are also welcome.


texts: SQLite search disregarding spaces and Pinyin tones

texts:
I have a column where, pretty much, each entry has numbers (specifically #1-4) and spaces (' '). I wanted to make a query that could avoid having to know these numbers and spaces.

$results = $db->query( "SELECT CHS, PIN, DEF FROM MAIN WHERE CHS LIKE '%".$q."%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(PIN, '1',''),'2',''),'3',''), '4',''),' ','') LIKE '%".$q."%' OR PIN LIKE '%".$q."%'");

The part that I'm worried (read:ashamed) about is:

REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(PIN, '1',''),'2',''),'3',''), '4',''),' ','')

Is this a super bad way to code?


texts:
I'm trying to port some MonteCarlo code to CUDA (this is my first CUDA experience).

The CPU code often calls a function which generates a random number:

float generate_random_number() {...}

Since all the existing code base runs fine on the GPU, that is basically the only thing to adjust.

My strategy is to put a curandState for each thread in global memory. Is this reasonable? Why/why not? Is the following code ok? Can I make it faster using shared memory or so?

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "curand_kernel.h"

__device__ curandState* random_generator_states;
__global__ void set_pointer(curandState* pointer) {
    random_generator_states = pointer;
}
__global__ void initialize_device(const unsigned int seed) {
    int idx = blockDim.x*blockIdx.x + threadIdx.x;
    curand_init(seed, idx, 0, &random_generator_states[idx]);
}
__device__ float generate_random_number() {
    int idx = blockDim.x*blockIdx.x + threadIdx.x;
    curandState localState = random_generator_states[idx];
    float RANDOM = curand_uniform(&localState);
    random_generator_states[idx] = localState;
    return RANDOM;
}

int main() {
    cudaError_t cudaStatus;
    size_t number_of_threads = 128;
    size_t number_of_blocks = 128;
    size_t blocks_times_threads = number_of_blocks * number_of_threads;
    size_t size = blocks_times_threads * sizeof(float);

    unsigned int seed = 0;

    // initialize memory for random generator states
    curandState* random_generator_states_pointer;
    cudaStatus = cudaMalloc(&random_generator_states_pointer, blocks_times_threads * sizeof(curandState));
    // initialize values for random generator states
    set_pointer<<< 1, 1>>>(random_generator_states_pointer);
    initialize_device<<< number_of_blocks, number_of_threads >>>(seed);

    // free GPU
    cudaFree(random_generator_states_pointer);
}


texts:
I'm looking for a way to shrink this down. It'not anything special or unique but I feel the repetitive nature of the code could lend itself to a sleeker and more functional refactoring.

$.e = {
    doc: { ready:[], custom:[] },
    win: { scroll:[], scrollstart:[], scrollstop:[], load:[], resize:[], resizestart:[], resizestop:[], orientationchange:[] }
};

$(window).on({
    load:function(){for(var i = 0; i < $.e.win.load.length; i++){ $.e.win.load[i](); }},
    scroll:function(){for(var i = 0; i < $.e.win.scroll.length; i++){ $.e.win.scroll[i](); }},
    scrollstart:function(){for(var i = 0; i < $.e.win.scrollstart.length; i++){ $.e.win.scrollstart[i](); }},
    scrollstop:function(){for(var i = 0; i < $.e.win.scrollstop.length; i++){ $.e.win.scrollstop[i](); }},
    resize:function(){for(var i = 0; i < $.e.win.resize.length; i++){ $.e.win.resize[i](); }},
    resizestart:function(){for(var i = 0; i < $.e.win.resizestart.length; i++){ $.e.win.resizestart[i](); }},
    resizestop:function(){for(var i = 0; i < $.e.win.resizestop.length; i++){ $.e.win.resizestop[i](); }},
    orientationchange:function(){for(var i = 0; i < $.e.win.orientationchange.length; i++){ $.e.win.orientationchange[i](); }}
});


texts:
Series post - I am reading through Introduction to Algorithms, 3rd Edition implementing each algorithm as I read them.

Pretty basic insertion sort. Only considering numbers initially - how could I make this better and/or have better tests?

def insertion_sort(numbs):
    for cur_index in range(1, len(numbs)):
        cur_val = numbs[cur_index]

        lookup_index = cur_index - 1

        while lookup_index >= 0 and numbs[lookup_index] >= cur_val:
            numbs[lookup_index + 1] = numbs[lookup_index]
            lookup_index -= 1
        numbs[lookup_index + 1] = cur_val

    return numbs

def check_insertion_sort(input, expected):
    result = insertion_sort(input)
    if result != expected:
        print "Result={} does not equal expected={} for input={}".format(result, expected, input)
    else:
        print "Success for input={}".format(input)

check_insertion_sort([5, 2, 4, 6, 1, 3], [1, 2, 3, 4, 5, 6])
check_insertion_sort([190, 2, 4, 6, 1, 3], [1, 2, 3, 4, 6, 190])
check_insertion_sort([-190, 2, 4, 6, 1, 3], [-190, 1, 2, 3, 4, 6])
check_insertion_sort([0, 0, 4, 6, 1, 3], [0, 0, 1, 3, 4, 6])
check_insertion_sort([0, 0], [0, 0])
check_insertion_sort([1, 0], [0, 1])


texts: Printing facility for std::chrono::time_point

texts:
Motivation:

It is known that std::time_point<...> cannot be streamed directly using operator<<(), which is pretty disappointing. Although Howard Hinnant created a good library, I'd like to have sole ownership of all of the code in my library, so I could do some benchmarks without including extra license and setup repositories faster.

Description:

Mainly it is only a streaming operator, which actually uses some C date-time library under the hood. The approach creates a huge chance for data race if std::chrono::time_point<...>s are streamed from multiple threads, even into multiple streams, because std::localtime() can return a static variable.

The formatting string is shared as well, which increases burden on users.

The streaming operator is templated only on the duration type, since casting between clocks which produced time point is not possible via std::chrono::time_point_cast<>().

Code:

#include <iosfwd>
#include <chrono>
#include <iomanip>
#include <ctime>
#include <string>

namespace shino
{
    namespace detail
    {
        std::string time_format{"%Y %b %d %H:%M:%S"};
    }

    std::string time_format()
    {
        return detail::time_format;
    }

    void set_time_format(const std::string& format)
    {
        detail::time_format = format;
    }
}

template <typename Duration>
std::ostream& operator<<(std::ostream& os,
                         const std::chrono::time_point<std::chrono::system_clock, Duration>& timep)
{
    using system_clock_duration = std::chrono::system_clock::duration;
    auto converted_timep = std::chrono::time_point_cast<system_clock_duration>(timep);
    auto seconds_since_epoch = std::chrono::system_clock::to_time_t(timep);
    os << std::put_time(std::localtime(&seconds_since_epoch), shino::time_format().c_str());
    return os;
}

Small demonstration:

#include <iostream>

int main()
{
    std::cout << "current date and time: "
              << std::chrono::system_clock::now() << '\n';

    shino::set_time_format(shino::time_format() + " %a"); //add day of the week
    std::cout << "current date and time with day of the week: "
              << std::chrono::system_clock::now() << '\n';

    return 0;
}

Result:

current date and time: 2017 Jun 17 16:01:27
current date and time with day of the week: 2017 Jun 17 16:01:27 Sat


texts: Fibonacci generator python implementation

texts:
I wrote this code for a fibonacci sequence generator. Can anyone tell me whether my code is designed well? if not, why?
import logging

def fibonacci_calc(current_val, current_pos=0, max_seq_length=5, sequence_list=[]):
    try:
        if(current_pos != 0 and len(sequence_list) == 0):
            raise Exception("Please initalize {} argument: {} with 0".format(fibonacci_calc.__name__, fibonacci_calc.__code__.co_varnames[1]))
        else:
            if(len(sequence_list) == 0):
                print("Initialization, added 0 and starting number {} to sequence list".format(current_val))
                sequence_list.append(0)
                sequence_list.append(current_val)
                current_pos = 1
                print(sequence_list)
                fibonacci_calc(current_val, current_pos, max_seq_length, sequence_list)
            elif(len(sequence_list) == max_seq_length):
                print('{} values in the sequence'.format(max_seq_length))
                return
            else:
                print("Current position: {}, Total values: {}  calculating next value".format(current_pos, current_pos+1))
                next_val = sequence_list[current_pos] + sequence_list[current_pos-1]
                sequence_list.append(next_val)
                print("Current sequence list {}".format(sequence_list))
                fibonacci_calc(next_val, current_pos+1, max_seq_length, sequence_list)
    except Exception:
        logging.exception('ERROR')

fibonacci_calc(19,0, 7)


texts:
I'm new with Kotlin, and this is my first attempt of a two dimensional array.

 // private var roomGrid = arrayOfNulls<arrayOfNulls<Room>>(4)
private var roomGrid = Array(roomCountX) {arrayOfNulls<Room>(roomCountY)}

 init {
    for (gridY in 0 until roomCountY) {
        for (gridX in 0 until roomCountX) {
            val pixelX = gridX * roomWidth
            val pixelY = gridY * roomHeight
            val room = Room(pixelX.toFloat(), pixelY.toFloat(), s)
            roomGrid[gridX][gridY] = room
        }
    }

     // neighbor relations
    for (gridY in 0 until roomCountY) {
        for (gridX in 0 until roomCountX) {
            val room = roomGrid[gridX][gridY]
            if (gridY > 0)
                roomGrid[gridX][gridY - 1]?.let { room?.setNeighbor(Room.SOUTH, it) }
            if (gridY < roomCountY - 1)
                roomGrid[gridX][gridY + 1]?.let { room?.setNeighbor(Room.NORTH, it) }
            if (gridX > 0)
                roomGrid[gridX - 1][gridY]?.let { room?.setNeighbor(Room.WEST, it) }
            if (gridX < roomCountX - 1)
                roomGrid[gridX + 1][gridY]?.let { room?.setNeighbor(Room.EAST, it) }
        }
    }
}

Even though it works I don't like the look of these:

roomGrid[gridX][gridY + 1]?.let { room?.setNeighbor(Room.NORTH, it) }

They are harder to read, and I'm not really sure what .let and it are.
I would like some simpler syntax/solution to a two dimensional array.

How might I improve this?


texts: Simple input and output in assembly x86_64

texts:
I am new assembly programming in Linux (x86_64) and I want to make sure that I am programing in a correct way. I wrote a program that just takes an input from the user and then writes his input to stdout
SYS_WRITE   equ 1 ; write text to stdout
SYS_READ    equ 0 ; read text from stdin
SYS_EXIT    equ 60 ; terminate the program
STDOUT      equ 1 ; stdout

section .bss
    uinput resb 24 ; 24 bytes for user string
    uinput_len equ $ - uinput ; get length of user input

section .data
    text db "You wroted: "
    text_len equ $ - text

section .text
    global _start

_start:
    mov rax, SYS_READ
    mov rdi, STDOUT
    mov rsi, uinput
    mov rdx, uinput_len
    syscall

    mov rax, SYS_WRITE
    mov rdi, STDOUT
    mov rsi, text
    mov rdx, text_len
    syscall

    mov rax, SYS_WRITE
    mov rdi, STDOUT
    mov rsi, uinput
    mov rdx, uinput_len
    syscall

    mov rax, SYS_EXIT
    mov rsi, 0 ; successful exit
    syscall

Am I doing this experiment correctly?
Which suggestions do you find to improve this code?
Could you please provide some resources to deepen in good practices (and if posible more features or effective techniques)?
Thank you.


texts:
I wrote this working code to create a linked list of a given length and print each node's values.

#include <stdlib.h> //NULL
#include <stdio.h>  //printf

typedef struct Node {
    int val;
    struct Node* next;
} node;

node* make_ll(int len){
    node* head = malloc(sizeof(node));
    node* cur = head;
    for (int i = 0; i < len; i++) {
        cur->val = i;
        cur->next = (i < (len - 1)) ? malloc(sizeof(node)) : NULL;
        cur = cur->next;
    }
    return head;
}

void print_ll(node* head){
    node* cur = head;
    while (cur != NULL) {
        printf("Node: %d @ %p\n", cur->val, cur);
        cur = cur->next;
    }
}

int main(){
    node* ll = make_ll(4);
    print_ll(ll);
    free(ll);
}

Output:

Node: 0 @ 0x81b010
Node: 1 @ 0x81b030
Node: 2 @ 0x81b050
Node: 3 @ 0x81b070

I'm wondering if there's a practical way to write make_ll() so that, rather than checking if we've reached the last desired node on every pass of the for loop and setting cur->next accordingly, as done here with line 14:

cur->next = (i < (len - 1)) ? malloc(sizeof(node)) : NULL;

we can simply malloc() for each "next" node until the last, setting it equal to NULL.

I'm new to C, mostly influenced by Python, and the things I tried to no avail were the result of my ignorance of the languages' difference in scope rules. It would probably be noisy to try to reproduce them here.

Any pointers in the right direction?


texts:
Here is my code for this problem. Any bugs, performance in terms of algorithm time complexity, code style advice are appreciated.

The areas which I want to improve, but do not know how to improve are:

I sort the strings by length and I'm not sure if it's a smarter idea not using sorting at all.
I used a few set operations, which looks a bit ugly. I want to learn smarter ideas.

Problem:

  Given a set of strings, return the smallest subset that contains the longest possible
  prefixes for every string.

  If the list is ['foo', 'foog', 'food', 'asdf'] return ['foo', 'asdf']

The return is foo since foo is prefix for foo (itself), prefix for foog and prefix for food (in other words, foo could "represent" longer string like foog and food). Output also contains asdf because it is not prefix for any other words in the input list, so output itself.

The empty set is not a correct answer because it does not contain the longest possible prefixes.

Source code:

from collections import defaultdict
class TrieTreeNode:
    def __init__(self):
        self.children = defaultdict(TrieTreeNode)
        self.isEnd = False
        self.count = 0
    def insert(self, word, result_set):
        node = self
        for i,w in enumerate(word):
            node = node.children[w]
            if node.isEnd:
                result_set[word[:i+1]].add(word)
        node.isEnd = True

if __name__ == "__main__":
    words = ['foo', 'foog', 'food', 'asdf']
    words_length = []
    sorted_words = []
    for w in words:
        words_length.append(len(w))
    for t in sorted(zip(words_length, words)):
        sorted_words.append(t[1])
    result_set = defaultdict(set)
    root = TrieTreeNode()
    for w in sorted_words:
        root.insert(w, result_set)
    match_set = set()
    for k,v in result_set.items():
        for i in v:
            match_set.add(i)
    unmatch_set = set(words) - match_set
    print unmatch_set | set(result_set.keys())


texts: A small extension to the reCaptcha library

texts:
I have been writing a small extension to the reCaptcha library.

class Captcha
{
    private $config;

    public $error;

    public function __construct(array $config)
    {
        include './library/recaptchalib.php';
        $this->config = $config;
    }

    public function render($error = null, $use_ssl = false)
    {
        return recaptcha_get_html($this->config['recaptcha']['public_key'],
            $error, $use_ssl);
    }

    public function check()
    {
        $resp = recaptcha_check_answer ($this->config['recaptcha']['private_key'],
                                    $_SERVER["REMOTE_ADDR"],
                                    $_POST["recaptcha_challenge_field"],
                                    $_POST["recaptcha_response_field"]);
        if (!$resp->is_valid) {
            $this->error = $resp->error;
            return false;
        }
    }
}

What do you think? Is it anything to have? Anything I can improve/change?


texts:
I have the following function, intended to take standard dice notation (XdY+Z) and return a (sort of) random number based on the input. Are there any bugs/bad ideas/optimizable sections I am missing?

function dieRoll(dice) {
    if (/^[\d+]?d\d+[\+|\-]?\d*$/.test(dice) == false) { //Regex validate
        return "Invalid dice notation"; //Return if input invalid
    }

    if(dice[0]=="d") { //If the first character is a d (dY)
        dice = "1"+dice; //Add a 1
    }
    var minus = dice.search(/\-/); //Search for minus sign

    if (minus == -1 && dice.search(/\+/) == -1) { //If no minus sign and no plus sign (XdY)
        dice += '+0'; //Add a +0
    }
    if (minus == -1) { //If no minus sign (XdY+Z)
        var dicesplit = dice.split('+'); //Split for plus sign
        var modifier = dicesplit[1] * 1; //Number to add to total
    } else { //If there is a minus sign (XdY-Z)
        var dicesplit = dice.split('-'); //Split for minus sign
        var modifier = ("-" + dicesplit[1]) * 1; //Number to add to total
    }

    var diesplit = dicesplit[0].split('d'); //Take the first section (XdY) and split for d
    var howmany = diesplit[0] * 1; //Number of dice to roll
    var diesize = diesplit[1] * 1; //How many sides per die
    var total = 0; //Total starts as 0

    for (var i = 0; i < howmany; i++) { //Loop a number of times equal to the number of dice
        total += Math.floor(Math.random() * diesize) + 1; //Random number between 1 and diesize
    }
    total += modifier; //Add the modifier

    return total; //Return the final total
}


texts: Python's str.isAlpha(), reimplemented without Unicode support

texts:
I've created an alphabet checker that is similar to str.isAlpha().
I know that python has its built-in function.

  str.isalpha()
  Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

I put my implementation code here:
https://gist.github.com/anonymous/7833d25fc450e69ee323bfc39bdd0da5

I included my code snippet below:

import string
    # Hint: Use these string constants to ignore capitalization and/or punctuation
string.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_letters = string.ascii_lowercase + string.ascii_uppercase

def ascii_letters(text):
    #This m ethod will return True if the string
    # is an uppercase or lowercase letter from A to Z.
    # If the string contains any non-letter characters, then it will return False.
    for index in text:
        if index in string.ascii_letters:
            return True
        else:
            return False
    return None


texts:
I just wrote my first Java class, and I wanted to share it with you and maybe get some quick check from more experiences coders than I am.

I want to learn OOP, and Java is just the tool I thought was the best to start with (it's very similar to C in syntax, which I'm used to, and it's spreading more and more, day by day).

You can obviously comment on Java bad habits and ways to improve the class, but consider the class structure and the abstraction of the problem I wanted to solve, the separation between in data methods, etc.. as my main point of concern.

Here's the class. The aim is to create a random password generator.

import java.util.Random;

public final class PasswordGenerator {

  // DATAS
    // characters with which the password will be composed
    private static final int charactersSize = 100;
    private static char [] characters = new char [charactersSize];

    // keep the counts of used characters
    private static int charactersCount = 0;

    // size of the password to generate
    private int passwordSize;

  // CONSTRUCTOR
    public PasswordGenerator( int passwordSize ) {

      // set the password size
      this.passwordSize = passwordSize;

      // set the characters that will be used to generate the password
      initCharacters();
    }

  // METHODS
    // fill the array of characters that will be used to generate the password
    private static char [] initCharacters() {
      int i = 0;

      // add 0-9
      for ( int j = 48; j < 58; ++i, ++j, ++charactersCount ) {
        characters[i] = (char) j;
      }

      // add @ + a-z
      for ( int j = 64; j < 91; ++i, ++j, ++charactersCount ) {
        characters[i] = (char) j;
      }

      // add A-Z
      for ( int j = 97; j < 123; ++i, ++j, ++charactersCount ) {
        characters[i] = (char) j;
      }

      return characters;
    }

    // generate a random password
    public char [] get() {

      // initialize the random number generator
      Random rnd = new Random();

      char [] password = new char [passwordSize];

      // choose a random character from the array
      for ( int i = 0; i < passwordSize; ++i ) {
        password[i] = characters[ rnd.nextInt(charactersCount) ];
      }

      return password;
    }

  // DEBUG METHODS
    // show the characters the will be used to compose the pass
    public void showCharacters() {
      for ( int i = 0; i < charactersCount && characters[i] != 0; ++i ) {
        System.out.println(characters[i]);
      }
    }

  // MAIN - testing code
    public static void main(String[] args) {
      int passwordSize = 10;
      PasswordGenerator password = new PasswordGenerator( passwordSize );
      System.out.println( password.get() );
    }

}


texts: Crawl and gather all the urls recursively in a domain

texts:
This is the script :

#!/bin/bash

set -euo pipefail

SOFT="$(basename $0)"
random=$(( ( RANDOM % 100000 ) ))
tempfolder="/tmp/$SOFT/$random"

mkdir -p "$tempfolder"
pushd "$tempfolder" > /dev/null
cleanup (){
    cat wget.txt | sed 's/:$//'  | url_matcher
    popd > /dev/null
    rm -rf -- ${tempfolder}
}

trap cleanup EXIT
site="$1"

wget -nd --spider --recursive --no-verbose --output-file=wget.txt "$site"

the script essentially creates a subfolder in /tmp/crawl and puts into it the result of wget, then feeds it to sed and url_matcher.

Initially I though of putting the cat instruction just after the wget one, but for long wget it didn't work.

The sed instruction removes colons at the end of lines, which is added by wget when said url isn't valid.
(something along the lines of "http://...: Nothing there")

url_matcher is a c++ scanner made with flex, which recognises urls in a text fed with standard input and prints them to standard output, separated with new lines characters.

the scripts allows me to fetch all urls in a website and use that as a stream directly.

Example :

$ crawl www.example.com | sed 's/some_treatments//' > super_file


texts:
S is a given character string, then I have to find all the digits characters of S. Did I make it unnecessarily complicated?
bits 32

global start

extern exit
import exit msvcrt.dll

segment data use32 class=data
    s db '+', 'r', '0', '8', '8', '1', 'i', '5'
    len equ $ - s
    digits db '012345789'
    d times len db 0
segment code use32 class=code
    start:
        mov ecx, len

        mov esi,0
        mov ebx,0

        jecxz end_prog

        repeat_this:
            push ecx
            mov al, [s + esi]
            mov ecx, 10
            mov edi, digits
            find:
                scasb
                jz found
            loop find

            jmp next

            found:
                mov edi, ebx
                inc ebx
                mov [d + edi], al

            next:
                inc esi
                pop ecx
        loop repeat_this

        end_prog:

        push    dword 0
        call    [exit]


texts: Filtering an array according to 7 checkboxes in a form

texts:
I am filtering an array whenever checkboxes are checked.

if (this.deliveryConcession[0].checked) {
            this.allItems = this.allItems.filter(fil => fil.deliveryconcession.readytoship === this.deliveryConcession[0].checked);
        }
        if (this.deliveryConcession[1].checked) {
            this.allItems = this.allItems.filter(fil => fil.deliveryconcession.instantdownload === this.deliveryConcession[1].checked);
        }
        if (this.deliveryConcession[2].checked) {
            this.allItems = this.allItems.filter(fil => fil.deliveryconcession.unespecifiedshipment === this.deliveryConcession[2].checked);
        }
        if (this.seatConcession[0].checked) {
            this.allItems = this.allItems.filter(fil => fil.seatingConcession.parking === this.seatConcession[0].checked);
        }
        if (this.seatConcession[1].checked) {
            this.allItems = this.allItems.filter(fil => fil.seatingConcession.restrictedview === this.seatConcession[1].checked);
        }
        if (this.seatConcession[2].checked) {
            this.allItems = this.allItems.filter(fil => fil.seatingConcession.wheelchair === this.seatConcession[2].checked);
        }
        if (this.seatConcession[3].checked) {
            this.allItems = this.allItems.filter(fil => fil.seatingConcession.alcoholFree === this.seatConcession[3].checked);
        }

There are 7 checkboxes, each associated with an object.

  seatConcession = [
        { id: 1, name: 'Parking pass included', checked: false },
        { id: 2, name: 'Unrestricted view', checked: false },
        { id: 3, name: 'Wheel chair accessible', checked: false },
        { id: 4, name: 'Without age restrictions', checked: false }
    ];
    deliveryConcession = [
        { id: 1, name: 'Ready to ship(paper)', checked: false },
        { id: 2, name: 'Instant download(e-ticket)', checked: false },
        { id: 3, name: 'Unspecified shipment(paper)', checked: false }
    ];

How can i improve the above with simple loadash filter or another way?


texts:
I perform a mean blur on a number[][]-array (called grid in the code). I iterate the array, and calculate average values from adjacent "cells".
The kernel size defines how many adjacent values are used for average calculation.

/**
 * Performs a mean blur with a given kernel size.
 * @param {number[][]} grid - Data grid holding values to blur.
 * @param {number} kernelSize - Describes the size of the "blur"-cut for each cell.
 */
static MeanBlur(grid, kernelSize) {
    // Result
    let newGrid = [];

    // Iterate original grid
    for (let row = 0; row < grid.length; row++) {
        let newRow = [];
        for (let col = 0; col < grid[row].length; col++) {

            let adjacentValues = [];

            // Get all adjacent values
            for (let i = 1; i <= kernelSize; i++) {
                adjacentValues = adjacentValues.concat(this._getAdjacentValues(row, col, i, grid));
            }

            // Calculate average value
            const average = adjacentValues.reduce((a, b) => a + b, 0) / adjacentValues.length;

            // add average value to the current row
            newRow.push(average);
        }
        newGrid.push(newRow);
    }
    return newGrid;
}

/**
 * Return all adjacent values of a cell in a `number[][]`-array.
 * The amount of adjacent value depends on the kernel size.
 * @param {number} row - Describes the cell's row position.
 * @param {number} col - Describes the cell's column position.
 * @param {number} kernelSize - The kernel size.
 * @param {number[][]} grid - Original data grid.
 */
static _getAdjacentValues(row, col, kernelSize, grid) {

    if (kernelSize < 1) {
        throw "Kernel size value should be at least 1.";
    }

    let adjacentValues = [];

    // north
    if (row - kernelSize >= 0) {
        adjacentValues.push(grid[row - kernelSize][col]);
    }
    // north-east
    if (row - kernelSize >= 0 && col + kernelSize < grid[row].length) {
        adjacentValues.push(grid[row - kernelSize][col + kernelSize]);
    }
    // east
    if (col + kernelSize < grid[row].length) {
        adjacentValues.push(grid[row][col + kernelSize]);
    }

    // south-east
    if (row + kernelSize < grid.length && col + kernelSize < grid[row].length) {
        adjacentValues.push(grid[row + kernelSize][col + kernelSize]);
    }

    // south
    if (row + kernelSize < grid.length) {
        adjacentValues.push(grid[row + kernelSize][col]);
    }

    // south-west
    if (row + kernelSize < grid.length && col - kernelSize >= 0) {
        adjacentValues.push(grid[row + kernelSize][col - kernelSize]);
    }

    // west
    if (col - kernelSize >= 0) {
        adjacentValues.push(grid[row][col - kernelSize]);
    }

    // north-west
    if (row - kernelSize >= 0 && col - kernelSize >= 0) {
        adjacentValues.push(grid[row - kernelSize][col - kernelSize]);
    }

    return adjacentValues;
}

What I am most concerned with is _getAdjacentValues. I think there has to be a more convenient way to get adjacent values without including values at implausible indices.

What I mean is that i.e. at the grid position (0, 0) even with a kernel size of 1, values like (-1, -1) will be checked automatically by a loop.

Edit:
I was asked for clarification on how the kernel size actually is supposed to work.
Assuming that I want to calculate the value for the current position (black cell). With a kernel size of 1 I would include all green cells for average value calculation. With a kernel size of 2 I would include all green and blue cell values. And with a kernel size of 3 all orange, blue and green cell values will be used for average calculation.


texts:
Below is an algorithm to generate all pairwise combinations for a set of random variables. See here for an explanation of what constitutes a minimal all-pairs set. The algorithm below works but I feel that it is inefficient. Any suggestions would be welcome.

from operator import itemgetter
from itertools import combinations, product, zip_longest, chain, permutations

def pairwise(*variables, **kwargs):
    num_vars = len(variables)

    #Organize the variable states into pairs for comparisons
    indexed_vars = sorted(
        ([(index, v) for v in vals] for index, vals in enumerate(variables)),
        key=len,
        reverse=True)

    var_combos = combinations(range(num_vars), 2)
    var_products = (product(indexed_vars[i], indexed_vars[j]) for i, j in var_combos)
    vars = chain.from_iterable(zip_longest(*var_products))

    #Initialize the builder list
    builders = []
    seen_pairs = set()

    #Main algorithm loop
    for pair in vars:
        if not pair or pair in seen_pairs:
            continue

        d_pair = dict(pair)

        #Linear search through builders to find an empty slot
        #First pass: look for sets that have intersections
        for builder in builders:
            intersection = builder.keys() & d_pair.keys()
            if len(intersection) == 1:
                v = intersection.pop()
                if builder[v] == d_pair[v]:
                    builder.update(d_pair)
                    #Update seen pairs
                    seen_pairs.update(combinations(builder.items(), 2))
                    break
        else:
            #Second Pass
            for builder in builders:
                intersection = builder.keys() & d_pair.keys()
                if not len(intersection):
                    builder.update(d_pair)
                    #Update seen pairs
                    seen_pairs.update(combinations(builder.items(), 2))
                    break
            else:
                #No empty slots/pairs identified. Make a new builder
                builders.append(d_pair)
                seen_pairs.add(pair)

    #Fill in remaining values
    complete_set = set(range(num_vars))
    defaults = {var[0][0]: var[0][1] for var in indexed_vars}

    for builder in builders:
        if len(builder) == num_vars:
            yield tuple(val for index, val in sorted(builder.items()))
        else:
            for key in complete_set - builder.keys():
                builder[key] = defaults[key]
            yield tuple(val for index, val in sorted(builder.items()))

Usage Example:

u_vars = [
    [1, 2, 3, 4],
    ["A", "B", "C"],
    ["a", "b"],
    ]

result = list(pairwise(*u_vars))
print(result) #prints list of length 12


texts:
I did Advent of Code recently and enjoyed Day 15, which involves exploring a maze (my attempt in Kotlin). I've tried to recreate it partially in Python, minus the emulator:

https://repl.it/@MalcolmCrum/ReflectingFarNaturaldocs

It works but my code is largely 1:1 from Kotlin, and I'm not certain if I'm doing things in a Pythonic way. For example, I use this pattern regularly in Kotlin:

val direction = when (path.first()) {
            position + NORTH -> NORTH
            position + SOUTH -> SOUTH
            position + EAST -> EAST
            position + WEST -> WEST
            else -> error("Can't find first step from $position towards $destination in $path")
        }

The Python equivalent I found is this, which while nice and concise is maybe a little too "clever"? (ignore the 1 offset, I changed path logic slightly)

direction: Direction = {self.position + d: d for d in Direction}[path_to_destination[1]]


texts: Find area of intersection between 2 squares rotated 45 degrees

texts:
Ok so I am trying this task on a Code Challenge website, but I can't figure this out to do this fast enough. Because my current solutions has Time Limit Exceded Errors

This is the stated problem see images:

This is my current code:

def areaOfIntersection(shape1, shape2):
    def calc_points(shape):
        # shape = ["order(range)" , "x_center", "y_center"]
        points = []
        k = -1

        # k = Number of points in row-i in shape
        for i in range(shape[0]*2-1):
            if(i<=shape[0]-1):
                k += 2
            else:
                k -= 2

            # Add point to collection of points (x, y)
            for x in range(k):
                current_X = shape[1] + x - (k-1)/2
                current_Y = shape[2] + abs(shape[0] - i - 1) if i>shape[0]-1 else shape[2] - abs(shape[0] - i - 1)
                points.append( ( current_X , current_Y ) )
        return points

    p1 = calc_points(shape1)
    p2 = calc_points(shape2)

    # Return the length of the lists intersection
    return len(list(set(p1) & set(p2)))

Thus my Question is: How can above program complete faster?

I tried to add some logic to lessen the points to calculate but I am stuck...

My guess is I'm missing some simple math...


texts: Optimizing run time of Python solution to Project Euler Problem 34

texts:
This is a brute force solution to Project Euler Problem 34 with only 1 optimization (i.e.: caching factorials):

import time, math
start = time.time()

total = 0

# Cache factorials
factorials = [math.factorial(x) for x in xrange(0,10)]
range_end = 7 * factorials[9]

for i in range(3,range_end+1):
    number = i
    factorials_sum = 0

    while(number > 0):
        digit = number % 10
        number /= 10
        factorials_sum += factorials[digit]

    if(factorials_sum == i):
        total += factorials_sum

print "Time elapsed: %5.2f" % (time.time() - start)
print total

I know it could be further optimized (f.e. by choosing numbers that the for loop could pass on. However, I would like to ask why is this algorithm running 10.3 s on my computer (2.66 GHz Intel Core 2 Duo)? Similar solutions I have found run in ~2 seconds or less. Is there any general optimization I could make?


texts: An elegant way to find diff of two list of objects in Java

texts:
This is the simplest possible implementation.

The two lists will contain at max, 3-5 elements, so the size of lists is not a matter of concern.

Any recommendation on how can I make this pretty?

private ListsHolder findDiffOfLists(List<MyObject> objsFromDB, List<MyObjRequest> objsFromRequest) {
    ListsHolder holder = this.new ListsHolder(); //An object holding two lists

    for(MyObjRequest req_obj : objsFromRequest){
        boolean isAdded = false;
        for(MyObject db_obj : objsFromDB){
            if(isSameObj(db_obj, req_obj)){
                db_obj.setVal(req_obj.getVal()); //Set new value
                holder.matchingObjList.add(db_obj);
                isAdded = true;
                break;
            }
        }

        if(!isAdded){
            holder.newObjList.add(req_obj); //If element does not exist
        }
    }

    return holder;
}

private boolean isSameObj(MyObject db_obj, MyObjRequest req_obj) {
       return req_obj.getMatch().equals(db_obj.getMatch());
}


texts:
I'm currently facing a problem where I have to shift data in a multidimensional JS array in different directions, but I think the first solution I whipped up is not as efficient as it could be (some fancy math I don't know of maybe?).

Let me explain the problem a bit better with some examples of my data.

This is the array in question:

[1][0][1][0][1][0]
[0][1][1][0][0][0]
[0][0][1][0][1][1]
[0][0][0][0][1][1]
[0][0][1][1][0][0]
[1][0][0][1][1][1]

If I shifted it to the left, it should look like this:

[1][1][1][0][0][0]
[1][1][0][0][0][0]
[1][1][1][0][0][0]
[1][1][0][0][0][0]
[1][1][0][0][0][0]
[1][1][1][1][0][0]

Or down

[0][0][0][0][0][0]
[0][0][0][0][0][0]
[0][0][1][0][1][0]
[0][0][1][0][1][1]
[1][0][1][1][1][1]
[1][1][1][1][1][1]

To put it simple - shift 1's as far as possible.

The code I wrote is fairly simple

for (w = 0; w < arraySize; w++) {
    for (h = 0; h < arraySize; h++) {
        tiles = $('.arrayContainer .row').eq(w).children();
        if (tiles.eq(h).html() != "" && tiles.eq(h - 1).html() == "" && (h-1) >= 0) {
            tiles.eq(h - 1).html(tiles.eq(h).html());
            tiles.eq(h).html("");
        }
    }
}

This will shift values left-to-right by one step. arraySize is the variable that determines the size of the array, tiles gets each row of the array output.

If I wasn't here, posting and wouldn't think this could be done better I'd create four of these structures and just live with it, but I'm pretty sure this can be done better.


texts: Aggregating search results from multiple databases, in smaller work units

texts:
I have a large function that performs a search over a data set given a set of parameters. This function goes through multiple databases which all hold data that would comprise one final entry from the search.

def perform(self):
    #Go through each year and each DB in that year
    for year, yearInfo in data["preprocessDBInfo"].items():
        termsToCases = {}
        for dbName, dbInfo in yearInfo["dbs"].items():
            #Relevant to search?
            relevantTerms = self.search.ofDB(dbName)
            if len(relevantTerms) == 0:
                continue #Not a relevant database

            #Open the database and get cases
            fp = os.path.join(prefs["rootPath"], dbInfo["filePath"])
            caseDB = caseDB(fp)

            cases = caseDB.getCases(stubs=True,search=relevantTerms)
            termsToCases.update(cases)

        self.foundCases = self.foundCases.union(self.resolve(termsToCases))

Anyone who wants to call this function would have to wait for the entire search to complete which can take a couple of minutes depending on the search complexity.

Now I need to move this task to a separate thread of execution and be able to periodically check it and more drastically pause or kill it. In order to do this I need to break it up so that perform only does small work units so the caller of it has much more control over execution. I have come up with the following to solve this

def performGenerator(self):
    #Go through each year and each DB in that year
    for year, yearInfo in data["preprocessDBInfo"].items():
        for dbName, dbInfo in yearInfo["dbs"].items():
            #Relevant to search?
            relevantTerms = self.search.ofDB(dbName)
            if len(relevantTerms) == 0:
                continue #Not a relevant database

            #Open the database and get cases
            fp = os.path.join(prefs["rootPath"], dbInfo["filePath"])
            caseDB = caseDB(fp)
            cases = caseDB.getCases(stubs=True,search=relevantTerms)
            yield cases

Is there any sort of name for a function like this, a function that originally was large and autonomous but now only does tiny work units? (disregarding the fact that it's a generator in Python)
Is there any sort of pattern or methodology for breaking up a large subtask list this? Python's generator interface seems like it would be the best fit for my needs but I don't know what I would do if I didn't have such a high level interface (such as if I were programming in C)


texts: Selecting attributes corresponding to the most frequent entries in a junction table

texts:
I currently am writing a query which retrieves the max amount of rows for a junction table.  I'll use the following example in SQL Fiddle:

  MyTable

┌─────────┬─────────┐
│ a_field │ b_field │
├─────────┼─────────┤
│ a       │ 1       │
│ b       │ 2       │
│ c       │ 3       │
└─────────┴─────────┘

  JunctionTable

┌─────────┬──────────────────┐
│ a_field │ irrelevant_field │
├─────────┼──────────────────┤
│ a       │ z                │
│ a       │ y                │
│ a       │ x                │
│ b       │ z                │
│ b       │ y                │
│ b       │ x                │
│ c       │ z                │
└─────────┴──────────────────┘

Note that in the JunctionTable, 'a' and 'b' are both the most frequent.  I want my query to retrieve '1' and '2', which are the corresponding values to 'a' and 'b' in MyTable.

A naïve version of the query would rely on the fact that the ordering is done on the amount and then limits it on 1 to get the max value:

SELECT b_field
FROM MyTable
WHERE a_field IN (
    SELECT a_field
    FROM JunctionTable
    GROUP BY a_field
    ORDER BY COUNT(a_field) DESC
    LIMIT 1
);

What I want to do, though, is retrieve both 'a' and 'b' without increasing the LIMIT keyword. To achieve this, I can do the following:

SELECT b_field
FROM MyTable
INNER JOIN (
    SELECT a_field, COUNT(a_field) AS amount
    FROM JunctionTable
    GROUP BY a_field
) JC ON JC.a_field = MyTable.a_field
WHERE amount = (
    SELECT MAX(amount)
    FROM (
        SELECT COUNT(a_field) AS amount
        FROM JunctionTable
        GROUP BY a_field
    ) JC2
);

However this screams bad practice to me. Are there any better solutions to this problem?


texts: Sum of Subset of an Array equals a given number

texts:
The exact question that I am solving is given here:  Codechef - MARCHA1

Problem Statement

Basically, we have an array of n integers, say {1, 5, 6, 3, 12} where n = 5.

Then we have a given number m = 10, and we have to check if the sum of any subset of the array is equal to m or not.

In this case, we have 1+6+3 = 10, so we print Yes.

Proposed Solution

I proposed the following solution:

We create another array of n integers which only hold either 0 or 1. For example, in the case with n = 5, we can have this new array as {0, 0, 0, 0, 1}, {0, 0, 0, 1, 0} .. etc

In this manner, each time we check for the sum of numbers of original array which are at position 1. So there are 2^n such cases.

After checking, if none of them match, we print No, else we print Yes.

Here's the code in C:

#include <stdio.h>

int main()
{
    unsigned int n, m;
    scanf("%u%u", &n, &m);

    unsigned int note[n];
    unsigned long j;

    for (j = 0; j < n; ++j) {
        scanf("%u", note+j);
    }

    char teller[n], flag = 0;

    for (j = 0; j < n; ++j) {
        teller[j] = 0;
    }

    unsigned long two_pow_n = 1 << n;

    for (j = 0; j < two_pow_n; ++j)
    {
        unsigned int sum0 = 0, sum1 = 0, k;

        for (k = 0; k < n; ++k)
        {
            if (teller[k] == 0) {
                sum0 += note[k];
            }
            else {
                sum1 += note[k];
            }
            if (j % (1 << k) == 0) {
                teller[k] = teller[k] == 0 ? 1 : 0;// swap 0 and 1
            }
        }

        if (sum0 == m || sum1 == m)
        {
            flag = 1;
            break;
        }
    }

    flag ? printf("Yes\n") : printf("No\n");
    return 0;
}

The problem with this approach is that it took too much time and too many comparisons. On the codechef website, I found my solution was among the slowest.

Please help me by suggesting a better algorithm, I couldn't think of any optimisation either. Thank you!


texts: Update HTML4 to new HTML5 Semantic/Structural Elements

texts:
I'm trying to update my website's code to HTML5's semantic and structural elements, but I'm not very sure with the sections and article element.

Here's the structure of my page:

                    <form action="user_login.php" method="post"></form>

                    <form action="user_register.php" method="post"></form>

Should I turn the main div and/or the content div into a section, and should the
 be the article, or should I put each of the <form> in an article?

Any other hints about the structure are also welcome.

You can take a look at the whole page here.


texts:
I created a Kik messenger bot using Flask microframework and python that accepts POST requests on the provided webhook and then responds appropriately. I have excluded custom module imports because they are not relevant in my problem.

import os
from flask import Flask, request, Response
from flask import Flask, request, Response, url_for
from kik import KikApi, Configuration
from kik.messages import LinkMessage, PictureMessage, VideoMessage
from kik.messages import StartChattingMessage, ScanDataMessage, StickerMessage
from kik.messages import SuggestedResponseKeyboard, TextResponse
from kik.messages import messages_from_json

app = Flask(__name__)
BOT_USERNAME = os.environ['BOT_USERNAME']
BOT_API_KEY = os.environ['BOT_API_KEY']
WEBHOOK = os.environ['WEBHOOK']

features = {'manuallySendReadReceipts': False,
            'receiveReadReceipts': True,
            'receiveDeliveryReceipts': False,
            'receiveIsTyping': False}

static_keyboard = SuggestedResponseKeyboard(
    responses=[TextResponse('PLACEHOLDER1'),
               TextResponse('PLACEHOLDER2')
               ])

kik = KikApi(BOT_USERNAME, BOT_API_KEY)
kik.set_configuration(Configuration(
    webhook=WEBHOOK, static_keyboard=static_keyboard, features=features))

@app.route('/incoming', methods=['POST'])
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        user = message.from_user
        chat_id = message.chat_id

        if isinstance(message, LinkMessage):
            # do something

        elif isinstance(message, PictureMessage):
            # do something

        elif isinstance(message, VideoMessage):
            # do something

        elif isinstance(message, StartChattingMessage):
            # do something

        elif isinstance(message, ScanDataMessage):
            # do something

        elif isinstance(message, StickerMessage):
            # do something

        elif isinstance(message, TextMessage):
            query = message.body
            query_words = query.split()
            chat_type = message.chat_type
            participants = message.participants

            if query.lower() in ['placeholder1', 'placeholder2']:
                # do something

            elif query_words[0] in ['placeholder3', 'placeholder4']:
                # do something

            elif query_words[0] in ['placeholder5'] and user in ['mamun']:
                # do something

            # a large number of more elif statements present in actual app
            else:
                # do something

    return Response(status=200)

if __name__ == '__main__':
    app.run(port=8000, debug=True)

What I have done so far is create separate modules for custom functionality that I created, but in the end they are consumed by the large number of elif statements which I don't like. Is there any way I can avoid the elif statement hell?

My actual bot is 100% complete, production ready and approved by kik, but the way I had to program it still bothers me when I look at it.


texts: Rosalind problem "Consensus and Profile"

texts:
Source: Rosalind("Consensus and Profile")

  Brief summary

                A T C C A G C T
                G G G C A A C T
                A T G G A T C T
DNA Strings     A A G C A A C C
                T T G G A A C T
                A T G C C A T T
                A T G G C A C T

            A   5 1 0 0 5 5 0 0
Profile     C   0 0 1 4 2 0 6 1
            G   1 1 6 3 0 1 0 0
            T   1 5 0 0 0 1 1 6

Consensus       A T G C A A C T

  Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format.

  Return: A consensus string and profile matrix for the collection. (If several possible consensus strings exist, then you may return any one of them.)

Model (cons.rb):

#!/usr/bin/env ruby
require_relative '../ie_module'

class DnaConsensus
  include ImportExport
  DNA_BASES = %w(A C G T)

  attr_reader :dna_strings, :consensus, :profile

  def initialize(source = "rosalind_#{current_dir_name}.txt")
    @dna_strings = (source =~ /txt$/ ? import_lines(source) : source).values
    @profile = build_profile
    @consensus = build_consensus
  end

  def to_s
    "#{consensus.join}\n#{stringify(profile)}"
  end

private

  def build_profile
    prof = DNA_BASES.map{|b| [b, []]}.to_h
    dna_strings.map(&:chars).transpose.each.with_object(prof) do |arr, hsh|
      hsh.merge!(hashed(arr)){ |_, oldval, newval| oldval << newval }
    end
  end

  def hashed(arr)
    hsh = arr.group_by(&:chr).map{ |k,v| [k, v.size] }.to_h
    (DNA_BASES - hsh.keys).each { |b| hsh[b] = 0 }
    hsh
  end

  def build_consensus
    dna_strings.first.length.times.with_object([]) do |index, arr|
      arr << profile.max_by{|_, list| list[index]}.first
    end
  end

end

a = DnaConsensus.new
a.export_to_file([a.to_s])

File read/write logic (ie_module.rb):

module ImportExport

  def export_to_file(result, file = "result_#{current_dir_name}.txt")
    File.open(file, 'w') do |f|
      result.each{ |val| f << "%s" % val }
    end
  end

private

  def current_dir_name
    File.basename(Dir.getwd)
  end

  def stringify(obj)
    if obj.is_a?(Hash)
    then obj.map{|k,v| "#{k}: #{v.join(' ')}"}
    else obj.map{|e| e.join(' ')}
    end.join("\n")
  end

  def import_lines(file)
    File.foreach(file).with_object({}) do |line, hsh|
      line = line.strip.sub(/^>/, '')
      $' ? hsh[line] = '' : hsh[hsh.keys.last] << line
    end
  end

end

Here is a lot of code, but #build_profile is the most "complicated" part. I know, that "alternate way" exists.
All suggestions are welcome.


texts: Calculating the total daily amount of confirmed cases of Coronavirus

texts:
I'm writing a small program to plot new COVID-19 infections. As of right now, I have it so the program reads the given data file, pulls out the daily cases and dates for each country, and adds together all the cases for a given date. However, because both of the lists generated have lengths of over 2000, it currently runs extremely slowly. Is there any change I can make to improve the speed of my program?
import pylab as pl

cases = pd.read_csv("daily-cases-covid-19.csv")
dc = cases.loc[:,'Daily confirmed cases (cases)']
dd = cases.loc[:,'Date']

worldCases = []

for i in range(0,len(dd)):
    count = 0
    for j in range(0,len(dd)):
        if dd[j]==dd[i]:
            count+=dc[i]
    worldCases.append(count)

Here is an example of the CSV I am reading through. The purpose of the nested loops is to add together all of the confirmed cases in each country on a given date.
Afghanistan,AFG,"Jan 1, 2020",0
Afghanistan,AFG,"Jan 2, 2020",0
Afghanistan,AFG,"Jan 3, 2020",0
Afghanistan,AFG,"Jan 4, 2020",0
Afghanistan,AFG,"Jan 5, 2020",0
Afghanistan,AFG,"Jan 6, 2020",0
Afghanistan,AFG,"Jan 7, 2020",0
Afghanistan,AFG,"Jan 8, 2020",0
Afghanistan,AFG,"Jan 9, 2020",0
Afghanistan,AFG,"Jan 10, 2020",0
Afghanistan,AFG,"Jan 11, 2020",0
Afghanistan,AFG,"Jan 12, 2020",0
Afghanistan,AFG,"Jan 13, 2020",0
Afghanistan,AFG,"Jan 14, 2020",0
Afghanistan,AFG,"Jan 15, 2020",0
Afghanistan,AFG,"Jan 16, 2020",0
Afghanistan,AFG,"Jan 17, 2020",0
Afghanistan,AFG,"Jan 18, 2020",0
Afghanistan,AFG,"Jan 19, 2020",0


texts:
I built a simple Rock Paper Scissors game in Python as my first "project", and I want a feedback from you. I want your opinion on how I write my code, is it okay and readable enough? PEP8 laws, things to improve or preserve?

Computer Choice - Generating a random choice with the random module and the random.randomchoice() method from a list.

User Choice - Taking an Input from the user as a character (R, P and S) and uppercasing the character.

Finally, I'm checking who is the winner with if conditions.

import random

choices = ['Rock', 'Paper', 'Scissors']
bot_choices = random.SystemRandom().choice(choices)

def result(user, bot):
    return f'\nComputer Choice: {bot}\nYour Choice: {user}'

class RPS:
    def __init__(self):
        self.user_choice = str(input('(R)ock, (P)aper, (S)cissors: ')).upper()
        if not self.user_choice or self.user_choice not in ['R', 'P', 'S']:
            print('Invalid Input!')
        else:
            self.get_winner()
            print(result(self.user_choice, bot_choices))

    def get_winner(self):
        if self.user_choice == 'R' and bot_choices == 'Paper' or self.user_choice == 'P' and bot_choices == 'Scissors' or self.user_choice == 'S' and bot_choices == 'Rock':
            print('Result: Computer Won!')
        elif self.user_choice == 'R' and bot_choices == 'Rock' or self.user_choice == 'P' and bot_choices == 'Paper' or self.user_choice == 'S' and bot_choices == 'Scissors':
            print('Result: Tie!')
        else:
            print('Result: You Won!')

if __name__ == '__main__':
    game = RPS()


texts:
Ok, So first I must say that everything I know about coding I have learned on my own in my spare time so bear with me if my code is primitive, but please, I am open to any comments to make me better...

Anyway, as for my question. I have an application I am building in C# for .NET Compact Framework (for an HP iPaq) the program's purpose is to act similarly to a Restaurant POS terminal to "ring up" food orders.  it has gotten to the point where some of my code is the same line copied god even knows how many times with only a numerical difference between them. here is an example:

    private void button9_Click(object sender, EventArgs e)
    {
        AddItem(buttonNames[0], prices[0]);
    }

    private void button14_Click(object sender, EventArgs e)
    {
        AddItem(buttonNames[1], prices[1]);
    }

    private void button5_Click(object sender, EventArgs e)
    {
        AddItem(buttonNames[2], prices[2]);
    }

    private void button10_Click(object sender, EventArgs e)
    {
        AddItem(buttonNames[3], prices[3]);
    }

    private void button13_Click(object sender, EventArgs e)
    {
        AddItem(buttonNames[4], prices[4]);
    }

    private void button4_Click(object sender, EventArgs e)
    {
        AddItem(buttonNames[5], prices[5]);
    }

or

                button9.Text = buttonNames[0];
                button14.Text = buttonNames[1];
                button5.Text = buttonNames[2];
                button10.Text = buttonNames[3];
                button13.Text = buttonNames[4];
                button4.Text = buttonNames[5];
                button11.Text = buttonNames[6];
                button15.Text = buttonNames[7];
                button7.Text = buttonNames[8];
                button12.Text = buttonNames[9];
                button16.Text = buttonNames[10];
                button8.Text = buttonNames[11];

I KNOW there are easier ways to do a lot of the code I have written, I just don't know how to do it.


texts:
I have a Core Data model with two entities: Video and Playlist.

A Video can be a member of many Playlists
A Playlist can have many Videos, including the same Video multiple times
A Playlist's Videos are ordered

  Video <<----->> Playlist

That being said, I've decided that I need a third entity: Playlist Item.

A Playlist Item has an index
A Playlist Item can only have a relationship with one Video entity and one Playlist entity

And so, this causes the original specification to be revised...

A Video can have many Playlist Items
A Playlist can have many Playlist Items, but each Playlist Item has a unique index
A Playlist's Playlist Items are ordered using the index attribute

Video <---->> Playlist Item <<----> Playlist

So, the addition of the Playlist Item entity allows me to have many-to-many relationships between Video and Playlist and still maintain ordered lists. Adding this third entity however adds complexity to the overall design.

I am wondering if it is wise to hide that complexity managing the Playlist Item objects in the Video and Playlist implementations.

Video

@interface Video : NSManagedObject

@property (strong, nonatomic) NSSet *playlists; // Custom accessor; Transient attribute; data persisted in Playlist Item
// No declared NSSet for playlistItems

@end

Playlist

@interface Playlist: NSManagedObject

@property (nonatomic, strong) NSArray *videos; // Custom accessor...
// No declared playlistItems here either!

@end

It seems by doing this I will gain code that is better at revealing intentions.

The code smell I'm getting is that NSManagedObjects subclasses are model classes and should therefore not have any controller type glue. Furthermore it makes my Video and Playlist classes completely dependent upon the Playlist Items class. But, all of that said writing the accessor is trivial, which is why I'm considering this approach:

- (NSArray *)videos
{
    [self willAccessValueForKey:@"videos"];
    NSArray *v = [self primitiveVideos];
    [self didAccessValueForKey:@"videos"];

    if (v) {
        return v;
    }

    NSSet *pi = [self playlistItems];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES];
    NSArray *orderedPlaylistItems = [pi sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    NSUInteger count = [orderedPlaylistItems count];
    NSMutableArray *videos = [NSMutableArray arrayWithCapacity:count];
    for (int index = 0; index < count; index++) {
        [videos addObject:[[orderedPlaylistItems objectAtIndex:index] video]];
    }

    v = videos;
    [self setPrimitiveVideos:v];

    return v;
}

(This code is pretty rough, but you get the point, a few lines and voila! an array of video objects from the set of playlist items)

Maybe there is a design pattern or best practice that would help guide my decision?


texts: Longest collatz sequence using dynamic programming

texts:
I am trying to solve longest collatz sequence problem under 1000000 with the below code.  Can anyone suggest a faster way to approach this problem?  I was thinking of dynamic programming, but I'm having trouble in understanding it.

#include <stdio.h>

long long int col(long long int n)
{
    if(n==1)
    {
        return 1;
    }
    else
    {
        if(n%2==0)
            return (1+col(n/2));
        else
            return (1+col(3*n+1));
    }
}

int main()
{
    long long int i=0, c, max, k=1;
    max=1;
    for(i=1; i<1000000; i++)
    {
        c=col(i);
        if(c>max)
        {
            max=c;
            k=i;
        }
    }

    printf("%lld",max);
    printf("\n%lld\n",k);
    return 0;
}


texts:
I am implementing a simple recursive Depth-First Search algorithm on graphs, using StateT and ReaderT for encapsulating all the required information.

Pre-requisite definitions

type Vertex = Int
type Cost = Int
data Edge = Edge { vertex:: Vertex, cost:: Cost } deriving (Eq, Show, Ord)

newtype Graph = Graph { adjacencyList :: Map.Map Vertex [Edge] } deriving (Eq, Show)

type DFSState = ([Vertex], [Vertex])
type Env = Graph
type DFSNextState = ReaderT Env (StateT DFSState Identity) Vertex

and then the main function:

{-# LANGUAGE FlexibleContexts #-}

dfsGetNext :: DFSNextState
dfsGetNext = do
    graph <- ask
    s <- get
    let candidates = fst s
    let visited = snd s
    let ret = case candidates of
                []     -> return 0 :: DFSNextState
                (x:xs) -> if elem x visited
                            then put (xs, visited) >> (return 1 :: DFSNextState)
                          else put ((getNeighbors x graph) ++ xs, visited ++ [x]) >> (return 1 :: DFSNextState)
    ret

I can then simply run the algorithm for n steps and get the nodes visited in a depth-first fashion using

dfsStartState :: DFSState
dfsStartState = ([0], [])

dfsSteps = replicateM 13 dfsGetNext

runStateT (runReaderT dfsSteps graph) dfsStartState

Questions:
1) Is my style in the main function good? Can it be simplified?
2) Is there a way to remove the magic number (13 in this case) for replicateM? Is there a replicate until which I could use for this?

Update
I added a replicateMUntil function myself:

{-# LANGUAGE RankNTypes, KindSignatures #-}
replicateMUntil :: forall (m :: * -> *) a. Monad m => (m a -> m Bool) -> m a -> m [a]
replicateMUntil f ma = do
    res <- f ma
    if res then liftM2 (:) ma (replicateMUntil f ma) else return []

The driver now becomes:

isNextAvailable :: DFSNextState -> ReaderT Env (StateT DFSState Identity) Bool
isNextAvailable nextState = do
    s <- get
    return (fst s /= [])

dfsStartState :: DFSState
dfsStartState = ([0], [])

dfsSteps = replicateMUntil isNextAvailable dfsGetNext

runStateT (runReaderT dfsSteps graph) dfsStartState


texts: HackerEarth problem : number of occurrences of a number in the array

texts:
I have written a solution to Memorise me problem on Hacker Earth but it takes a lot of memory space and time limit exceeds in the last test case.

The first line of input will contain \$N\$, an integer, which is the total number of numbers shown to your team.

The second line of input contains \$N\$ space separated integers.

The third line of input contains an integer \$Q\$, denoting the total number of integers.

The Next \$Q\$ lines will contain an integer denoting an integer, \$Bi\$, for which you have to print the number of occurrences of that number (\$Bi\$) in those \$N\$ numbers on a new line.

If the number \$Bi\$ isn’t present then print NOT PRESENT on a new line.

Constraints

\$1 \le N \le 105,
0 \le Bi \le 1000,
1 \le Q \le 1055\$

This is my code :

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

    // BufferedReader
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String noOfElements = br.readLine();
    int n = Integer.parseInt(noOfElements);
    int i = 0;

    String[] numberArray = br.readLine().split(" ");

    String noOfQueries = br.readLine();
    int q = Integer.parseInt(noOfQueries);

    String[] queries = new String[q];

    for (i = 0; i < q; i++) {
        String query = br.readLine();
        String queryNumber = query.trim();
        queries[i] = queryNumber;
    }

    for (i = 0; i < queries.length; i++) {
        int count = 0;
        for (int j = 0; j < n; j++) {
            if (queries[i].equals(numberArray[j])) {
                count++;
            }
        }
        if (count == 0) {
            System.out.println("NOT PRESENT");
        } else {
            System.out.println(count);
        }
    }

}


texts:
I am trying to learn the absolute best way to program/design classes in PHP. I am hoping that you would be able to review and critique this simple class.

Note: I know that there aren't any comments. Please don't critique me on that.

<?php
class VisitorCounter
{
    protected $numVisits;
    protected $db;

    public function __construct($dbh)
    {
        $this->db = $dbh;
    }

    public function updateNumVisits()
    {
        if(!$this->getNumVisits() || !$this->firstTimeHere()){ return false; }

        $_SESSION['new_visitor'] = 1;

        $sql = "UPDATE stats SET visits=". ++$this->numVisits ." WHERE id=2";
        if(!$this->db->query($sql)){
            $sql = "INSERT INTO stats (visits) VALUES (". ++$this->numVisits .")";
            return $this->db->query($sql)? true : false;
        }
        return true;
    }

    protected function firstTimeHere()
    {
        if(isset($_SESSION['new_visitor'])){
            return false;
        }
        return true;
    }

    protected function getNumVisits()
    {
        $result = $this->db->query("SELECT * FROM stats");
        if($row = $this->db->fetch_array($result)){
            return $this->numVisits = $row['visits'];
        }
        return false;
    }

}

Implementation

$Counter = new VisitorCounter($db);
$Counter->updateNumVisits();

Questions

Is it ever ok to "for example", to move the $Counter->updateNumVisits() directly into the constructor? Or is that NEVER good to do, even in the simplest of scenarios? I'm reading that it is best only to do simple assignments in the constructor.
Inside the function updateNumVisits(), I have a conditional that runs a function getNumVisits(). If this is not advisable, when should I call this function so that updateNumVisits() will have access to the latest visit count?
I read many Code Review posts about not using globals, and so I got rid of my $db global out of the class, and injected it in the constructor. What about $_SESSION and $_POST values? Is it ok to have them inside your class?
How would you write this class?
I was also hoping that you might know of a very simple open source PHP project that someone built that I can study and learn from. One that follows all the best practices mentioned here on this website. For instance that uses DI, and follows all the principles of good coding practices. I downloaded the Zend framework and CodeIgnitor but they are too complex and too big for my current understanding.


texts: Writing input into separate arrays and an output file

texts:
The code inputs an int, n, which is the number of lines to follow. Then, on each line, the first number goes to array A, the second to B, and the third to C. I then pass these 4 arguments to sub which I have no control over (in an object file where I don't know the implementation). All I know is that it returns an int.
What I do then is write n, the three arrays, and the result of sub into an output file. Pretty simple code.
This code works as expected, but I just want to see if there are any conventions I should be following (especially C++11) and ideas to consider for efficiency.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include "sub.h"

int main()
{
    std::ifstream file;
    file.open(...);

    if (!file) {
        std::cerr << "Error opening file." << std::endl;
        return EXIT_FAILURE;
    }

    int n;
    std::string firstLine;
    getline(file, firstLine);
    std::stringstream(firstLine) >> n;

    int a,b,c;
    std::vector<int> A1,B1,C1;
    while (file >> a >> b >> c) {
        A1.push_back(a);
        B1.push_back(b);
        C1.push_back(c);
    }

    file.close();

    std::ofstream output;
    output.open(...);

    output << n << "\n";

    size_t size = A1.size();
    for (size_t i=0; i<size; ++i) {
        output << A1[i] << " " << B1[i] << " " << C1[i] << std::endl;
    }

    //call sub method with pointer to beginning of vectors
    //I have no control over sub method, its signature is (int, int*, int*, int*)
    int n1 = sub(n, &A1[0], &B1[0], &C1[0]);

    //output result and close file
    output << n1;
    output.close();
}

Example input:

0 1 2 <- This is A[0], B[0], C[0]
2 3 4 <- This is A[1], B[1], C[1]
4 5 6 <- This is A[2], B[2], C[2]

The range-based for-loop would not work in this case. It would, however, if I printed all of A, B, or C on one line.


texts:
I have some code which executes a simple task, counting the number of states reachable from a particular state, would just like some advice on how to improve it.

So far it stores all the states it has seen in seen_states. It's just counting them seems so clunky.

move([Head, Head1|Tail], [N|Tail]):-
    N is Head1 - Head,
    N >= 0.
move([Head|Tail], [Head|Tail1]):-
    move(Tail, Tail1).

:- dynamic counted_states/1.

count_state(S, V):-
    count_state(S,V, V).

count_state([], N,N).
count_state(S, Acc, Acc):-
    findall(X, move(S,X), Succ),
    count_sub_states(Succ, Acc, 0).

count_sub_states([],L,L).
count_sub_states([HeadList|List], Count, Acc):-
    count_node(HeadList,N),
    Acc1 is Acc+N,
    count_sub_states(List, Count, Acc1).

count_node(State, 0):-
    counted_states(State),!.

count_node(State, V):-
    not(counted_states(State)),
    assert(counted_states(State)),
    count_state(State, V1, V1),
    V is V1 +1.


texts:
I've written code that selects column D and checks it for codes 1 to 92 however I have to write out c4.Value = 1 Or c4.Value = 2 all the way up to c4.Value = 92, is there a quicker way of doing this? Please see below for my code and I appreciate all help.

Sub q2country_and_q2country_other()

   Dim i As Long, c4 As Range, c5 As Range

   For i = 2 To 456
      Set c4 = Range("D" & i)
      Set c5 = Range("E" & i)

  If c4.Value = 94 Then
      Select Case c5.Value
      Case "", " ", "0", -99, -66, -77
         c4.Interior.color = vbRed
         c5.Interior.color = vbRed
      Case Else
         c4.Interior.color = vbGreen
         c5.Interior.color = vbGreen
   End Select

  ElseIf c4.Value = 1 Or c4.Value = 92 Then
      Select Case c5.Value
      Case -99, ""
         c4.Interior.color = vbGreen
         c5.Interior.color = vbGreen
      Case Else
         c4.Interior.color = vbRed
         c5.Interior.color = vbRed
      End Select

End If
Next i

End Sub


texts: Monthly change query with SQL Server 2012

texts:
I'm new to SQL and working on a monthly change calculation.  I want to calculate the change between this months balance and the previous months balance.

This query is working for me but does not feel like the best syntax.  Do you think this is fine, or are there any suggestions?

SELECT
        ROW_NUMBER() OVER(ORDER BY (CONVERT(varchar, effectivedate, 102)) ASC) Rn,
        CONVERT(varchar, effectivedate, 102) effectivedate,
        SUM(EuroCurrentBalance/1000000) TotalArrears,
        SUM(CASE WHEN Multiplier > 2 THEN EuroCurrentBalance/1000000 ELSE 0 END) NPLs,
        CASE WHEN ROW_NUMBER() OVER(ORDER BY (CONVERT(varchar, effectivedate, 102)) ASC) = 1 THEN 0 ELSE SUM(EuroCurrentBalance/1000000) - (LAG(SUM(EuroCurrentBalance/1000000),1,0) OVER (ORDER BY (CONVERT(varchar, effectivedate, 102)))) END MonthlyChange
    FROM
        DataWarehouse.dwa.FinanceMonthEndData
    GROUP BY
        CONVERT(varchar, effectivedate, 102)
    GO


texts:
I am trying to implement substring in C. How efficient and standard is this code? I have a hard time understanding how C functions are usually meant to work, like how printf() returns an int or size_t.

size_t substring(char *destination, char const *string,  int start, int len) {
    // writes a substring to the destinaton starting at start index of string until end stepping by step
    // follows the same start at 0 off by one on the end format as Java substring method
    int substringLength = len;

    int stringLength = strlen(string);

    if (start > stringLength || len > stringLength || start < 0 || len < 0) {
        fputs("start and len must be 0 < start/len < length of string", stderr);
        return -1;
    }
    if (start >= len) {
        fputs("start must be start < len", stderr);
        return -1;
    }

    memcpy(destination, &string[start], substringLength);

    if (destination[stringLength] != '\x0') {
        destination[stringLength] = '\x0';
    }
    return substringLength;
}


texts:
I have a modelScan.php file, as you can see,

I have codes that repeated within the function/method. How can I make this code more readable?

<?php
/**
 * Class for Scanning files
 */
class modelScan
{
    /**
     * Get the total size of file in the directory
     * @param string $sPath and integer $iTotalCount
     */
    public function getBytesTotal($sPath, $iTotalCount)
    {
        $sPath = realpath($sPath);
        if($sPath!==false && $sPath!='' && file_exists($sPath)){
            foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sPath, FilesystemIterator::SKIP_DOTS)) as $oObject){
                $iTotalCount += $oObject->getSize();
            }
        }
        return $iTotalCount;
    }

    /**
     * Get the total files in the directory
     * @param string $sPath and integer $iTotalCount
     */
    public function getFilesTotal($sPath, $iTotalCount)
    {
        $ite = new RecursiveDirectoryIterator($sPath);
        foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
            if(is_file($cur)){
                $iTotalCount++;
            }
        }
        return $iTotalCount;
    }

    /**
     * Get the total Class in the directory
     * @param string $sPath and integer $iTotalCount
     */
    public function getClassTotal($sPath, $iTotalCount)
    {
        $ite = new RecursiveDirectoryIterator($sPath);
        foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
            if(is_file($cur)){
                $fileToString = file_get_contents($cur);
                $token = token_get_all($fileToString);
                $tokenCount = count($token);

                //Class Count
                $sPathInfo = pathinfo($cur);
                if ($sPathInfo['extension'] === 'php') {
                    for ($i = 2; $i < $tokenCount; $i++) {
                        if ($token[$i-2][0] === T_CLASS && $token[$i-1][0] === T_WHITESPACE && $token[$i][0] === T_STRING ) {
                        $iTotalCount++;
                        }
                    }
                } else {
                    error_reporting(E_ALL & ~E_NOTICE);
                }
            }
        }
        return $iTotalCount;
    }

    /**
     * Get the total Method in the directory
     * @param string $sPath and integer $iTotalCount
     */
    public function getMethodTotal($sPath, $iTotalCount)
    {
        $ite = new RecursiveDirectoryIterator($sPath);
        foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
            if(is_file($cur)){
                $fileToString = file_get_contents($cur);
                $token = token_get_all($fileToString);
                $tokenCount = count($token);

                //Method Count
                $sPathInfo = pathinfo($cur);
                if ($sPathInfo['extension'] === 'php') {
                    for ($i = 2; $i < $tokenCount; $i++) {
                        if ($token[$i-2][0] === T_FUNCTION) {
                                $iTotalCount++;
                        }
                    }
                } else {
                    error_reporting(E_ALL & ~E_NOTICE);
                }
            }
        }
        return $iTotalCount;
    }

}


texts:
This is small utility class I made format.utility.ts. There are some other one off utility methods in here I removed for this. The one in question is duration()

class Duration {
  constructor(public value: number, public name: string) { }
}

export class FormatUtility {

  private static durations: Array<Duration> = [
    new Duration(60, 'seconds'),
    new Duration(60, 'minutes'),
    new Duration(24, 'hours'),
    new Duration(7, 'days'),
    new Duration(4, 'weeks'),
    new Duration(12, 'months'),
    new Duration(null, 'years')
  ]

  public static duration(time: number, interval?: string, duration?: Duration): string {
    time = Math.abs(time);
    duration = duration == null ? (interval == null ? this.durations[0] : this.durations.find(x => x.name == interval)) : duration;

    if (!duration)
      throw new Error(`The interval specified (${interval}) is unknown`);

    if (!duration.value || time <= duration.value)
      return Math.round(time) + ' ' + duration.name;

    let i: number = this.durations.findIndex(x => x.name == duration.name);

    return this.duration(time / duration.value, null, this.durations[i+1]);

  }

}

tests/examples:

FormatUtility.duration(12)
// '12 seconds'

FormatUtility.duration(87)
// '1 minutes'

FormatUtility.duration(112, 'hours')
// '5 days'

FormatUtility.duration(4585, 'minutes')
// '3 days'

FormatUtility.duration(23999999, 'hours')
// '2976 years'

The point of this is I have a lot of places in my app where I have display a duration like '12 days ago' or '6 minutes ago' but there are no requirements on the specific interval to use. They wanted to always have 'the most human readable interval for the specific time'. So I came up with this utility and method. Using moment.js elsewhere I get the duration between two dates in seconds and then call FormatUtility.duration(seconds) and have it generate that human readable label for me.

For the review, I'm notoriously awful with recursion which is why I chose to use it here. Looking for general feedback on Typescript usage, vanilla JS, recursion, and whatever else. Is there a better way? Or changes to make this better?

If anyone sees red flags, please let me know.


texts: Binary Search Tree implementation with unique pointers

texts:
I have implemented a binary search tree using templates and unique_ptr in C++ 11. At present, only insertion and deletion are implemented. Please provide your feedback for improvements.

#include <iostream>
#include <memory>

template<typename T>
class Btree {
public:
    void insert(T data)
    {
        _insert(root, data);
    }
    void traverse(void (*func)(T data))
    {
        _traverse(root, func);
    }
    void del(T data)
    {
        _del(root, data);
    }
private:
    struct node {
        T data;
        std::unique_ptr<node> left, right;
        node(T data): data(data), left(nullptr), right(nullptr) {}
    };

    std::unique_ptr<node> root;
    void _insert(std::unique_ptr<node>& curr, T data);
    void _del(std::unique_ptr<node>& curr, T data);
    void _traverse(std::unique_ptr<node>& curr, void (*func)(T data));
    T _findmin(std::unique_ptr<node> &curr);
};

template<typename T>
void Btree<T>::_insert(std::unique_ptr<node>& curr, T data)
{
    if (curr == nullptr) {
        curr.reset(new node(data));
        return;
    }

    if (data < curr->data)
        _insert(curr->left, data);
    else
        _insert(curr->right, data);
}
template<typename T>
T Btree<T>::_findmin(std::unique_ptr<node>& curr)
{
    if (curr && curr->left == nullptr)
        return curr->data;
    return _findmin(curr->left);
}
template<typename T>
void Btree<T>::_del(std::unique_ptr<node>& curr, T data)
{
    if (curr == nullptr)
        return;
    if (data < curr->data)
        _del(curr->left, data);
    else if (data > curr->data)
        _del(curr->right, data);
    else {
        // if one child is nullptr or both child are nullptr
        if (curr->left == nullptr) {
            auto &p = curr->right;
            curr.reset(p.release());
        }
        else if (curr->right == nullptr) {
            auto &p = curr->left;
            curr.reset(p.release());
        }
        //if child is non leaf node
        else {
            T temp = _findmin(curr->right);
            curr->data = temp;
            _del(curr->right, temp);
        }
    }
}
template<typename T>
void Btree<T>::_traverse(std::unique_ptr<node>& curr, void (*func)(T data))
{
    if (curr == nullptr)
        return;
    _traverse(curr->left, func);
    func(curr->data);
    _traverse(curr->right, func);
}


texts:
I'm trying to improve my functional skills and seeing where it fits and where it might not. Please review the code and see where functional practices might be applied. I'm specifically looking at trying to get rid of the state variables.

private int GetFirstLineFrameCount(XDocument doc)
{
    var subElement = (from res in doc.Descendants(_xmlns + "subelements")
                      where res.Element(_xmlns + "object")
                                 .Element(_xmlns + "metadata")
                                 .Element(_xmlns + "identifier").Value == "1"
                      select res).FirstOrDefault();

    var offsetElement = subElement.Descendants(_xmlnsEc + "start").Select(x => x.Element(_xmlnsEc + "editUnitNumber")).FirstOrDefault();

    if (offsetElement == null)
    {
        Logger.Error<SubtitleNormalizer>("no offset found");
        return 0;
    }

    return Int32.Parse(offsetElement.Value);
}


texts: Is it ok to add a static method to the IEqualityComparer implementation?

texts:
Linq methods like Distinct need IEqualityComparer object. But sometimes I just compares two objects and to create Comparer instance for that is seems redundant. So it would be nice to use static Equals method. But I'm not sure does not it break some guidelines.

public class ByteArrayComparer : EqualityComparer<byte[]>
{
    [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern int memcmp(byte[] b1, byte[] b2, long count);

    //http://stackoverflow.com/a/1445405/2336304
    public override bool Equals(byte[] b1, byte[] b2)
    {
        return AreEqual(b1, b2);
    }

    // http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode/263416#263416
    // http://stackoverflow.com/a/7244729/2336304
    public override int GetHashCode(byte[] array)
    {
        unchecked
        {
            return array == null ? 0
                  : array.Aggregate(17, (current, element) => current * 31 + element.GetHashCode());
        }
    }

    public static bool AreEqual(byte[] b1, byte[] b2)
    {
        // Validate buffers are the same length.
        // This also ensures that the count does not exceed the length of either buffer.
        return b1 != null && b2!= null && b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0;
    }
}


texts: Framework to drive a small personal site

texts:
I have been writing a very slim MVC framework to drive a small personal website. It's nothing intricate, just mostly for fun and a learning experience.

Specifically, this is the initial part of the MVC and just the entry point. I don't want to develop all this logic for the models and views if my dispatcher is not going to work right in a production site. Again, this is just the entry of the project and handles requests to load the controllers via the URL. This is not the entire MVC project.

When I am looking at other frameworks out there, they seem quite complex in their handling of the routing and controller dispatching, and my final code is just a fraction of the size.

I have the server redirect all requests back to index.php using an .htaccess file or via a Nginx config file. I have tried both.

I use the index.php file as the entry point (this is the relevant part):

/* using "Example Implementation" of the PSR-0 standards supporting both '\' and '_' namespace seperations
 * https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
 * using file_exists to deal with otherwise unhandled errors
 */
function autoload($className) {
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';

    if($lastNsPos = strripos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DS, $namespace) . DS;
    }

    $fileName .= str_replace('_', DS, $className) . '.php';

    $fileName = ROOT . DS . $fileName;
    if(file_exists($fileName)) {
        require($fileName);
    }
}

$test = new framework\core\Router();

Router.php:

<?php

namespace framework\core {

class Router {

    function __construct() {
        //get the raw url
        $urlRaw = $_SERVER['REQUEST_URI'];

        //do the route :)
        $this->route($urlRaw);
    }

    private function route($urlRaw) {
        //do our best to split the url at the most obvious parts (/, ?, $, =)
        $urlRawParts = preg_split('/[\/?&=]+/', $urlRaw, -1, PREG_SPLIT_NO_EMPTY);

        //do a simple sanitization on the parts (allow alphanumeric and dash while stripping common web extensions)
        $urlRawParts = preg_replace('/[^A-Za-z0-9\-]|\bhtm\b|\bphp\b|\bhtml\b/', '', $urlRawParts);

        //set our controller and action or use defaults
        $controller =   ((!empty($urlRawParts[0])) ? $urlRawParts[0] : 'Index');
        $action =       ((!empty($urlRawParts[1])) ? $urlRawParts[1] : 'index');
        $arguments =    ((count($urlRawParts) > 2) ? array_slice($urlRawParts, 2) : array());

        $this->dispatch($controller, $action, $arguments);
    }

    private function dispatch($controller, $action, $arguments) {
        //format the call to our class
        $controller = 'application\\controllers\\' . ucfirst($controller) . 'Controller';

        //load our class or show the appropriate error page
        $controller = ((class_exists($controller) ? new $controller() : new Error('404')));

        //use the default class method unless a valid one exists
        $method = ((method_exists($controller, $action)) ? $action : 'index');

        //call our class method
        call_user_func_array(array($controller, $method), $arguments);
    }
}
}

?>

This works for any URL that I throw at it and will always default to a known file (Error.php which is just a simplified controller and view in one).

Am I missing anything huge here? Is my logic way off or not complete? Is this utilization slow or wasteful on resources?  I'm just looking for a general idea on if I am on the right track.


texts: Avoiding use of an initialized variable that will either be changed or ignored

texts:
Follow on from this question

This is a follow on question from one I asked a few days ago. I am making (or rather have made) a recursive method that takes a list of ArrayList objects as its parameters. There can be any number of them, but let's pretend there are five. They are numbered from 1 to 5, so the Array contains: [1 2 3 4 5].

The Array is then passed through a recursive method which returns only the numbers at odd indices in the Array, i.e. [2 4] (as they are at indices 1 and 3).

This is the code for the recursive method:

public static ArrayList<Integer> oddList (ArrayList<Integer> tList) {

    ArrayList<Integer> oddList = ListMethods.deepClone(tList);
    int tempStorage = -1;

    if (oddList.size() <= 0)
        return oddList;
    else
    {
        if (oddList.size()%2==0)
            tempStorage = oddList.remove(oddList.size()-1);

        oddList.remove(oddList.size()-1);
        oddList = ListMethods.oddList(oddList);

        if (tempStorage >= 0)
            oddList.add(tempStorage);
    }
    return oddList;
}

There are two things I am curious about:

Firstly, is there an alternative to that if statement at the very end, to check that tempStorage >= 0.
Secondly, and probably more importantly, should I care? In other words, is what I've done there a cheap, easy fix, or is that common coding practice? It just seems strange having an initialised variable that will always be either changed or ignored.

Any feedback would be fantastic, thanks (and to the guys who posted on my previous post, I'm still reviewing all the information - not allowed to use most of it in this assignment, but thanks anyway!)