texts: UITableViewDataSource with different sections and SearchController

texts:
I have a UIViewController holding one UITableView with 3 sections. Also this UIViewController implements UISearchResultsUpdating for searching in that UITableView. The UIViewController looks like this:

class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {

    var searchController = UISearchController(searchResultsController: nil)

    @IBOutlet weak var tableView: UITableView!

    private struct TableViewSections {
        static let sectionOne = 0
        static let sectionTwo = 1
        static let sectionThree = 2
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupTableView()
        self.setupSearchController()
    }

    private func setupSearchController() {
        self.searchController.searchResultsUpdater = self
        self.searchController.dimsBackgroundDuringPresentation = false
        self.searchController.searchBar.placeholder = "Search"
        self.searchController.searchBar.autocapitalizationType = .sentences
        self.searchController.hidesNavigationBarDuringPresentation = false
        if #available(iOS 11.0, *) {
            self.navigationItem.searchController = self.searchController
        } else {
            self.tableView.tableHeaderView = self.searchController.searchBar
        }
    }

    private func setupTableView() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        // In each of these cases i will do the work that is needed to return the correct number of rows
        // Just for demonstration i return a random int in every case

        if self.searchController.isActive {
            switch section {
            case TableViewSections.sectionOne:
                return 10

            case TableViewSections.sectionTwo:
                return 20

            case TableViewSections.sectionThree:
                return 30

            default:
                return 0
            }
        } else {
            switch section {
            case TableViewSections.sectionOne:
                return 15

            case TableViewSections.sectionTwo:
                return 25

            case TableViewSections.sectionThree:
                return 35

            default:
                return 0
            }
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // In each of these cases i will do the work that is needed to show the correct content
        // Just for demonstration i return UITableViewCell() in every case

        switch indexPath.section {
        case TableViewSections.sectionOne:

            if self.searchController.isActive {
                return UITableViewCell()
            } else {
                return UITableViewCell()
            }

        case TableViewSections.sectionTwo:

            if self.searchController.isActive {
                return UITableViewCell()
            } else {
                return UITableViewCell()
            }

        case TableViewSections.sectionThree:

            if self.searchController.isActive {
                return UITableViewCell()
            } else {
                return UITableViewCell()
            }

        default:
            return UITableViewCell()
        }
    }

    // MARK: UISearchResultsUpdating

    func updateSearchResults(for searchController: UISearchController) {
        // do the search work here...
    }
}

You can see the difference between tableView(_:numberOfRowsInSection:) and cellForRow(at:).

My Question now is: What is recommended way to do so? Is the better solution tableView(_:numberOfRowsInSection:), cellForRow(at:) or is there even a better solution?


texts:
This piece of code basically just asks for a word and sees if it exists in a file. If not, the user is asked if it should be added to the file.

I am new to C programming and I want to know what you think about my code: things to change, things to remove, what not to do.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
    //Declarations
    //**********************************************************
    char wordContainer[20],wordFinder[20],ans[2];
    int wordChecker=0;
    FILE* filePtr=NULL;
    //**********************************************************
    filePtr=fopen("wordDic.dic","a+");//opening the file with the a+ option
    printf("please enter the word you want to look for : ");
    fgets(wordContainer,20,stdin);//entering the word we want to look for
    if(filePtr==NULL)
    {
        printf("error while trying to open the dictionnary file");//allways good to check
    }

    /*while we haven't reach the end of the file see if the current word matchs the word we are looking for*/
    while(fgets(wordFinder,20,filePtr)!=NULL)
    {
        if(strcmp(wordContainer,wordFinder)==0)
        {
            printf("this word was found in the dictionnary , would you like to perform another search ? y/n... ");
            fgets(ans,2,stdin)
            wordChecker++;//when the word is matched increase wordChecker and quit the while
            break;
        }
    }
    if(wordChecker==0)//if no match is found ask to enter this new word
    {
        printf("we couldn't find the word %s would you like to add it ? y/n ... ",wordContainer);
        fgets(ans,2,stdin);
        if(strcmp(ans,"y")==0 || strcmp(ans,"Y")==0)
        {
            fprintf(filePtr,"%s",wordContainer);
            fflush(filePtr);//not exactly sure what it does exept that it clear the output buffer maybe ?
            printf("this word has been added");
        }
        else
        {
            printf("thank you for using this program,bye");
            exit(0);
        }
    }
    fclose(filePtr);
    return 0;
}


texts: Simpler and faster code for reversing list?

texts:
I wrote this code for reversing a doubly linked list containing words in each node, which works perfectly fine. My teacher says the algorithm is difficult to understand and the code as a whole could be made more efficient(reducing overhead and memory consumption).

What changes can i make to the code/the reversing algorithm?
Also is there a way I could input the sentence without having to ask the number of words in advance?

Here is the code:

#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct NODE
{
    char *item;
    struct NODE *next;
    struct NODE *prev;
}NODE;
void Insert(char data[],NODE **List)
{
    NODE *temp,*last;
    last=(*List);
    temp=(NODE*)malloc(sizeof(NODE));
    temp->item=(char*)malloc(strlen(data));
    temp->item=data;
    temp->next=NULL;
    temp->prev=NULL;
    if((*List)->item==NULL)
        (*List)=temp;
    else
    {
        while(last->next!=NULL)
            last=last->next;
        temp->prev=last;
        last->next=temp;
        last=temp;
    }
}
void Reverse(NODE **List)
{
    int flag1=0;
    NODE *temp,*temp1,*last,*flag;
    temp1=(NODE*)malloc(sizeof(NODE));
    last=(*List);
    while(last->next!=NULL)
        last=last->next;
    temp=last;
    while(temp->prev!=NULL)
    {
        temp1->item=temp->item;
        temp1->next=temp->next;
        temp1->prev=temp->prev;
        temp->next=temp->prev;  //swap prev and next links
        temp->prev=temp1->next;
        temp=temp->next;
        if(flag1==0)  //record the last node which becomes the first node in new list
        {
            flag1++;
            flag=temp;
        }
    }
    temp1->item=temp->item;
    temp1->next=temp->next;
    temp1->prev=temp->prev;
    temp->next=NULL;
    temp->prev=temp1->next;
    (*List)=flag->prev;  //give control of the first node
    free(temp1);
};
void display(NODE *List)
{
    if(List->next==NULL)
    {
        printf("%s",List->item);
        return;
    }
    NODE *temp;
    temp=List;
    do
    {
        printf("%s<-->",temp->item);
        temp=temp->next;
    }while(temp->next!=NULL);
    printf("%s\n",temp->item);
}
int main()
{
    int i=0,n;
    char s[10][50];
    NODE *List;
    List=(NODE*)malloc(sizeof(NODE));
    List->item=NULL;
    List->next=NULL;
    List->prev=NULL;
    printf("Provide number of words(max 10): ");
    scanf("%d",&n);
    printf("Enter string of words for the list: ");
    while(i<n)
    {
        scanf("%s",s[i]);
        Insert(s[i],&List);
        i++;
    }
    printf("\nOriginal List is: ");
    display(List);
    Reverse(&List);
    printf("\nReversed List is: ");
    display(List);
    getch();
    return 0;
}


texts:
I was wondering if you can give me advice on this solution to assess if an user input string is a palindrome or not.
How can I optimize this solution?

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;

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

    // user enters string
    System.out.println ("Please enter string");

    InputStreamReader input = new InputStreamReader (System.in);
    BufferedReader reader = new BufferedReader (input);
    String userinput = "";
    userinput = reader.readLine();

    // test if string is valid
        if (!userinput.matches("[A-Za-z]+")){
            System.out.println ("Invalid Input");
            System.exit(1);
        }

        else if (userinput.length() > 10){
            System.out.println ("String too long");
            System.exit(2);
        }

    String stringReverse = "";
    for (int i = userinput.length()-1; i >= 0; i--){
        stringReverse += String.valueOf(userinput.charAt(i));
    }

    if (userinput.equals(stringReverse)){
        System.out.println ("String is a Palindrome");
        System.exit(0);
    }

    else if (userinput != stringReverse) {
        System.out.println ("String is not a Palindrome");
        System.exit(0);
    }

    }
}


texts:
Here is a problem I solved. Please review this.

<!DOCTYPE HTML>

            <title>BLA| Welcome </title>

Meet Jack

 He is Jack.He is an odd little boy that just got an empty box for his birthday. He may look  happy but is a little  disappointed. Now he will have to put a little things in the box.

            Jack would really like...

Roller blades

Magic tricks

Anything Pokemon

A motorized Lego set

                You can get all this (and more) at an online toy store. Two very popular ones are toysrus.com and eToys.


texts:
The goal is to flatten an array of nested arrays of integers.
For example [1, [2], [3, [4]]] should return [1, 2, 3, 4]

I'm particularly looking for some feedback on the following:

Is usage of TypeError exception justified?
Did I miss some valid edge cases in my tests?

Here is my solution including unit tests:

#!/usr/bin/env python

import unittest

def flatten_list(array):
    """ Returns a flattened array of integers from arbitrarily nested arrays of integers.

    >>> flatten_list([[1, 2, [3]], 4])
    [1, 2, 3, 4]
    """

    flat_array = []
    for element in array:
        if isinstance(element, int):
            flat_array.append(element)
        elif isinstance(element, list):
            flat_array += flatten_list(element)
        else:
            raise TypeError("Unsupported type ({})".format(
                type(element).__name__))
    return flat_array

class FlattenListTestCase(unittest.TestCase):
    """Tests for flatten_list"""

    def test_empty_list(self):
        self.assertEqual(flatten_list([]), [])

    def test_single_integer(self):
        self.assertEqual(flatten_list([3]), [3])

    def test_already_flattened(self):
        self.assertEqual(flatten_list([1, 2, 3, 4]), [1, 2, 3, 4])

    def test_single_element_multiple_nested(self):
        self.assertEqual(flatten_list([[1]]), [1])

    def test_arbitary(self):
        self.assertEqual(flatten_list(
            [1, [2], [3, 4], [[5]], 6]), [1, 2, 3, 4, 5, 6])

    def test_empty_sublists(self):
        self.assertEqual(flatten_list([1, [[], 2]]), [1, 2])
        self.assertEqual(flatten_list([[]]), [])

    def test_invalid_input(self):
        with self.assertRaises(TypeError):
            flatten_list(3)
        with self.assertRaises(TypeError):
            flatten_list([3, "2"])
        with self.assertRaises(TypeError):
            flatten_list(None)

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


texts:
I have written the following service class for my application and at the moment it only contains a single method which is responsible for carrying out the necessary actions to add a new team to the database. More methods will be added later but I want to make sure that I'm on the right track with regards to OOP and it's various principles.

The current addTeam() method essentially accepts a number of parameters, validates them to ensure that they are in the correct format and then determines if they violate any business rules i.e. team name must be unique and the league & country id's must already exist in the database.

I've only recently started to write in the OOP style, so it would be great to get some feedback on whether this is the right approach to take. The class seems to have a lot of dependencies which must be injected through the constructor method so I'm sure there is a better way to do it. In addition, the code within the addTeam() method still looks very procedural like and probably violates the single responsibility principle too.

class TeamService implements TeamServiceInterface {

     private $validator;
     private $teamMapper;
     private $leagueMapper;
     private $countryMapper;

     function __construct(ValidatorInterface $validator, TeamMapperInterface $teamMapper, LeagueMapperInterface $leagueMapper, CountryMapperInterface $countryMapper)
     {
         // Attempt to populate the class's variables with the information that has been passed to the object
         $this->validator = $validator;
         $this->teamMapper = $teamMapper;
         $this->leagueMapper = $leagueMapper;
         $this->countryMapper = $countryMapper;
     }

     public function addTeam($name, $country, $league, $active)
     {
         // Set the rules for the data that we want to pass to our team object
         $validator->setRule($name, 'name', 'required|alpha_numeric_ampersand_space|min_length[3]|max_length[30]');
         $validator->setRule($country, 'country', 'required|is_natural_no_zero');
         $validator->setRule($league, 'league', 'required|is_natural');
         $validator->setRule($active, 'active', 'required|boolean');

         // Execute the validation rules
         if($validator->run() === false)
         {
             throw new Exception('The information provided doesn\'t meet the required validation rules.');
         }

         // Check to see if the team name already exists in the database
         if($this->teamMapper->isTeamByName($name) === true)
         {
             throw new Exception('The name specified for the team already exists in the system.');
         }

         // Check to see if the country id specified exists in the database
         if($this->countryMapper->isCountryById($country))
         {
             throw new Exception('The country id specified could not be found in the system.');
         }

         // Check to see if the league id specified exists in the database
         if($this->leagueMapper->isLeagueById($league) === null)
         {
             throw new Exception('The league id specified could not be found in the system.');
         }

         // Create an instance of the team class
         $team = new Team($name, $country, $league, $active);

         // Attempt to persist the new team to the database
         if($this->teamMapper->insert($team) === false)
         {
             // Throw an exception because a certain event happened
             throw new Exception('The were was a problem adding the team to the system.');
         }

         return true;
     }
}


texts: Simple c++ triple class to mimic pair for use with uniform initialization

texts:
I'm trying to create a simple triplet class, but the more I look at the implementation of std::pair the more I feel like I'm missing important details.  What I have feels "too simple".  I am aware of std::tuple and other options, but the use case is to be able to use uniform initialization -- so we can make certain assumptions / ignore complications (?)

I am restricted to c++11, none of those beautiful c++14/17 magical unicorns added.

/// keeping class and test in self-contained file {test.cpp}
/// Compile: g++ -o test -std=c++11 test.cpp
#include <iostream>
#include <vector>

/// class definition
template <class T1, class T2, class T3>
struct triple {
    /// q1
    typedef T1 first_type;
    typedef T2 second_type;
    typedef T3 third_type;

    T1 first;
    T2 second;
    T3 third;

    /// q2
    triple() : first(), second(), third() {}

    triple(const T1 &f, const T2 &s, const T3 &t)
        : first(f), second(s), third(t) {}

    /// q3
    template<class U1, class U2, class U3>
    triple(const triple<U1, U2, U3> &t)
        : first(t.first), second(t.second), third(t.third) {}

    triple(const triple<T1, T2, T3> &t) = default;
    triple(triple<T1, T2, T3> &&t) = default;
};

/// simple function to "use" these
void print(const std::vector<triple<int, const std::string, const std::string>> &vals) {
   for(auto &tup : vals) {
        std::cout << "First:  " << tup.first  << std::endl
                  << "Second: " << tup.second << std::endl
                  << "Third:  " << tup.third  << std::endl;
        std::cout << "------------------" << std::endl;
   }
}

/// simple main, goal: uniform initialization
int main(int argc, char **argv) {
    print({
        {1, "hi", "billy"},
        {2, "you", "cool"},
        {3, "no", "not"}
    });
}

q1: the purpose of typedef

I know it's kind of old, but it's easier to explain from this implementation -- I'm looking at the implementation for clang.  Anyway, they all do this

typedef _T1 first_type;    ///<  @c first_type is the first bound type
typedef _T2 second_type;   ///<  @c second_type is the second bound type

and subsequently never use them.  What is the purpose, just to be able to do something like typename std::pair<int, float>::second_type f = 0.012f;?

q2: default constructors

My ultimate purpose is to just enable uniform initialization of something instead of a (large) number of std::make_tuple calls.  In this context, it seems reasonable to include some static_assert for

is_trivially_constructible
is_trivially_default_constructible
is_trivially_move_constructible
is_trivially_destructible

Does adding these make sense or is that over-limiting for no real reason?

q3: reflection construction?

Concerning the constructor with U1, U2, and U3, the purpose of this is to allow for automatic conversions?  Say automatically converting a triple<unsigned int, float, bool> -> triple<size_t, double, int>?

q4: any alarms going off?

Like I said, this is intended to be a simple and non-robust class.  I've been playing around with it, no memory leaks I can find, etc.  The operator overloads would be easy to put in, but other than that is there anything I should be more concerned with?  The stl implementation of pair is much more complex, and being that I ditched std::tuple so that I can do uniform initialization, this makes me think I'm missing something.


texts: Replacing div if there is any validation error connected with the div value

texts:
I have an input group:

        @Html.DisplayNameFor(m => m.StorageId)

    @if(ViewData.ModelState["StorageError"] !=null && ViewData.ModelState["StorageError"].Errors.Count>0)
    {

            @Html.DropDownList("storageId", null, new { @class = "form-control",@style="border-color:red" })

    }
    else
    {

            @Html.DropDownList("storageId", null, new { @class = "form-control" })

    }

As you can see, if there are no errors, the site should render div without a red border and tooltip.

Do you think it's efficient and good-looking enough to leave it as it is, or does it need to be rewritten?


texts: Project Euler 22: Assigns scores for names that are imported from text file

texts:
Project Euler 22

  Using atext file containing over five-thousand first names, and you
  will calculate a score for each name. Begin by reading the names from
  the file and sorting them in alphabetical order. Then, you will
  compute an alphabetical value for each name where A is 1, B is 2, C is
  3 and so on. The alphabetical value of a name is just the sum of the
  values of the letters in the name. To compute the name-score for a
  name, you simply multiply this alphabetical value by its position in
  the sorted list.

  For example, when the list is sorted into alphabetical order, COLIN,
  which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the
  list.

So, the name-score for COLIN would be 938 * 53 = 49714.
What is the sum total of all the name-scores in the file?

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class ScoringNames {
    BufferedReader x = null;
    String location = "C:\\Users\\xxxxxxxi\\Dropbox\\"
                    + "College\\COSC 1430\\Scoring Names\\names.txt";

    ArrayList<String> names = new ArrayList<String>();
    static ArrayList<Integer> scores = new ArrayList<Integer>();
    static int ns[];

    public void fillNS(){
        for (int x = 0; x < ns.length; x++){
            ns[x] = scores.get(x) * (x+1);
        }
    }

    public void printNS(){
        for (int x = 0; x < ns.length; x++)
            System.out.print(ns[x] + ", ");
    }

    public void readFile(){ //Opens file, and prints every line.
        try{
            x = new BufferedReader(new FileReader(location));
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        }

        try{
            String name = x.readLine();
            while(name != null){
                //System.out.println(name);
                names.add(name);
                name = x.readLine();
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    public void sortNames(){ //Sort names array in alphabetical order
        Collections.sort(names);
    }

    public void printNames(){
        for(String counter: names)
            System.out.println(counter);
    }

    public int alphValue(char x){
        return (x - 'A' + 1);
    }

    public void returnSize(){
        System.out.println(names.size());
    }

    public int nameScore(String name){
        int score = 0;
        char[] tempName = name.toCharArray();
        for (char i : tempName){
                score += alphValue(i);
            }

        return score;
    }

    public void addScores(){
        for(String x : names){
            scores.add(nameScore(x));
        }
    }

    public void printScores(){
        for(int counter: scores)
            System.out.println(counter);
    }

    public int totalNS(int[] x){
        int sum = 0;
        for(int i = 0; i < x.length; i++){
            sum += x[i];
        }
        return sum;
    }

    public static void main(String[] args) {
        ScoringNames abc = new ScoringNames();
        abc.readFile();
        abc.sortNames();
        //abc.printNames();
        abc.addScores();
        //abc.printScores();
        ns = new int[scores.size()];
        abc.fillNS();
        //abc.printNS();
        //System.out.println(ns[937]); //"COLIN"
        System.out.println("The sum total of all name scores is: " +
                            abc.totalNS(ns));
    }

}


texts: Determine if simple arithmetic expression is valid

texts:
This looks very messy to me, and I'm fairly new to java, so I don't know what data structures could have helped me achieve the same result more efficiently. I just went ahead and brute-forced all possible failing scenarios:

Could this be further optimized to reduce the number of checks?

public static boolean isAnOperator(char c){
        return (c == '*' || c == '/' || c == '+' || c == '-' || c == '%');
    }

    private static boolean isValidExpression(String expression){
        //TEST 1: False if expression starts or ends with an operator
        if (isAnOperator(expression.charAt(0)) || isAnOperator(expression.charAt(expression.length()-1)))
            return false;

        //TEST 2: False if test has mismatching number of opening and closing parantheses
        int openParenthCount = 0;
        int closedParenthCount = 0;
        int consecutiveOpCount = 0;

        for (int i = 0; i < expression.length(); i++){
            if (expression.charAt(i) == '('){
                openParenthCount++;
                consecutiveOpCount = 0;
                //SUBTEST: False if expression ends with '('
                if (i == expression.length()-1) return false;
            }
            if (expression.charAt(i) == ')'){
                closedParenthCount++;
                consecutiveOpCount = 0;
                //SUBTEST: False if expression starts with ')'
                if (i == 1) return false;

            }
            if (isAnOperator(expression.charAt(i))){
                consecutiveOpCount++;
                //TEST 3: False if operator is preceded by opening paranthesis or followed by closing paranthesis
                if (expression.charAt(i-1) == '(' || expression.charAt(i+1) == ')')
                    return false;
            }
            //TEST 4: False if 2 operators found next to each other
            if (isAnOperator(expression.charAt(i)) || consecutiveOpCount > 0)
                return false;
        }
        if (openParenthCount != closedParenthCount)
            return false;

        //LAST TEST 5: All preceding checks ensure that
        // by this point, all exisiting parantheses open and close properly
        return true;
    }


texts:
The program should accept a name of a country as input. It should then parse the Wikipedia page for that country and find all links to the wikipedia pages of other countries on that page and make a list of all such countries.

For example, if the argument was India and http://en.wikipedia.org/wiki/India has links to wiki pages of Nepal and Pakistan, the list associated with India is [Nepal, Pakistan]. The program should recursively perform the above operation for any country you have not encountered so far.

After parsing the wiki page for India, it should parse the wiki page of Nepal, Pakistan and so on.

The final output is a json object with key being the country and value being the list of countries which were linked to the wiki page for the key country.

Sample output can be:

{"India": ["Nepal", "Pakistan"], "Nepal": ["India", "China"], "Pakistan": ["India"], "China": ["Japan"], "Japan": ["India", "China"]}

This is what I have tried, but I want to get the best approach for it:

import pycountry
import wikipedia

country_dict = {}
final_dict = {}

refr_list = []

def GetCountryDict():
    country_list = list(pycountry.countries)

    for country in country_list:
        country_dict[country.name] = 1

    return country_dict

def internalParse(internal_list,final_dict,countryDict,refr_list):

    for i in refr_list:
        if not final_dict.has_key(i):
            WikiParser(i,countryDict)
        else:
            refr_list.remove(i)

def WikiParser(country_name,country_dict):
    wiki_resp =[]
    internal_list = []
    try:
        wiki_resp = wikipedia.page(country_name)
    except:
        pass

    for i in wiki_resp.links:

        if country_dict.has_key(i):

            if i not in internal_list:
                refr_list.append(i)
                internal_list.append(i)
    final_dict[country_name] = internal_list
    try:

        refr_list.remove(country_name)
    except:
        pass
    return internal_list, final_dict,refr_list

if __name__ == '__main__':
    country_name = raw_input("Please enter country name: ")
    countryDict = GetCountryDict()

    internal_list,final_dict,refr_list = WikiParser(country_name,countryDict)

    while refr_list:

        internalParse(internal_list,final_dict,countryDict,refr_list)


texts: All subsets of a String in java using recursion

texts:
I wrote this code for printing all sets of a String. It also prints the empty subset. Is this the right approach

public class AllSubSet {

    public static void allSet(String s, String t) {
        System.out.print(t + " ");
        if (s.length() > 0) {
            for (int i = 0; i < s.length(); i++) {
                allSet(s.substring(i + 1, s.length()), t + s.charAt(i));
            }
        }
    }

    public static void main(String args[]) {
        String a = "ABC";
        String t = "";
        allSet(a, t);
    }
}


texts: Compute interval for a node in a binary tree

texts:
Given a binary tree organised as in the diagram below (a static tree represented by an array of 15 nodes), I am writing code to compute the interval represented by a given node at index i, given the interval of the entire tree (node 0)?  My motivation to do this is to get rid of the need to store the interval in a node instance.

Here's my stab at computing the value.  It appears to be correct but I'm wondering if there's a much smarter way of calculating it:

int Log2i(int x)
{
    auto r = 0;

    while (x >>= 1)
    {
        ++r;
    }

    return r;
}

void Interval(int i, int min, int max, int & a, int & b)
{
    auto d = Log2i(i);      // Depth of node i.
    auto k = 1 << d;        // At this level, there are k intervals.
    auto s = max - min;     // Total span over which we're partitioned.
    auto p = s / k;         // Therefore, size of each interval.
    auto f = k - 1;         // Index of first node for this partition.

    a = min + (p * (i - f));
    b = a + p;
}

int main(void)
{
    auto a = int(), b = int();

    Interval(6, 1000, 2000, a, b);

    return 0;
}


texts: Change architecture of Ruby app to be more object oriented, readable

texts:
I'm working on a Slack bot for service desk which sends direct message to user on a Slack when their ticket will be on user_action_needed status. I'm using AWS Lambda to handle Jira incoming webhooks. Everything works well but I think I've got an issue with whole architecture of the app - I quess the code is not so readable, name of the class probably doesn't match what they do.

First of all I've got the handler on AWS lambda:

  module JiraHandler
    extend self
    def handle(event:, _context:)
      Parsers::JiraParser.new(event).call
      { statusCode: 200 }
    end
  end

Parsers::JiraParser is responsible not only for parsing events but it calls another class which grabs userId from Slack, and then inside of GetUserId I've got another class which sends message to user. So at the end if you call Parsers::JiraParser class you will receive slack message instead of parsed data.

Details of what I wrote about each class below:

Parsers::JiraParser

module Parsers
  class JiraParser
    def initialize(event)
      payload = event['body']
      @event = JSON.parse(payload)
    end

    def call
      ::Slack::GetUserId.new(reporter_email, reporter_name, ticket_number).call
    end
    # reporter_email, reporter_name, ticket_number are methods to pull data by .dig from event hash

GetUserId

  class GetUserId
    SLACK_LOOKUP_BY_EMAIL = 'https://slack.com/api/users.lookupByEmail'

    def initialize(email, name, ticket_number)
      @email = email
      @name = name
      @ticket_number = ticket_number
    end

    def call
      user_id = set_slack_user.dig('user', 'id')
      ::Slack::SlackMessenger.new(user_id, name, ticket_number).call
    end

    def set_slack_user
      HTTParty.get(SLACK_LOOKUP_BY_EMAIL, options)
    end

SlackMessanger

module Slack
  class SlackMessenger
    SLACK_API_ENDPOINT = 'https://slack.com/api/chat.postMessage'

    def initialize(user_id, name, ticket_number)
      @user_id = user_id
      @name = name
      @ticket_number = ticket_number
    end

    def call
      HTTParty.post(SLACK_API_ENDPOINT, body: params, headers: headers)
    end

I don't think this is a good approach, should I create an extra class where all those classes will be called? or maybe I should use monads?


texts: To check if a string C is an interleaving of A and B Code

texts:
This is my code to check if a string C is an interleaving of Strings A and B. Please suggests optimizations, and where I can improve.

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include<string.h>

using namespace std;
int isInterleaved(char a[100],char b[100],char c[200],int i, int j, int k)
{
    if(i==0&&j==0)
        return true;
    if(i>=0&&j>=0)
    {

    if(c[k]==a[i]&&c[k]!=b[j])
        return isInterleaved(a,b,c,i-1,j,k-1);
    else if(c[k]==b[j]&&c[k]!=a[i])
        return isInterleaved(a,b,c,i,j-1,k-1);
    else if(c[k]==a[i]&&c[k]==b[j])
        return isInterleaved(a,b,c,i-1,j,k-1)||isInterleaved(a,b,c,i,j-1,k-1);
    else
        return false;
    }
    else
    {
        if(i<0&&j>=0)
        {
            if(c[k]==b[j])
            return isInterleaved(a,b,c,i,j-1,k-1);
            else
                return false;
        }
        if(j<0&&i>=0)
        {
            if(c[k]==a[i])
                return isInterleaved(a,b,c,i-1,j,k-1);
            else
                return false;
        }

    }
}
int main()
{
char a[100],b[100],c[200];
cin>>a;
cin>>b;
cin>>c;
int l1=strlen(a),l2=strlen(b),l3=strlen(c);
if(l3>l1+l2)
    {
        printf("C is not an interleaving of A and B\n");
        return 0;
    }
int ans=isInterleaved(a,b,c,l1-1,l2-1,l3-1);
printf("%d\n",ans);
return 0;
}


texts: Implemnting a Trie Data structures problem from HackerRank using Python3

texts:
I'm trying to write a better code in python. I don't know where to start checking. I want to make sure that I do write a best practice code.

This is the second problem in Hackerrank trie data structure:

  Given N strings. Each string contains only lowercase letters from (both inclusive). The set of  strings is said to be GOOD SET if no string is prefix of another string else, it is BAD SET. (If two strings are identical, they are considered prefixes of each other.)

  For example, aab, abcde, aabcd is BAD SET because aab is prefix of aabcd.

  Print GOOD SET if it satisfies the problem requirement.
  Else, print BAD SET and the first string for which the condition fails.

  Input Format

  First line contains , the number of strings in the set.
  Then next  lines follow, where  line contains  string.

  Output Format

  Output GOOD SET if the set is valid.
  Else, output BAD SET followed by the first string for which the condition fails.

  Sample Input00

7
aab
defgab
abcde
aabcde
cedaaa
bbbbbbbbbb
jabjjjad

  Sample Output00

BAD SET
aabcde

  Sample Input01

4
aab
aac
aacghgh
aabghgh

  Sample Output01

BAD SET
aacghgh

from sys import stdin

class Node:
    def __init__(self,char):
        self.character = char
        self.children = {}
        self.counter = 0
        self.end_word = False

class Trie:
    def __init__(self):
        self.root = Node('*')

    def add(self,word):
        current = self.root
        fail = False
        for char in word:
            if char not in current.children:
                new_node = Node(char)
                current.children[char] = new_node
                current = new_node
                new_node.counter += 1

            else:
                current = current.children[char]
                current.counter += 1
                if current.end_word:
                    fail = True

        current.end_word = True
        # first word > second word : second word is prefix of first word
        if current.counter >=2:
            fail = True

        return fail

if __name__ == "__main__":
    tree = Trie()
    n = stdin.readlines()
    for i in n[1:]:
        i = i.strip()
        add_check_string = tree.add(i)
        if add_check_string:
            print("BAD SET")
            print(i)
            break
    if not add_check_string:
        print("GOOD SET")


texts:
I have an input which contains a dropdown list of 8 items. Depending on the option the user picks, I want to change the value of their input into a a different string value. In order to do this, I am using a ton of if else statements, which make this look very bulky and I would like to condense this if at all possible. I have the following code:

if (inputFive == "Corporation"){
inputFive = "534"
}else if (inputFive == "LLC"){
inputFive = "535"
}else if(inputFive == "LLP"){
inputFive = "536"
}else if(inputFive == "Partnership"){
inputFive = "537"
}else if(inputFive == "Sole Proprietorship"){
inputFive = "538"
}else if(inputFive == "Limited Partnership"){
inputFive = "539"
} else {
inputFive = "540"
}

As you can see, this looks a little old-school, and I would like to see if there is a better/simpler way to make this happen. Just looking to condense this code if at all possible. All options/hints will be appreciated!


texts:
I'm currently using SciPy's mode function to find the most occurring item in different iterable objects. I like the mode function because it works on every object type I've thrown at it (strings, floats, ints).

While this function seems reliable, it is very slow on bigger lists:

from scipy.stats import mode

li = range(50000)
li[1] = 0

%timeit mode(li)
1 loops, best of 3: 7.55 s per loop

Is there a better way to get the mode for a list? If so, would the implementation be different depending on the item type?


texts: Using UPSERT to maintain word counts for subtitles

texts:
I will first explain the context. I want to read serie subtitles contained in .srt files. I have already done the part of extracting the words from the files (and how many times the word appears for a serie) but when it comes to inserting the data in my SQL Server database, it takes more and more time to do the updates or inserts because i am checking if the word exists or not. I call a stored procedure from C# with the following parameters : the word, how many times it appears in my files, the serie name.

ALTER PROCEDURE [dbo].[INSERT_WORD_FOR_SERIE]
    @word nvarchar(50),
    @counter int,
    @serie nvarchar(50)
AS
BEGIN
    DECLARE @idSerie AS int
    DECLARE @idWord AS int

    SELECT @idWord = IDWORD FROM WORD WHERE WORD=@word;

    IF @idWord IS NOT NULL
        BEGIN
            SELECT @idSerie = IDSERIE FROM SERIE WHERE SERIE=@serie;
            IF EXISTS (SELECT counter FROM APPEARS WHERE IDWORD=@idWord AND IDSERIE=@idSerie)
                BEGIN
                    UPDATE APPEARS SET counter = counter + @counter WHERE IDWORD=@idWord AND IDSERIE=@idSerie;
                END
            ELSE
                BEGIN
                    INSERT INTO APPEARS VALUES (@idWord, @idSerie, @counter);
                END
        END
    ELSE
        BEGIN
            INSERT INTO WORD VALUES (@word);
            SELECT @idWord = IDWORD FROM WORD WHERE WORD=@word;
            SELECT @idSerie = IDSERIE FROM SERIE WHERE SERIE=@serie;
            INSERT INTO APPEARS VALUES (@idWord, @idSerie, @counter);
        END
END

I have inserted only two series and I can already see that it is taking more and more time to insert or update one word.

Can you see any improvements that can be done or different way of doing what I want more efficiently ?


texts:
Assume the built-in function Ascii(c), where c is a one character
  string, will return an integer containing the ASCII value of that
  character. Write a function that accepts a string, uses Ascii(c) and
  additional processing to produce a one way hash value from the string,
  and returns the hash value as a string. You may assume the initial
  string is not empty and contains several characters.

//one way hash using ascii
static string hashViaAscii(String S)
{
    int hashVal = 0;

    for (int k = 0; k < S.Length; k++)
        hashVal += Ascii(S[k]);  //gets Ascii value, add them all

    return ((hashVal % HASH_TABLE_SIZE).ToString());  //return sum % table size as string
}

I don't think is a good approach. How can this be improved?


texts: A beautiful and easy way of permutation with recursion

texts:
I want to share a better version of permutation with you.

Yesterday, when I was reading Horowitz's Fundamentals of Data Structures In C++, and I noticed that the result of the code, at page 32, in the book is not what I want.

For example, if I have an array of {'a', 'b', 'c'}, then the result it provides is:

abc
acb
bac
bca
cba
cab

Notice that the last two cases don't fit what I want: when 'c' is fixed, all the other letters at its right should start from a, with relative order, \$a \lt b \lt c \lt \ldots \lt z\$, so the result should be:

...
cab
cba

Here is my code, which corrects the order with two modified swaps:

#include <iostream>
using namespace std;

void printPermutation(char *a, const int k, const int m);
void swap2(char *a, const int l, const int r);
void swap3(char *a, const int l, const int r);

int main() {
    char str[] = {'a', 'b', 'c', 'd', 'e'};
    printPermutation(&str[0], 0, sizeof(str)-1);
    return 0;
}

void printPermutation(char *a, const int k, const int m) {
    if (k == m) {
        for (int i = 0; i <= m; i++) {
            cout << a[i];
        }
        cout << endl;
    }
    else {
        for (int i = k; i <= m; i++) {
            // the code in the book just use swap, but I change them.
            swap2(a, k, i); // here
            printPermutation(a, k+1, m);
            swap3(a, k, i); // and here
        }
    }
}

// swap2 will move the element at index r to l,
// by continuously swap with element at its left
void swap2(char *a, const int l, const int r) {
    for (int i = r; l < i; i--) {
        swap(a[i], a[i-1]);
    }
}

// The same concept with swap2, but from left to right
void swap3(char *a, const int l, const int r) {
    for (int i = l; i < r; i++) {
        swap(a[i], a[i+1]);
    }
}

How can I further simplify the code?

I like the idea that the author used recursion to make things beautifully simple. But to achieve the result I want as described above, I have to add two additional, a little bit similar, functions.


texts: Equals method for a class representing an origin and destination

texts:
Have I over-ridden GetHashCode properly in the below code?

public class ODPair
{
    #region Constructors and Destructors

    public ODPair(string origin, string destination)
    {
        if (string.IsNullOrEmpty(origin))
        {
            throw new ArgumentNullException(origin, "Origin of an ODPair should be non-null");
        }

        if (string.IsNullOrEmpty(destination))
        {
            throw new ArgumentNullException(destination, "Destination of an ODPair should be non-null");
        }

        this.Origin = origin;
        this.Destination = destination;
    }

    #endregion

    #region Public Properties

    public string Destination { get; private set; }

    public string Origin { get; private set; }

    #endregion

    #region Public Methods and Operators

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }

        var pair = obj as ODPair;
        if (pair == null)
        {
            return false;
        }

        return this.Origin == pair.Origin && this.Destination == pair.Destination;
    }

    public bool Equals(ODPair pair)
    {
        if (pair == null)
        {
            return false;
        }

        return this.Origin == pair.Origin && this.Destination == pair.Destination;
    }

    public override int GetHashCode()
    {
        return this.Origin.GetHashCode() ^ this.Destination.GetHashCode();
    }

    #endregion
}


texts: A package for communications between packages - v2

texts:
This is basically the registry pattern and a pub/sub event system.

Very simple and minimalist.  Looking for general feedback.

/***************************************************************************************************
**COMMS
 - provides registry and event system
 - reduces dependencies
***************************************************************************************************/

// self used to hold client or server side global
(function (self) {

    "use strict";

    // holds (Pub)lic properties
    var Pub = {},

        // holds (Priv)ate properties
        Priv = {},

        // holds "imported" library properties
        $A;

    (function manageGlobal() {

        // Priv.g holds the single global variable, used to hold all packages
        Priv.g = '$A';

        if (self[Priv.g] && self[Priv.g].pack && self[Priv.g].pack.utility) {
            self[Priv.g].pack.comms = true;
            $A = self[Priv.g];
        } else {
            throw new Error("comms requires utility module");
        }
    }());

    Pub.Reg = (function () {
        var publik = {},
            register = {};
        publik.get = function (key) {
            return register[key];
        };
        publik.set = function (key, value) {
            register[key] = value;
        };
        publik.setMany = function (o) {
            $A.someKey(o, function (val, key) {
                register[key] = val;
            });
        };
        publik.getMany = function () {
            return register;
        };
        return publik;
    }());

    Pub.Event = (function () {
        var publik = {},
            events = {};
        publik.add = function (name, callback) {
            if (!events[name]) {
                events[name] = [];
            }
            events[name].push(callback);
        };
        publik.remove = function (name, callback) {
            if (name && callback) {
                delete events[name][callback];
            } else if (name) {
                delete events[name];
            }
        };
        publik.trigger = function (name) {
            if (events[name]) {
                $A.someIndex(events[name], function (val) {
                    val();
                });
            }
        };
        return publik;
    }());
    self[Priv.g] = $A.extendSafe(self[Priv.g], Pub);
}(this));


texts:
I'm looking for a way to get a subset of a given enum to avoid repetition and use same enum type while comparing.

I found this question Enum subset or subgroup in C# and like the idea of using static class. Whoever, It doesn't allow to iterate over all elements in the class. So I added GetValues method.

Edit:

Here is my full code:

    public partial class Devices : Form
        {
            public Devices()
            {
                InitializeComponent();

                // Here, I need to iterate over StatusEnum items
                foreach (var item in Enum.GetValues(typeof(StatusEnum)))
                {
                    checkedListBoxParent.Items.Add(item);
                }

                // and iterate over ValidStatusEnum items
                foreach (var item in ValidStatusEnum.GetValues())
                {
                    checkedListBoxChild.Items.Add(item);
                }
            }

            private void On_MouseUp(object sender, MouseEventArgs e)
            {
                // Here, I need to compare StatusEnum and ValidStatusEnum
                if (Equals(checkedListBoxParent.CheckedItems.Cast<StatusEnum>().ToList(),
                    checkedListBoxChild.CheckedItems.Cast<StatusEnum>().ToList()))
                {
                    MessageBox.Show("Parent and child are similar");
                }
            }

            private bool Equals(List<StatusEnum> list1, List<StatusEnum> list2)
            {
                if (list1.Count != list2.Count)
                    return false;
                for (int i = 0; i < list1.Count; i++)
                {
                    if (list1[i] != list2[i])
                        return false;
                }
                return true;
            }

            private bool Equals(StatusEnum status, StatusEnum validStatus)
            {
                return status == validStatus;
            }
        }

        public enum StatusEnum { Unknown, Known, NotAvailable, Available };

        internal static class ValidStatusEnum
        {
            public const StatusEnum Known = StatusEnum.Known;
            public const StatusEnum Available = StatusEnum.Available;

            public static StatusEnum[] GetValues()
            {
                return new StatusEnum[] { Known, Available };
            }
        }
}

So basically, in my winforms application, I have two CheckedListBoxes (Parent and Child) populated from StatusEnum Enum and ValidStatusEnum static class.
So, I need to iterate over enums to populate Checkboxes and I need to compare StatusEnum and ValidStatusEnum to display a message to user in case I have the same selection in both checkboxes.

Any thoughts about the design and the code?


texts: Copying and pasting one inputs value into other input with the same name

texts:
I am trying to write something that will copy the current <input>s value and enter it into any <input> that start with the same name.

<input> names will follow this pattern: price-0, price-1, price-2, upc-0, upc-1, upc-2.

So if a user enters a value in <input name="price-0"> and hits copy the value should be transferred over to all input whos name start with price

This is the code I've written:

$(document).on('click', '.--copy', function () {
    var input_name = $(this).closest('div').find('input').attr('name').split('-')[0];
    $('input[name^=' + input_name + ']').val($(this).closest('div').find('input').val());
});

A fiddle to make everyones life easier: http://jsfiddle.net/6jGLD/

I feel like there are too many selectors being called upon and the code is somewhat difficult to read.


texts: Determine the class hierarchy of a class

texts:
My only concern with the following class is the line hierarchy.trimToSize() in determineHierarchy, because it is not necessary for determining the class hierarchy. However, putting it in the constructor clutters the code more than my current solution. Any recommendations or should I just live with it?

Since this class is completely finished and tested, I also look for any other helpful comments. The target version is 1.8.

/** The class hierarchy of a class. */
public class ClassHierarchy {

    private final List<Class<?>> hierarchy;

    /**
     * Creates a ClassHierarchy instance for the given class {@literal clazz}.
     *
     * @param clazz
     *            Class for which the class hierarchy should be determined. Must not be null and must refer to a class
     *            type.
     *
     * @throws IllegalArgumentException
     *             if {@literal clazz} does not refer to a class type
     * @throws NullPointerException
     *             if {@literal clazz} is null
     */
    public ClassHierarchy(Class<?> clazz) {
        validateConstructorArgument(clazz);
        hierarchy = Collections.unmodifiableList(determineHierarchy(clazz));
    }

    /**
     * Returns the class hierarchy as an immutable list.
     *
     * <p>
     * The classes are ordered, starting with the class for which the instance was created and ending with
     * {@code Object.class}.
     *
     * @return the class hierarchy as an immutable list.
     */
    public List<Class<?>> getHierarchy() {
        return hierarchy;
    }

    private static void validateConstructorArgument(Class<?> clazz) {
        Objects.requireNonNull(clazz, "clazz must not be null");

        if (clazz.isEnum() || clazz.isAnnotation() || clazz.isInterface() || clazz.isArray() || clazz.isPrimitive()) {
            throw new IllegalArgumentException("clazz must refer to a class type");
        }
    }

    private static ArrayList<Class<?>> determineHierarchy(Class<?> clazz) {
        ArrayList<Class<?>> hierarchy = new ArrayList<>();
        for (Class<?> currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) {
            hierarchy.add(currentClass);
        }
        hierarchy.trimToSize();
        return hierarchy;
    }

}


texts: Entity - Model (EAV) system with delta updates

texts:
I am trying to create my first eav system that can handle updates as well.

The user can create models with list and objects inside and with references other models. the user can then create instances of the model ModelDataFields.

First we have the ModelParameteres. that will store all the models and their parameters and the fields and their parameters.

A parameter is like 'name'or 'islist' or 'order' or whatever. We have a enum for that.
UpdateType is 'created' or 'updated' or 'deleted'.
updatedby is UserId.
Updated is datetime stamp and delta for what is updated.
Model is ModelId
Value is some user data for the parameter like the name value when parameter is 'name'.

 CREATE TABLE [dbo].[ModelParameters]
                 (
                    [UpdateType]    [TINYINT]           NOT NULL,
                    [UpdatedBy]     [uniqueidentifier]  NOT NULL,
                    [Updated]       [datetime2](0)      NOT NULL,
                    [Model]         [uniqueidentifier]  NOT NULL,
                    [Field]         [uniqueidentifier]  NULL,
                    [Parameter]     [smallint]          NOT NULL,
                    [Value]         [nvarchar](MAX)    NULL
                 );

 CREATE CLUSTERED INDEX [IX_ModelParameters]
                    ON [dbo].[ModelParameters]([Updated] DESC, [Model], [Field]);

Then we have the ModelDataFields that holds data records for each of the fields in a model. the ModelData is the id of each instance of the model.
the index is when we have a user list of some field soo we know what data belongs together in a dynamic list.

UpdateType is 'created' or 'updated' or 'deleted'.
updatedby is UserId.
Updated is datetime stamp and delta for what is updated.

Value is the current value for the modeldata => field => index?.
LastValue is for undo and restoring in case of deleting.

 CREATE TABLE [dbo].[ModelDataFields] (
                [UpdateType]     [TINYINT]           NOT NULL,
                [UpdatedBy]      [uniqueidentifier]  NOT NULL,
                [Updated]        [datetime2](0)      NOT NULL,
                [ModelData]      UNIQUEIDENTIFIER    NOT NULL,
                [ModelField]     UNIQUEIDENTIFIER    NOT NULL,
                [Index]          INT                 NULL,
                [Value]          NVARCHAR (MAX)      NULL,
                [LastValue]      NVARCHAR (MAX)      NULL,
            );

CREATE CLUSTERED INDEX [IX_ModelDataFields]
                ON [dbo].[ModelDataFields]([Updated] DESC, [ModelData], [ModelField]);

Do i need multi tables for the ModeldataFields like for each model or is this fine? do you see something else wrong, We are gonna go with EAV so it not a question about EAV vs setting up tables.


texts: Counting weather events for visualization using Gnuplot

texts:
I wrote this code to analyze ~800 MB of weather data from the US. I am planning on visualizing the data with Gnuplot and Gimp. I have already made the images and a gif file. This code runs somewhat fast, although I do not suppose it is efficent. How can I improve it?

The idea behind my code is:

find keywords in the lines, such as state names and their weather conditions
save the weather condition in a map according to the state and year
get the yearly weather conditions to a file named after the analyzed state

main code:

int main()
{
    std::string data[18] = {"stormdata_1996.csv",
                            ... // I left out the files from her on purpose
                            "stormdata_2013.csv"};
    for(int j=0;j<18;j++){
        std::string city[36] = {"TEXAS",
                                ... // left out on purpose as well
                                "OREGON",
                                "MISSOURI"};
        for(int i=0;i<36;i++){
            std::map<std::string, int> weather;
            std::ifstream fin(data[j].c_str(),std::ios::in);
            getWeather(weather, fin, city[i]);
            fin.close();
            std::ofstream fout(city[i].c_str(),std::ios::app);
            outPut(weather, fout, city[i],j+1996);
            fout.close();
            weather.clear();
        }
    }
    return 0;
}

functions:

void getWeather(std::map<std::string, int>& weather, std::ifstream& fin, std::string& city){
    std::string line;
    while(!fin.eof()){
        getline(fin, line);
        if(line.find(city) != std::string::npos){
            if(line.find("Drought") != std::string::npos){
                weather["Drought"]++;
            }else if(line.find("Flood") != std::string::npos){
                weather["Flood"]++;
            }else if(line.find("Heavy Snow") != std::string::npos){
                weather["Heavy Snow"]++;
            ... // I left out some else if statements from here to shorten the post
            }else if(line.find("High Surf") != std::string::npos){
                weather["High Surf"]++;
            }
        }
    }
}

void outPut(std::map<std::string, int>& weather, std::ofstream& fout,std::string& city, int date){
    fout << city << "-" << date << std::endl;
    for(auto i:weather){
        fout << i.first << "\t" << i.second << std::endl;
    }
    fout << std::endl;
}

Here's a gif of ALASKA's weather from 1996 to 2013:


texts: Making as many unique strings as possible by removing two characters

texts:
I'm attempting a programming challenge type task in C#, where the goal is to determine how many unique strings can be obtained by removing two characters. The prompt for the task implied that I should create the set of all possible strings with 2 chars removed, then return the number of items in the set. I was initially suspicious of this, as I've often found that the only way to complete these kinds of tasks is to abstract away from actually storing results or enumerating possibilities wherever possible - but due to the requirement that only unique strings should be counted, I don't know how to avoid storing information about every result so far. Supposedly I have to be able to handle strings of up to a million characters in length - and I can't think of any way right now to avoid the hideous iteration count and massive result set that a million character string would require.
Here is my code so far. It works, but its way too slow, and I think large inputs might be generating incorrect results, but I'm not actually sure:
 private static void Main(String[] args)
{
    var input = Console.ReadLine();
    Console.WriteLine(FindBeautifulStrings(input).Count);
}

// B will always be larger than A because of the way we're iterating so we have to remove it first.
private static string RemoveTwo(string input, int indexA, int indexB)
{
    return input.Remove(indexB, 1).Remove(indexA, 1);
}

private static HashSet<int> FindBeautifulStrings(string input)
{
    // Iterate over every character in the string, then for each character, iterate over every
    // other character, removing the two selected characters; return set of all possible results.
    int inputLength = input.Length;
    HashSet<int> results = new HashSet<int>();
    for (int i = 0; i < inputLength; ++i)
    {
        for (int j = i + 1; j < inputLength; ++j)
        {
            results.Add(RemoveTwo(input, i, j).GetHashCode());
        }
    }
    return results;
}

Storing hashes of strings instead of strings themselves is the only idea I've come up with in terms of more efficiently detecting a string identical to one I've already seen. Since the non-duplicate requirement means that the resulting combinations themselves are significant, I haven't been able to avoid working with strings entirely and solve it mathematically instead (if duplicates were permissable, I feel like this could be solved using the equation n!/(n - (n - 2)! * (n - 2)!. Is there any way to determine the non-duplicate possibilities mathematically without iterating over or storing the strings themselves? If not, is there any way to optimise what I have so far?
Edit:
I thought I should clarify - although the question intuitively feels like it's about permutations, a mistake made both by myself initially and by a few others so far, the only operation performed on the original string is removal of characters.
It works, I think, like this:
input: apple

i=0, j=1: ple
i=0, j=2: ple **Doesn't count, duplicate**
i=0, j=3: ppe
i=0, j=4: ppl
i=1, j=2: ale
i=1, j=3: ape
i=1, j=4: apl
i=2, j=3: ape **Doesn't count, duplicate**
i=2, j=4: apl **Doesn't count, duplicate**
i=3, j=4: app

Unique strings: 7


texts: Implementation of a queue for digicode-like system

texts:
What it is about

I created an application where you need to push invisible buttons in a certain order to unlock the advanced mode. To handle this, I wanted to use a queue (FIFO) of my own, adapted to my problem.

Every time I click a button, its ID is added to the queue with addItem, and the password gets checked with checkCorrect. It is meant to work similarly to digicode doors. The size attribute determines how many values the queue can remember, hence the maximum length of the password.

What I'd like to know

Do you think this is a good code? In which ways can it be improved? Are there other ways (with smaller / more elegant code) to implement this?

The code

class MyQueue():
    def __init__(self, size, default_value=None):
        self.size = size
        self.content = [default_value]*size
        self.end = self.size-1
    def addItem(self, value):
        self.end = (self.end+1) % self.size
        self.content[self.end] = value
    def printQueue(self):
        print 'end='+str(self.end)+' - '+str(self.content)
    def checkCorrect(self, password):
        pw = list(reversed(password))
        i = 0
        j = self.end
        if len(pw) > self.size:
            return False
        while True:
            if pw[i] <> self.content[j]:
                return False
            else:
                i += 1
                j = (j-1) % self.size
                if i == len(pw):
                    return True

if __name__=='__main__':
    q = MyQueue(size=4, default_value=0)
    q.addItem(1)
    q.addItem(8)
    q.addItem(8)
    q.addItem(5)
    q.addItem(7)
    q.addItem(3)
    print q.checkCorrect([5, 7, 3])
    print q.checkCorrect([2, 7, 3])


texts:
I've written the following function to parse a configuration file. I did my best to make it simple, but it's still over 30 lines and has too much indentation caused by a series of if statements.

Any suggestions make it easier to read are welcome.

int
parse_config (FILE * conf_file, module_initializer_t init)
{
  char *line; /* Current line */
  char *type; /* Type of current module */
  char *name; /* Name of current module */
  char *envz;
  size_t envz_len;
  size_t lineno = 0;

  line = type = name = envz = NULL;
  while (getline (&line, NULL, conf_file) != EOF)
    {
      lineno++ ;
      if (!is_comment(line))
        if (line[0] == '[')
          if (update_header(line, &type, &name)) {
            if (type)
              if ((*init)(type, name, envz, envz_len)) {
                fprintf("failed to initialize module %s with name %s", type, name);
                return 1;
              }
            clear_envz(&envz, &envz_len);
            }
          else {
            fprint("syntax error on line %d", lineno);
            return 1;
          }
      else
        argz_add(&envz, &envz_len, line);
    }
  if ((*init)(type, name, envz, envz_len)) {
    fprintf("failed to initialize module %s with name %s", type, name);
    return 1;
  }
}

It parses a configuration file with the following syntax:

   #comment and empty lines ignored
   [module-type]{module-name}
   var1=val1
   #comment
   var2=val2
   [another-type]{another-name}
   var3=val3


texts:
I'm working on a managed OpenGL game engine for C#, and here's how I'm managing shader parameters (uniforms). Is it "alright"? Could it be better? I'm a bit unsure about using generics in this case.

public abstract class ShaderParameter
{
    public readonly string Name;
    internal readonly int Location;
    internal readonly Shader Parent;

    internal ShaderParameter(string name, int location, Shader parent)
    {
        Name = name;
        Location = location;
        Parent = parent;
    }
    //Ensures that the value is set on the shader,
    //this should be called before using the parent shader
    internal abstract void EnsureSet();
    //Gives a value to this shader paramerter
    public abstract void SetValue<T>(T value);
}

//A shader paramater of type float
public sealed class ShaderParamFloat : ShaderParameter
{
    float value = 0;
    bool valueChanged = false; //If the value has changed since the last time it was set on the shader

    internal ShaderParamFloat(string name, int location, Shader parent)
        : base(name, location, parent)
    { }
    internal override void EnsureSet()
    {
        if (valueChanged)
        {
            //Hands over a single value to OpenGL.
            GL.Uniform1(Location, value);
            valueChanged = false;
        }
    }
    //Gives a value to this shader parameter
    public override void SetValue<T>(T value)
    {
        if (typeof(T) != typeof(float))
            throw new ArgumentException("Value is of type: " + typeof(T).ToString() + ", expected: float", "value");

        this.value = (float)(object)value;
        valueChanged = true;
    }
}

The reason for using inheritance is because other ShaderParameter classes behave differently in EnsureSet(). For example, ShaderParamVector3 uses GL.Uniform3(...), and ShaderParamTexture needs to ensure that the texture is valid and set on the graphics card.


texts:
This is my first asp.net core web api and i did followed the Repository pattern but i don't know whether this approach is good practice.

public class TrainerRepo : IRepoTrainer
{
    private readonly IConfiguration _config;

    public TrainerRepo(IConfiguration config)
    {
        _config = config;
    }

    public IDbConnection dbConnection
    {
        get
        {
            return new SqlConnection(_config.GetConnectionString("MyConnString"));
        }
    }

    public List<Trainer> GetTrainers()
    {
        string sql = "select trainer_id,trainer_name from trainer";
        using(IDbConnection conn = dbConnection)
        {
            conn.Open();
            var res = conn.Query<Trainer>(sql).ToList<Trainer>();
            conn.Close();
            return res;
        }

    }

    public int NewTrainer(Trainer trainer)
    {
        string sql = "insert into trainer ( trainer_name) values ( @name)";
        using(IDbConnection conn = dbConnection)
        {
            conn.Open();
            var res = conn.Execute(sql, param: new
            {
                //id = trainer.trainer_id,
                name = trainer.trainer_name
            });
            conn.Close();
            return res;
        }
    }

    public async Task<int> updateTrainer(Trainer trainer)
    {
        string sql = "update trainer set trainer_name = @tname where trainer_id = @tid";
        using(IDbConnection conn = dbConnection)
        {
            conn.Open();
            var res = await conn.ExecuteAsync(sql, param: new { tname = trainer.trainer_name, tid = trainer.trainer_id });
            conn.Close();
            return res;
        }
    }

    public int deleteTrainer(int id)
    {
        string sql = "delete from trainer where trainer_id=@trainerId";
        using(IDbConnection conn = dbConnection)
        {
            conn.Open();
            var res =  conn.Execute(sql, param: new { trainerId = id });
            conn.Close();
            return res;
        }
    }

}

IRepoTrainer interface

public interface IRepoTrainer
{
    List<Trainer> GetTrainers();
    int NewTrainer(Trainer trainer);
    Task<int> updateTrainer(Trainer trainer);
    int deleteTrainer(int id);
}

my problem is that reuse of following code block, is it good practice ?

 using(IDbConnection conn = dbConnection)
   {
    conn.Open();
    //
    conn.Close();
    return res;
   }


texts: Listing files whose names match a pattern with a date

texts:
My directory folderMarket has lots of files with the same name but are tagged with a date string at the end. The date tag can be formatted differently, e.g. "2018-07-25" or "25Jul18".  My helper function is tasked with extracting a path list matching each found file name against filename_list.  is there a better way to build a filename_list instead of brute force used below?

from datetime import datetime

strToday = "2018-07-25"
files_market = ['apples_DATE.xml', 'peaches_DATE.xml', 'cucumbers_DATE.xml', 'potatos_DATE.xml', 'tomates.DATE.csv']

def get_path_list(directory, base_filename_list, savedAsOf):

    strDate1 = savedAsOf
    filename_list1 = [n.replace('DATE', strDate1) for n in base_filename_list]

    strDate2 = datetime.strptime(savedAsOf, '%Y-%m-%d').strftime('%d%b%y')
    filename_list2 = [n.replace('DATE', strDate2) for n in base_filename_list]
    filename_list = filename_list1 + filename_list2

    path_list = []
    for file in os.listdir(directory):
        filename = os.fsdecode(file)
        if filename in filename_list:
            path_list.append(os.path.join(directory, filename))
            continue
    return path_list

print (len(get_path_list(folderMarket, files_market, strToday)))


texts:
I have this old code and I want it to be easier to understand. Originally, it loaded using an onload on the opening body tag, so I managed to change that to a window.onload, but now redundant code is getting elements by ID, since it first finds the form and after that the actual select box.

var localidades = new Array(
  new Array("Baja California","Tijuana","Rosarito","Ensenada","Tecate","Mexicali","San Felipe"),
  new Array("Sonora","San Luis Río Colorado","Sonoita","Sásabe","Nogales","Naco","Agua Prieta"),
  new Array("Chihuahua","El Berrendo","Puerto Palomas","San Jerónimo","Ciudad Juárez","El Porvenir","Ojinaga"),
  new Array("Coahuila","Ciudad Acuña","Piedras Negras"),
  new Array("Nuevo León","Colombia"),
  new Array("Tamaulipas","Nuevo Laredo","Reynosa","Río Bravo","Nuevo Progreso","Matamoros")
);
function seleccionLocal(selection){
  var cajon = document.getElementById("forma1").city;
  for(var x=0;x<localidades.length;x++){
    if(selection==localidades[x][0]){
      var cities = localidades[x];
      cajon.length = cities.length;
      for(var n=1;n<cities.length;n++){
        cajon[n] = new Option(cities[n],cities[n]);
      }
      break;
    }
  }
}
window.onload = function StartIt(){
  var cajon = document.getElementById("forma1").country;
  cajon.length = localidades.length+1;
  for(var x=0;x<localidades.length;x++){
    cajon[x+1] = new Option(localidades[x][0],localidades[x][0]);
  }
}
<form id="forma1" action="" onsubmit="" style="margin:auto;">
    <select name="country" onchange="seleccionLocal(this.options[this.selectedIndex].value)">
    <option value="-1" >Estado</option>
  </select>
  <select name="city">
    <option value="-1" >Ciudad</option>
  </select>
</form>

It's working, but I guess it can be lighter. What say You?


texts: Checking address fields for presence of a Post Office Box

texts:
I'm just trying to learn how to write jQuery better so I wanted some smart peoples opinions.

The code is checking the billing and shipping address fields to see if it contains a PO Box address by looking for variations of "PO" and then displays a warning message after the input if it does contain it.

The code is duplicated for each one so there has to be a better way to write this.

jsFiddle

(function ($) {
    'use strict';

    // Check for PO Box text in address fields on checkout
    var $shipAddress = $('#checkout input[name="user_data[s_address]"]'),
        $billAddress = $('#checkout input[name="user_data[b_address]"]'),
        message = '

We don\'t ship to PO Boxes. Sorry for the inconvenience.

';

    $shipAddress.after(message);
    $billAddress.after(message);

    $shipAddress.keyup(function () {
        var $value = $(this).val();

        if ($value === 'po' || $value === 'Po' || $value === 'PO' || $value === 'P.O' || $value === 'p.o') {
            $shipAddress.siblings('.message').removeClass('hidden');
        } else if ($value === '') {
            $shipAddress.siblings('.message').addClass('hidden');
        }
    });

    $billAddress.keyup(function () {
        var $value = $(this).val();

        if ($value === 'po' || $value === 'Po' || $value === 'PO' || $value === 'P.O' || $value === 'p.o') {
            $billAddress.siblings('.message').removeClass('hidden');
        } else if ($value === '') {
            $billAddress.siblings('.message').addClass('hidden');
        }
    });

}(jQuery));


texts: Complete missing data in timeseries pandas

texts:
I collected data using a smartphone. The phone could run out of battery or the collection software could fail, leading to missing data.

For this example let's say I already compute the number of calls per day calls_per_day from the smartphone data. Besides the days where I actually call someone, I want to consider the days where I did not. To do this I have to consider the time where the phone was sensing and assign a zero to that day if there were no calls. In order to know if the phone was sensing, I have a reference sensor that records a tick every 25 seconds: sensed_time.

The code below does what I just described. First, it groups sensed_time by the minute, hour, and day, labelling a day as 'sensed' if it has collected at least 80% minutes of at least 80% of each of the 24 hours of a day. Then it just filters the days from calls_per_day that are labeled as sensed and replaces NaN values with 0.

import numpy as np
def count_per_minute(group):
    if group[group.columns[0]].count() == 0:
        return pd.Series({'count_per_minute':np.nan})
    else:
        return pd.Series({'count_per_minute':group[group.columns[0]].count()})

def label_sensed_days(group, hours_in_day, percentage_valid_hours, percentage_valid_minutes):
    sensed_hours_count = group['sensed_minutes'].loc[group['sensed_minutes'] > 60 * percentage_valid_minutes].count()

    if  sensed_hours_count > 24 * percentage_valid_hours:
        return pd.Series({'sensed_day':True, 'sensed_hours':sensed_hours_count})
    else:
        return pd.Series({'sensed_day':False, 'sensed_hours':sensed_hours_count})

# Create fake DF with the timestamps where the phone was sensing
index = pd.date_range("2018-01-01", "2018-01-03 23:59", freq='25S')
sensed_time = pd.DataFrame(index=index, columns=['was_sensed'])
sensed_time = sensed_time.fillna(1)
sensed_time = sensed_time.sample(frac=0.6)

# Count records sensed per minute, return nan if count == 0
sensed_minutes = sensed_time.groupby(pd.Grouper(freq='1Min')).apply(count_per_minute)

# Complete missing minutes
sensed_minutes = sensed_minutes.reindex(pd.date_range(sensed_time.index.min().date(), sensed_time.index.max().date() + pd.DateOffset(1), freq='1Min'))

# Group sensed minutes by hour
sensed_hours = sensed_minutes.groupby([pd.Grouper(freq='1H')]).count()
sensed_hours = sensed_hours.rename(columns={'count_per_minute':'sensed_minutes'})

# Group sensed hours per day but only consider a valid day the ones where at least 0.8 percent of 24 hours were sensed with at least 0.8 percent of minutes
sensed_days = sensed_hours.groupby([pd.Grouper(freq='1D')]).apply(label_sensed_days, hours_in_day=24, percentage_valid_hours= 0.8, percentage_valid_minutes=0.8)

# Create fake DF with the number of calls on every other day
index = pd.date_range("2018-01-01", "2018-01-05", freq='2D')
calls_per_day = pd.DataFrame([10,5,8], index=index, columns=['calls'])

# Only keep the days that we consider valid sensed days
calls_per_day = calls_per_day.reindex(sensed_days[sensed_days['sensed_day'] == True].index)

# All the NaN values mean that the phone was sensing but we didn't record a call, thus there were 0 calls.
calls_per_day = calls_per_day.fillna(0)

display(calls_per_day)


texts:
I created a Time class. Now I want to modify the code to perform input validation. Hour should be between 0-24, minutes and seconds between 0-59. If class need improvements, please offer suggestions.

Time.h Header File

#ifndef TIME_H
#define TIME_H

class Time
{
    private :
        int hour;
        int minute;
        int second;
    public :
        Time(const int h = 0, const int m  = 0, const int s = 0);    //with default value
        void setTime(const int h, const int m, const int s);        //  setter function
        void print() const;       // Print a description of object in " hh:mm:ss"
        bool equals(Time) const;     //compare two time object
};

#endif

Time.cpp implementation file

#include <iostream>
#include "Time.h"

Time :: Time(const int h, const int m, const int s) : hour(h), minute (m), second(s)
{}

void Time :: setTime(const int h, const int m, const int s)
{
     hour = h;
     minute = m;
     second = s;
}

void Time :: print() const
{
    (hour < 10) ? std::cout << 0 << hour : std::cout << hour;
    std::cout << ":" ;
    (minute < 10) ? std::cout << 0 << minute : std::cout << minute ;
    std::cout << ":" ;
    (second < 10) ? std::cout << 0 << second : std::cout << second ;
    std::cout << "\n" ;
}

bool Time :: equals(Time otherTime) const
{
    if(hour == otherTime.hour && minute == otherTime.minute && second == otherTime.second)
        return true;
    else
        return false;
}

main.cpp

#include <iostream>
#include "Time.h"

int main()
{
   Time t1(10, 50, 59);
   t1.print();   // 10:50:59
   Time t2;
   t2.print(); // 06:39:09
   t2.setTime(6, 39, 9);
   t2.print();  // 06:39:09

   if(t1.equals(t2))
        std::cout << "Two objects are equal\n";
    else
        std::cout << "Two objects are not equal\n";

   return 0;
}

modified code of setTime for input validation (need suggestions)

void Time :: setTime(const int h, const int m, const int s)
{
    if(h>=0 && h <=23)
        hour = h;
    else
        hour = 0;

    if(m>=0 && m <=59)
        minute = m;
    else
        minute = 0;

    if(s>=0 && s <=59)
        second = s;
    else
        second = 0;
}


texts:
This code is executed very often, so I'm wondering if it's already ideal or if it's possible to optimize it further.

var highlightLinks = function(e)
{
  var anchors = e.target.getElementsByTagName("a");
  let file = Components.classes["@mozilla.org/file/directory_service;1"]
                  .getService(Components.interfaces.nsIProperties)
                  .get("ProfD", Components.interfaces.nsIFile);
  file.append("test.sqlite");

  var storageService = Components.classes["@mozilla.org/storage/service;1"]
          .getService(Components.interfaces.mozIStorageService);
  var conn = storageService.openDatabase(file);

  var statement = conn.createStatement("select * from links where url=?1");
  for (var i = 0; i < anchors.length; i++) {
    statement.bindStringParameter(0, anchors[i].href);
    statement.executeAsync({
      anchorIndex: i,
      handleResult: function(aResultSet) {
        for (let row = aResultSet.getNextRow();
             row;
             row = aResultSet.getNextRow()) {

          let value = row.getResultByName("url");
          if (value == anchors[this.anchorIndex]) {
           anchors[this.anchorIndex].innerHTML += "+";
          }
        }
      },

      handleError: function(aError) {
        print("Error: " + aError.message);
      },

      handleCompletion: function(aReason) {
        if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED)
          print("Query canceled or aborted!");
      }
    });
  }
  statement.finalize();
  conn.close();
}

window.addEventListener("DOMContentLoaded", highlightLinks, false);


texts:
I had an idea recently of simplifying some of the code I already have in my Android app that uses Kotlin. I somewhat new to Kotlin, so any opinion would be very appreciated.
Before giving you what idea I had, I will give a base example of what code I have right now:
Lets say that in my app I have a functionality for user to log in and save his credentials for automatic future logging in. Here it is in code.
object MyRepository {
 // Plenty of irrelevant code here...
 fun getUserInfo(): User? {
  // Here we fetch the local data storage and check if any credentials are saved
  return userInfoDao.getUserInformation()
 }

 fun setUserInfo(user: User) {
  // Here we save user credentials to local data storage for future uses
  userInfoDao.saveUserInformation(user)
 }
}

This lead me to think that something like this could be done in a simpler manner, and here is the example:
object MyRepository {
 var userInfo: User?
   get() = userInfoDao.getUserInformation()
   set(value) = userInfoDao.saveUserInformation(value)
 }
}

This of course is much simpler version of what was written above. However, what I am curious is how good of a practice this is in terms of Kotlin standards and general code readability?


texts: Haskell network connection graceful handler

texts:
Just trying to work out some simple graceful connection handling code in Haskell to get my head around some of the IO/Networking/Threading stuff, some tips where I'm doing things poorly would be appreciated! I'm sure I could just use a module like network pipes that would handle all the graceful stuff for me out of the box, but this was just an exercise to try and understand basic network/multithreaded IO handling in haskell.

import Network
import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception
import System.IO

type Connection = (Handle, HostName, PortNumber)
type ConnectionHandler = Connection -> IO ()
type Pool = [(ThreadId, Connection)]

main = runConn

fst' (a,b,c) = a
connFromPool (a,(b,c,d)) = b

runConn = withSocketsDo $ do
  s <- (listenOn (PortNumber 1234))
  p <- atomically (newTVar ([]::Pool))
  t <- forkIO (repeatAccept s p)
  repeatUntilExit stdin stdout putChar ""
  p' <- atomically $ readTVar p
  mapM_ killThread (t:map fst p')
  sClose s
  putStrLn "Enter to exit." >> getLine

repeatAccept s p = do
  c <- accept s
  t <- forkFinally (echoHandler c) (exitPool p)
  atomically $ do
    p' <- readTVar p
    writeTVar p ((t,c):p')
  repeatAccept s p

exitPool :: TVar Pool -> a -> IO ()
exitPool pool = \_ -> do
  tid <- myThreadId
  print $ "Exiting: " ++ (show tid)
  p <- (atomically $ readTVar pool)
  h <- hdl p tid
  open <- hIsOpen h
  if open then do hPutStrLn h "bye\n" >> hFlush h >> hClose h else return ()
  atomically $ do
    pool' <- readTVar pool
    writeTVar pool $ filter ((/=tid).fst) pool'
    return ()
  where hdl p tid = return.connFromPool $ head $ filter ((==tid).fst) p

echoHandler :: ConnectionHandler
echoHandler a@(hdl,_,_) = repeatUntilExit hdl hdl echoToHandleAndStdout ""
  where echoToHandleAndStdout x = hPutChar hdl x >> putChar x

repeatUntilExit :: Handle -> Handle -> (Char -> IO ()) -> [Char] -> IO ()
repeatUntilExit hIn hOut f "exit\n" = return ()
repeatUntilExit hIn hOut f x = do
  c <- hGetChar hIn
  f c
  repeatUntilExit hIn hOut f (appendToLastFive c)
  where appendToLastFive a = (reverse . (:)a . take 4 . reverse) x

-- this is just here because I'm using an older version of base which doesn't have it yet
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally action and_then =
  mask $ \restore ->
    forkIO $ try (restore action) >>= and_then


texts: Converting a number to binary and back as a test in Java

texts:
This is one of my first takes on Java, coming mainly from Matlab I found I had many things to learn.
The code will try to convert a number into an array of ones and zeros and then do the opposite returning you the original number (or at least something very close to it, as it is hard to return the exact number). It is not tested very well, so I can only tell that it is symmetric and not that it is correct.

It would be nice to know any errors I have made, or things that I could improve. An idea I had was using BigInt, I have read about it but not yet used it.

If you could focus on the language specific issues and kindly point them out I would be grateful.

package baseconversion;

import java.lang.Math;
import java.util.Arrays;

public class FloatToBin{

    public static double pow2(double a, double b) {
        return a * (java.lang.Math.pow(2, b));
    }

    public static double rem(double a, double b) {
        return a % b;
    }

    public static double fix(double val) {
        if (val < 0) {
            return Math.ceil(val);
        }
        return Math.floor(val);
    }

    public static double vConv(int[] a, double[] b) {
        int aRows = a.length;
        int bRows = b.length;
        double c = 0;
        for (int i = 0; i < aRows; i++) {
                c += a[i] * b[i];
        }
        return c;
    }

    public static void main(String []args){
        double a = 340.3562;
        int n = 20;
        int m = 20;

        int count = 0;

        int[] out = new int[n + m];

        for (int i = -(n-1); i <= m; i++) {
             out[count] = (int)rem(a * pow2(1, (double)i), 2);
             count++;
        }

        double[] temp = new double[n + m];
        double origVal;
        count--;
        int revCount = 0;

        for (int ii = n - 1; ii >= -m; ii--) {
             temp[revCount] = pow2(1, (double)ii);
             count--;
             revCount++;
        }

        origVal = vConv(out, temp);

        System.out.println("Original number is:");
        System.out.println(a);
        System.out.println("Binary representation is:");
        System.out.println(Arrays.toString(out));
        System.out.println("Inverting we get:");
        System.out.println(origVal);
    }
}


texts:
My goal is to implement a simple pomodoro timer using Go: channels, goroutines.
I'm a newbie in Go world and have some misunderstanding about naming convention. I read a lot of Docker's code on GitHub and there I saw that people sometimes use very short names. These names are not clear for me (a man who comes from C++ world).
func main() {
   app := pomodoro.NewPomodoro()
   app.Start()
}

Give me a review about structure's name
type (
    PomodoroManager struct {
        dur    Duration
        interv Interval
        ch     Chanel
        serv   PomodoroService
    }

    Duration struct {
         working    int
         shortBreak int
         longBreak  int
    }

    Interval struct {
        shortInterval int
        longInterval  int
    }

    Chanel struct {
        start         chan bool
        endShortBreak chan bool
        endLongBreak  chan bool
        end           chan bool
    }
)

func NewPomodoro() *PomodoroManager {
    dur := Duration{
        working:    25,
        shortBreak: 5,
        longBreak:  15,
    }

    interv := Interval{
        shortInterval: 1,
        longInterval:  5,
    }

    ch := Chanel{
        start:         make(chan bool),
        endShortBreak: make(chan bool),
        endLongBreak:  make(chan bool),
        end:           make(chan bool),
    }

    serv := PomodoroService{}

    return &PomodoroManager{dur, interv, ch, serv}
}

func (p *PomodoroManager) Start() {
    go p.serv.StartWorking(p.ch.start, p.dur.working)
    go p.startServManager(p.ch.start, p.ch.endShortBreak, p.ch.endLongBreak, p.ch.end)

    <-p.ch.end
}

func (p *PomodoroManager) startServManager(start, endBreak, endLong, end chan bool) {
    for {
        select {
        case afterWorking := <-start:
            _ = afterWorking
            if p.interv.shortInterval == p.interv.longInterval {
                go p.serv.StartLongBreak(endLong, p.dur.longBreak)
            } else {
                p.interv.shortInterval += 1
                go p.serv.StartBreak(endBreak, p.dur.shortBreak)
            }
        case endShortRelax := <-endBreak:
            _ = endShortRelax
            go p.serv.StartWorking(start, p.dur.working)

        case endLongRelax := <-endLong:
            _ = endLongRelax

            userAnswer := askUser()
            if userAnswer == "Y" {
                p.interv.shortInterval = 1
                go p.serv.StartWorking(start, p.dur.working)
            } else {
                end <- true
            }
        }
    }
}

func askUser() string {
    fmt.Println("Do you want to coninue? Y/N")

    var answer string
    fmt.Scanln(&answer)

    return answer
}

And Last component of the program.
import (
    "os/exec"
    "time"
)

type (
    Service interface {
        StartWorking(chan bool, int)
        FinishBreak(chan bool, int)
        FinishLongBreak(chan bool, int)
    }

    PomodoroService struct {
    }
)

func (p *PomodoroService) StartWorking(start chan bool, duration int) {
    exec.Command("say", "Start working").Output()
    time.Sleep(time.Millisecond * time.Duration(duration))
    exec.Command("say", "Time to Relax").Output()
    start <- true
}

func (p *PomodoroService) StartBreak(endBreak chan bool, duration int) {
    exec.Command("say", "Start short relax").Output()
    time.Sleep(time.Millisecond * time.Duration(duration))
    exec.Command("say", "Relax has finished, getting back to job").Output()
    endBreak <- true
}

func (p *PomodoroService) StartLongBreak(endLong chan bool, duration int) {
    exec.Command("say", "Start long relax").Output()
    time.Sleep(time.Millisecond * time.Duration(duration))
    exec.Command("say", "Long pause has finished").Output()
    endLong <- true
}


texts:
I wanted to create a short little piece of code so that I could see the biases in the random function.

import random
import statistics
import time

num = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
average = []

while True:
    randomNum = random.randint(0, 9)
    num[randomNum] += 1
    average.append(randomNum)
    print(f"\nThe average for all the numbers is {round(statistics.mean(average), round(sum(num) / 20))}")  # The second part of the round function is to keep as few digits on screen while still showing changes with every number. 20 is the arbitrary number I found worked best.
    print(f"The most common number is {num.index(max(num))}\n")
    time.sleep(0.5)

Since I am new-ish to python I wanted to know if, even though its only 15 lines, that I am following good coding practices. That way when my code gets more complicated, I don't have to worry about that as much


texts:
I completed the following exercise:

  You are given an array of repeating numbers. All numbers repeat in an even way, except for one. Find that odd occurring number.

function findOdd(arr){
  obj = {};

  for (var el in arr) {
    if (!obj[arr[el]]) {
      obj[arr[el]] = 1;
    } else {
      obj[arr[el]]++;
    }
  }

  for (var key in obj) {
    if(obj[key] % 2 === 1){
      obj = {'odd': key}
    }
  }
  return parseInt(obj['odd']);
}

findOdd([1,1,2,4,4,4]);

I am trying to figure out if there are better ways to implement this. A few things come to mind:

I believe I can nest the for loops together. I'm not sure if this saves any space or is preferable styling wise.
I re-assigned the created object in the function so it just holds the result. I figured it's a bit more readable. Should I have just returned it in the second for loop?
The code seems 'dirty' to me. What might be another possible solution?


texts: Need unique url but require non unique information from other columns

texts:
I am making a review system and I need to be able to only select the DISTINCT url from the database, but then pull the relevant page title and rating time. I have managed to get it working by using:

<?php
//opens conection
include 'conn.php';

echo $_COOKIE["search"];

$sql = "SELECT * FROM feedback WHERE url LIKE '%$_COOKIE[search]%' GROUP BY url ORDER   BY ratingtime DESC";

//runs the query
$query = mysql_query($sql);
$linecount = 1;

//populates the table with the information
echo '
';
echo'

      URL
      Page Title
      Date Last Modified
      Average Rating

';
echo '
';
echo '
';

while($row = mysql_fetch_array($query))
{
  echo '' .$row['url']. '	';
  echo '' . $row['pagetitle'] . '	';
  echo '' . $row['ratingtime'] . '	';

  $check = mysql_query("SELECT `rating` FROM feedback WHERE url = '$row[url]'");
  $totalvotes = mysql_num_rows($check);
  $result = mysql_query("SELECT SUM(rating) AS 'rating_total' FROM feedback WHERE url = '$row[url]'") or die(mysql_error());
  $row = mysql_fetch_assoc($result);
  $add = $row['rating_total'];
  $average = $add / $totalvotes;

  echo '' .round($average, 2). '	';
  echo '
';

  $linecount++;
}

echo '
';
echo "
";
?>

I just wondered if there was a much better way to go about doing this?
I am a complete noob when it come to php so if you provide any advice could you please provide evidence/documentation so that I can read up on it and learn.


texts:
I decided to write a function divisorSum that sums the divisors of number. For instance 1, 2, 3 and 6 divide 6 evenly so:

$$ \sigma(6) = 1 + 2 + 3 + 6= 12 $$

I decided to use Euler's recurrence relation to calculate the sum of divisors:

$$\sigma(n) = \sigma(n-1) + \sigma(n-2) - \sigma(n-5) - \sigma(n-7) + \sigma(n-12) +\sigma(n-15) + \ldots$$

i.e.

$$\sigma(n) = \sum_{i\in \mathbb Z_0} (-1)^{i+1}\left( \sigma\left(n - \tfrac{3i^2-i}{2}\right) + \delta\left(n,\tfrac{3i^2-i}{2}\right)n \right)$$

(See here for the details). As such, I decided to export some other useful functions like nthPentagonal which returns the nth (generalized) pentagonal number. I created a new project with stack new and modified these two files:

src/Lib.hs

module Lib
    ( nthPentagonal,
      pentagonals,
      divisorSum,
    ) where

-- | Creates a [generalized pentagonal integer]
-- | (https://en.wikipedia.org/wiki/Pentagonal_number_theorem) integer.
nthPentagonal :: Integer -> Integer
nthPentagonal n = n * (3 * n - 1) `div` 2

-- | Creates a lazy list of all the pentagonal numbers.
pentagonals :: [Integer]
pentagonals = map nthPentagonal integerStream

-- | Provides a stream for representing a bijection from naturals to integers
-- | i.e. [1, -1, 2, -2, ... ].
integerStream :: [Integer]
integerStream = map integerOrdering [1 .. ]
    where
    integerOrdering :: Integer -> Integer
    integerOrdering n
        | n `rem` 2 == 0 = (n `div` 2) * (-1)
        | otherwise = (n `div` 2) + 1

-- | Using Euler's formula for the divisor function, we see that each summand
-- | alternates between two positive and two negative. This provides a stream
-- | of 1 1 -1 -1 1 1 ... to utilze in assiting this property.
additiveStream :: [Integer]
additiveStream = map summandSign [0 .. ]
    where
    summandSign :: Integer -> Integer
    summandSign n
        | n `rem` 4 >= 2 = -1
        | otherwise = 1

-- | Kronkecker delta, return 0 if the integers are not the same, otherwise,
-- | return the value of the integer.
delta :: Integer -> Integer -> Integer
delta n i
    | n == i = n
    | otherwise = 0

-- | Calculate the sum of the divisors.
-- | Utilizes Euler's recurrence formula:
-- | $\sigma(n) = \sigma(n - 1) + \sigma(n - 2) - \sigma(n - 5) \ldots $
-- | See [here](https://math.stackexchange.com/a/22744/15140) for more informa-
-- | tion.
divisorSum :: Integer -> Integer
divisorSum n
    | n <= 0 = 0
    | otherwise = sum $ takeWhile (/= 0)
                                  (zipWith (+)
                                           (divisorStream n)
                                           (markPentagonal n))
    where
    pentDual :: Integer -> [Integer]
    pentDual n = [ n - x | x <- pentagonals]
    divisorStream :: Integer -> [Integer]
    divisorStream n = zipWith (*)
                              (map divisorSum (pentDual n))
                              additiveStream
    markPentagonal :: Integer -> [Integer]
    markPentagonal n = zipWith (*)
                               (zipWith (delta)
                                        pentagonals
                                        (repeat n))
                               additiveStream

app/Main.hs (mostly just to "test" it.)

module Main where

import Lib

main :: IO ()
main = putStrLn $ show $ divisorSum 8


texts:
This code adds the toggle functionality for mobile devices. So, for width lower than 990px, the panel collapses, and the user can toggle to open / close it.

angular.module('app')
.directive('ngContentToggle', function($window) {

    return {
        link: function(scope, $element){
            var w = angular.element($window, $element);

            scope.toggleClass = function(){
                if($window.outerWidth < 990) {
                    $element.addClass('slide-content');
                }
                else {
                    $element.removeClass('slide-content');
                }
            };

            w.bind('resize load', function(){
               scope.toggleClass();
            });

            $element.bind('click', function(){
                if($element.hasClass('slide-content')){
                    if(($element).next().height > 0) {
                        $element.next().toggleClass('slide-content-open');
                    }
                    else {
                        $element.next().toggleClass('slide-content-open');
                    }
                }
            });
        }
    };
});


texts:
What I am trying to do is to find count of alternating numbers such that it alternates with -ve and positive sign for e.g.: 1 -2 3 -4 would get me 4 3 2 1 as from 1 to -4 including the two numbers there are 4 numbers. Similarly, for 1 1 -3 2 would get me 1 3 2 1. Now I have the code but I cannot optimise it and it returns me a time limit exceeded error even though it works for moderate input stream.

Here, alternating means like first number is positive and second number is negative and next number is positive and so on. So if input is 1 -2 3 -4 then from number 1 maximum I can travel to -4 such that there is an alternating sequence. So the count =3 numbers + the number itself i.e 4. Again from -2 if I travel from I can go till -4 as it alternates from negative positive and negative. So it is 2 numbers +1=3 again. Similarly, for r=each position I get it as 4 3 2 1. Now suppose number is 1 1 -3 2 then there is no number for 1 to find the next alternating number immediately so 1.

So for 1 1 -3 2 for 1 since there is no immediate -ve number it is a 1.For the second 1 I can traverse to a -3 and 2 i.e 2 number so count=2+1=3.For -3 all I find is a single 2 so count is 1+1=2.For the last number it is 1.So the answer is 1 3 2 1

Sample input: 1 -2 1 -3 2

Output: 4 3 2 1

j=0
count=0
length=(raw_input())
st=map(int,raw_input().split())
while j+1 < len(st):
     k=j+1
     count=0
     temp=j
     while k<len(st) and ((st[k]<0 and st[j]>0) or (st[k]>0 and st[j]<0)):
       count+=1
       k+=1
       j+=1
     print count+1,
     j=temp+1
print 1