texts:
I decided to do Advent of Code this year in D, and the following is my solution to day 8.

Algorithm aside, I was specifically wondering if there was a better way to use ranges in a recursive manner here. I feel like I should be able to do write the functions in a more generic way (not just int[], avoiding the .array in main), and without destroying the original array in the process - avoiding the temporary variable p1.

My use of the header variable seems suspect to me as well - basically I want a popFront that returns a value, I think, but have been unable to find anything like that.

I'm also happy to hear general advice about usual best practices and efficiencies.

import std.algorithm;
import std.conv;
import std.file;
import std.range;
import std.stdio;
import std.string;

int count_metadata(ref int[] r)
{
    auto header = r.take(2);
    int num_child = header.front;
    int num_metadata = header.back;
    r = r.drop(2);
    int count;
    for (int i; i < num_child; i++) {
        count += r.count_metadata;
    }
    count += r.take(num_metadata).sum;
    r = r.drop(num_metadata);
    return count;
}

int node_value(ref int[] r)
{
    auto header = r.take(2);
    int num_child = header.front;
    int num_metadata = header.back;
    r = r.drop(2);
    int[] child_values;
    for (int i; i < num_child; i++) {
        child_values ~= node_value(r);
    }
    int count;
    if (num_child == 0) {
        count = r.take(num_metadata).sum;
    } else {
        // ignore out of range
        count = r.take(num_metadata).filter!(a => 0 < a && a <= child_values.length).map!(a => child_values[a - 1]).sum;
    }
    r = r.drop(num_metadata);
    return count;
}

void main(string[] args)
{
    // integers separated by spaces
    auto input = readText(args[1]).split.map!(a => to!int(a)).array;
    //auto input = [2, 3, 0, 3, 10, 11, 12, 1, 1, 0, 1, 99, 2, 1, 1, 2];
    auto p1 = input.dup;
    writeln("Metadata total: ", count_metadata(p1));
    writeln("Node value: ", node_value(input));
}

(args[1] is a file with integers separated by spaces, sample input is commented out below it.)


texts: Using default None values in Python when assigning split() to a tuple

texts:
Let's say I want to parse audio track information into two variables like this:

'2/15' -> track = 2, num_tracks = 15
'7' -> track = 7, num_tracks = None

What's an elegant way to do this in Python? For example:

track, num_tracks = track_info.split('/')

This works for the first format, but not for the second, raising ValueError: need more than 1 value to unpack. So I came up with this:

try:
    track, num_tracks = track_info.split('/', 1)
except:
    track, num_tracks = track_info, None

How can this be more elegant or better?


texts: Product of all ints in array besides that an index i

texts:
I'm looking for a better implementation of the algorithm.

/*
 * You have an ordered array X of n integers. Find the array M containing
 * elements where Mi is the product of all integers in X except for Xi.
 * You may not use division. You can use extra memory.
 */

#include <iostream>
#include <stack>
#include <queue>
#include <vector>

/*!
 * Class used to generate sequences with helper function
 */
template <class T>
class sequence : public std::iterator<std::forward_iterator_tag, T>
{
    T val;
public:
    sequence(T init) : val(init) {}
    T operator *() { return val; }
    sequence &operator++() { ++val; return *this; }
    bool operator!=(sequence const &other) { return val != other.val; }
};

template <class T>
sequence<T> gen_seq(T const &val) {
    return sequence<T>(val);
}

static const int N = 3;
std::stack<int> stk;
std::queue<int> que;
int main(int argc, char *argv[]) {
  std::vector<int> seq(gen_seq(1), gen_seq(N + 1));
  for (int x = 0, y = N - 1; x < N && y >= 0; ++x, --y) {
    if (x == 0 && y == N - 1) {
      stk.push(1);
      que.push(1);
    } else {
      stk.push(stk.top() * seq[x - 1]);
      que.push(que.back() * seq[y + 1]);
    }
  }
  for (int x = 0; x < N; ++x) {
    std::cout << (stk.top() * que.front()) << std::endl;
    stk.pop();
    que.pop();
  }
}


texts: Get username from active directory if you know active directory Id in SharePoint

texts:
I have created JavaScript code using REST API for getting the username of a SharePoint user from an active directory if you know the ID. Please suggest any improvements.

// get user name from id
function getUserFromId(userid) {

// var userid = _spPageContextInfo.userId;
   var requestUri = _spPageContextInfo.webAbsoluteUrl + “/_api/web/getuserbyid(” + userid + “)”;
   var requestHeaders = {
      “accept”: “application/json;odata=verbose”
   };
   $.ajax({
      url: requestUri,
      async: false,
      contentType: “application/json;odata=verbose”,
      headers: requestHeaders,
      success: onSuccess,
      error: onError
  });

   function onSuccess(data, request) {
      var Logg = data.d;
      userLoginName = Logg.Title;
   }

   function onError(error) {
      alert(“error”);
   }
   return userLoginName;
}


texts: Retrieving doubles from string - simple problem

texts:
The problem is not very complicated (I mean it is easy to solve it), but the question is how to make it in the easiest way (Java)

Input String:

String inputString = "[value=20][param=304.2][indicator=1500]";

Expected output: array of doubles : [20.0][304.2][1500.0]

Sample solution:

String[] chunks = inputString.split("=");
String valueStr = chunks[1].substring(0, chunks[1].indexOf(']'));
String paramStr = chunks[2].substring(0, chunks[2].indexOf(']'));
String indicatorStr = chunks[3].substring(0, chunks[3].indexOf(']'));
// parsing by Double.parseDouble forming an array and returning it as a result.

What other (smarter) way would you propose using Java?


texts:
I am creating a string extension to validate some input.

My scenario is when we have a string it will format it according to following guideline.
If the sample string is “One Two Three Four Five” and the length is <=20 return same. If more than 20 then “One Two Three F Five”. If still length is more than 20 the “One Two T  F Five” etc...

Is there any way I can improve this code? I thought it can use recursion?

public static string ToShortName(this string name)
        {
            if (name.Length <= 20) return name;

            var namelist = name.Split(' ');

            var length = name.Length;

            //add spaces
            length = length + namelist.Count() - 1;

            var output = "";
            var indexList = new List<int>();
            for (var i = namelist.Count() - 2; i >=1 ; i--)
            {
                indexList.Add(i);
                if (length - namelist[i].Length <= 20)
                {
                    break;
                }
                length = length - namelist[i].Length;
            }

            foreach (var i in indexList)
            {
                namelist[i] = namelist[i].Substring(0, 1);
            }
            output = string.Join(" ", namelist);

            return output;
        }


texts: optimize nested for loops within nested if statements

texts:
I am trying to optimize this code. The only optimization I can think of is to ?¿? a return or break statement after applyOfferChanges(…) inside the second if condition which does not work either because there could be multiple matches. I cannot either use a map for favoriteMerchantsList because getFavoriteMerchantsList() return type is a list (of favorited merchants). Any ideas?

void applyFavoriteChangesToMerchantStore(){

    List<Merchant> favoriteMerchantsList = FavoriteMerchantStore.getInstance().getFavoriteMerchantsList();
    if(favoriteMerchantsList != null && !favoriteMerchantsList.isEmpty()) {
        List<Merchant> storeMerchantList = MerchantStore.getInstance().getMerchantList();
        for (Merchant storeMerchant : storeMerchantList) {
            for (Merchant favoriteMerchant: favoriteMerchantsList){
                if(TextUtils.equals(storeMerchant.getId(), favoriteMerchant.getId())){
                    //merchant match found
                    //set merchant favorite status

                   storeMerchant.setFavoriteMerchant(favoriteMerchant.getFavoriteMerchant());
                    //set offer favorite status
                    applyOfferChanges(favoriteMerchant.getOffferList(),
                            storeMerchant.getOffferList());
                }
            }
        }
    }
}


texts:
I am working again and got this to work. Is this the best way to write this code?

$(window).load(function(){
var $window = $(window),
$sticky = $('#contentSideIner'),
elTop = $sticky.offset().top;

$window.scroll(function() {
$sticky.toggleClass('sticky', $window.scrollTop() > elTop);
});
$window.scroll(function() {
$sticky.toggleClass('stickyBottom', $window.scrollTop() > elTop + 4685);
});
});

I had such a hard time to get this function to work in the first place. For the longest time I was told it was not executing at all.


texts: Counting subscribers with matching ZIP code, interests, and sex

texts:
I am trying to cycle through a few of these blocks. They basically narrow down a number of people that fulfill a bunch of attributes.

I apologize if this seems really messy, but my database is really taking a toll processing this, and I know there's a better way. I'm just lost on strategy right now.

def count_of_distribution
  #beginning with an array..
  array_of_users = []

  # any matching zip codes? ..
  # zip_codes
  @zip_codes = self.distributions.map(&:zip_code).compact
  unless @zip_codes.nil? || @zip_codes.empty?
    @matched_zips = CardSignup.all.map(&:zip_code) & @zip_codes
    @matched_zips.each do |mz|
      CardSignup.find(:all, :conditions => ["zip_code = ?", mz]).each do |cs|
        array_of_users << cs.id
      end
    end
  end

  # any matching interests?..
  # interest
  @topics = self.distributions.map(&:me_topic).compact
  unless  @topics.nil? || @topics.empty?
    @matched_topics = MeTopic.all.map(&:name) & @topics
    @matched_topics.each do |mt|
      MeTopic.find(:all, :conditions => ["name = ?", mt]).each do |mt2|
        mt2.users.each do |u|
          array_of_users << u.card_signup.id if u.card_signup
        end
      end
    end
  end

  # any matching sexes?..
  # sex
  @sexes = self.distributions.map(&:sex).compact
  unless @sexes.nil? || @sexes.empty?
    @matched_sexes = CardSignup.all.map(&:sex) & @sexes
    @matched_sexes.each do |ms|
      CardSignup.find(:all, :conditions => ["sex = ?", ms]).each do |cs|
        array_of_users << cs.id
      end
    end
  end

  total_number = array_of_users.compact.uniq

  return total_number
end


texts: Bash script to extract wifi passwords from NetworkManager

texts:
This is my first shell script, so I am trying to see if I can get some suggestions. It extracts saved wifi passwords from Linux.

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

# This script is used to copy wifi password files from /etc/NetworkManager/system-connections folder

# check if the wifi_pass_dir exists, and delete it if it does
if [ -d "wifi_pass_dir" ]
then
    rm -rf wifi_pass_dir
fi

# Create wifi_pass_dir folder
mkdir wifi_pass_dir

#copy the files from NetworkManager to the folder created, these files can only be read by the root user so use sudo
sudo cp /etc/NetworkManager/system-connections/* ./wifi_pass_dir

# change the file permission from read only by root to read and write by any user (666)
sudo chmod 666 ./wifi_pass_dir/*

#create a list so we know what wifi passwords are saved
sudo ls /etc/NetworkManager/system-connections > ./wifi_pass_dir/pass_list.txt

# Read name of wifi from pass_list.txt and print on screen
cd wifi_pass_dir
filename="pass_list.txt"

while read -r line
do
    name="$line"
    echo $name
    cat "$name" | grep psk=
done < "$filename"
##################################################################


texts:
Can I reduce the loop inside my method with map or is there a shorter implementation of this code that's dropping elements in sequence?

// Method that drops one element in sequence
def drop_Val_In_List[String](ls: Seq[String], value: String):  Seq[String] = {
    val index = ls.indexOf(value)  //index is -1 if there is no matc
    if (index < 0) {
        ls
    } else if (index == 0) {
        ls.tail
    } else {
        // splitAt keeps the matching element in the second group
        val (a, b) = ls.splitAt(index)
        a ++ b.tail
    }
}

val KeepCols = Seq("id", "type", "month", "car", "road")

// Generalization of the above method to drop multiple elements
def drop_Val_List_In_List[String](ls: Seq[String], in_ls: Seq[String]): Seq[String] = {
    var tmp_ = ls
    //println(tmp.getClass)
    for(x <- in_ls ){ // should work without var x
        tmp_ = drop_Val_In_List(tmp_, x)
    }
    tmp_;
}

val tmp = drop_Val_List_In_List(KeepCols, List("id", "type", "month"))
```


texts: Extracting and normalizing URLs in an HTML document

texts:
I have written code to get all urls on a webpage & put them in a set, and would like tips on simple changes I can make to increase its performance.

soup = BeautifulSoup(html_doc)
for link in soup.find_all('a'):
    url = link.get('href')
    if url is None or ' ' in url or '<' in url or '>' in url:
        continue
    if url.startswith('//'):
        url = url.replace('//', 'http://')
    if url.startswith('/'):
        url = hostname + url
    if '?' in url:
        url = url.split('?')[0]
    if '#' in url:
        url = url.split('#')[0]
    if url.endswith('/'):
        url = url[:-1]
    if url.endswith(excluded_extensions):
        continue
    if url.startswith(hostname):
        urls_set.add(url)


texts:
Following is based on a problem description from a Codility test, as a task in an interview.

DeepestPit - problem description

A non-empty zero-indexed array B consisting of M integers is given. A pit in this array is any triplet of integers (X, Y, Z) such that:

0 ≤ X < Y < Z < M
sequence [B[X], B[X+1], ..., B[Y]] is strictly decreasing, i.e. B[X] > B[X+1] > ... > B[Y]
sequence  B[Y], B[Y+1], ..., B[Z] is strictly increasing, i.e. B[Y] < B[Y+1] < ... < B[Z]

The depth of a pit (X, Y, Z) is the number min{B[X] − B[Y], B[Z] − B[Y]}.

For example, consider array B consisting of 10 elements such that:

B[0] = 0
B[1] = 2
B[2] = 7
B[3] = -4
B[4] = 0
B[5] = 4
B[6] = 0
B[7] = -6
B[8] = 4
B[9] = 6

Triplet (2, 3, 4) is one of pits in this array, because sequence [B[2], B[3]] is strictly decreasing (7 > −4) and sequence [B[3], B[4]] is strictly increasing (−4 < 0). Its depth is min{B[2] − B[3], B[4] − B[3]} = 4. Triplet (2, 3, 5) is another pit with depth 8. Triplet (5, 7, 8) is yet another pit with depth 10. There is no pit in this array deeper (i.e. having depth greater) than 10.

Write a function:

function deepest_pit(B)

that, given a non-empty zero-indexed array B consisting of M integers, returns the depth of the deepest pit in array B. The function should return −1 if there are no pits in array B.

For example, for the above array B, the function should return 10, as explained above.

Write an efficient algorithm for the function.

Assume that:

  M is an integer within the range [1..1,000,000];
  each element of array B is an integer within the range
  [−100,000,000..100,000,000].

(A previous test instead stated the complexity conditions as follows.)
Complexity:

·         expected worst-case time complexity is O(M);·         expected worst-case space complexity is O(M), beyond input storage (not counting the storage required for input arguments).

My solution, as follows, gets a task score of 100% (100% for correctness and 100% for performance). (A previous version only got 26%, with 44% correctness and 0% performance.)

function deepest_pit(B) {
    // write your code in JavaScript (Node.js 8.9.4)

    var M = B.length,
        depth = -1;

    if (M < 3) {
        return depth;
    }

    var X, Y, Z;
    var i = 0, j, k;

    while (i < M - 2) {
        X = B[i];
        // console.log("i = ", i, "X = ", X)
        j = i + 1;
        while (B[j] < B[j - 1] && j < M - 1) {
            j++;
        }
        if (j === i + 1) {
            i++;
            continue;
        }
        j = j - 1;
        Y = B[j];
        // console.log("i = ", i, "Y = ", Y)
        k = j + 1;
        while (B[k] > B[k - 1] && k < M) {
            k++;
        }
        if (k === j + 1) {
            i++;
            continue;
        }
        k = k - 1;
        Z = B[k];
        depth = Math.max(depth, Math.min(p - Y, Z - Y));
        // console.log("depth is", depth)
        i++;
    }

    return depth;
}

JSFiddle with the above code, plus tests.


texts:
The calculator evaluates a mathematical expression with binary operators +, -, *, / and ^ in C. I store numbers and operators into two different arrays and process them according to precedence.

Please review my code and suggest me on changes on approaches to make it scalable to add unary operators and parenthesis.

#include <stdio.h>
#include <math.h>

double evaluate (char []);
int precedence(char);
double calculate(char , double , double );
char checknumber(char);

int main(void)
{
    char expression[100];
    double result;

    printf("Enter the Expression: "); scanf("%[^\n]", expression);
    result = evaluate(expression);
    printf("Result = %lf\n", result);
    return 0;
}

double evaluate(char expr[])
{
    double numbers[5]; int nsi = 0;
    char operators[5]; int osi = 0;
    char numbuf[16]; int nbi = 0;
    char ch; int  i = 0;

    while ((ch = expr[i]) != 0) {
        if (checknumber(ch))
        {
            numbuf[nbi++] = ch;
            if (!checknumber(expr[i + 1]))
            {
                numbuf[nbi] = 0; nbi = 0;
                sscanf(numbuf, "%lf", &numbers[nsi++]);
            }
        }
        else
        {
            while ((osi > 0) && (precedence(ch) <= precedence(operators[osi - 1])))
            {
                numbers[nsi - 2] = calculate(operators[osi - 1], numbers[nsi - 2], numbers[nsi - 1]);
                osi--; nsi--;
            }
            operators[osi++] = ch;
        }
        i++;
    }
    while (osi > 0) {
        numbers[nsi - 2] = calculate(operators[osi - 1], numbers[nsi - 2], numbers[nsi - 1]);
        osi--; nsi--;
    }
    return numbers[0];
}

char checknumber(char ch)
{
    if ((ch >= '0' && ch <= '9') || ch == '.') return 1; else return 0;
}
int precedence(char ch)
{
    int precedence;
    switch (ch)
    {
    case '+':
    case '-':
        precedence = 0;
        break;
    case '*':
    case '/':
        precedence = 1;
        break;
    case '^':
        precedence = 2;
    }
    return precedence;
}

double calculate(char moperator, double num1, double num2)
{
    double result;
    switch (moperator)
    {
    case '+':
        result = num1 + num2;
        break;
    case '-':
        result = num1 - num2;
        break;
    case '*':
        result = num1 * num2;
        break;
    case '/':
        result = num1 / num2;
        break;
    case '^':
        result = pow(num1, num2);
        break;
    default:
        printf("Invalid Operator\n");
        exit(-1);
    }
    return result;
}


texts: Transactionally create something, if allowed

texts:
I have been looking over this block of code for hours trying to simplify it. Would there be a better way to check all those conditions before creating a transaction object without using so many if-elses?

def create(self, validated_data):

    user = self.context['request'].user
    if user.role == 'super_admin':  # ref PR 25.1
        return Transaction.objects.create(**validated_data)
    elif user.role == 'user' or user.role == 'org_admin' or user.role == 'site_admin':  # ref PR 25.4
        if check_user_institution_exists(validated_data['user_institution'].id):
            if check_user_belongs_to_institution(validated_data['user_institution'].id, None, user.id) > 0:
                if check_upload_permission(validated_data['user_institution'].id):
                    return Transaction.objects.create(**validated_data)
                else:
                    raise serializers.ValidationError({'Error': 'You do not have upload permission for this '
                                                                'institution.'})
            else:
                raise serializers.ValidationError({'Error': 'You do not belong to this institution.'})
        else:
            raise serializers.ValidationError({'Error': 'This user institution does not exist.'})
    else:
        raise serializers.ValidationError({'Error': 'You are not assigned a role.'})


texts:
I came up with the following solution for rotating an NxN matrix 90 degrees clockwise, to solve this CodeEval challenge:

  Input

  The first argument is a file that contains 2D N×N matrices (where 1 <= N <= 10), presented in a serialized form (starting from the upper-left element), one matrix per line. The elements of a matrix are separated by spaces.

  For example:

a b c d e f g h i j k l m n o p

  Output

  Print to stdout matrices rotated 90° clockwise in a serialized form (same as in the input sample).

  For example:

m i e a n j f b o k g c p l h d

It looks elegant to me, but can someone explain how its performance compares to the more common solutions mentioned here? Does it have \$O(n^2)\$ time complexity?

import sys, math

for line in open(sys.argv[1]):
    original = line.rstrip().replace(' ', '')
    nSquared = len(original)
    n = int(math.sqrt(nSquared))
    output = ''

    for i in range(nSquared):
        index = n * (n - 1 - i % n) + int(i / n)
        output += original[index] + ' '

    print(output.rstrip())

The expression n * (n - 1 - i % n) + int(i / n) is something I found while observing common patterns among rotated matrices.


texts: Selecting elements from the DOM of a page

texts:
To get the book list from https://www.java67.com/2015/09/top-10-algorithm-books-every-programmer-read-learn.html , I am using the following code in the console of the firefox DevTools:
var select =  document.querySelectorAll("div.post-body.entry-content div h3 b");

for (i = 0; i < select.length; ++i) {

  try {
    var title =  select[i].querySelectorAll("u")[0];
    console.log (title.innerHTML);
  }
  catch(err) {
  }

  try {
    var author =  select[i].querySelectorAll("a")[0];
    console.log (author.innerHTML);
  }
  catch(err) {
  }

}

The output is:
Introduction to Algorithms by Thomas H. Corman debugger eval code:12:13
Algorithms by Robert Sedgewick &amp; Kevin Wayne debugger eval code:12:13
The Algorithm Design Manual by Steve S. Skiena debugger eval code:12:13
Algorithm for Interviews debugger eval code:12:13
5. Algorithm in Nutshell debugger eval code:5:13
6. Algorithm Design by Kleinberg &amp; Tardos debugger eval code:5:13
7. Introduction to Algorithms: A Creative Approach debugger eval code:5:13
7. Introduction to Algorithms: A Creative Approach debugger eval code:12:13
8. The Design and Analysis of Algorithms debugger eval code:5:13
9. Data Structures and Algorithms. Aho, Ullman &amp; Hopcroft debugger eval code:5:13
10. Python Algorithms: Mastering Basic Algorithms in the Python Language debugger eval code:5:13
undefined

You can see from the code that the first part div.post-body.entry-content div h3 b is same. Then I am using u or a. Is there any easier way to achieve this.


texts: Constructor function for persons with hobbies

texts:
I'm trying to write a constructor function that generates instances of a user. One of the properties of the user class is an array of the user's hobbies. I'd like my constructor to have a method that generates a string representation of the array of hobbies provided to the constructor function. The goal is to create a grammatically correct sentence containing the hobbies of the Person instance, so if interests = ['hiking', 'biking', 'skiing'] the Person.bio() method will alert something like: This person's interests are: hiking, biking and skiing. I am trying to account for an array of unknown length being passed to the constructor.

I haven't used .reduce() much but from the little bit of testing I've done, this seems to do what I want it to do. I'm just looking for any critiques on how to make things more readable or performant!

Below is a stripped down version of the constructor function (missing things like name, age, etc. for clarity).

function Person(interests = []) {
  this.interests = interests;
  this.hobbiesSentence = interests.reduce((hobbyString, hobby, index, interests) => {
    switch(index) {
      case (interests.length - 1):
        return hobbyString += `${hobby}.`
      case (interests.length - 2):
        return hobbyString += `${hobby} and `
      default:
        return hobbyString += `${hobby}, `
    }
  }, '');

  this.bio = function () {
    alert(`This person's interests are: ${this.hobbiesSentence}`)
  };
}

As I'm writing this, I could see a case for making the function exist but not necessarily creating/storing the sentence unless the bio() method is called. Any other ideas? Thanks in advance.


texts:
Instead of writing HtmlAgilityPack document code over and over, I've decided to create a helper class for HtmlAgilityPack that prevents me that problem and adds a dispose feature for HtmlDocuments.

What can I do better?

public class HtmlParser
{
    private ArrayList Documents { get; set; }

    public HtmlParser()
    {
        Documents = new ArrayList();
    }

    ~HtmlParser()
    {
        Dispose();
    }

    public string ParseNode(string page, string xPath, ParseType type, string attributes = null)
    {
        int index = Documents.Add(new HtmlDocument());
        ((HtmlDocument)Documents[index]).LoadHtml(page);
        HtmlNode node = ((HtmlDocument)Documents[index]).DocumentNode.SelectSingleNode(xPath);
        if (null != node) return type == ParseType.InnerHtml ? node.InnerHtml : type == ParseType.OuterHtml ? node.OuterHtml : type == ParseType.InnerText ? node.InnerText : node.Attributes[attributes].Value;
        return null;
    }

    public HtmlNode GetNode(string page, string xPath)
    {
        int index = Documents.Add(new HtmlDocument());
        ((HtmlDocument)Documents[index]).LoadHtml(page);
        return ((HtmlDocument) Documents[index]).DocumentNode.SelectSingleNode(xPath);
    }

    public HtmlNodeCollection GetNodes(string page, string xPath)
    {
        int index = Documents.Add(new HtmlDocument());
        ((HtmlDocument)Documents[index]).LoadHtml(page);
        return ((HtmlDocument)Documents[index]).DocumentNode.SelectNodes(xPath);
    }

    public void Dispose()
    {
        if (null != Documents)
            Documents.Clear();
        Documents = null;
        GC.Collect();
    }
}

public enum ParseType
{
    InnerHtml,
    OuterHtml,
    InnerText,
    Attribute
}


texts:
HTML

Where data-parent points to the data-id of another row.

JQUERY/JS

$("tr[data-parent='" + id + "']").css("background-color", "#1ba1e2").each(function () {
    $("tr[data-parent='" + $(this).attr("data-id") + "']").css("background-color", "#75F7FF").each(function () {
        $("tr[data-parent='" + $(this).attr("data-id") + "']").css("background-color", "#98E8E3").each(function () {
            $("tr[data-parent='" + $(this).attr("data-id") + "']").css("background-color", "#B6DCE8")
    });});});

(I know that I could have written a recursive function as well, that's not the point right now)

When someone mouse-overs a TR, I want that row to be one color, all the rows that has the hovered row as parent, another color, the grandchildren another color etc (for several levels deep).

Now, for 100 rows, this isn't a problem, but my data contains around 30 000 rows, and that's where it starts to go wrong, several-seconds-of-freezing-wrong.

How can I optimise this code?

jsFiddle


texts: Converting a hexadecimal string to a binary string using Rust pattern matching lookup

texts:
I am getting started in Rust, and as a part of my first exercise, I decided to write a small program that converts a hexadecimal string to a binary string using a pattern matched lookup. I would appreciate a constructive review.

fn main() {
    let binary_value = convert_to_binary_from_hex("0x39A7F8");
    println!("Converted: {}", binary_value);
}

fn convert_to_binary_from_hex(hex: &str) -> String {
   let to_binary = hex[2 ..]
       .chars()
       .map(|c| to_binary(c))
       .collect();

   to_binary
}

fn to_binary(c: char) -> String {
    let b = match c {
       '0' => "0000",
       '1' => "0001",
       '2' => "0010",
       '3' => "0011",
       '4' => "0100",
       '5' => "0101",
       '6' => "0110",
       '7' => "0111",
       '8' => "1000",
       '9' => "1001",
       'A' => "1010",
       'B' => "1011",
       'C' => "1100",
       'D' => "1101",
       'E' => "1110",
       'F' => "1111",
        _  => "",
    };

   b.to_string()
}


texts: Ensure instance of class is initialized before using

texts:
I'm beginning to work with VBA class modules more in Excel and want to make sure that no properties can be used if the class hasn't been initialized. Below is the class and my attempt to at doing so.

Private Type helper
    Prop1 As Boolean
    Prop2 As Boolean
    Prop3 As String
    Prop4 As String
End Type

Private m_initialized As Boolean

Private this As helper

Public Sub Init(ByVal Prop1 As Boolean, ByVal Prop2 As Boolean, ByVal Prop3 As String, ByVal Prop4 As String)
    this.Prop1 = Prop1
    this.Prop2 = Prop2
    this.Prop3 = Prop3
    this.Prop4 = Prop4

    m_initialized = True
End Sub

Public Property Get Prop1() As Boolean
    If Not m_initialized Then ThrowNotInitializedError

    Prop1 = this.Prop1
End Property

Public Property Get Prop2() As Boolean
    If Not m_initialized Then ThrowNotInitializedError

    Prop2 = this.Prop2
End Property

Public Property Get Prop3() As String
    If Not m_initialized Then ThrowNotInitializedError

    Prop3 = this.Prop3
End Property

Public Property Get Prop4() As String
    If Not m_initialized Then ThrowNotInitializedError

    Prop4 = this.Prop4
End Property

Public Function Self() As Foo
    Set Self = Me
End Function

Private Sub ThrowNotInitializedError()
    Err.Raise 5, "Init() not run.", "Values weren't initially assigned. Make sure they are assigned before use"
End Sub

The repetition of If Not m_initialized Then ThrowNotInitializedError is the part that I don't like. I can already imagine myself forgetting to put it on a property. Are there any other options?

Testing in a standard module to make sure it worked as I expected

Sub TestingFooInitializeProtection()
    Dim properlyInitialized As Foo
    Set properlyInitialized = New Foo
    properlyInitialized.Init True, False, "Input3", "Input4"
    Debug.Print properlyInitialized.Prop1
    Debug.Print properlyInitialized.Prop2
    Debug.Print properlyInitialized.Prop3
    Debug.Print properlyInitialized.Prop4

    Dim improperlyInitialized As Foo
    Set improperlyInitialized = New Foo
    'improperlyInitialized.Init False, True, "input3", "input4"
    Debug.Print improperlyInitialized.Prop1 'If above line is left commented out error is thrown.
    Debug.Print improperlyInitialized.Prop2
    Debug.Print improperlyInitialized.Prop3
    Debug.Print improperlyInitialized.Prop4
End Sub


texts: LeetCode 952: Largest Component Size by Common Factor

texts:
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem

Given a non-empty array of unique positive integers A, consider the
following graph:

There are nums.length nodes, labeled nums[0] to nums[nums.length - 1];

There is an edge between nums[i] and nums[j] if and only if nums[i] and nums[j] share a common factor greater than 1.

Return the size of the largest connected component in the graph.

Example 1:

Input: [4,6,15,35]
Output: 4

Example 2:

Input: [20,50,9,63]
Output: 2

Example 3:

Input: [2,3,6,7,4,12,21,39]
Output: 8

Note:

\$1 <= nums.length <= 20000\$
\$1 <= nums[i] <= 100000\$

Inputs
[4,6,15,35]
[20,50,9,63]
[2,3,6,7,4,12,21,39]
[2,3,6,7,4,12,21,39,100,101,102,103,104,1200,123,123,13424]

Outputs
4
2
8
15

Code
#include <cstdint>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <cmath>

#define max(a, b) (a > b ? a : b) // std::max(a, b)

// Union Find
struct DisjointSets {
    DisjointSets(int_fast64_t n) : parent(n) {
        for (int_fast64_t index = 0; index < n; index++) {
            parent[index] = index;
        }
    }

    void union_ds(const int_fast64_t x, const int_fast64_t y) {
        parent[find_ds(x)] = parent[find_ds(y)];
    }

    const int_fast64_t find_ds(const int_fast64_t x) {
        if (parent[x] != x) {
            parent[x] = find_ds(parent[x]);
        }

        return parent[x];
    }

private:
    std::vector<int> parent;
};

struct Solution {
    static const size_t largestComponentSize(const std::vector<int> &nums) {
        const size_t max_nums = *std::max_element(nums.begin(), nums.end());
        DisjointSets union_find(max_nums + 1);

        for (const auto &num : nums) {
            for (size_t k = 2; k <= std::sqrt(num); k++) {
                if (num % k == 0) {
                    union_find.union_ds(num, k);
                    union_find.union_ds(num, num / k);
                }
            }
        }

        std::unordered_map<int, int> component_map;
        size_t largest_component = 1;

        for (const auto &num : nums) {
            size_t curr_component = ++component_map[union_find.find_ds(num)];
            largest_component = max(largest_component, curr_component);
        }

        return largest_component;
    }
};

References

Problem

Discuss

Solution

Union Find


texts: Calculating continued fraction expansions (without requiring arbitrary precision decimals)

texts:
I'm writing a program that will compute a continued fraction expansion of a number. I've been learning Racket/Scheme for a few weeks and I wanted to see what I can do better.

Usage: This program takes computes an arbitrary number of terms of the continued fraction of an algebraic number (the root of a polynomial with rational coefficients), starting only with an initial decimal approximation.

Example: To compute 100 terms of the continued fraction of the cube root of two, you would enter

(cfrac 100 #e1.2599 (poly -2 0 0 1))

The last argument is read "the polynomial with list of coefficients (-2 0 0 1)" (the polynomial \$x^3 - 2\$, which is the minimal polynomial of cube root of two.)

Remarks: There are some things I haven't gotten around to yet, for instance there is a bug when you try to compute the golden ratio (which should be trivial to fix, the problem is that this is c.fraction with all ones). Also, I will eventually extend this to numbers which are zeros of differentiable functions, like pi. Finally, the algorithm itself is documented very well in the paper Shiu, "Computation of continued fractions without input values".

Should I include comments for each step in the algorithm anyways? The main procedure is pretty big and it seems like it would be unreadable if you weren't already familiar with it.

#lang racket

(define poly list)
(define (sq x) (* x x))

; Evaluate a polynomial (a degree-ascending list of coefficients) using
; Horner's rule
(define (horner-eval x coeffs)
  (foldr (lambda (coeff h.o.t.)
           (+ coeff (* x h.o.t.)))
         0
         coeffs))

(define (deriv poly)
  (define (iter coeff li)
    (if (null? li)
        null
        (cons (* coeff (car li)) (iter (+ coeff 1) (cdr li)))))
  (iter 1 (cdr poly)))

; Returns a function which corresponds to polynomial evaluation
(define (polyfn poly)
  (lambda (x) (horner-eval x poly)))

; Given an *exact* number n, returns the sequence of terms in simple continued
; fraction expansion of n
(define (simple-c-frac n)
  (let ((int-part (floor n)))
    (cond ((= int-part n)
           (list n))
          (else
           (cons int-part
                 (simple-c-frac
                  (/ (- n int-part))))))))

; Given a sequence corresponding to a simple continued fraction, returns the
; rational number it equals
(define (eval-c-frac li)
  (if (null? (cdr li))
      (car li)
      (+ (car li)
         (/ 1 (eval-c-frac (cdr li))))))

; Computes cont. fraction expansion of an algebraic number given only a
; fixed number of decimals. Arguments: No. of terms, an initial approximation
; of the number (must be an exact type), and the polynomial that it satisfies
; (given as a list of coefficients in degree-ascending order).
(define (cfrac terms approx f)
  (define (iter li i x y prx pry)
    (define (next-quot x y pry)
      (let ((complete-quot
             (- (abs (/ ((polyfn (deriv f)) (/ x y))
                        (* (sq y)
                           ((polyfn f) (/ x y)))))
                (/ pry y))))
        (if (= (denominator complete-quot) 1)
            (- complete-quot 1)
            (floor complete-quot))))
    (let ((quot (next-quot x y pry)))
      (if (< i 0)
          li
          (iter (append li (list quot))
                (- i 1)
                (+ (* quot x) prx)
                (+ (* quot y) pry)
                x y))))
  (define (first2 li)
    (list (eval-c-frac (take li 1))
          (eval-c-frac (take li 2))))
  (let ((init (first2 (simple-c-frac approx))))
    (let ((prev (cadr init))
          (pprev (car init)))
      (append (list pprev)
              (list (/ (- prev pprev)))
              (iter null
                    (- terms 3)
                    (numerator prev)
                    (denominator prev)
                    (numerator pprev)
                    (denominator pprev))))))


texts: Project Euler #7: What is the 10,001st prime number?

texts:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13.

  What is the 10 001st prime number?

How can I make this more efficient and cleaner?

public class Problem7 {

    public static void main(String[] args) {
        // a prime factor is something that can divide by only 1 and itself evenly
        int counter = 0;
        int primeNum = 0;

        for (int num = 2; num < 10000000; num++) {
            boolean isPrime = true;
            for (int factor = 2; factor < num; factor++) {

                if (num % factor == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                primeNum = num;
                counter++;
            }
            if (counter == 10001) {
                break;
            }
        }
        System.out.println(primeNum);
    }
}


texts: Fastest way to cut an array into two arrays at a particular index

texts:
Suppose I have the array:

double[] arrayToCut = new double[100];
for(int i = 0 ; i < 100 ; ++i) {
    arrayToCut[i] = Math.random();
}

My objective is to end up with two arrays, firstArray and secondArray. firstArray is equal to (for example);

double[] firstArray = new double[50];
for(int i = 0 ; i < 50 ; ++i) {
    firstArray[i] = arrayToCut[i];
}

and secondArray is defined analogously (taking values from arrayToCut from 50 to 99 index).

However, this is linear time complexity and I want to cut gigantic arrays over 1 million in length. How can I speed up the above code (reduce computational overhead in any way for large arrays, whether by time complexity reduction or some other approach)?


texts:
I made a simple script to load other scripts into the page without worrying about caching. It's meant to be used by a considerable amount of people, so I would like it to be as clean as possible, and I would like your advice.

window.load_scripts = function () {
    var callbacks = {
        jqueryCallback: function (script_path) {
            $.getScript(script_path, function (data, textStatus, jqxhr) {
                if (jqxhr.status === 200) {
                    console.log(script_path + ' loaded correctly.');
                } else {
                    console.log(script_path + ' failed to load');
                }
            });
        },
        vanillaCallback: function (script_path) {
            var script = document.createElement('script');
            script.src = script_path + '?d=' + (new Date()).getTime();
            document.head.appendChild(script);
        }
    }
    var callback;
    //if we don't have arguments, just return.
    //no scripts have to be loaded
    if (!arguments || !arguments.length)
        return;

    //if we have jquery, we will use $.getScript
    callback = window.$ ? callbacks['jqueryCallback'] : callbacks['vanillaCallback'];

    //loop through all scripts
    for (let i = 0; i < arguments.length; i++) {
        var path = arguments[i];
        //just be sure that the argument is a string
        if (typeof path === "string") {
            callback(path);
        }
    }
}


texts: Copy an Entity With Navigation Property in C#

texts:
I have a table named Asset and each Asset has schedules. I create a method like this for copying an entity:

    public bool Copy(CopyAssetViewModel copyAssetViewModel,out string message)
    {
        var source = _equipments.AsNoTracking().FirstOrDefault(row => row.Id == copyAssetViewModel.AssetId);
        if (source == null) return false;
        int count = source.Schedules.Count;
        Asset newAsset = new Asset();
        Guid tempId = newAsset.Id;
        newAsset = source;
        newAsset.Id = tempId;
        newAsset.AssetCode = copyAssetViewModel.AssetCode;
        if (copyAssetViewModel.CopySchedules)
        {
            newAsset.Schedules = source.Schedules.ToList();
            newAsset.Schedules.ToList().ForEach(row =>
            {
                Schedule newSchedule = new Schedule();
                Guid scheduleId = newSchedule.Id;
                newSchedule = row;
                newSchedule.Id = scheduleId;
                newSchedule.AssetId = tempId;
            });
        }
        else
            newAsset.Schedules.Clear();
        _uow.MarkAsAdded(newAsset, _userManager.GetCurrentUserId());
        _uow.SaveChanges();
        return true;
    }

All entities inherit BaseEntity and I have a constructor for creating a new Id like this:

 public BaseEntity()
    {
        Id = SequentialGuidGenerator.NewSequentialGuid();
        CreatedOn = DateTime.Now;
    }

But when I use this code:

newAsset.Schedules = source.Schedules.ToList();

Id and createdOn are the same. I've gotten an error for a duplicate key. For solve this I used these lines:

 Schedule newSchedule = new Schedule();
                Guid scheduleId = newSchedule.Id;
                newSchedule = row;
                newSchedule.Id = scheduleId;

And I have another field that needs to update like: CreatedByUserId.

I think my code is very poor. Can everyone give me an idea to improve it?

copyAssetViewModel:

public class CopyAssetViewModel
{
    public Guid AssetId        { get; set; }
    public bool CopySchedules  { get; set; }
    public int AssetCode       { get; set; }
}


texts:
I'm new to Haskell, and am trying to learn the basics with a simple function that will calculate the list of primes up to a given value (using the Sieve of Eratosthenes). Here is my code so far, which has the problem of becoming very slow for large inputs nmax:

primes :: Integer -> [Integer]
primes nmax
  | nmax <= 2 = [2]
  | otherwise = sieve (2:[3,5..nmax])
  where
    sieve :: [Integer] -> [Integer]
    sieve [] = []
    sieve [a] = [a]
    sieve (p:xs) = p : sieve [multiple*p+offset | multiple <- [1..(last xs) `quot` p], offset <-[1..(p-1)], multiple*p+offset `elem` xs]

I am aware of this resource which gives implementations of Eratosthenes' Sieve, however, their methods are beyond me as I'm only just beginning. I'm also aware of this this question, but they have used entirely different methods again. I would like to know what it is about my code that is so inefficient.

Example timings:

primes 100 takes 0.01s and uses 0 bytes of RAM.
primes 1000 takes 0.41s and uses ~38.5MB of RAM.
primes 2000 takes 3.15s and uses ~153MB of RAM.

I suspect the problem lies in checking if multiple*p+offset is an element of the list xs, but I'm not sure how to circumvent this check.


texts: Selectively mapping one object to another

texts:
I'm taking an input object and returning a reduced and slightly changed object:

var source = {_a: 1, b:2 , c: 3}

function map(source) {
  return {a: source._a, b: source.b}
}

map(source) // > {a: 1, b: 2}

The key _a becomes a and c is dropped.

This works and is clear to read.

Now ES6 and ES7 is an option, I was wondering if there was another way to do it.

This is what I now have:

const source = {_a: 1, b:2 , c: 3}

const map = ({_a, b}) => ({a: _a, b})

map(source) // > {a: 1, b: 2}

The source object argument is destructed and combination of a new a key and object key shorthand is used to construct a return object.

Forgetting the ES6ness for a second, to compare more like-for-like:

var source = {_a: 1, b:2 , c: 3}

function map({_a, b}) {
  return ({a: _a, b})
}

map(source) // > {a: 1, b: 2}

How does the first object mapping compare to the last?


texts: C function delimiates strings using a single character array

texts:
I am a complete noob to C and I've shied away from using such a powerful language due to it's large learning curve and other complicated mechanisms. For my first minor project I plan to create a small HTTP client that requests for a webpage. Before I start, I need to create a function that can correctly parse a URL using the URI scheme. I devised this function to help me separate http from a host name like www.google.com by recognizing ://. Space and clock efficiency is are priorities of mine. I'm looking for any tips that would help someone who is new to C.

int delimiateString(const char *string, const char *delimiator) {
    const char *buffer;
    int x, len = strlen(delimiator);
    for (buffer = string; *buffer != '\0'; buffer++) {
        if (*delimiator == *buffer) {
            for (x = 1; x <= len; x++) {
                if (*(delimiator+x) == *(buffer+x)) {
                    if (x+1 == len) {
                        return (buffer - string);
                    }
                } else {
                    break;
                }
            }
        }
    }
    return strlen(string);
}


texts: Round-tripping from LinkedHashMaps to Clojure collections

texts:
I'm trying to implement round-tripping from LinkedHashMaps to Clojure collections. The implementation below works for smaller collections, but larger collections raise OutOfMemoryError: GC overhead limit exceeded. Below is a generative test that passes, when the number of tests is small (~10), but exhausts memory for larger numbers of tests (~100).

I would appreciate any tips how to reduce the memory requirements of the implementation as well as general tips on how to improve the code's quality.

(import '[clojure.lang IPersistentMap IPersistentVector]
        '[java.util ArrayList LinkedHashMap])

(defprotocol LinkedHashMappable
  "Convert Clojure data structure to LinkedHashMap."
  (->linked-hash-map [data]))

(extend-protocol LinkedHashMappable
  IPersistentMap
  (->linked-hash-map [m]
    (let [lhm (LinkedHashMap.)]
      (doseq [[k v] m]
        (.put lhm
              (if (keyword? k) (name k) k)
              (->linked-hash-map v)))
      lhm))

  IPersistentVector
  (->linked-hash-map [v]
    (let [alist (ArrayList.)]
      (doseq [i v] (.add alist (->linked-hash-map i)))
      alist))

  Object
  (->linked-hash-map [o] o))

(defprotocol Clojurizable
  "Convert LinkedHashMap to Clojure data structure."
  (->clj [lhm]))

(extend-protocol Clojurizable
  LinkedHashMap
  (->clj [lhm]
    (reduce (fn [m [k v]]
              (assoc m (keyword k) (->clj v)))
            {}
            (iterator-seq (.. lhm entrySet iterator))))

  ArrayList
  (->clj [alist]
    (mapv ->clj alist))

  Object
  (->clj [o] o))

; ----- Test -----

(require '[clojure.test.check :as tc]
         '[clojure.test.check.generators :as gen]
         '[clojure.test.check.properties :as prop])

(def map-generator
  (gen/recursive-gen (fn [inner]
                       (gen/map gen/keyword (gen/one-of [(gen/map gen/keyword inner)
                                                         (gen/vector inner)])))
                     gen/string))

(def linked-hash-map-round-tripping
  (prop/for-all [m map-generator]
                (= (->clj (->linked-hash-map m)) m)))

; The test passes for smaller numbers of tests (~10), but exhausts memory for larger numbers (~100).
#_(tc/quick-check 100 linked-hash-map-round-tripping)


texts:
The code reads an input with numbers and find the sum with the minimum difference of the first two big numbers. The sums are three.

Is there is any way to make the code cleaner? (Note that I don't need to take any restrictions such as NULL parameters, etc)

Moreover, there is an int in my program pA = -1 with that value. Now, because the pA used as pointer you see below that I have the statement ProfitA = array[pA];, that statement doesn't give any problems, but I just wanted to point it out in case you could clean my code a bit.

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

#define TRUE 1
#define FALSE 0
#define min(ProfitA, ProfitB, ProfitC) ProfitA > (ProfitB > ProfitC ? ProfitB : ProfitC) ? ProfitA : (ProfitB > ProfitC ? ProfitB : ProfitC)

int main() {

    FILE* input = fopen("share.in","r");
    int bestMin = INT_MAX;
    int N = 0;
    fscanf(input,"%d",&N);

    int *array = malloc(N * sizeof(int));

    int pA = -1, pB = N - 1;
    int ProfitA = 0, ProfitC = 0, ProfitB = 0;

    for (int i = 0; i < N; i++) {
        fscanf(input,"%d",&array[i]);
        ProfitB += array[i];

    }

    ProfitB = ProfitB - array[pA] - array[pB];
    ProfitA = array[pA];
    ProfitC = array[pB];

    fclose(input);

    short flag = TRUE;
    int check_L = 0, check_R = 0;

    while ((pB - pA != 1) && (flag == TRUE)) {
        flag = FALSE;

        check_L += ProfitA + array[pA + 1];
        check_R += ProfitC + array[pB - 1];

        if (check_L < check_R) {

            ProfitA = check_L;
            ProfitB -= array[pA + 1];
            pA++;
            flag = TRUE;

        }
        else {

            ProfitC = check_R;
            ProfitB -= array[pB - 1];
            pB--;
            flag = TRUE;
        }
      check_R = 0, check_L = 0;

        printf("k1 = %d, k3 = %d, k2 = %d\n",ProfitA,ProfitB,ProfitC);

           int  currentMin = min(ProfitA, ProfitB, ProfitC);

            if (currentMin < bestMin) {
                bestMin = currentMin;
            }

    }
    printf("%d\n",bestMin);

    return 0;
}


texts:
I have a program to read signal data from 120 files in a folder and performing the energy of the signal.

It works correctly, but execution time is more than 20 mins, so there may be a problem with the code.  Can someone look into it and suggest possible methods to reduce the execution time?

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

public class myclass {
  static int total = 1;
  static int r = 0;

  public static void main(String[] args) {

    ArrayList<Double> mysignal = new ArrayList<Double>();
    ArrayList<Double> mylist = new ArrayList<Double>();

    double x;
    double a;
    myclass obj = new myclass();
    String target_dir = "path for folder";
    File dir = new File(target_dir);
    File[] files = dir.listFiles();

    for (File f : files) {
      if (f.isFile()) {
        BufferedReader inputStream = null;

        try {
          inputStream = new BufferedReader(new FileReader(f));
          String line;

          while ((line = inputStream.readLine()) != null) {

            mysignal.add(Double.valueOf(line));
            total++;

          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        a = obj.funtioneg(mysignal, total);
        mylist.add(r, a);
        System.out.println(mylist.get(r));
        r++;

      }
    }
  }

  public double functioneg(ArrayList<Double> s, int N) {

    ArrayList<Double> y = new ArrayList<Double>();
    double sum = 0, a1 = 0;
    double[] o1 = new double[N - 1];// processed signal

    for (int n = 0; n < N - 1; n++) {
      for (int k = 0; k < 40; k++) {

        if (n - k >= 0) {
          a1 = s.get(n - k);
          sum = sum + (a1 * a1);// energy

        } else
          sum = sum + 0;
      }

      o1[n] = sum;

      sum = 0;

    }
    double sum1 = 0;
    double avg;
    for (int t = 0; t < N- 1; t++) {

      sum1 = sum1 + o1[t];
    }

    avg = sum1 / N - 1;

    return (avg);
  }
}


texts:
I've just been putting together an audio meter by stacking bootstrap progress bars, and thought there was probably a better way, mathematically / logically, of achieving this.

levels = (vumeter) ->
  green = if vumeter % 50 < vumeter then 50 else vumeter
  yellow = if vumeter % 85 < vumeter then 35 else vumeter - 50
  red = if vumeter % 100 < vumeter then 15 else vumeter - 85

  'green': green
  'yellow': yellow
  'red': red


texts: javascript - create an object containing objects based on JSON data

texts:
Based on JSON data I receive, I am trying to track a team's home and away games. The JSON data is stored in $scope.gameSchedules and has "team1" for home games and "team2" for away games. I need to initially create an object with each team's name and the only way I can get all the teams' names is via the "team1/team2" values in the initial JSON data (thus the two loops below). This was my working solution to create an object that looks like this (called homeVsAwayGames):

The initial JSON data response:

Here is my code. Is there a better way to do it, or more concise, perhaps using underscore (not necessary)? I feel that perhaps I have too many lines of code and it can be refactored:

 $scope.getSchedules = function() {
        return TeamsScheduleService.getTeamSchedules().then(function(response) {
            $scope.gamesSchedule = response.data.games;
        }, function(err) {
            console.log("there was an error getting the schedules");
        })
    }
    $scope.homeVsAwaySchedules = {};
    $scope.getSchedules().then(trackHomeVsAway).then(function(){
        console.log($scope.homeVsAwaySchedules);
    })
    //TODO: ng-repeat over the homeVsAwaySchedules Object to display in the view.

    function trackHomeVsAway() {
        //initialize homeVsAwaySchedules object in separate loop for efficiency and readability, instead of trying to initialize + tally at the same time.
        $scope.gamesSchedule.forEach(function(gameData) {
          var homeTeam = gameData.team1;
          var awayTeam = gameData.team2;
            if (homeTeam) {
                if (!$scope.homeVsAwaySchedules[homeTeam]) {
                    $scope.homeVsAwaySchedules[homeTeam] = {
                        "Home Games": 0,
                        "Away Games": 0
                    };
                }
            }
            if (awayTeam) {
                if (!$scope.homeVsAwaySchedules[awayTeam]) {
                    $scope.homeVsAwaySchedules[awayTeam] = {
                        "Home Games": 0,
                        "Away Games": 0
                    };
                }
            }
        })

        $scope.gamesSchedule.forEach(function(gameData) {
          var homeTeam = gameData.team1;
          var awayTeam = gameData.team2;
            if (homeTeam) {
                if ($scope.homeVsAwaySchedules[homeTeam]) {
                    $scope.homeVsAwaySchedules[homeTeam]["Home Games"]++;
                }
            }
            if (awayTeam) {
                if ($scope.homeVsAwaySchedules[awayTeam]) {
                    $scope.homeVsAwaySchedules[awayTeam]["Away Games"]++;
                }
            }
        })
    };
}


texts: Implementation of linear regression in Python

texts:
I wrote an implementation for multivariate linear regression in Python, for data in this link: http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv

My main focus is to avoid loops as much as possible by using vectorization, and letting numpy's functions do all the work.

How can I improve my code for performance and enhanced vectorization?

This is my code:

import numpy as np
import matplotlib.pyplot as plt

# read data matrix
data = np.genfromtxt('Advertising.csv', delimiter=',',dtype=float, skiprows=1)
m, n = data.shape

X = data[:, 0:n-1]
Y = data[:, n-1].reshape((m, 1))

# add unity vector column with size m to the X matrix, to account for theta_0
ones = np.ones((m, 1))
X = np.hstack((ones, X))

iterations = 500        # gradient descent iterations count
alpha = 0.01            # learning rate

theta = np.random.rand(n, 1)

def plotData():
    # get rid of X_0 constants column
    features = X[:, 1: n]
    plt.figure(1)

    plt.subplot(131)
    plt.plot(features[:, 0], Y, 'bo')
    plt.title('Ad dollars spent on TV')
    plt.ylabel('Sales')

    plt.subplot(132)
    plt.plot(features[:, 1], Y, 'ro')
    plt.title('Ad dollars spent on Radio')
    plt.ylabel('Sales')

    plt.subplot(133)
    plt.plot(features[:, 2], Y, 'yo')
    plt.title('Ad dollars spent on Newspaper')
    plt.ylabel('Sales')

    plt.show()

def computeCost():
    hypothesis = np.dot(X, theta);
    delta = np.dot((hypothesis - Y).transpose(), (hypothesis - Y))
    return (1 / m) * delta

# normalizeFeatures: scale-normalize all features to speed up gradient descent convergence
def normalizeFeatures():
    # 1) generate Average vector mu, contains the average of each feature in the X matrix
    # 2) generate Std. deviation vector sigma, contains the std. dev. of each feature in the X matrix
    # 3) subtract average value and divide by the standard deviation, for each feature column
    mu = np.ones((1, n))
    sigma = np.ones((1, n))

    # range() starts from 1 not 0, to skip the first all-ones constants column in the features matrix
    for i in range(1,n):
        mu[0][i] = np.mean(X[:, i])
        sigma[0][i] = np.std(X[:, i])
        X[:, i] = (X[:, i] - mu[0][i]) / sigma[0][i]

    return mu, sigma;

# gradientDescent() calculates hypothesis equation coefficients using gradient descent algorithm
def gradientDescent(theta):
    # vector to keep track of progression of cost function with each iteration
    J_history = np.ones((iterations, 1))

    for i in range(iterations):
        delta = np.dot((np.dot(X,theta) - Y).transpose(), X).transpose()
        theta -= (alpha/m) * delta
        J_history[i, 0] = computeCost()

    plt.plot(np.linspace(0, iterations, iterations), J_history)
    plt.title('Cost function against number of iterations')
    plt.xlabel('Number of iterations')
    plt.ylabel('Cost function J(theta)')
    plt.show()
    return

# normalEquation() calculates hypothesis equation coefficients analytically
def normalEquation():
    A = np.linalg.pinv(np.dot(X.transpose(), X))
    B = np.dot(X.transpose(), Y)
    theta = np.dot(A, B)

    return theta

def predict(x_vector, mu, sigma):
    # scale feature vector
    for i in range(1, n):
        x_vector[0][i] = (x_vector[0,i]- mu[0][i]) / sigma[0][i]

    return np.dot(x_vector, theta)

if __name__ == '__main__':
    plotData()
    mu, sigma = normalizeFeatures()
    gradientDescent(theta)
    print('Hypothesis coefficients from gradient descent:\n {}'.format(theta))
    print('Hypothesis coefficients from normal equation:\n {}'.format(normalEquation()))

    prediction_vector = np.array([1, 40, 40, 48]).reshape(1,4)
    print('Prediction for values [1, 40, 40, 48] is {}'.format(predict(prediction_vector, mu, sigma)))


texts: Comparing database values with values from a GridView

texts:
I have a block of C# code here that stores data to an ArrayList from the database and compares each with the values from the GridView.

Is there a way to reduce the line of code and improve its readability?

 while (DataReader.Read())
{
    arrHostName.Add(DataReader.GetString(0));
    arrUsers.Add(DataReader.GetString(2));
    arrPSName.Add(DataReader.GetString(3));
}
foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)
{
    string rowHostName = row.Cells["HostName"].Value.ToString();
    string rowUsers = row.Cells["Users"].Value.ToString();
    string rowPSName= row.Cells["PS_NAME"].Value.ToString();

    foreach (string a in arrHostName)
    {
        if (rowHostName == a.ToString())
        {
            row.Appearance.BackColor = Color.Yellow;
            row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
        }
    }
    foreach (string a in arrUsers)
    {
        if (rowUsers == a.ToString())
        {
            row.Appearance.BackColor = Color.Yellow;
            row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
        }
    }
    foreach (string a in arrPSName)
    {
        if (rowPSName == a.ToString())
        {
            row.Appearance.BackColor = Color.Yellow;
            row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
        }
    }
}


texts:
I have just started a course on C and wanted to test what I have learned so far. I did so by making a small program that tells you how much you should charge for a shot of a spirit you put in.
The code will ask if you want to do a calculation.  It will follow up with a question about the name, price and size of a product and respond with the calculation.
I have just learned how to use a Struct and just worked on Arrays. My next step will be to try and implement arrays to store the Structs you made and have the option to return to previous input.
How did I do so far and what could I improve on?
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>

//structs
typedef struct
{
    string name;
    float price;
    int size;
} Bottles;

//prototypes
Bottles get_newBottle(void);

//main
int main(void)
{
    string newBottles;
    //Ask user for input, repeat untill answered correctly.
   do
   {
       do
        {
            newBottles = get_string("Do you want to calculate a new shot y/n? ");
            if (strcmp(newBottles, "y") == 0)
            {
                //Build struct
                Bottles newBottle = get_newBottle();
                int shotSize = get_int("What is the size of your pour of %s in ML? ", newBottle.name);
                int bevCost = get_int("What percentage beverage cost do you want your drink to be? ");
                float shotCost = (newBottle.price / newBottle.size) * shotSize;
                float bevPrice = ((shotCost / bevCost) * 100) *1.21;
                printf("The cost of your shot of %s is %.2f Euro. \n", newBottle.name, shotCost);
                printf("At the cost of %.2f you will have to charge %.2f Euro including 21 percent VAT. \n", shotCost, bevPrice);

            }
            else if(strcmp(newBottles, "n") == 0)
            {
                printf("ok. doei!\n");
            }
        }
        while (! (strcmp(newBottles, "y") == 0) && ! (strcmp(newBottles, "n") == 0));
    }
    while (strcmp(newBottles, "y") == 0);
    return 0;
}

//extra functions
Bottles get_newBottle(void)
{
    string name = get_string("What is the name of your product? ");
    float price = get_float("What is the price of your product? ");
    int size = get_int("What is the size in ML of your product? ");

    Bottles newName = {name, price, size};
    return newName;
}


texts:
I use .NET 3.5 framework, so no tuples. I have many use cases where I have to create a custom key for a dictionary. How can I make this better?

public class CompositeKey<T>
{
    public T Content { get; set; }
    public Func<T, object>[] Lambdas { get; set; }

    public CompositeKey(T obj, params Func<T, object>[] propLambdas)
    {
        Content = obj;
        Lambdas = propLambdas;
    }

    public override int GetHashCode()
    {
        int hash = 0;
        foreach (var l in Lambdas)
        {
            hash ^= l(Content).GetHashCode();
        }
        return hash;
    }

    public override bool Equals(object obj)
    {
        bool isEqual = true;
        if (obj is T)
        {
            T o = (T)obj;
            foreach (var l in Lambdas)
            {
                isEqual &= (l(Content) == l(o));
            }
            return isEqual;
        }
        return false;
    }
}

public class TestCode
{
    public void somemethod()
    {
        Dictionary<CompositeKey<TestPOCO>, string> dict = new Dictionary<CompositeKey<TestPOCO>, string>();
        var t1 = new TestPOCO() { ID=1, Name="A" };
        var t2 = new TestPOCO() { ID = 2, Name = "B" };
        dict.Add(new CompositeKey<TestPOCO>(t1, x => x.ID, x => x.Name) , t1.Name);
        dict.Add(new CompositeKey<TestPOCO>(t2, x => x.ID, x => x.Name), t2.Name);
    }
}

public class TestPOCO
{
    public int ID;
    public string Name;
}

Especially this part:

        dict.Add(new CompositeKey<TestPOCO>(t1, x => x.ID, x => x.Name) , t1.Name);
        dict.Add(new CompositeKey<TestPOCO>(t2, x => x.ID, x => x.Name), t2.Name);

The challenge is to have lambda defined only once, but have different key objects based on the POCO.


texts: Rspec - testing basic functionality - redundant testing?

texts:
Being pretty new to testing, I was wondering how many of these tests make sense.

restaurants_controller_spec.rb

require 'spec_helper'

describe RestaurantsController do

  describe "GET #index" do
    before(:each) { get :index }
    let(:restaurants) { create_list :restaurant, 5 }

    it "populates @restaurants" do
      expect(restaurants).to match_array assigns(:restaurants)
    end
    it "renders the :dailycious view" do
      expect(response).to render_template :index
    end
  end

  describe "GET #show" do
    let(:restaurant) { create :restaurant }
    before(:each) { get :show, id: restaurant }

    it "assigns @restaurant" do
      expect(restaurant).to eq assigns(:restaurant)
    end
    it "renders :show" do
      expect(response).to render_template :show
    end
  end

  describe "GET #new" do
    before(:each) { get :new }

    context "user signed in" do
      before(:each) do
        login_user
        get :new
      end

      it "assigns @restaurant" do
        expect(assigns(:restaurant)).to be_a_new(Restaurant)
      end
      it "renders :new" do
        expect(response).to render_template :new
      end
    end

    context "user signed out" do
      it "redirects to login page" do
        expect(response).to redirect_to new_user_session_path
      end
    end
  end
end

support/controllers/controller_macros.rb

module Controllers
  module ControllerMacros
    def login_admin
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      sign_in create(:confirmed_admin)
    end

    def login_user
      @request.env["devise.mapping"] = Devise.mappings[:user]
      sign_in create(:confirmed_user)
    end
  end
end

The new test makes sense to me, since it behaves differently when logged in / logged out, but do the other ones make sense as well?

Especially the index test seems superfluous. Doesn't this just check basic rails functionality? The index tests of other controllers will surely share most of the same code. Isn't this a contradiction to the DRY-Principle?

My setup includes Rspec, Capybara & FactoryGirl.

Next to the explanations I'm glad if you review this code, maybe DRY things up etc. :)

Sidenote: I adjusted my code to this tutorial.


texts:
I have a 7x7 board and I want to select some elements from it. The elements I want to select are marked o, the other ones are marked x.

Here is the board:

xoxoxox
ooooooo
xooooox
ooooooo
xooooox
ooooooo
xoxoxox

I use indexing starting from 1. The point (1,1) is the top left.

The current list comprehension I have to select the o-elements is the following:

[(r,c) | r<-[1..7], c<-[1..7],
         (not (even r) && not (even c) && r/=1 && r/=7 && c/=1 && c/=7)
         || even r
         || even c]

I am wondering if I can make this list comprehension more simple. The code above is in Haskell, however, pseudo-code or Python list comprehensions are also fine with me.


texts:
I have written a basic REST endpoint in Ktor and would like some pointers.
Application.kt
@KtorExperimentalAPI
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
    install(Authentication)
    install(ContentNegotiation) {
        gson {}
    }

    val materialRepository = MaterialRepository(environment.config.property("repo.ws").getString())

    routing {
        route("/api") {
            materials(materialRepository)
        }
    }
}

MaterialResource.kt
fun Route.materials(
    repo: MaterialRepository
) {
    route("/materials") {
        get("/{id}") {
            when (val idParam = call.parameters["id"]) {
                is String -> {
                    val id = idParam.toIntOrNull()
                    if (id == null) {
                        call.respond(HttpStatusCode.NotFound)
                    } else {
                        when (val material = repo.get(id)) {
                            is Material -> call.respond(material)
                            else -> call.respond(HttpStatusCode.NotFound)
                        }
                    }
                }
                else -> call.respond(HttpStatusCode.BadRequest)
            }
        }
    }
}

MaterialRepository.kt

class MaterialRepository(
    val wsInput: String
) {
    private var materials: Map<Int, Material> = HashMap()

    init {
        val jsonMaterials = Gson().fromJson(FileReader(wsInput), JsonMaterialTable::class.java)

        materials = jsonMaterials.rows.map {
            it.ID_WS to Material( /*...snip as the model is quite large...*/ )
        }.toMap()
    }

    fun get(id: Int): Material? {
        return materials[id]
    }
}

It feels like I am not using the whole power of kotlin and writing too much boilerplate. I am following the general guidelines of Kotlin and Ktor tutorials, but I still think this is too compliated and could be massively improved in terms of readability and general best practices before I continue writing the whole rest of the application.


texts:
In an effort to create ever-improving code, I've written a DelegateCommand that takes a generic type parameter to be acted upon. It's pretty trivial, so it should hopefully be easy to review.

In order to do this, I had to create two interfaces: IGenericCommand and IWindowsUniversalCommand.

///
/// Requires the implementation of System.Windows.Input.ICommand as well.
///
/// <typeparam name="T"></typeparam>
public interface IGenericCommand<T> : ICommand
{
    ///
    /// A generic version of System.Windows.Input.ICommand.CanExecute(object).
    ///
    /// <param name="parameter"></param>
    /// <returns></returns>
    bool CanExecute(T parameter);
    ///
    /// A generic version of System.Windows.Input.ICommand.Execute(object).
    ///
    /// <param name="parameter"></param>
    void Execute(T parameter);
}

///
/// Requires the implementation of System.Windows.Input.ICommand as well.
///
interface IWindowsUniversalCommand : ICommand
{
    ///
    /// Should refresh whether or not the ICommand can execute, or call System.Windows.Input.ICommand.CanExecuteChanged.
    ///
    void RaiseCanExecuteChanged();
}

Then I created an abstract class WindowsUniversalCommand which implements some of the basic logic needed for the command, to save from having to repeat it regularly. (Just in case I create other commands for Windows Universal Apps.)

public abstract class WindowsUniversalCommand : IWindowsUniversalCommand
{
    public abstract bool CanExecute(object parameter);
    public abstract void Execute(object parameter);

#if WINDOWS_UWP
    // The .NET version on Windows RT (Universal Apps) does not support the `CommandManager` trick below, so we just make a regular event and fire it.
    public event EventHandler CanExecuteChanged;
#else
    // Programmes that are not Windows Universal Apps support the `CommandManager` trick.
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
#endif

    protected virtual void OnCanExecuteChanged(EventArgs e)
    {
        var handler = CanExecuteChanged;
        handler?.Invoke(this, e);
    }

    ///
    /// This method is required for Windows Universal Apps (WinRT). Non-WinRT programmes may simply ignore this method.
    ///
    public void RaiseCanExecuteChanged() => OnCanExecuteChanged(EventArgs.Empty);
}

The two abstract methods are required so that WindowsUniversalCommand can satisfy the ICommand interface.

Lastly, I have a DelegateCommand<T>.

public class DelegateCommand<T> : WindowsUniversalCommand, IGenericCommand<T>
{
    private readonly Func<T, bool> _canExecuteMethod;
    private readonly Action<T> _executeMethod;

    public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod = null)
    {
        _executeMethod = executeMethod;
        _canExecuteMethod = canExecuteMethod;
    }

    public override bool CanExecute(object parameter) => parameter is T ? CanExecute((T)parameter) : false;

    public override void Execute(object parameter) => Execute((T)parameter);

    public bool CanExecute(T parameter) => _canExecuteMethod == null || _canExecuteMethod.Invoke(parameter);

    public void Execute(T parameter) => _executeMethod?.Invoke(parameter);
}


texts: Listing every date between two dates in input fields

texts:
Using the following HTML:

<input type="date" value="2015-07-26" name="startdate">
<input type="date" value="2015-07-29" name="enddate">

First, the JS calculates the number of days between two dates:

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var start = document.querySelector('[name="startdate"]').value;
var end = document.querySelector('[name="enddate"]').value;
var firstDate = new Date(start);
var secondDate = new Date(end);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

↑ startdate is the name of the first input field and enddate is the name of the second field.

Date.prototype.addDays = function(diffDays) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + diffDays);
    return dat;
};

function getDates(startDate, stopDate) {
    var dateArray = [];
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        dateArray.push(currentDate);
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

var dateArray = getDates(new Date(start), (new Date(start)).addDays(diffDays));

↑ That is the part of the script I'm not really contented with, because I can imagine that the code could have been written simpler.

for (i = 0; i < dateArray.length; i++) {
    var input = document.createElement('input');
    var br = document.createElement("br");
    input.setAttribute("value", dateArray[i]);
    input.setAttribute("type", "date");
    document.body.appendChild(input);
    document.body.appendChild(br);
}

↑ Finally, it'll create for each day (between two dates) an input field, plus an linebreak after each input.

By the way, it would be nice to use the date format "DD.MM.YYYY", instead of "YYYY-MM-DD".

// Calculate number of days between two dates
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var start = document.querySelector('[name="startdate"]').value;
var end = document.querySelector('[name="enddate"]').value;
var firstDate = new Date(start);
var secondDate = new Date(end);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

Date.prototype.addDays = function(diffDays) {
   var dat = new Date(this.valueOf());
   dat.setDate(dat.getDate() + diffDays);
   return dat;
};

function getDates(startDate, stopDate) {
    var dateArray = [];
    var currentDate = startDate;
    while (currentDate <= stopDate) {
        dateArray.push(currentDate);
        currentDate = currentDate.addDays(1);
    }
    return dateArray;
}

var dateArray = getDates(new Date(start), (new Date(start)).addDays(diffDays));

// create input fields (for each date one field)
for (i = 0; i < dateArray.length; i++) {
    var input = document.createElement('input');
    var br = document.createElement("br");
    input.setAttribute("value", dateArray[i]);
    input.setAttribute("type", "date");
    document.body.appendChild(input);
    document.body.appendChild(br); // linebreak after each input field
}
<input type="text" value="2015-07-26" name="startdate">
<input type="text" value="2015-07-29" name="enddate">


texts: Hover effects for red, blue, and green boxes

texts:
I've created a JQuery script to help illustrate a few points for my teaching class, but I have having trouble slimming it down.

$(document).ready(function() {
    var red = $(".small-box");
    var blue = $(".small-box2");
    var green = $(".large-box");
    red.hover(
        function () {
            red.addClass("selected-highlight");
            blue.addClass("selected-highlight2");
            green.addClass("selected-highlight3");
        },
        function () {
        red.removeClass("selected-highlight");
            blue.removeClass("selected-highlight2");
            green.removeClass("selected-highlight3");
       }
    );
    blue.hover(
        function () {
            red.addClass("selected-highlight3");
            blue.addClass("selected-highlight");
            green.addClass("selected-highlight2");
        },
        function () {
            red.removeClass("selected-highlight3");
            blue.removeClass("selected-highlight");
            green.removeClass("selected-highlight2");
       }
    );
    green.hover(
        function () {
            red.addClass("selected-highlight2");
            blue.addClass("selected-highlight3");
            green.addClass("selected-highlight");
        },
        function () {
            red.removeClass("selected-highlight2");
            blue.removeClass("selected-highlight3");
            green.removeClass("selected-highlight");
       }
    );
});

Everything works as it should, but I know there is a way to slim down the "removeClass" part to one single line. I am having trouble remembering how to do so. The idea is to whatever box you hover over is red and the colors follow accordingly in the order of: red, blue, and green.

.container-left {
    float:left;
}
.small-box {
    width:300px;
    height:300px;
    background-color:#FFF;
    border-top:1px #000 solid;
    border-left:1px #000 solid;
}
.small-box2 {
    width:300px;
    height:300px;
    background-color:#FFF;
    border-left:1px #000 solid;
    border-bottom:1px #000 solid;
    border-top:1px #000 solid;;
}
.container-right {
    float:left;
}
.large-box {
    width:300px;
    height:601px;
    background-color:#FFF;
    border:1px #000 solid;
}
.selected-highlight{
    background-color:red;
}
.selected-highlight2 {
    background-color:blue;
}
.selected-highlight3 {
    background-color:#00FF00;
}


texts: Spreadsheet function that gives the number of Google indexed pages

texts:
I've developed this spreadsheet in order to scrape a website's number of indexed pages through Google and Google Spreadsheets.

I'm not a developer, so how can I improve this code in order to have less code, to use less resources, or to go faster?

I've explained everything here.

//-------------------------------------------
//   scrape a website's number of indexed pages through Google and Google Spreadsheets.
//-------------------------------------------
function indexedpages(myUrl)
    {
    var request = "http://www.google.com/search?&hl=en&q=site:http://" + unescape(myUrl); // Google Request for indexed pages

    var sourcecode = UrlFetchApp.fetch(request).getContentText(); // scrape the page content

    Utilities.sleep(1000); // 1000ms pause to prevent spam

    var codebefore = '
About '; // the code before the number we want

    var codeafter = ' results<'; // the code after the number we want

    var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want

    var theresult =  theresult.replace(",", ""); // delete the ","

    if (isNaN(theresult)) // if the result is not a number

    {
        var codebefore = '
'; // the code before the number we want

        var codeafter = ' result<'; // the code after the number we want

        var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want

        if (isNaN(theresult)) // if the result is not a number

        {
            var codebefore = '
'; // the code before the number we want

            var codeafter = ' results<'; // the code after the number we want

            var theresult = sourcecode.substring(sourcecode.indexOf(codebefore)+codebefore.length, sourcecode.indexOf(codeafter)); // scrape the number we want

            if (isNaN(theresult)) // if the result is not a number (0 result)

            {
                return 0; // returns 0
            }

            else

            {
                return theresult; // returns the number we want
            }
        }

        else
        {
            return theresult; // returns the number we want
        }

    }

    else
    {
        return theresult; // returns the number we want
    }

}


texts:
I wrote a program that encrypts a users string by increasing every char's position by a random number. I'm looking for any and all criticism on it.

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Encryption2
{
 class Program
 {
    public static void Main()
    {
        Console.Clear();

        bool valid = true;

        while (valid) //while loop is here for error handling in case user inputs something other than
        {
            Console.WriteLine("Enter d for decrypt and e for encrypt");

            string uInput = Console.ReadLine().ToLower();

            if (uInput == "e")
            {
                encrypt();
                valid = false;
            }
            else if (uInput == "d")
            {
                decrypt();
                valid = false;
            }
            else
            {
                Console.Clear();
            }
        }
    }

    public static void encrypt()
    {
        Console.Clear();

        Console.WriteLine("Enter a string for encryption");

        string input = Console.ReadLine(); //string that will be encrypted

        int[] keyVals = new int[input.Length]; //decryption key

        Random generateKeyVals = new Random();

        for (int i = 0; i < input.Length; i++) //generates input.Length amount of numbers between 1 and 9 that are used to increase
        {                                       //each char in in the input string and then decrease each char when you decrypt
            keyVals[i] = generateKeyVals.Next(1, 9);

            Console.Write(keyVals[i]);
        }

        Console.WriteLine(" : This is your decryption key");

        for (int i = 0; i < input.Length; i++) //encrypts string by adding first char in the encrypted string with the first value in the key and so on
        {
            char encrypted = Convert.ToChar(input[i] + keyVals[i]);

            Console.Write(encrypted);
        }

        Console.WriteLine(" : This is your encrypted string");

        Console.ReadKey();

        Main();
    }

    public static void decrypt() //decrypts an encrypted message using a decryption key
    {
        Console.Clear();

        Console.WriteLine("Enter a string for decryption");

        string input = Console.ReadLine(); //user inputs the encrypted message

        int[] keyVals = new int[input.Length]; //stores all values entered from the for loop below. This is the decryption key used to decrypt the string

        for (int i = 0; i < input.Length; i++) //using a for loop to get all numbers from the key one at a time.
        {
            Console.WriteLine("Enter the #" + (i + 1) + " of the key");
            keyVals[i] = Convert.ToInt32(Console.ReadLine());
        }

        for (int i = 0; i < input.Length; i++) //decrypts string by subtracting first char in the encrypted string by the first value in the key and so on
        {
            char decrypted = Convert.ToChar(input[i] - keyVals[i]);

            Console.Write(decrypted);
        }

        Console.WriteLine(System.Environment.NewLine);

        Console.WriteLine("Press any key to return to the main menu");

        Console.ReadKey();

        Main();
    }
}

}


texts: Function for iterating out an unordered list of custom taxonomy terms

texts:
I've created a function that generates an
 of my wordpress custom taxonomy terms, displaying parent > child > second child heirachy. Functionally it is working perfectly and replaces my old hard-coded menu.

The problem is I'm inexperienced and recognise it as an ugly, inefficient function but could not figure out how to make it better. I tried use 'While()' loops to simplify things but came unstuck. Could someone help me understand how to improve this. The final output (including CSS and jQuery to collapse deactivated menu items) is included below.

//Display Navigation Menu

function taxonomy_nav(){

  //Get Parent Terms
  $getParents = [
    'taxonomy'     => 'kernal_category',
    'parent'        => 0,
    'number'        => 0,
    'hide_empty'    => false
  ];

  //Assign parent terms to variable
  $parent_terms = get_terms( $getParents );

  //Loop through parent terms
  foreach ( $parent_terms as $parent_term ) {

    //Store children terms
    $childrenCheck = get_term_children( $parent_term->term_id, $parent_term->taxonomy );

    //If parent term has children...
    if ( ! is_wp_error( $childrenCheck ) && ! empty ( $childrenCheck ) ) {

      //Output parent term and start new children list
      echo '
'. $parent_term->name.'';
      echo '
';

        //Loop through child items and output name
        foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term) {

            //Check if children have children
            $secondChildrenCheck = get_term_children( $child_term->term_id, $child_term->taxonomy );

              //Generate list for second children
              if ( ! is_wp_error( $secondChildrenCheck ) && ! empty( $secondChildrenCheck ) ) {

                echo '
' . $child_term->name.'';
                echo '
';

                //If child has child, look through child
                foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $child_term->term_id ) ) as $second_child_term) {

                 echo '
'.$second_child_term->name . '
';

                }

                echo '
';
                echo '
';

              } else {

              echo '
'. $child_term->name.'
';

              }
        }

      echo '
';
      echo '
';

    } else {

      echo '
'. $parent_term->name.'
';

    }

  }


texts:
Here is a function for creating sliding windows from a 1D NumPy array:
from math import ceil, floor
import numpy as np

def slide_window(A, win_size, stride, padding = None):
    '''Collects windows that slides over a one-dimensional array.

    If padding is None, the last (rightmost) window is dropped if it
    is incomplete, otherwise it is padded with the padding value.
    '''
    if win_size <= 0:
        raise ValueError('Window size must be positive.')
    if not (0 < stride <= win_size):
        raise ValueError(f'Stride must satisfy 0 < stride <= {win_size}.')
    if not A.base is None:
        raise ValueError('Views cannot be slided over!')

    n_elems = len(A)
    if padding is not None:
        n_windows = ceil(n_elems / stride)
        A = np.pad(A, (0, n_windows * win_size - n_elems),
                   constant_values = padding)
    else:
        n_windows = floor(n_elems / stride)
    shape = n_windows, win_size

    elem_size = A.strides[-1]
    return np.lib.stride_tricks.as_strided(
        A, shape = shape,
        strides = (elem_size * stride, elem_size),
        writeable = False)

(Code has been updated based on Marc's feedback)
Meant to be used like this:
>>> slide_window(np.arange(5), 3, 2, -1)
array([[ 0,  1,  2],
       [ 2,  3,  4],
       [ 4, -1, -1]])

Is my implementation correct? Can the code be made more readable? In NumPy 1.20 there is a function called sliding_window_view, but my code needs to work with older NumPy versions.


texts: Lists highly divisible numbers, oeis squence: A002182

texts:
My code works (as far as I can tell), so I'm looking mostly for readability and efficiency tips.

Goal of my code: Generate a list of all numbers that have more divisors than any lower number up to a certain limit. In other words this sequence: https://oeis.org/A002182

Background:  The number of divisors of \$n=p_1^{k1} \times p_2^{k2} \times p_3^{k3}\$ is just \$(k_1+1)\times(k_2+1)\times(k_3+1)\$... so the primes themselves don't matter, just the set of exponents.  Thus to be the smallest possible number with that number of divisors, the exponents are required be in order from largest (on the smallest primes) to smallest (on the largest primes).

My code breaks into 3 sections, the first figures out the largest prime needed.  The second generates a list of candidate numbers which is a list of all numbers that fit the descending exponent requirement.  Finally, the third part puts them in order and checks which of the candidates actually have more divisors than any previous numbers.

Final Random question: Is there a name for the middle algorithm? An algorithm that finds a list of all lists that are under a certain threshold?  A more generic version would probably set pows[:marker] = [0] * marker instead, but in my case I only want descending lists.

from numpy import prod

def highlydiv(n):
    """ Returns a list of all numbers with more divisors than any lower numbers, up to a limit n """
    primeprod = 1
    plist =  []
    for p in gen_prime(50): #gen_prime: generates primes up to n, can just use [ 2,  3,  5,  7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
        primeprod *= p
        if primeprod <= n:
            plist.append(p)
        else:
            break

    pows = [0 for x in plist]
    breakout = False
    candidate_list = []
    calcsum = 1
    while True:
        marker = 0
        pows[marker] += 1
        calcsum *= 2
        while calcsum > n:
            marker += 1
            if marker == len(pows):
                breakout = True
                break
            pows[marker] += 1
            pows[:marker] = [pows[marker]] * marker
            calcsum = prod([p**k for p, k in zip(plist, pows)])
        if breakout:
            break
        ndivs = prod([x+1 for x in pows])
        candidate_list.append((calcsum,ndivs))

    candidate_list.sort()
    maxdivs = 0
    final_list = []
    for candidate, ndivs in candidate_list:
        if ndivs > maxdivs:
            maxdivs = ndivs
            final_list.append(candidate)
    return final_list

print(highlydiv(1000000))


texts: Descriptive quantity (one, two, many) from number

texts:
I just write a simple method which returns a string based on the number in accepts as a parameter. I used if/elif/esle here but I think for this simple scenario I wrote long code. I want to know is it possible to shorten this code in any way except using a lambda method. Also, I'm interested to know about the performance of if/elif/else. Is there any other solution which can make faster this method?

def oneTwoMany(n):
    if n == 1:
        return 'one'
    elif n == 2:
        return 'two'
    else:
        return 'many'


texts: Word break problem with dynamic programming

texts:
This is the original question.

I have implemented it in both ways. If I enter the word "icecream", should I output "ice" "cream" and also "icecream", or just "ice" and "cream"?

Is this a good example of dynamic programming?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{

    public class DynamicProgramming
    {
        public DynamicProgramming()
        {
            List<string> dictionary = new List<string>{"mobile","samsung","sam","sung","man","mango",
                           "icecream","and","go","i","like","ice","cream"};
            var result = ContainsWordRecursive("ilike",dictionary);
            var result2 = ContainsWordDP("icecream", dictionary);
        }

        private List<string> ContainsWordRecursive(string word, List<string> dictionary)
        {
            List<string> res = new List<string>();
            for (int i = 0; i <= word.Length; i++)
            {
                if(dictionary.Contains(word.Substring(0,i)))
                {
                    res.Add(word.Substring(0,i));
                    var list = ContainsWordRecursive(word.Substring(i, word.Length - i ),dictionary);
                    if(list.Count > 0)
                    {
                        res.AddRange(list);
                    }
                }
            }
            return res;
        }

        private List<string> ContainsWordDP(string word, List<string> dictionary)
        {
            List<string> list = new List<string>();
            bool[] wb= new bool[word.Length+1];
            for (int i = 0; i <= word.Length; i++)
            {
                list.Clear();
                if (wb[i] == false && dictionary.Contains(word.Substring(0, i)))
                {
                    wb[i] = true;
                    list.Add(word.Substring(0, i));
                }

                if (wb[i] == true)
                {
                    if (i == word.Length)
                    {
                        return list;
                    }
                    for (int j = i + 1; j <= word.Length; j++)
                    {
                        if (wb[j] == false && dictionary.Contains(word.Substring(i, j - i)))
                        {
                            wb[j] = true;
                            list.Add(word.Substring(i, j - i));
                        }
                        // If we reached the last character
                        if (j == word.Length && wb[j] == true)
                        {
                            return list ;
                        }
                    }
                }
            }
            return list;
        }
    }
}


texts: Change all pixels that lie in a given color range to a new color

texts:
This is what I have so far but it's not perfect... Any input would be very helpful!

def picture_reset_pixels(filename, from_color, to_color, target_color):
    img = Image.open(filename)
    pixels = list(img.getdata())
    red_list=[]
    for i in pixels:
        R= i[0]
        G=i[1]
        B=i[2]

        if R >= from_color[0] and R<= to_color[0] and G >=from_color[1]
                and G<= to_color[1] and B >= from_color[2] and B<=
                to_color[2]:
                    red_list.append(target_color)
        else:
            red_list.append((round(R),round(G),round(B)))

    red_image = Image.new(img.mode,img.size)
    red_image.putdata(red_list)
    return red_image


texts: List all direct and indirect employees of a manager

texts:
This is the question:

  You have an Employee class:

class Employee {
    String name;
    Integer id,
    Employee manager
}

  Each employee has a manager and the manager of CEO is null. Find all
  direct and indirect employees of a manager.

  For example:

  Say Employee e1 reports to CEO
  e2 and e3 reports to e1
  e4 and e5 reports to e2
  e6 reports to e3

  Then by giving e1 as input, output should be e2, e3, e4, e5 and e6.

I know I am using the stupidest way to do it. But I wonder if there is any better way to do the if-statement?

function func() {
  function Employee(name, id, manager) {
    this.name = name;
    this.id = id;
    this.manager = manager;
  }

  const ceo = new Employee("ceo", 1, null);
  const e1 = new Employee("e1", 2, ceo);
  const e2 = new Employee("e2", 3, e1);
  const e3 = new Employee("e3", 4, e1);
  const e4 = new Employee("e4", 5, e2);
  const e5 = new Employee("e5", 6, e2);
  const e6 = new Employee("e6", 7, e3);

  var name = document.getElementById("txtName").value;

  var eArr = [];

  if (e1.manager.name === name.toLowerCase()) {
    eArr.push(e1.name);
  }
  if (e2.manager.name === name.toLowerCase() || (e2.manager.manager !== null && e2.manager.manager.name === name.toLowerCase())) {
    eArr.push(e2.name);
  }
  if (e3.manager.name === name.toLowerCase() || (e3.manager.manager !== null && e3.manager.manager.name === name.toLowerCase())) {
    eArr.push(e3.name);
  }
  if (e4.manager.name === name.toLowerCase() || (e4.manager.manager !== null && e4.manager.manager.name === name.toLowerCase()) || (e4.manager.manager.manager !== null && e4.manager.manager.manager.name === name.toLowerCase())) {
    eArr.push(e4.name);
  }
  if (e5.manager.name === name.toLowerCase() || (e5.manager.manager !== null && e5.manager.manager.name === name.toLowerCase()) || (e5.manager.manager.manager !== null && e5.manager.manager.manager.name === name.toLowerCase())) {
    eArr.push(e5.name);
  }
  if (e6.manager.name === name.toLowerCase() || (e6.manager.manager !== null && e6.manager.manager.name === name.toLowerCase()) || (e6.manager.manager.manager !== null && e6.manager.manager.manager.name === name.toLowerCase())) {
    eArr.push(e6.name);
  }

  if (eArr.length !== 0)
    document.getElementById("ans").innerHTML = "Ans: " + eArr;
  else
    document.getElementById("ans").innerHTML = "Ans: No reportees";
}
Manager Name = <input type="text" id="txtName">
<button onclick="func()">Result</button>