texts: A hash cracker for Python 3.0 and up (module)

texts:
I've worked on pycrack.py to improve it (hopefully). New features:

Renamed to kronos (kronos.py).
Attack modes:

Bruteforce;
Wordlist attack.

Portability:

Kronos can run on Windows, MacOS and Linux, as well as Android (iPhone?).
Kronos can run under any Python 3 installation, not just Python 3.6 or higher.

The full code is now available on GitHub, along with a guide on how to use it.

I'm looking to get some feedback on the current state of the project. What do you think of the setup of classes and functions within the file? Is there a way to significantly shorten the code, without decreasing functionality? -Any other feedback-

GitHub

GitHub guide

I have included a code sample below:

class Bruteforce:
"""Class containing Active and Passive classes,
for verbose and non-verbose bruteforcing.
Class contents:

* class Active
* class Passive
"""
    class Active:
        """Class for active bruteforce attacks, with
        optional debug mode (boolean). Active mode
        should be utilized from the command line or in
        situations where statistical information is required.
        Class contents:

        * __init__()
        * timer()
        * bruteforce()
        """
        def __init__(self, hash_, algo, charset, min_, max_, debug):
            # Function arguments:

            # hash_:
                    # [1] UTF-8-encoded hash hashlib.<algo>().hexdigest().
                    # [1] Supported algorithms from
                    # [1] hashlib.algorithms_available.

                    # [2] A valid file name or valid file path.
                    # [2] The program will treat each new line
                    # [2] as a new hash. Files must be UTF-8 encoded.
                    # [2] Results will be returned as a list.

                    # [3] A list containing one or more hashes.
                    # [3] Results will be returned as a list.

            # algo: Hashlib algorithm (must be available on system).
            # charset: String, can contain "L" / "U" / "D";
                    #  for lowercase, uppercase and digits.
                    #  Example: lower + upper = LU.
            # min_: Minimum length for expected string (any integer);
                  # bruteforce() will echo a warning if min_ > 6,
                  # because of performance.
            # max_: Maximum length for expected string (any integer).
            # debug: Boolean (1 or True for debug mode, else 0 or False);
                  # Debug mode is not recommended due to performance,
                  # use only if absolutely needed.

            self.hash_ = hash_
            self.algo = algo
            self.algo_ = algo       # This retains a copy of algo argument.
            self.charset = charset
            self.min_ = min_
            self.max_ = max_
            self.debug = debug

            if self.min_ > 5 and self.debug:
                print("""{}Warning: minimum length > 5.
Bruteforcing may take a long time. Consider a wordlist attack.{}"""
                .format(colors['yellow'], colors['none']))

            if path.isfile(self.hash_):
                with open(self.hash_, "r") as infile:
                    hashes = infile.read()
                self.hash_ = hashes.split()

            charset = ""
            charsets = {"L":ascii_lowercase,
                    "U":ascii_uppercase,
                    "D":digits
                   }
            for key in self.charset:
                charset += charsets[key]
            self.charset, charset = charset, None

            self.algo = hashlib.new(self.algo)


texts:
I've been making a bot for Reddit that finds reposts (based on image MD5 comparing) and posts a small comment on the thread (that part will be later, right now it downloads images and compares MD5). If the image is original content, it will add it to its list of hashes. The source code is here. Any suggestions as to what I can improve?

public static bool DownloadImage(string url, bool isDirect) // returns if repost
{ // example url: http://imgur.com/UndN77d
    if (url.Contains('?'))
    {
        url = url.Split('?')[0]; // if it has a query at the end like ?1
    }
    string filename = null;
    if (url.Contains("imgur"))
    { // is imgur, so use ImgurAPI class for it
        string imgurID = url.Split('/')[url.Split('/').Length - 1];
        Console.WriteLine("Processing imgur id {0}", imgurID);
        if (!isDirect)
        { // the sole goal for this block is to get Vars.picToCompare
            string details = Imgur.GetImageDetails(imgurID);
            if (details == null)
            {
                return false;
            }
            Console.WriteLine("Got response: {0}", details); // json
            JObject imgur = JObject.Parse(details);
            if (imgur["success"].ToString() == "false")
            { // auth failed
                Console.WriteLine("Imgur processing failed.. Printing JSON contents: ");
                Console.WriteLine(details);
                Console.ReadKey();
                return false;
            }
            else
            {
                Console.WriteLine("Imgur details recieved successfully!");
                filename = imgur["data"]["link"].ToString();
                url = filename;
                Console.WriteLine("Processed direct URL: " + filename);
                filename = filename.Split('/')[filename.Split('/').Length - 1];
                Console.WriteLine("Processed image filename: " + filename);
                Vars.picToCompare = Path.Combine(Vars.picsFolder, filename);
            }
        }
        else
        {
            Vars.picToCompare = Path.Combine(Vars.picsFolder, url.Split('/')[url.Split('/').Length - 1]); // should be filename
        }
    }
    else
    { // for example mysite.com/blah.jpg
        Vars.picToCompare = Path.Combine(Vars.picsFolder, url.Split('/')[url.Split('/').Length - 1]);
        Console.WriteLine("Processing image url {0}", url);
        Console.WriteLine("Processed image {0}", Vars.picToCompare);
    }
    bool isRepost = false;
    using (WebClient client = new WebClient())
    {
        if (File.Exists(Vars.picToCompare))
            File.Delete(Vars.picToCompare);
        client.DownloadFile(url, Vars.picToCompare);
        Console.WriteLine("Successfully downloaded image {0}", Vars.picToCompare);
    }
    isRepost = Processing.CompareHash(url);
    if (isRepost)
        Console.WriteLine("This is a repost!");
    else
        Console.WriteLine("This is OC. Adding to hashlist..");
    //foreach (string hash in Vars.totalHashes)
    //{
    //    Console.WriteLine("Written hash to file: " + hash);
    //}
    return isRepost;
}


texts: Hiding multiple elements' parent container (by child element id)

texts:
Summary:

I need to hide several (pre-determined) divs based on a child element's ID.

Caviats:

I can't alter the HTML directly in any way (by modifying the literal .html file).  The IDs of the child elements for which the parents are to be hidden are known and not likely to change often (or even at all).

I can't add CSS that will be available to the HTML page.

Here is the solution that I came up with

JavaScript

var toHide = $("#item2, #item3, #item6");
toHide.parent().hide();

HTML

item 1

related item stuff

item 2

related item stuff

item 3

related item stuff

item 4

related item stuff

item 5

related item stuff

item 6

related item stuff

item 7

related item stuff

Is there a better way to select these multiple elements than by using $("#item2, #item3, #item6")?

Are there any options I'm missing?


texts: Find the biggest rectangle in a bar graph

texts:
Find the largest rectangle area on a bar graph. Example: if you had a graph of 1,4,5,3,3,5 the answer would be 15 (3x5) which is formed by the rectangle that is 3 high and spans from position 2 (1 based) to 6.

Please review my answer and comment about runtime complexity, memory usage, and basically anything else you think I need to improve if this was a job interview for your company.

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

namespace Interviews
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> barGraph = new List<int>() { 1, 4, 5, 3, 3, 5 };
            int max = GetBiggestRectSize(barGraph);
            //should output 15
            barGraph = new List<int>() { 1, 4, 2, 3, 3, 5 };
            max = GetBiggestRectSize(barGraph);
            //should output 10
        }

        private static int GetBiggestRectSize(List<int> barGraph)
        {
            int maxRectSize = 0;
            int max = barGraph.Max();
            for (int i = 1; i <= max; i++)
            {
                int tempSize = 0;
                for (int j = 0; j < barGraph.Count; j++)
                {
                    if (barGraph[j] >= i)
                    {
                        tempSize += i;
                    }
                    else
                    {
                        if (tempSize > maxRectSize)
                        {
                            maxRectSize = tempSize;
                        }
                        tempSize = 0;
                    }
                    if (tempSize > maxRectSize)
                    {
                        maxRectSize = tempSize;
                    }
                }
            }
            return maxRectSize;
        }
    }
}


texts: Mounting a disk with the DiskArbitration framework

texts:
I have the following code that makes use of the DiskArbitration framework to mount a disk to its default location:

#import <CoreFoundation/CoreFoundation.h>
#import <DiskArbitration/DiskArbitration.h>

void MountCallback(DADiskRef disk, DADissenterRef dissenter, void *context);

int main(int argc, const char *argv[]) {
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <disk>\n", argv[0]);
    return EXIT_FAILURE;
  }

  const char *deviceName = argv[1];

  DASessionRef session = DASessionCreate(kCFAllocatorDefault);
  DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, deviceName);

  // Pass NULL for a "standard" mount path.
  DADiskMount(disk, NULL, kDADiskMountOptionWhole, MountCallback, (void *)deviceName);

  DASessionSetDispatchQueue(session, NULL);
  CFRelease(session);
  session = NULL;

  return EXIT_SUCCESS;
}

void MountCallback(DADiskRef disk, DADissenterRef dissenter, void *context) {
  const char *mountedDisk = context;
  fprintf(stderr, "Device mounted: %s\n", mountedDisk);
  fflush(stderr);
  return;
}

To compile the code:

clang -Wall -Werror -g -v main.m -lobjc -framework DiskArbitration -framework Foundation -o mount

To run the program:

./mount diskN

The program works fine, however as a developer without much knowledge on the Apple platform, I'm interested in the following points:

The MountCallback function doesn't appear to be called. I don't see the line I'm printing to stderr.
In case the mount operation fails, how do I access the error, and use it return a different exit status on main? (I assume the error is caught from the callback, but can't find documentation about it).
Am I releasing the session and other resources I'm using for the task correctly?


texts: A faster way to look up for a url in a WebRequest/WebResponse html

texts:
What I'm trying to do here is get an RSS feed and append an Enclosure XML node to each item, which has a link to a video file (wmv).

Try the below code with

url = "http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss"

for eg to get the point

The performance hit here consists of two parts: the LONG "foreach" loop, along with the HUGE number of requests done to retrieve the media link (marked in the code by the comment "This part needs attention"). Any advice concerning how to get the media link a much faster manner would really be appreciated!

You can get a glimpse of what that code do, by comparing this feed (the URL):

http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss

to this feed (created by the code below), note that it will be slow and might give error, if it did just refresh the page:

http://mshady.apphb.com/feeds/index?url=http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss

public class FeedsController : Controller
{
    private XmlDocument _Xml;

    [OutputCache(VaryByParam = "url", Duration=86400)]
    public string Index(string url)
    {
        string feed = "";

        _Xml = new XmlDocument();
        _Xml.Load(url);

        foreach (XmlNode node in _Xml.ChildNodes[0].ChildNodes[0].ChildNodes)
        {
            if (node.Name == "item")
            {
                XmlNode childnode = GetEnclosureXmlNode(node);
                node.AppendChild(childnode);
            }
        }

        feed =  _Xml.OuterXml;

        return feed;
    }

    private string GetMediaUrl(string articleUrl)
    {
        string mediaUrl = "";

        ////////////////////////////////////////////
        // This part needs attention
        ////////////////////////////////////////////
        Regex regex = new Regex(@"WMV Download");
        var request = HttpWebRequest.Create(articleUrl);
        var response = request.GetResponse();
        string responseHtml = new StreamReader(response.GetResponseStream()).ReadToEnd();
        var match = regex.Match(responseHtml);
        ////////////////////////////////////////////
        // This part needs attention
        ////////////////////////////////////////////

        if (match.Success)
            mediaUrl = match.Groups[1].Value;

        return mediaUrl;
    }

    private XmlNode GetEnclosureXmlNode(XmlNode node)
    {
        string articleUrl = node["link"].InnerText;
        string mediaUrl = GetMediaUrl(articleUrl);

        XmlElement childnode = CreateEnclosureXmlNode(mediaUrl);
        return childnode;
    }

    private XmlElement CreateEnclosureXmlNode(string mediaUrl)
    {
        XmlElement childnode = _Xml.CreateElement("enclosure");
        childnode.SetAttribute("url", mediaUrl);
        childnode.SetAttribute("type", "video/wmv");
        return childnode;
    }
}


texts: An object exposed to directives that need to track changes on it

texts:
This is an object exposed to the view and is being used on directives within the same view. The directives need to track changes on the ctrl.filters.applied object. It's a simple part of a project at my work and I'd like to know if I'm doing it right.

Other properties and methods are just being used on the view itself.

ctrl is the controller, since I'm using controllerAs syntax.

var ctrl = this;

Filters object:

ctrl.filters = (function filters() {

    var currentFilters,
        appliedFilters,
        initialFilters = {
            companies: [],
            user: null,
            workDate: {
                initial: null,
                final: null
            }
        };

    currentFilters = angular.copy(initialFilters);
    appliedFilters = angular.copy(currentFilters);

    function apply() {
        appliedFilters = angular.copy(currentFilters);
    };
    function clear() {
        currentFilters = angular.copy(initialFilters);
        appliedFilters = angular.copy(currentFilters);
    };

    return function filtersReturn() {
        return {
            current: currentFilters,
            applied: appliedFilters,
            apply: apply,
            clear: clear
        };
    };

})();

Directive example:

<wkp-my-directive
    wkp-filters="ctrl.filters().applied">
</wkp-my-directive>


texts:
We have a main application made of a few separate parts - Unity and Clc.

I'm writing a new tool which will be used to manage them: deploy Unity, or run some checks and a lot of other stuff. As there will be a lot of options, I want split them in to separate namespaces.

Here is my implementation, it works, but I'm not sure if it's the best way.

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

parser_unity = subparsers.add_parser('unity', help='Unity help')
parser_unity.add_argument('-t', '--tagcheck', dest='unity_tagcheck', action='store_true', help='Check tags in .csproj files')
parser_unity.add_argument('-d', '--deploy', dest='unity_deploy', action='store_true', help='Deploy Unity project to appropriate URL')

parser_clc = subparsers.add_parser('clc', help='Clc help')
parser_clc.add_argument('-d', '--deploy', dest='clc_deploy', action='store_true', help='Deploy Cloudlibrary project to appropriate environment')

res = parser.parse_args()

print('All %s' % res)

try:
    if res.unity_deploy:
        print('Unity deploy')

    if res.unity_tagcheck:
        print('Unity tagcheck')
except AttributeError:
    pass

try:
    if res.clc_deploy:
        print('Clc deploy')
except AttributeError:
    pass

And here is how is works:

d:\RDS\rdsmanager>tmp\test.py clc -d
All Namespace(clc_deploy=True)
Clc deploy

d:\RDS\rdsmanager>tmp\test.py unity -d -t
All Namespace(unity_deploy=True, unity_tagcheck=True)
Unity deploy
Unity tagcheck

d:\RDS\rdsmanager>tmp\test.py unity -d
All Namespace(unity_deploy=True, unity_tagcheck=False)
Unity deploy


texts: Is this the right way to implement a simple hash table in C++?

texts:
Does this look like a proper implementation of a hash table in C++? Any errors anyone can find?
Thanks in advance (:

template <typename T>
class HashTable
{
public:
HashTable(int amount)
{
    size = amount;
    values = new T*[size];
    for (int i = 0; i < size; i++)
    {
        *(values + i) = nullptr;
    }
}
~HashTable()
{
    if(values != nullptr)
    {
        for (int i = 0; i < size; i++)
        {
            if(*(values + i) != nullptr)
            {
                delete *(values + i);
                *(values + i) = nullptr;
            }
        }
        delete[] values;
    }
}

void addValue(const std::string & key, T value)
{
    int location = hash(key);

    if (*(values + location) == nullptr)
    {
        *(values + location) = new T;
    }

    **(values + location) = value;
}

void printValues()
{
    for (int i = 0; i < size; i++)
    {
        if (*(values + i) != nullptr)
        {
            printf("value : %i\n", **(values + i));
        }
    }
}

T* getValue(const std::string & key)
{
    return *(values + hash(key))
}

private:

int hash(const std::string & key)
{
    int value = 0;
    for (unsigned int i = 0; i < key.length(); i++)
    {
        value += key[i] * (i + 1);
    }
    return value % size;
}

int size;
T ** values = nullptr;
};


texts: Decoupling with a self-descriptive mediator function

texts:
I don't have a lot of experience writing libraries and just recently started thinking a lot about structure and patterns.

I wrote a tiny module manager based on the facade and mediator design patterns and very vaguely based on require.js / AMD and libraries using facade+mediator patterns like jQuery.

My goal is not only to decouple but to provide a minimal, self-descriptive mediator function as an entrance point into modules serving as a kind of tutorial.

So if everything works out inspecting a module via console.log(), it only shows the exposed mediator function and hopefully gives the required information needed to use the module without looking up in the documentation most of the time

Here is an example module featuring all structural components:

imports(["module1","module2"],function privateModuleConstructor(moduleOne,moduleTwo){
    var privateVar = "hidden and can only be accessed through the closure";

    return exports(function longDescriptiveMediatorName(){
         var a = arguments,
             l = a.length;
             c = a.callee;
         /* ...exposed part of the facade... */
         if(l===0)                     {return privateMethod()};
         if(typeof a[0] === "string")  {return privateVar+a[0]};
         if(a[0] instanceof Array)     {return privateMethod.apply(c,a[0])}

    },[module1,module2,publicMethod],"shortAlias");

    function privateMethod(){
        return privateVar.replace(/hidden/,"now revealed");
    }
    function publicMethod(){
        return "exposing methods without mediator increases coupling but is possible"
    }
})

How intuitive does this feel to you?  Even without seeing the exact source of imports and exports, does this give you the information you would need to write a module yourself?

edit:
After using the pattern for a month it turned out to be rather tedious most of the time. Some modules just can't be reasonably decoupled this way, so it's far from being the magic formula solution that solves all my problems. But it did work out very well for some modules.

I ended up just not using the mediator function when starting out to write a new module, simply use the module and then pay attention and decouple when I ended up actually using the module in many different places and saw an opportunity to reduce the complexity of my use cases.


texts:
I have some C# unit tests which each basically perform the same steps but supply different arguments to the unit under test.

I wanted to encapsulate the logic inside some "helper methods" but found that the method names, while descriptive, were cumbersome. For example, the code inside a test method would look like this contrived example:

var expected = 1;
var set = new [] { 1, 2, 3, 4, 5 };
AssertThatCallToGetSmallestReturnsExpectedValueFromGivenSet(expected, set);

I simplified the method names and took up a convention of using C#'s named arguments feature:

AssertThatCallToGetSmallest(
    returnsValue: 1,
    fromSet: new [] { 1, 2, 3, 4, 5 }
);

The latter approach seems cleaner and more readable to me. I've been working with objective-c for a few months now so invoking methods in this manner has become less of an issue for me aesthetically. The other advantage is that this convention scales better with an increase in the number of parameters (if that should ever really be of value).

One thing I'm particularly concerned with is the lack of enforced readability because named arguments are optional. There is the potential for programmers to later come along and "misuse" the helper methods I've created by failing to specify the parameter names:

AssertThatCallToGetSmallest(1, new [] { 1, 2, 3, 4, 5 }); // what does this even mean?

So, which way is "better"?

I'm using the Visual Studio Unit Testing Framework with MSTest.


texts: Thumbnails for bootstrap carousel jQuery plugin

texts:
Codepen: http://codepen.io/srkimir/pen/mGbrf
Github: https://github.com/srkimir/thumbnails-carousel

While you slide left or right appropriately, thumbnails gets selected and change their opacity to be different among others thumbnails.  You can also click on thumbnails to show the appropriate image on carousel.

HTML

Add child
 of thumbnails in the end of  carousel bootstrap parent, like:

    ...

CSS

ul.thumbnails-carousel {
    padding: 5px 0 0 0;
    margin: 0;
    list-style-type: none;
    text-align: center;
}
ul.thumbnails-carousel .center {
    display: inline-block;
}
ul.thumbnails-carousel li {
    margin-right: 5px;
    float: left;
    cursor: pointer;
}
.controls-background-reset {
    background: none !important;
}
.active-thumbnail {
    opacity: 0.4;
}
.indicators-fix {
    bottom: 70px;
}

JavaScript:

// thumbnails.carousel.js jQuery plugin
;(function(window, $, undefined) {

    var conf = {
        center: true,
        backgroundControl: false
    };

    var cache = {
        $carouselContainer: $('.thumbnails-carousel').parent(),
        $thumbnailsLi: $('.thumbnails-carousel li'),
        $controls: $('.thumbnails-carousel').parent().find('.carousel-control')
    };

    function init() {
        cache.$carouselContainer.find('ol.carousel-indicators').addClass('indicators-fix');
        cache.$thumbnailsLi.first().addClass('active-thumbnail');

        if(!conf.backgroundControl) {
            cache.$carouselContainer.find('.carousel-control').addClass('controls-background-reset');
        }
        else {
            cache.$controls.height(cache.$carouselContainer.find('.carousel-inner').height());
        }

        if(conf.center) {
            cache.$thumbnailsLi.wrapAll("

");
        }
    }

    function refreshOpacities(domEl) {
        cache.$thumbnailsLi.removeClass('active-thumbnail');
        cache.$thumbnailsLi.eq($(domEl).index()).addClass('active-thumbnail');
    }

    function bindUiActions() {
        cache.$carouselContainer.on('slide.bs.carousel', function(e) {
            refreshOpacities(e.relatedTarget);
        });

        cache.$thumbnailsLi.click(function(){
            cache.$carouselContainer.carousel($(this).index());
        });
    }

    $.fn.thumbnailsCarousel = function(options) {
        conf = $.extend(conf, options);

        init();
        bindUiActions();

        return this;
    }

})(window, jQuery);

// Kick it
$('.thumbnails-carousel').thumbnailsCarousel({});

Additionally, you can pass center (default: true) and backgroundControl (default: false) if you want (or no) to center your thumbnails or backgroundControl if you want (or no) controls background which is activated on hover in bootstrap carousel.


texts:
It's a coding challenge you have to output the closest free index. It has to run sub 1 second.

Input looks like this:

The first line is 2 numbers. The first of them is the number of indexes that is. The second one is number of inputs for which you have to find a free index.

The rest of the lines is composed of a letter and a number:

If the letter is L then a index is freed with the supplied number.
If the letter is C then it is a request for an index at the supplied number.
If there is a free spot where it requested then it should just assign that. If not then it should find closest one that is free, with priority for lower numbers.

Here is an example:

#include <iostream>
#include <vector>
long int pos;
char inputcharacter;
long int salepoints;
long int numberofsales;
int main() {
    std::ios::sync_with_stdio(false);
    std::cin >> salepoints >> numberofsales;
    salepoints++;
    std::vector<int> kasser(salepoints);
    while (std::cin && numberofsales != 0) {
        std::cin >> inputcharacter >> pos;
        if (inputcharacter != 'L' && inputcharacter != 'C' && pos != 0) {
            exit;
        }
        if (inputcharacter == 'L')
            kasser[pos] = false;
        else if (kasser[pos] == false) {
                kasser[pos] = true;
                std::cout << pos << std::endl;
                }
        else if (inputcharacter == 'C'){
            bool fundetplads = false;
            int tries = 1;
            while (fundetplads != true) {
                if(pos - tries > 0){
                    if (pos - tries > 0 && kasser[pos - tries] == false) {
                        kasser[pos - tries] = true;
                        std::cout << pos - tries << std::endl;
                        fundetplads = true;
                        break;
                    }
                }
                if(pos + tries < salepoints){
                    if (pos + tries < salepoints && kasser[pos + tries] == false) {
                        kasser[pos + tries] = true;
                        std::cout << pos + tries << std::endl;
                        fundetplads = true;
                        break;
                    }
                }
                tries++;
            }
        }
        numberofsales--;
    }
    return 0;
}


texts:
Newbie OCaml review:

Given lists xs and ys that are both ordered in the same way (e.g. monotonically ordered integers), I want to return a list containing all elements of xs not in ys, with order preserved.  I can assume that the elements in ys are a (perhaps improper) subset of xs.

The key is that I have to walk two lists, but they are different lengths and I don't necessarily move through them at the same rate, so I can't use one of the fold2 functions, as far as I can see.

let rec subtract_list xs ys =
  match xs with
  | [] -> []
  | x::more_xs -> match ys with
                  | [] -> xs
                  | y::more_ys ->
                      if x = y
                      then subtract_list more_xs more_ys
                      else x::(subtract_list more_xs ys)

This is the best method I came up with, but I wonder if there's some better strategy that doesn't involve embedding a match inside a match or that's simpler or more idiomatic in some other way.  This version isn't tail recursive, but that's OK.  Comments on indentation or other formatting issues are welcome too.


texts: DuplicateDictionary - A dictionary-like class which allows duplicates

texts:
Since I couldn't find any good answers I made my own class called DuplicateDictionary for personal usage. I would like some tips to improve it.

public class DuplicateDictionary<TKey, TValue>: List<KeyValuePair<TKey, TValue>>
{
    public DuplicateDictionary()
    {

    }

    public DuplicateDictionary(List<KeyValuePair<TKey, TValue>> list)
    {
        foreach(KeyValuePair<TKey, TValue> kvp in list)
        {
            this.Add(kvp);
        }
    }

    public DuplicateDictionary(Dictionary<TKey, TValue> dictionary)
    {
        foreach(KeyValuePair<TKey, TValue> kvp in dictionary)
        {
            this.Add(kvp);
        }
    }

    public TValue this[TKey index]
    {
        get
        {
            this.ContainsKey(index);
            return this[index];
        }
        set
        {
            this[index] = value;
        }
    }

    public void Add(TKey key, TValue value)
    {
        this.Add(new KeyValuePair<TKey, TValue>(key, value));
    }

    public bool ContainsKey(TKey key)
    {
        foreach(KeyValuePair<TKey, TValue> kvp in this)
            if(kvp.Key.Equals(key)) return true;

        return false;
    }
}

This class is useful for log things. I use it to log a calculator's past functions and numbers, and once equals is pressed, adds all the past numbers with the functions.


texts:
I recently worked on a module, in which I implemented the functionality of downloading the CSV files.

@RequestMapping(value = "/export_data")
public void downloadDataInCsv(
        @RequestParam("type") String type,
        @RequestParam("tID") String tableId,
        HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    if (type.equals("csv")) {
        List<UserInfo> list = userInfoDao.findById(tableId);
        ExportCsvUtil.downloadCsv(request, response, list);
    }
}
private void downloadCsv(HttpServletRequest request, HttpServletResponse response, List<UserInfo> list) throws IOException {
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=Table_Data.csv");
    response.setContentType("text/csv");
    response.setHeader(headerKey, headerValue);

    try (final CSVWriter writer = new CSVWriter(response.getWriter(), ",")) {

        writer.writeNext(new String[]{"User Id", "First Name", "Last Name", "Roll No", "Email ID", "Gender"});

        for (UserInfo entry: list) {
            // cast/convert to String where needed
            writer.writeNext(new String[]{entry.getUserId()+"", entry.getFirstName(), entry.getLastName(),entry.getRollNo(),entry.getEmail(),entry.getGender()});
        }
        writer.close();
    }
}

I am using OpenCSV library for reading and writing the CSV files, in addition, one thing should be note down here is, the function writeNext() accepts String[] .

I initialized the String[] inside writeNext(). I want to know the better way to do the same, so the readability enhanced.

Please review my code and suggest me the best practice.


texts:
How to set in HTML/CSS a section just like in this picture https://snag.gy/mStL9H.jpg ?
I have tried something but am not sure if it's right.

#trd-banner{
    background-color:#284c57;
    width:100%;
    height:50%;
    margin:auto;
}
#list{
    position:relative;
 left:110px;
 top:1px;
 width:200px;
 height:150px;
    margin:0px 15px 15px 0px;
}
#list img{
    margin:0px 50px 50px 15px;
}
#prah {
    position:right;
 right:610px;
 top:180px;
 width:240px;
 height:171px;
    margin:0px 0px 15px 15px;
}
#prah img{
    float:right;

}

Unsere Zeolithprodukte sind reine Naturprodukte.

Sie bestehen zu 100% aus Zeolith mit einem hohen

Klinoptilolithanteil.

Das Produkt wurde von uns selbst 2 Jahre lang getestet,

bevor wir auf die Idee kamen, dass wir allen Menschen

diese Freude übermitteln wollen, dieses überwältigende

positive Gefühl von dessen Wirkung.

Da wir viel auf Reisen sind, nehmen wir Zeolith überall mit.

Für uns ist es das Wichtigste, etwas worauf man nicht

vergessen darf.

Deswegen wollen wir, dass jeder der Zeolith probieren will,

sich auch ein Produkt von hochwertiger Qualität leisten kann.

In Liebe und Respekt,

Ihre ZeolithFit Familie


texts: Finding the shortest excerpt that contains all search terms

texts:
Write a function called answer(document, searchTerms) which
  returns the shortest snippet of the document, containing all of the
  given search terms. The search terms can appear in any order.

Inputs:
(string) document = "many google employees can program"
(string list) searchTerms = ["google", "program"]
Output:
(string) "google employees can program"

 Inputs:
(string) document = "a b c d a"
(string list) searchTerms = ["a", "c", "d"]
 Output:
(string) "c d a"

My program below is giving the correct answer but the time complexity is very high since I am doing the Cartesian product. If the input is very high then I am not able to clear to those test cases. I am not able to reduce the complexity of this program, and any help will be greatly appreciated.

import itertools

import sys

def answer(document, searchTerms):

    min = sys.maxint

    matchedString = ""

    stringList = document.split(" ")

    d = dict()

    for j in range(len(searchTerms)):

        for i in range(len(stringList)):

            if searchTerms[j] == stringList[i]:

                d.setdefault(searchTerms[j], []).append(i)

    for element in itertools.product(*d.values()):

        sortedList = sorted(list(element))

        differenceList = [t - s for s, t in zip(sortedList, sortedList[1:])]

       if min > sum(differenceList):

          min = sum(differenceList)
          sortedElement = sortedList

          if sum(differenceList) == len(sortedElement) - 1:
            break

    try:
        for i in range(sortedElement[0], sortedElement[len(sortedElement)-1]+1):

            matchedString += "".join(stringList[i]) + " "

    except:
        pass

    return matchedString

If anyone wants to clone my program here is code


texts:
I've been reading about WeakPointer and WeakPointer<T> today, and it looks very useful.  Rather than just using it as-is though, I decided to write a wrapper around it that covers a common usage case for me.

Code as follows:

public class Temporary<T> where T : class
{
    Func<T> generator = null;
    WeakReference<T> reference = null;

    public T Value
    {
        get
        {
            return GetValue();
        }
    }

    public Temporary(T value)
        : this(value, null)
    { }

    public Temporary(Func<T> generator)
        : this(null, generator)
    { }

    public Temporary(T value, Func<T> generator)
    {
        reference = new WeakReference<T>(value);
        this.generator = generator;
    }

    public T GetValue()
    {
        if (reference == null)
            return null;
        T res;
        if (!reference.TryGetTarget(out res) && generator != null)
        {
            res = generator();
            reference.SetTarget(res);
        }
        return res;
    }
}

I've tested this against my use-case and it works as I expect - the garbage collector cleans out items with no active references, and they are re-instantiated at need.

I'm looking for critiques of the implementation and suggestions for improvements/additions.


texts: Project Euler #12 in Swift - Highly divisible triangular number

texts:
I just finished Project Euler #12 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.

  The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
  = 28. The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

  1: 1

  3: 1,3

  6: 1,2,3,6

  10: 1,2,5,10

  15: 1,3,5,15

  21: 1,3,7,21

  28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have
  over five divisors.

  What is the value of the first triangle number to have over five
  hundred divisors?

import Foundation

let OverNumberOfDivisors = 500

extension Int {
    func isMultipleOf(factor: Int) -> Bool {
        return self % factor == 0
    }
}

func findPrimesFactorFrom(let smallest: Int, let toFactor: Int, inout primesFactor:[Int:Int]) {
    var maxFactor = Int(sqrt(Double(toFactor)))
    maxFactor = maxFactor < smallest ? smallest : maxFactor
    for factor in smallest...maxFactor {
        if toFactor.isMultipleOf(factor) {
            primesFactor[factor] = (primesFactor[factor] ?? 0) + 1
            return findPrimesFactorFrom(factor, toFactor / factor, &primesFactor)
        }
    }

    primesFactor[toFactor] = (primesFactor[toFactor] ?? 0) + 1
}

func highlyDivisibleTriangularNumber() -> Int {

    var currentNumberOfDivisors = 1
    var triangleNumber = 1
    var number = 1

    var primesFactor:[Int:Int] = [:]

    while OverNumberOfDivisors >= currentNumberOfDivisors {

        number++
        triangleNumber += number
        primesFactor = [:]

        findPrimesFactorFrom(2, triangleNumber, &primesFactor)

        currentNumberOfDivisors = 1
        for (index, factor) in primesFactor {
            if index != 1 {
                currentNumberOfDivisors *= (factor + 1)
            }
        }
    }

    return triangleNumber
}

func euler12() {
    let number = highlyDivisibleTriangularNumber()

    println(number)
}

func printTimeElapsedWhenRunningCode(operation:() -> ()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed : \(timeElapsed) s")
}

printTimeElapsedWhenRunningCode(euler12)

The code executes in 0.3s


texts:
I made a simple AngularJS text function. The purpose is to provide an array of content to display. A 'slider' will be made with next and previous buttons that hide on the last and first slide, respectively. I can't help but feel it isn't very efficient. Any thoughts?

Here is a JSFiddle for those who want a live example.

Here is the code:

PREVIOUS

{{box}}

NEXT


texts: Calculating count of square numbers between two numbers

texts:
The problem is to find out the squares between two numbers, inclusive of the numbers. The two numbers are in the range between 1 and 109.

long numberOne = in.nextLong();
            long numberTwo = in.nextLong();
            int count=0;
            for(long j=numberOne;j<=numberTwo;j++){
                double numSquareRoot=Math.sqrt(j);
                double numFloor=Math.floor(numSquareRoot);
                if(numSquareRoot == numFloor) count++;
            }

What changes can be made to work efficiently on large numbers?


texts: Finding the lowest perfect square that can be added to a number to make another perfect square

texts:
The code below returns the smallest perfect square that can be added to a number n to result in a perfect square. It works perfectly fine but I need it to run faster.
def solve n
  (1..n).each do |i|
    i = i**2 + n
    return i -= n if (Math.sqrt(i) % 1).zero?
  end
  -1
end

p solve(13) #36
 # because 36 is the smallest perfect square that can be added to 13 to form a perfect square => 13 + 36 = 49

p solve(3) #= 1 # 3 + 1 = 4, a perfect square
p solve(12) #= 4 # 12 + 4 = 16, a perfect square
p solve(9) #= 16
p solve(4) #= -1`


texts: Satisfying general rate limits in PowerShell

texts:
I wrote this code for a PowerShell function that allows you to specify rate limits and makes a script block follow those limits.

The script block return value is for specifying if it should be counted, i.e., when a server has rate limits and the request to the server doesn't happen due to a client-side error, the script block should return false.

(Work in progess, still)

function Add-Delays {
    param (
        [ScriptBlock]$ScriptBlock,
        [Hashtable]$Delays,
        [Int32]$BaseDelay
    )

    begin {
        $Trackers = @{ }
        foreach ($Key in $Delays.Keys) {
            $IntKey = $Key -as [Int32]
            if ($null -eq $IntKey) {
                throw "$Key couldn't be converted to Int32"
            }
            elseif ($IntKey -le 0) {
                throw "$Key is not a positive number"
            }

            $IntValue = $Delays[$Key] -as [UInt32]
            if ($null -eq $IntValue) {
                throw "$($Delays[$Key]) couldn't be converted to UInt32"
            }
            elseif ($IntValue -le 0) {
                throw "$($Delays[$Key]) is not a positive number"
            }
        }

        foreach ($Key in $Delays.Keys) {
            $Trackers += @{
                $Key = @{
                    Timer = [System.Diagnostics.Stopwatch]::new()
                    Counter = [UInt64]1
                }
            }
        }
    }

    process {
        foreach ($Key in $Delays.Keys) {
            # Write-Host "D `t $Key `t $($Trackers[$Key].Timer.elapsedMilliseconds) ms `t $($Trackers[$Key].Counter)"
        }

        foreach ($Key in $Delays.Keys) {
            if (
                $Trackers[$Key].Timer.elapsedMilliseconds -gt
                [Int32]$Key
            ) {
                $Trackers[$Key].Timer.Reset()
                $Trackers[$Key].Counter = [UInt64]0
            }
        }

        foreach ($Key in $Delays.Keys) {
            $Trackers[$Key].Timer.Start()
        }

        $Wait = 0

        foreach ($Key in $Delays.Keys) {
            $Elapsed = $Trackers[$Key].Timer.elapsedMilliseconds

            if (
                $Elapsed -lt [Int32]$Key -and
                $Trackers[$Key].Counter -gt $Delays[$Key]
            ) {
                $RemainingTime = [Int32]$Key - $Elapsed
                $Wait = [Math]::Max($Wait, $RemainingTime)

                # Write-Host "A `t $Key `t $Elapsed `t $RemainingTime"
            }
        }

        foreach ($Key in $Delays.Keys) {
            $Trackers[$Key].Timer.Start()
        }

        # Write-Host "B `t $Wait `t $($Wait + $BaseDelay)"

        Start-Sleep -Milliseconds ($Wait + $BaseDelay)

        foreach ($Key in $Delays.Keys) {
            $Trackers[$Key].Timer.Stop()
        }

        $ReturnValue = & $ScriptBlock $_

        # Write-Host "C `t $_ `t $ReturnValue"

        foreach ($Key in $Delays.Keys) {
            # Write-Host "D `t $Key `t $($Trackers[$Key].Timer.elapsedMilliseconds) ms `t $($Trackers[$Key].Counter)"
        }

        foreach ($Key in $Delays.Keys) {
            $Trackers[$Key].Timer.Stop()
        }

        if ($ReturnValue) {
            foreach ($Key in $Delays.Keys) {
                $Trackers[$Key].Counter += 1
            }
        }
    }

    end {

    }
}
```


texts:
I would like to write simple application where I'm going to make a few views:

Login
Register
Main app

I think that my method is not the best way to do this. Can someone give me a tip?

Main.java

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.fxml.FXMLLoader;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("Login.fxml"));
            Scene scene = new Scene(root,400,400);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Controller.java

package application;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Controller implements Initializable{

    @FXML
    Button openRegister;

    @FXML
    Button openLogin;

    private Stage stage;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    @FXML
    private void openRegister() throws IOException{
        stage = (Stage) openRegister.getScene().getWindow();
        BorderPane root;
        root = (BorderPane) FXMLLoader.load(getClass().getResource("Register.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        stage.setScene(scene);
        System.out.println("Register.fxml opened");
    }

    @FXML
    private void openLogin() throws IOException{
        stage = (Stage) openLogin.getScene().getWindow();
        BorderPane root;
        root = (BorderPane) FXMLLoader.load(getClass().getResource("Login.fxml"));
        Scene scene = new Scene(root);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        stage.setScene(scene);

        System.out.println("Login.fxml opened");
    }

}

Login.fxml

    <?xml version="1.0" encoding="UTF-8"?>

    <?import java.lang.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.*?>
    <?import javafx.scene.layout.BorderPane?>

    <BorderPane xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">

          <Button fx:id="openRegister" mnemonicParsing="false" onMouseClicked="#openRegister" text="Button" BorderPane.alignment="CENTER" />

    </BorderPane>

Register.fxml

<?xml version="1.0" encoding="UTF-8"?>

        <?import java.lang.*?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.layout.*?>
        <?import javafx.scene.layout.BorderPane?>

        <BorderPane xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">

              <Button fx:id="openLogin" mnemonicParsing="false" onMouseClicked="#openLogin" text="Button" BorderPane.alignment="CENTER" />

        </BorderPane>


texts:
I'm working on a little AI to simulate ants (very basic). The full code can be found on Github. This function (in Ants.py) takes a list of Tuples containing coordinates and tells whether or not the ant is over one of them.

def Got_Food(self,all_foods):
    foods = []
    x,y = self.location[0],self.location[1]
    c_x,c_y = self.size[0],self.size[1]
    for food in all_foods:
          if food[1] >= y-c_y and food[1] <= y+c_y \
          and food[0] >= c_x and food[0] <=x+c_x:
            if food[1] > y and food[1] <y+c_y\
            and food[0] > x and food[0] <x+c_x:
                foods.append((food[0],food[1]))
            elif food[1] < y and food[1] >y-c_y\
            and food[0]  > x and food[0] >x-c_y:
                foods.append((food[0],food[1]))
          if food[0] >= x-c_x and food[0] <= x+c_x \
          and food[1] >= y and food[1] <=y+c_y:
                foods.append((food[0],food[1]))
    if len(foods) == 0:
        return None
    return foods

This function works exactly as I want, but it is probably one of the ugliest I've ever seen or written. Does anyone know a way around all these nested loops?


texts: Single Linked List Implementation in Ruby

texts:
The #traverse_until method is a helper function that traverses the linked list and returns the node and index of the node once a condition (in a block) is met or until the end of the list. I would greatly appreciate feedback about verbosity, efficiency, readability, etc.

module DataStructures
  class Node
    attr_accessor :value, :next_node

    def initialize(value = nil, next_node = nil)
      @value = value
      @next_node = next_node
    end
  end

  class LinkedList
    attr_accessor :head

    def initialize(element = nil)
      element.nil? ? @head = nil : @head = Node.new(element)
    end

    def append(data)
      prepend(data) if @head.nil?
      current = @head
      until current.next_node.nil?
        current = current.next_node
      end
      current.next_node = Node.new(data)
    end

    def prepend(data)
      @head = Node.new(data, @head)
    end

    def find(data)
      result = traverse_until { |node, index| node.value == data }
      result[:node].value == data ? result[:index] : "Data not found."
    end

    def contains? (data)
      result = traverse_until { |node, index| node.value == data }
      result[:node].value == data
    end

    def node_at_index(index)
      result = traverse_until { |node, i| i == index }
      "Node at index #{index}: #{result[:node].value}"
    end

    def head
      @head.nil? ? "Empty list" : @head.value
    end

    def tail
      last_node = traverse_until { |node, index| node.next_node.nil? }
      last_node[:node].value
    end

    def size
      last_node = traverse_until { |node, index| node.next_node.nil? }
      "List Size: #{last_node[:index] + 1}"
    end

    def insert_at(data, index)
      current = @head

      (index - 1).times do |n|
        current = current.next_node
      end

      node_shifted_right = current.next_node
      current.next_node = Node.new(data, node_shifted_right)
    end

    def remove_at(index)
      node_after_index = @head
      previous = node_after_index
      (index + 1).times do |n|
        node_after_index = node_after_index.next_node
      end

      (index - 1).times do |n|
        previous = previous.next_node
      end

      previous.next_node = node_after_index
    end

    def pop
      node_before = nil
      current = @head
      until current.next_node.nil?
        node_before = current
        current = current.next_node
      end
      node_before.next_node = nil
    end

    def to_s
      result = ""
      current = @head
      loop do
        result += "(#{current.value}) -> "
        break if current.next_node.nil?
        current = current.next_node
      end
      result += "nil"
    end

    private

    def traverse_until
      current = @head
      index = 0
      until current.next_node.nil? || yield(current, index)
        current = current.next_node
        index += 1
      end
      {node: current, index: index}
    end
  end
end


texts:
I completed writing a dice roll script in Python but I thought it looked too messy. Is there anything I should change here?

import random, os

class Dice:
    result = []
    total = 0

    def __roll_(sides=1):
        return random.randint(1, sides)

    def roll(sides=1, times=1):
        for time in range(0, times):
            Dice.result.append(Dice.__roll_(sides))
            Dice.result = Dice.result[len(Dice.result) - times:len(Dice.result)]
        Dice.sumResult()
        return Dice.result

    def sumResult():
        Dice.total = 0
        for num in range(0, len(Dice.result)):
            Dice.total += Dice.result[num]
        return Dice.total

    def saveResult(directory=''):
        if directory == '':
            savetxt = open('savedResult.txt', 'a+')
        else:
            savetxt = open(os.path.join(directory, 'savedResult.txt'), 'a+')
        savetxt.write(str(Dice.result) + '\n')
        savetxt.close()

    def saveTotal(directory=''):
        if directory == '':
            savetxt = open('savedTotal.txt', 'a+')
        else:
            savetxt = open(os.path.join(directory, 'savedTotal.txt'), 'a+')
        savetxt.write(str(Dice.total) + '\n')
        savetxt.close()


texts:
I have made a simple command line version of connect 4. It is my first time using classes and importing one part of my project into another so any feedback on how I've done and any way it could be changed or improved would be helpful.

This code file (connect4.py) contains the basic functions I have made:

class connect4:
    def __init__(self, height=6, width=7):
        self.height = height
        self.width = width
        self.board = [['' for x in range(width)] for i in range(height)]

    def return_board(self):
        return self.board

    def get_column(self, index):
        return [i[index] for i in self.board]

    def get_row(self, index):
        return self.board[index]

    def get_diagonals(self):
        diagonals = []
        for p in range(self.height + self.width - 1):
            diagonals.append([])
            for q in range(max(p - self.height + 1, 0),
                           min(p + 1, self.height)):
                diagonals[p].append(self.board[self.height - p + q - 1][q])
        for p in range(self.height + self.width - 1):
            diagonals.append([])
            for q in range(max(p - self.height + 1, 0),
                           min(p + 1, self.height)):
                diagonals[p].append(self.board[p - q][q])
        return diagonals

    def make_move(self, team, col):
        if '' not in self.get_column(col):
            return self.board
        i = self.height - 1
        while self.board[i][col] != '':
            i -= 1
        self.board[i][col] = team
        return self.board

    def check_win(self):
        for i in range(self.height):  # check rows
            for x in range(self.width - 3):
                if self.get_row(i)[x:x + 4] in [['0', '0',
                                                 '0', '0'], ['1', '1', '1', '1']]:
                    return self.board[i][x]
        for i in range(self.width):  # check columns
            for x in range(self.height - 3):
                if self.get_column(
                        i)[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:
                    return self.board[x][i]
        for i in self.get_diagonals():
            for x in range(len(i)):
                if i[x:x + 4] in [['0', '0', '0', '0'], ['1', '1', '1', '1']]:
                    return i[x]

        return None

This file is what I run and imports the connect4.py file:

import connect4

b = connect4.connect4()

while True:
    for i in b.return_board():
        print(i)
    if b.check_win() != None:
        break
    col = int(input('Team 0 choose column: '))-1
    b.make_move('0' , col)
    for i in b.return_board():
        print(i)
    if b.check_win() != None:
        break
    col = int(input('Team 1 choose column: '))-1
    b.make_move('1' , col)

print('Thank you for playing')


texts: PRNG - Algorithm: Performance vs Readability

texts:
I have a PRNG-Algorithm:

/**
* Generates an integer. Min: 0 | Max: total - 1
* @param    total The number of possibilities.
* @return The generated number.*/
public function generate_normal(total:int):int
{
    _seed = (_seed * MULTIPLIER) % MODULUS;
    return (_seed * total / MODULUS);
}

The constants are defined as follows:

/**The Multiplier.*/
private const MULTIPLIER:int = 48271;

/**The Modulus.*/
private const MODULUS:int = 2147483647;

This is readable and understandable, but pretty slow (~50% more time).

Simply using the numbers would be faster, but less readable. Will people call these numbers "magic" and kill me or will everything be fine? Should I change this part in the class description:

Modulus suggested 1988 by Stephen K. Park and Keith W. Miller.
Multiplier suggested 1993 by Park and Miller.

to this:

Modulus (2147483647) suggested 1988 by Stephen K. Park and Keith W. Miller.
Multiplier (48271) suggested 1993 by Park and Miller.

Should I keep my approach or use the numbers directly?

TL;DR What's more important, performance or readability?


texts:
I've implemented a multicolored bar as shown in the image below. It is a bar that is placed above the legend of an HTML form. (Ignore the border radius for now.)

I have accomplished this with a simple approach of using span elements.

*{
    margin: 0px;
    padding: 0px;
}

span{
    height: 5px;
    width: calc(100% / 7);
    background: black;
    display: inline-block;
}

span[data-color='green']{
    background: #C3E279;
}

span[data-color='pale-yellow']{
    background: #F7FEC8;
}

span[data-color='orange']{
    background: #FFD069;
}

span[data-color='red']{
    background: #F27669;
}

span[data-color='light-purple']{
    background: #DC9CBE;
}

span[data-color='purple']{
    background: #C59AE0;
}

span[data-color='blue']{
    background: #969DCC;
}

Is there a better way to do this to make the code smarter, presentable and easy to understand to other developers?


texts: Repeated DB connection at max user connections

texts:
I am trying to create class with connect to mysql database. And if there is max number of connections I want to wait and try it again. I figured out, how it can works, but I am not sure, if its the right way of doing it. So, my code looks like this:
<?php

class DbConnect {

  private $attemps = 1;
  private $errorCode;
  private $maxAttemps = 10;
  private $pdo;
  private $dsn = "mysql:host=localhost;dbname=...;charset=utf8";
  private $options = [
    PDO::ATTR_EMULATE_PREPARES   => false, // turn off emulation mode for "real" prepared statements
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
    /*PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,*/ //make the default fetch be an associative array
  ];

  public function __construct(){
    $this->tryConnect();
    while ($this->errorCode == 1040 && $this->attemps <= $this->maxAttemps) {
      usleep(pow(2, $this->attemps)*10000);
      $this->tryConnect();
    }

  }

  protected function tryConnect(){
    try {
      $this->pdo = new PDO($this->dsn, "root", "", $this->options);
    } catch (Exception $e) {
      error_log($e->getMessage());
      $this->errorCode = $e->getCode();
      $this->attemps++;
    }
  }

}

?>

Is there anything i should change? Thank you very much.


texts:
Can this be improved?

static int find(string term, string text)
    {
        int found = -1;
        int termIndex = 0;

        for (int textIndex = 0; textIndex < text.Length; textIndex++)
        {
            if (term[termIndex] == text[textIndex])
            {
                if (termIndex == term.Length-1)
                    return found;
                if (termIndex == 0)
                    found = textIndex;
                termIndex++;
            }else
            {
                termIndex = 0;
                found = -1;
            }
        }
        return found;
    }


texts: Get current user middleware from JWT using express

texts:
I'm using Sequelize and Google oAuth for authentication, I want to create a middleware that

Verifies the sent token passed in the headers matches the  one the user was initially signed to.
Finds the user if he/she exists and returns it to the client.

The middleware be used for protected routes.

const getCurrentUser = (req, res, next) => {
  if (!req.headers || !req.headers.authorization) return res.status(401).end();

  const token = req.headers.authorization.split(' ')[1];
  if (!token) return res.status(401).end();

  JWT.verify(token, process.env.JWT_SECRET, async (err, decoded) => {
    if (err) {
      res.status(401).end();
    } else {
      res.locals.JWT = decoded;
      const user = await models.user.findOne({ where: { id: decoded.id } });
      if (!user) return res.status(404).send({ message: 'No user found' });
      req.user = user;
      next();
    }
  });
};

One thing I'd like to make sure I'm doing correctly is error handling. Does this look alright? Anything to change/improve on?


texts:
The following is my attempt to implement a insert_sorted() C++ function that accepts any sorted STL container and item and inserts it at the right position in the container:
template<template<typename, typename, typename> typename C, typename T1, typename Comp, typename A, typename T2>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, Comp, A>::iterator
insert_sorted (C<T1, Comp, A> & c, T2 && item)
{
    return c.insert (c.end(), std::forward<T2> (item));
}

template<template<typename, typename> typename C, typename T1, typename A, typename T2, typename Comp = std::less<T1>>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, A>::iterator
insert_sorted (C<T1, A> & c, T2 && item, Comp comp = Comp{})
{
    return c.insert (std::upper_bound (std::begin (c), std::end (c), static_cast<T1>(item), comp), std::forward<T2> (item));
}

These two compile and work fine; the first overload works for set-like containers, while the second for vector-like containers.
I was wondering if you see any drawbacks to this solution and if there is a more generic way to approach the problem, that is, is it possible to write a single insert_sorted() function that does the same as the above two?
EDIT:
Thanks to the comments, I was able to replace the two template functions above with the following:
template<typename C, typename T, typename Comp = std::less<T>,
         typename = std::enable_if<is_convertible_v<std::remove_reference_t<T>, typename C::value_type>>>
    inline auto insert_sorted (C & c, T && item, Comp comp = Comp{})
{
    return c.insert (std::upper_bound (std::begin (c), std::end (c), item, comp), std::forward<T> (item));
}

Thank you all for your help!


texts:
I have to read a line of strings and split it for whitespace:

ArrayList<HashSet<String>> setOfStrings = new ArrayList<HashSet<String>>();
while ((currentLine = bufferedReader.readLine()) != null) {
        String[] tokens = currentLine.split(" ");
        for (int i = 0; i < tokens.length; i++) {
        setOfStrings.add(new HashSet<String>(Arrays.asList(tokens[i])));
        }
    }

i have to do this ,and for this reason i need for each tokens a new hashSet

i need to make operations on tokens like

[afaf] -> one hashset in first position inside the arrayList
[bafafa] -> one hashset in second position inside the arrayList
[cssss]
[dggg]
...

with your solution ,to make a unique hashset for the tokens, i can't do separate operations for each tokens.

How can I improve the split of the currentLine and the insertion into the arrayList?  As I did it, it's very slow because I first have to split and then iterate on the array of tokens.  How can I optimize this operation?


texts: Sharing File (Content) without saving it before

texts:
I have a listview of PrivateFile objects which contain the fileId (int), fileName (String) and the fileContent (byte []). In order to share the file, I currently save the file first, open it again, and then I share it. In my opinion this is really semi-professional. Is there a way wherein I can only share the file (content)/byte array without saving it before? Or can I improve my code in general?

privateDocs.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            try {
                PrivateFile selFile = (PrivateFile) arg0.getItemAtPosition(pos);

                File folder = new File(Environment.getExternalStorageDirectory() + "/myFolder");
                boolean success = true;
                if (!folder.exists()) {
                    success = folder.mkdir();
                }
                if (success) {
                    //safe file in order to open it later
                    File file = new File(folder.getAbsolutePath() + "/" + selFile.getFileName());
                    FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
                    fos.write(selFile.getFileContent());
                    fos.close();

                    Intent intentShareFile = new Intent(Intent.ACTION_SEND);

                    if(file.exists()) {
                        String newMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()));
                        intentShareFile.setType(newMimeType);
                        intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath()));
                        intentShareFile.putExtra(Intent.EXTRA_SUBJECT,
                                    "Sharing File...");
                        intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File...");

                        startActivity(Intent.createChooser(intentShareFile, "Share File"));
                    }

                } else {
                    throw new Exception("could not open folder");
                }
            } catch (Exception ex) {
                System.out.println("Err:" + ex.getMessage());
            }
            return true;
        }
    });


texts:
I was given this task: Calculate amount of elements in collection by property: "name"

 let array = [
    {name: 'Serhii'},
    {name: 'Serhii'},
    {name: 'Nile'},
    {name: 'Apple'},
    {name: 'Serhii'},
    {name: 'Serhii'},
    {name: 'Apple'},
    {name: 'Serhii'},
];

Here is my solution:

 function calculateElements(property, arr) {
    let amount = {};

    arr.forEach((e) => {
        let p = e[property];
        p in amount ? amount[p]++ : amount[p] = 1;
    });
    return amount;
}
console.log(calculateElements('name', array));

Is there more efficient way to do it?


texts:
I have implemented a simple do/while loop to handle a http request to a third-party. I don’t know when the data I receive will have elements in its array so I retry up to 10 times until the array given to me has data which then I stop and store the data in my database.

My question is in terms of performance is my API going to be affected by having this retry mechanism using a simple do/while loop? If so what is a better way to implement a retry mechanism like this??

public MAX_RETRY = 10;

public async processMetrics(sessionId: any, side: any): Promise <any> {

  try {

    let metrics;
    let retryAttempts = 0;

    do {
      await new Promise((done) => setTimeout(done, 2000));
      metrics = await this.getMetrics(session._id, sessionRequest._id);
      retryAttempts++;

    } while (!metrics.body.metrics.length && (retryAttempts < this.MAX_RETRY));

    // Store in DB
  } catch (err) {

  }

}

public async getMetrics(sessionId: any, requestId: any): Promise <any> {

  const url = this.config.backendUrl + "/check/metrics";

  const options = {
    uri: url,
    headers: {
      "X-IDCHECK-SESSION_ID": sessionId,
    },
    body: {},
    json: true,
    resolveWithFullResponse: true,
  };

  const metrics = await request.get(options);

  return metrics;

}

I am calling processMetrics from a different async function.  processMetrics is calling a backend (getMetrics) every 2 seconds, it will retry 10 times to see if the result is ready. If it is I will store something in the database and then return.


texts:
For one of my labs I need to write a complete java program which will simulate a "very simple" dice betting game. The specifications are as follows: simulate the throw of 3 dice. If you throw three sixes then you win $20; if you throw three of any other value then you win $10; if you throw two dice which are the same value then you win $5. If none of the conditions above are met, then you would lose $1.
Example Runs: Dice Throw
Dice 1 : 2     Dice 2 : 1    Dice 3 : 2
Congratulations : You threw TWO - 2s
You win $5

Dice 1 : 2    Dice 2 : 2    Dice 3 : 2
Congratulations : You threw THREE - 2s
You win $10

Dice 1 : 4    Dice 2 : 6    Dice 3 : 3
Unfortunately : You did not throw anything of value
You lose $1

The resulting code that I wrote to solve this problem is as follows:
/**
 * SRN: 507-147-9
 */
public class Lab6_part3 {

    public static void main(String[] args) {

        // define vars
        int round = 1;
        int dice1, dice2, dice3;

        while (round <= 3) {

            dice1 = 1 + (int)(Math.random() * 6);
            dice2 = 1 + (int)(Math.random() * 6);
            dice3 = 1 + (int)(Math.random() * 6);

            System.out.println();
            System.out.println("Dice 1 : " + dice1 + "    Dice 2 : " + dice2 + "    Dice 3 : " + dice3);

            // Three of a kind
            if ((dice1 == dice2) && (dice1 == dice3)) { // 3-of-a-kind (D1)

                // Rolls three sixes
                if (dice1 == 6) {
                    System.out.println("Congratulations : You threw THREE - 6s");
                    System.out.println("You win $20");
                } else {
                    // Rolls three of anything else
                    System.out.println("Congratulations : You threw THREE - " + dice1 + "s");
                    System.out.println("You win $10");
                }
            }

            // Two of a kind (PRINT "dice1")
            else if (dice1 == dice2 || dice1 == dice3) {
                System.out.println("Congratulations : You threw TWO - " + dice1 + "s");
                System.out.println("You win $5");
            }

            // Two of a kind (PRINT "dice2")
            else if (dice2 == dice1 || dice2 == dice3) {
                System.out.println("Congratulations : You threw TWO - " + dice2 + "s");
                System.out.println("You win $5");
            }

            // Two of a kind (PRINT "dice3")
            else if (dice3 == dice1 || dice3 == dice2) {
                System.out.println("Congratulations : You threw TWO - " + dice3 + "s");
                System.out.println("You win $5");
            }
            // Did not throw anything of value
            else {
                System.out.println("Unfortunately : You did not throw anything of value");
                System.out.println("You lose $1");
            }
            round++;
        }
    }
}

The problem that I'm running into with this approach is that although the code functions as it's supposed to, I would like to have a simpler way to write the two-of-a-kind instead of having three "if" statements.
My goal in this, is to create a three-way "or" statement instead of comparing dice1 with dice 2 and 3, and dice 2 with dice 1 and 3, etc...
else if (dice1 == dice2 || dice1 == dice3 || dice2 == dice3) {
    System.out.println("Congratulations : You threw TWO - " + somethings?? + "s");
    System.out.println("You win $5");

If I were to do that, how would I then be able to print out the value of the pair which I've identified?


texts: Custom header with React-Navigation and React-Native-Paper

texts:
Thanks to the discussion in this issue combined with issue 1886 and issue 716 and issue 570 I was able to integrate the Toolbar of react-native-paper and with react-navigation.

As I am quite new to react-native development I am unsure if I might have broken some don'ts. I am also unsure about the prop-types I have defined.

import * as React from 'react';
import { Platform, StatusBar } from 'react-native';
import PropTypes from 'prop-types';
import { StackNavigator } from 'react-navigation';
import { Toolbar, ToolbarContent, ToolbarBackAction } from 'react-native-paper';
import Home from '../screens/Home';
import First from '../screens/First';

const CustomHeader = (props) => {
  const { getScreenDetails, scene, navigation } = props;
  const details = getScreenDetails(scene);

  return (
    <Toolbar dark statusBarHeight={Platform.OS === 'ios' ? 20 : StatusBar.currentHeight}>
      {navigation.state.routes.length > 1 && <ToolbarBackAction onPress={() => navigation.pop()} />}
      <ToolbarContent title={details.options.title} />
    </Toolbar>
  );
};

CustomHeader.propTypes = {
  getScreenDetails: PropTypes.func.isRequired,
  scene: PropTypes.shape({
    isActive: PropTypes.bool,
  }).isRequired,
  navigation: PropTypes.shape({
    state: PropTypes.object,
  }).isRequired,
};

const Stack = StackNavigator(
  {
    Home: {
      screen: Home,
      navigationOptions: () => ({
        title: 'Home Screen',
        header: props => <CustomHeader {...props} />,
      }),
    },
    First: {
      screen: First,
      navigationOptions: () => ({
        title: 'First Screen',
        header: props => <CustomHeader {...props} />,
      }),
    },
  },
  {
    initialRouteName: 'Home',
  },
);


texts: Template function which determines how to move-assign a type

texts:
In some code that I am writing, I am manipulating some heterogeneous containers of user-defined types.

I desperately need to be able to move-assign these types without generating exceptions.

However, this can cripple the usability of my code because on many older compilers, important standard library types do not have noexcept markings on their move-assignment operators. For instance std::string appears not to be noexcept move-assignable with gcc 4.9, it is only noexcept move constructible in C++11.

To work around this, I have developed a template function which tries various strategies for move-assigning things until it finds one which is noexcept, if it cannot then it gives up.

namespace traits {

template <bool b, typename V = void>
using enable_if_t = typename std::enable_if<b, V>::type;

} // end namespace traits

namespace detail {

template <typename T>
auto move_assign_noexcept(T & dest, T && src) noexcept -> traits::enable_if_t<std::is_nothrow_move_assignable<T>::value> {
  dest = std::move(src);
}

template <typename T, typename ENABLE = void>
struct is_nothrow_swappable : std::false_type {};

template <typename T>
struct is_nothrow_swappable<T, traits::enable_if_t<noexcept(std::swap(*static_cast<T*>(nullptr), *static_cast<T*>(nullptr)))>> : std::true_type {};

template <typename T>
auto move_assign_noexcept(T & dest, T && src) noexcept -> traits::enable_if_t<!std::is_nothrow_move_assignable<T>::value
                                                                   && is_nothrow_swappable<T>::value> {
  std::swap(dest, src);
}

template <typename T>
auto move_assign_noexcept(T & dest, T && src) noexcept -> traits::enable_if_t<!std::is_nothrow_move_assignable<T>::value
                                                                   && !is_nothrow_swappable<T>::value
                                                                   && std::is_nothrow_move_constructible<T>::value> {
  dest.~T();
  new (&dest) T(std::move(src));
}

} // end namespace detail

This code is supposed to work at C++11 standard.

I recall that there is a standard function std::move_if_noexcept which is useful for standard containers which are trying to avoid exception problems.

Is there an existing standard idiom for doing what I am trying to do?

Are there other strategies that I should try? Am I actually using standard traits correctly to ensure that each implementation actually won't throw?


texts:
Any pointers, or any advice on how to clean up my code/make more pythonic would be appreciated.

graph = {'A': ['B','Y','D', 'E',],
         'B': ['F','F'],
         'C': ['F'],
         'D': [],
         'E': ['F','G'],
         'F': ['F','A'],
         'G': ['E','K'],
         'K': ['M','L']
         }

def bfs(graph,start,end):
    vertex = [start]
    history = []

    #  create new node to be iterated through
    #  update history
    #  update vertex

    while vertex:  #  while vertex is not empty. len(li) == 0:

        node = vertex[0]  #  get the 0th element of the vertex
        history.append(node)
        print(node)

        vertex.pop(0)  #  pop the 0th element of the vertex
        if node == end:
            return end

      #  iterate through the graph. gather all of the values per node

        for i in graph.get(node, '/'): #  if key does not exist, print '/'

            if i:  #if i is not empty
                vertex.append(i)
                # append the dict values into vertex list
                print('vertex',vertex)

            if i in history:
               vertex.pop(-1)


texts:
Following these two SO questions:

Find duplicates for mixed type values in dictionaries
Group similar dict entries as a tuple of keys

I came to the conclusion that the solution I proposed is mature enough to be reviewed here.

The idea is to find duplicates in a dictionary such as example below, but with extended support for mixed type content (seq/mapping/scalars):

d = collections.defaultdict(set)
[d[k].add(v) for k, v in s]

Here's my solution:

import copy
import collections

def faithfulrepr(ds):
    """Returns a plain-text representation of a mixed seq/mapping/scalar
    type data structure.

    The datastructure is recursively ordered (ordereddict) then a
    dataset representation is returned.

    Args:

        ds  Dataset (mixed seq/mapping/scalar data structure)

    Returns:

        Sorted plain-text representation of the input dataset.
    """
    ds = copy.deepcopy(ds)
    if isinstance(ds, collections.Mapping):
        res = collections.OrderedDict()
        for k, v in sorted(ds.items()):
            res[k] = faithfulrepr(v)
        return repr(res)
    if isinstance(ds, list):
        for i, v in enumerate(ds):
            ds[i] = faithfulrepr(v)
        return repr(ds)
    return repr(ds)

def tupelize_dict(ds):
    """Group identical values of a dictionary under the same key. The keys
    become a tuple of all the duplicate keys.

    Args:

        ds: Input dictionary

    Example::

        ds = {23: 'foo',
              25: 'bar',
              28: 'foo',
              30: 'bar',
              33: 'foo'}

        >>>tupelize_dict(ds)
        {
            (23,28,33): 'foo',
            (25,30): 'bar'
        }
    """
    taxonomy = {}
    binder = collections.defaultdict(list)
    for key, value in ds.items():
        signature = faithfulrepr(value)
        taxonomy[signature] = value
        binder[signature].append(key)
    return {tuple(keys): taxonomy[s] for s, keys in binder.items()}

I am open for any better name for tupelize_dict :)


texts: Script for starting a rails app, with some peculiarities

texts:
I wanted to write a script, which starts a rails app, and opens it in the browser.
I'm trying to implement this in a peculiar way though - I expect two things:

the script must wait until the server is started, then open the browser within a short time
when I stop the script (Ctrl+C), the server process must stop.

The script I've written actually works, but I was wondering if there is a simplerr/more standard/more correct way of writing it.

The script is written for linux, but it's not meant to be platform specific - or more precisely, anything except Windows.

PROJECT_DIR          = '/path/to/app'
POLLING_TIME         = 0.1
SERVER_STARTED_REGEX = /WEBrick::HTTPServer#start/
BROWSER_COMMAND      = 'browser http://localhost:3000 &'

Dir.chdir( PROJECT_DIR )

thread = Thread.new do
  IO.popen( 'script/rails server 2>&1' ) do | io |
    Thread.current[ :last_server_line ] = io.gets while true
  end
end

sleep POLLING_TIME while thread[ :last_server_line ] !~ SERVER_STARTED_REGEX

`#{ BROWSER_COMMAND }`

thread.join


texts: Class method to insert a record into MySQL

texts:
I'm just starting out using OOP; classes and methods etc. I've been looking around for some PDO classes/wrappers out there, but there's not much to choose from. So I've tried to make my own. Started out by writing an "insert" method.

As a man with low self esteem, I never like what I do myself, so I thought I'd ask you guys here for feedback. Here it is:

public function insert($tbl, $data) {

    $this->_stmt = $this->_dbh->prepare("INSERT INTO $tbl (" . implode(', ', array_keys($data)) . ") VALUES (:" . implode(', :', array_keys($data)) . ")");

    foreach($data as $key => $value) {
        $this->_stmt->bindValue($key, $value, PDO::PARAM_STR);
    }

    $this->_stmt->execute();
}

The meaning was that it could all be done in one sweep instead of having several methods to do one thing; inserting a record.

An example of using this code:

$message   = 'A message for the ones who like to read it!';
$sent_on   = 'Saturday 23rd 2012';
$unique_id = 'unique_as_can_get';

$data = array(
    'message'   => $message,
    'sent_on'   => $sent_on,
    'unique_id' => $unique_id
);

$insert = new DB;
$insert->insert('tablename', $data);

I've put the database connection into the constructor.

The code works as I want it to, but I'm still confused if it's "accepted" amongst you people who are way more skilled that I will ever be.

Please let me know if this code if "usable" and/or what is wrong with it, what can be improved/changed etc.


texts:
I'm writing code to find the available ports on 127.0.0.1. I'd like it to be faster, but it's functional now.

def find_open_ports():
    for port in xrange(1,8081):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        res = sock.connect_ex(('localhost', port))
        if res == 0:
            yield port
        sock.close()

and it is called with available_ports = list(find_open_ports()).

There is no error handling because this will be running server-side. If localhost can't be found, there are bigger problems than failing a port scan.


texts: Calculate sum of an attribute across multiple repositories

texts:
I have multiple repositories that contain userId, paidDate and amount attributes like Bills(userId, paidDate, amount) Shoppings(userId, paidDate, amount) etc. I want to get sum of amounts and group them by userId and get something like this {user1: {amount1, amount2, amount3 ..}, user2: {amount4, ..}}

I created a expenseDetails model that contains all of repositories above.

public class ExpenseDetails
{
    public IEnumerable<ApplicationUser> ApplicationUsers { get; set; }
    public IEnumerable<Bill> Bills { get; set; }
    public IEnumerable<Shopping> Shoppings { get; set; }
    public IEnumerable<Rent> Rents { get; set; }
}

And I created a helper method for calculate the sum of amounts with looping every model in expenseDetails.

public static Dictionary<string, List<double>> UsersExpense(ExpenseDetails expenseDetails)
    {
        Dictionary<string, List<double>> TotalCosts = new Dictionary<string, List<double>>();
        List<double> Total = new List<double>();
        double sum = 0;

        foreach (var user in expenseDetails.ApplicationUsers)
        {
            foreach (var item in expenseDetails.Shoppings)
            {
                if (item.ApplicationUserId == user.Id)
                {
                    if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
                    {
                        sum = item.Amount + sum;
                    }
                }
            }

            Total.Add(sum);
            sum = 0;

            foreach (var item in expenseDetails.Bills)
            {
                if (item.ApplicationUserId == user.Id)
                {
                    if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
                    {
                        sum = item.Amount + sum;
                    }
                }
            }

            Total.Add(sum);
            sum = 0;

            foreach (var item in expenseDetails.Rents)
            {
                if (item.ApplicationUserId == user.Id)
                {
                    if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
                    {
                        sum = item.Amount + sum;
                    }
                }
            }

            Total.Add(sum);
            sum = 0;

            TotalCosts.Add(user.Id, Total.ToList());
            Total.Clear();
        }

        return TotalCosts;
    }

But this is not a good one for programming. How can I achive this with best practice? I am using repository pattern by the way.


texts: Rigidness and verbose nature of XML parsing

texts:
I've been developing a simple console application in C++ using the TinyXML2 library, and I honestly can't help but feel what I'm doing is not very robust. Maybe that's just the nature of parsing XML (this is my first foray into the topic, so I've no idea.)

The following code works to the best of my knowledge, but it feels like there has to be a better way than manually navigating to each element, checking for null pointers, then grabbing the information. Is there a more elegant way to handle this? I have to be missing something within the documentation, because I feel like I'm writing a lot of redundant code here.

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

int main() {
    tinyxml2::XMLDocument document;

    if (document.LoadFile("games.xml") == tinyxml2::XML_SUCCESS) {
        std::cout << "'games.xml' successfully loaded." << std::endl;

        tinyxml2::XMLElement *root = document.RootElement();

        std::cout << root->Value() << std::endl;

        tinyxml2::XMLElement *child;

        for (child = root->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()) {
            std::cout << "\t" << child->Value() << std::endl;

            if (child->FirstChildElement("name") == nullptr) {
                std::cerr << "Error: null pointer." << std::endl;
                return 1;
            }
            if (child->FirstChildElement("system") == nullptr) {
                std::cerr << "Error: null pointer." << std::endl;
                return 1;
            }
            if (child->FirstChildElement("status") == nullptr) {
                std::cerr << "Error: null pointer." << std::endl;
                return 1;
            }
            const char* game_name = child->FirstChildElement("name")->GetText();
            const char* game_system = child->FirstChildElement("system")->GetText();
            const char* game_status = child->FirstChildElement("status")->GetText();

            if (game_name == nullptr || game_system == nullptr || game_status == nullptr) {
                std::cout << "Error: null pointer." << std::endl;
                return 1;
            }
            std::cout << "\t\t" << game_name << std::endl;
            std::cout << "\t\t" << game_system << std::endl;
            std::cout << "\t\t" << game_status << std::endl;
        }
    } else {
        std::cerr << "Unable to load 'games.xml'. Error code: " << document.ErrorID() << std::endl;
        return 1;
    }
    return 0;
}


texts: Different Serializers for Different Methods in Django REST Framework

texts:
As I am developing my first real API, I encountered that I wrote a lot of serialisers and I think there could be a possibility to merge them together. For example I have this 3 distinct serialisers for different methods:
class PropertySerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Property

class PropertyPutSerializer(serializers.ModelSerializer):
    class Meta:
        exclude = ['creator']
        model = Property

class PropertyPatchSerializer(serializers.ModelSerializer):
    name = serializers.CharField(required=False)

    class Meta:
        exclude = ['creator']
        model = Property

I could use inheritance to clean up the code a bit, but I would like to know, what you think?


texts: Save parameters in a "key: value" format

texts:
I have been playing with Java for around a year and I started writing this API for storing data in files. I wrote this method which will save the parameters in a "key: value" format in a file.

The method is getting fairly long and I am just wondering if there is a better/shorter/more efficient way to do this.

public void set(String key, Object value) {
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(this.path, true));
        BufferedReader br = new BufferedReader(new FileReader(this.path));
        ArrayList<String> file = new ArrayList<String>();
        if(this.getValue(key) != null) {
            for(String line; (line = br.readLine()) != null;) {
                if(line.startsWith(this.COMMENT_PREFIX)) {
                    file.add(line);
                } else if(line.isEmpty()) {
                    file.add("");
                } else {
                    try {
                        if(!line.contains(":")) {
                            throw new MyFormatException("Missing a colon!");
                        }
                    } catch(MyFormatException e) {
                        e.printStackTrace();
                        bw.close();
                        br.close();
                        return;
                    }
                    String lineKey = line.substring(0, line.indexOf(":"));
                    String lineValue = line.substring(line.indexOf(":") + 2);
                    if(lineKey.equals(key)) {
                        if(value instanceof ArrayList) {
                            StringBuilder newValue = new StringBuilder(value.toString());
                            newValue.replace(value.toString().lastIndexOf("]"), value.toString().lastIndexOf("]") + 1, "");
                            newValue.replace(value.toString().indexOf("["), value.toString().indexOf("[") + 1, "");
                            bw.append(key + ": " + newValue.toString());
                            bw.newLine();
                        } else {
                            file.add(lineKey + ": " + value);
                        }
                    } else {
                        file.add(lineKey + ": " + lineValue);
                    }
                }
            }
            this.clear();
            for(String line : file) {
                bw.append(line);
                bw.newLine();
            }
        } else {
        if(value instanceof ArrayList) {
                StringBuilder newValue = new StringBuilder(value.toString());
                newValue.replace(value.toString().lastIndexOf("]"), value.toString().lastIndexOf("]") + 1, "");
                newValue.replace(value.toString().indexOf("["), value.toString().indexOf("[") + 1, "");
                bw.append(key + ": " + newValue.toString());
                bw.newLine();
            } else {
                bw.append(key + ": " + value);
                bw.newLine();
            }
        }
        br.close();
        bw.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
}


texts: Calculating the push or pull force of a molecule at a vertex

texts:
The basic idea of the code is to calculate the push or pull force at a vertex, given the number of "push causing molecules" and "pull causing molecules" at a polygon vertex.

The code thus mainly performs arithmetic (including the function it calls, calculate_edge_force), and has a couple of if-statements. The function is called many times since it is required in order to compute the derivatives, which is later used by scipy.odeint for integration.

Here is my code, in plain Python (note that import numpy as np has been put in somewhere higher up in the file, and that the functions are inside a class, hence there are references to this as self.<something>):

def calculate_point_forces(self, PushMolecules, PushMolecules_iPlus1, PushMolecules_iMinus1, PullMolecules, PullMolecules_iPlus1, PullMolecules_iMinus1, point_index, num_nodes, polygon, polygon_compression, point_interpolygon_contact, push_vector, pull_vector, a1, a2):

    max_push_force = self.max_push_force
    max_pull_force = self.max_pull_force
    tangent_factor = self.tangent_factor
    rac_force_exponent = self.rac_force_exponent
    rho_force_exponent = self.rho_force_exponent

    avg_PushMolecules_plus1 = (PushMolecules + PushMolecules_iPlus1)*0.5
    avg_PullMolecules_plus1 = (PullMolecules + PullMolecules_iPlus1)*0.5

    avg_PushMolecules_minus1 = (PushMolecules + PushMolecules_iMinus1)*0.5
    avg_PullMolecules_minus1 = (PullMolecules + PullMolecules_iMinus1)*0.5

    if self.enable_compression_stiffening == True:
        if polygon_compression < 1:
            F_internal = ((1-polygon_compression)+self.cytosolic_baseline)*self.cytosolic_pressure
        else:
            F_internal = 0
    else:
        F_internal = 0

    if PushMolecules > PullMolecules:
        Fpush = int(not point_interpolygon_contact)*max_push_force*(1 - (1/(1 + (PushMolecules/a2)**rac_force_exponent)))*push_vector
        Fpull = 0
        Fe_pull = 0
    elif PushMolecules < PullMolecules:
        pull_magnitude = max_pull_force*(1 - (1/(1 + (PullMolecules/a1)**rho_force_exponent)))
        Fpull = (1-tangent_factor)*pull_magnitude*pull_vector
        Fe_pull = 0.5*tangent_factor*pull_magnitude
        Fpush = 0
    else:
        Fpush = 0
        Fpull = 0
        Fe_pull = 0

    Fe_pull_minus1 = 0
    Fe_pull_plus1 = 0
    if PushMolecules_iMinus1 < PullMolecules_iMinus1:
        pull_magnitude_iMinus1 = max_pull_force*(1 - (1/(1 + (PullMolecules_iMinus1/a1)**rho_force_exponent)))
        Fe_pull_minus1 = 0.5*tangent_factor*pull_magnitude_iMinus1
    if PushMolecules_iPlus1 < PullMolecules_iPlus1:
        pull_magnitude_iPlus1 = max_pull_force*(1 - (1/(1 + (PullMolecules_iPlus1/a1)**rho_force_exponent)))
        Fe_pull_plus1 = 0.5*tangent_factor*pull_magnitude_iPlus1

    Fe_pull  = np.max([Fe_pull_minus1, Fe_pull_plus1, Fe_pull])

    Fe_plus, Fe_plus_ = self.calculate_edge_force(
        avg_PushMolecules_plus1, avg_PullMolecules_plus1, point_index,
        (point_index+1) % num_nodes, polygon)
    Fe_minus, Fe_minus_ = self.calculate_edge_force(
        avg_PushMolecules_minus1, avg_PullMolecules_minus1, point_index,
        (point_index-1) % num_nodes, polygon)

    F = Fpush + Fpull + Fe_plus + Fe_minus + Fe_pull*Fe_plus_ + Fe_pull*Fe_minus_ + push_vector*F_internal

    return F

When I profile this, I get that the function itself takes about 3 seconds. Out of this, 1 second is spent in calls to the calculate_edge_force and 1 second is spent by np.max.

If I "naively" put in float and int wherever I can (I don't know how to type the NumPy arrays, e.g. push_vector or pull_vector, so I only do it for things like PushMolecules, max_push_force or point_index, which I know will be float or int), I actually get a very mild slowdown in speed (about 0.2 seconds)!

Clearly then, that's not the way to go about "Cythonizing" my code. What should I be doing instead?


texts:
This is a prime numbers generator class, loosely based on the sieve of Eratosthenes. It is supposed to generate a decent quantity (i.e. millions) of prime numbers.

static class PrimesGenerator
{
    private const int StartFrom = 2;

    public static IEnumerable<int> GetPrimes()
    {
        var number = StartFrom;
        var dividers = new List<int>();
        while (true)
        {
            if (!IsDividedBy(number, dividers))
            {
                yield return number;
                dividers.Add(number);
            }
            number++;
        }

        bool IsDividedBy(int inputValue, IEnumerable<int> increasingSeriesOfDividers)
        {
            foreach (var divider in increasingSeriesOfDividers)
            {
                if (divider * divider > inputValue)
                    return false;
                if (inputValue % divider == 0)
                    return true;
            }

            return false;
        }
    }
}

For C# 6.0 or earlier IsDividedBy can be written as a private method instead of a local function.

Here's a console application I've used to estimate the generation time:

class Program
{
    static void Main(string[] args)
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        var primes = PrimesGenerator.GetPrimes().Take(1000000).ToList();
        stopwatch.Stop();
        Console.WriteLine(string.Join(", ", primes));
        Console.WriteLine($"Time elapsed: {stopwatch.Elapsed}");
    }
}

What I want to know:

Is there a way to get rid of the dividers list, saving the memory, without decreasing the performance? (by "performance" here I mean time needed to generate the sequence)
How can I decrease the computational complexity of this code? For now, the bigger value the current value is, the noticeably slower it works.
How this code can be improved in a broad sense?


texts: Statistical function which computes the average work time in different months

texts:
It's a task from a Ruby-course, in which I'm currently enrolled:
Ruby Course - Page

Precisely it's one of the assignments for the first week.

Following idea:
Your are given a list in which finished work-tasks are logged.
[
  {work: "item 1", date: "2017-04-26", time: 20},
  {work: "item 2", date: "2017-04-27", time: 27},
  ...

You shall write a function which computes the daily work-time for the different months.
Means: The average daily work-time in April, avg. time in May, ... in June. And so on ...

A data-structure, to work upon, was given. Even the result, which is expected for that data-structure: { "2017-04" => 40, "2017-05" => 14 }.

I was able to write a function, which passed all unit-tests.
Here it is:

#!/usr/bin/ruby
tasks = [
  {work: "item 1", date: "2017-04-26", time: 20},
  {work: "item 2", date: "2017-04-27", time: 27},
  {work: "item 3", date: "2017-04-27", time: 33},
  {work: "item 4", date: "2017-05-05", time: 20},
  {work: "item 5", date: "2017-05-06", time: 12},
  {work: "item 6", date: "2017-05-14", time: 10},
]

# Expected result : { "2017-04" => 40, "2017-05" => 14 }
def work_per_month(tasks)
  days_aggregate = {}

  tasks.each do | task |
    key = task[:date]

    if days_aggregate.key?(key)
      days_aggregate[key][0] = days_aggregate[key][0] + task[:time]
    else
      arr = []
      arr[0] = task[:time]

      days_aggregate[key] = arr
    end
  end

  months_aggregate = {}

  days_aggregate.each do | key, task |
    parts = key.split("-")
    k = "#{parts[0]}-#{parts[1]}"

    if months_aggregate.key?(k)
      months_aggregate[k][0] = months_aggregate[k][0] + task[0]
      months_aggregate[k][1] = months_aggregate[k][1] + 1
    else
      arr = []
      arr[0] = task[0]
      arr[1] = 1

      months_aggregate[k] = arr
    end
  end

  avg_hours_month = {}

  months_aggregate.each do | key, data |
    avg_hours_month[key] = data[0] / data[1]
  end

  avg_hours_month
end

puts work_per_month(tasks)  # Returns {"2017-04"=>40, "2017-05"=>14}

Please take into account that I started Ruby programming just a week ago.

It works and it has passed the tests. But I'm aware that it is clumsy.

Is there are more elegant way to solve the described task?

Without having this sequence of loops?