texts:
I understand there are a few similar tools available for testing speed but that's not what I'm looking for. I'm looking at seeing how long it takes to request a site's HTML. However, I'm getting slightly odd results.

The strange results are incredibly slow internet speeds so I'm confused about whether I'm doing something wrong or something isn't working.

It's reading at roughly 30 kilobytes a second which is quite odd.

Important Info

OS X (would like it to work the same on Windows as well)
Running using Sublime build, have also tried Python Launcher, but appears to be the same.

def getInternetSpeed():
    path = sys.argv[0]
    path = list(path)
    while True: # Just cuts back from say C:\User\Example\File.txt to
        if path[len(path)-1] == chr(92) or path[len(path)-1] == '/':
            path = ('').join(path)
            break
        else:
            path.pop(len(path)-1)
    testInternet();
    start = str(datetime.datetime.now())
    x = urllib2.urlopen('https://google.com')
    end = str(datetime.datetime.now())
    x = x.read()
    start = list(start)
    end = list(end)
    for i in range(17):
        start.pop(0)
        end.pop(0)
    start = ('').join(start)
    end = ('').join(end)
    start = float(start)
    end = float(end)
    diff = end - start
    f = open(path+'TEMP.txt','w')
    f.write(x)
    f.close()
    size = os.path.getsize(path+'TEMP.txt')
    os.remove(path+'TEMP.txt')
    print 'It took ' + str(diff) + ' second(s)'
    print 'to get a file that was ' + str(size / 1000) + ' kilobytes large!'

    scale = 1 / diff
    size = size * scale
    size = size / 1000

    print 'Download speed of ' + str(int(size)) + ' kilobytes a second'


texts: Filtering array by list of keys in PHP 5.5

texts:
I have an associative array with data (let's say language codes and descriptions) and a second array with allowed keys (lang codes). I want to filter the data array by these allowed keys.

The problem is I'm bound to PHP 5.5 and I can't use ARRAY_FILTER_USE_KEY flag.

I came up with the following solution:

$langs = [
 'en' => "English",
 'de' => "German",
 'fr' => "French",
 'ru' => "Russian",
];

$allowed_langs = ['en','de'];

var_export(
array_map( function($lang) use($langs) {return $langs[$lang];} , array_combine($allowed_langs, $allowed_langs))
);

/* Output as expected:
array (
  'en' => 'English',
  'de' => 'German',
)
*/

I wonder is there a more elegant and shorter solution to this task?


texts: Encrypting and decrypting strings using Caesar cipher

texts:
I was inspired by a solution in Think Python: How to Think Like a Computer Scientist. I structured mine (into two functions) according to it, and used the technique used in
rotate_letter. It's here if you're interested.

How can I make this better in all aspects (documentation, algorithm, variable names, and etc.)? Is memoizing rotated_string worth it?

def rotated_letter(letter, key):
    """Returns a single-letter string representing
       letter rotated by key, and returns letter if
       it doesn't belong to any of the English alphabet.

       letter: a single-letter string.

       key: an integer.
       """
    if letter.isupper():
        start = ord('A')

    elif letter.islower():
        start = ord('a')

    else:
        return letter

    diff = ord(letter) - start
    position = (diff + key) % 26 + start

    return chr(position)

def rotated_string(string, key, encrypt=True):
    """Returns string rotated by key.

       string: a string.

       key: an integer.

       encrypt: a boolean value.
       """
    result = ''
    memo = {}

    if not encrypt:
        key = -key

    for character in string:
        if character in memo:
            # rot_cahr denotes rotated character
            rot_char = memo[character]
        else:
            rot_char = memo.setdefault(character, rotated_letter(character, key))

        result += rot_char

    return result

def main():
    print(rotated_string('Hello!', 3))
    print(rotated_string('Khoor!', 3, encrypt=False))

if __name__ == '__main__':
    main()


texts: Reducing code for animation of expanding menus

texts:
I wonder if I can reduce the code to optimize it better?

$(document).ready(function () {
    $('#menu-1, #menu-event-1').hover(function () {
        $('#menu-deco-1').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-1').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-2, #menu-event-2').hover(function () {
        $('#menu-deco-2').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-2').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-3, #menu-event-3').hover(function () {
        $('#menu-deco-3').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-3').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-4, #menu-event-4').hover(function () {
        $('#menu-deco-4').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-4').stop().animate({
            right: -280
        }, 'fast');
    });
    $('#menu-5, #menu-event-5').hover(function () {
        $('#menu-deco-5').stop().animate({
            right: 0
        }, 'fast');
    }, function () {
        $('#menu-deco-5').stop().animate({
            right: -280
        }, 'fast');
    });
});


texts:
Earlier this year, I posted the following;
Extract data from API using VBA & XML (Performance)
The purpose of this project is/was to develop a small data extractor for our existing API to ensure that even the smallest of our customers could receive the data they need. As hinted, we provide our data through an API, but we are in an industry where the adaptation to this kind of technology is slow, which ultimately results in many ours of manual data-work on our side, because our customers simply need the data.
Fast forward, the project is kind of done (thanks!). However, I am close to paranoid in terms of security.
The newest version is almost the same as the one I have linked, but now also prompts the user for his/her Username and Password for our API, ultimately allowing them to get their own data (prices, etc).
These are my worries;

I want to be absolutely sure, that I do not send our customers something that potentially could allow them to check other customer's data (prices, etc.). I have tested my self, and since you need a user and pass to access the API it self - and hence also via this program - you wont get any data if you dont provide login information. But, since this is my first time doing something like this, I am naturally (?) scared, that things might be "different" when you do something like this via VBA and httprequest.

Is there anything I can/should do in terms of ensuring security? Any references, code or specific declaration of the username and password variables, which are asked for via Input Boxes (and then inserted into the API-URL)?

Should I password-protect my code or does it not make any difference? I have deleted everything that is not public in the code and have applied the inputboxes for username and password due to the same reason - I dont want confidential information stored, instead the customer inputs themselves.

New Code:
https://pastebin.com/8gFUqd6e
I must admit that I feel a bit embaressed for asking this question, as my logic is telling me that I am wasting everyones time, but I am a rookie after all and dont want to fuck up my belowed workplace :-)!
As always, I am exremely thankful for any help provided by you guys. Thank you so much for your time.
Snippet to allow posting;
Dim httpRequest As New WinHttpRequest
httpRequest.SetTimeouts 0, 0, 0, 0
httpRequest.Open "GET", strURL, False
httpRequest.Send

Again, Thanks!
Peder


texts:
This is the code for checking if a string is a palindrome. The execution time, for sample cases, is 0.40358 seconds. What must be done to increase the performance?

int main(){
    int c,flag = 0;
    char *ch, *h;
    ch = (char *)malloc(sizeof(char)*101);
    h = ch;
    while((c=getchar())!=EOF){
        *ch = c;
        ch++;
    }
    ch--;
    while(ch>=h){
        if(*ch-- != *h++){flag = 1; break;}
    }
    flag == 1?(printf("NO")):(printf("YES"));
}

This is the code with an execution time of 0.4017 seconds for same test cases:

void main()
{
    char a[100],b[1000];
    int n,i,j=0,f=0;
    scanf("%s",a);
    n=strlen(a);
    for(i=n-1;i>=0;i--)
    {
        b[j]=a[i];
        j++;
    }
    for(i=0;i<n-1;i++)
    {
        if(a[i]==b[i])
        {
            f++;

        }
    }
    if(f==n-1)
    {
        printf("YES");
    }
    else
    {
        printf("NO");
    }
}

Why is the former slower than the latter? Are the library functions faster?


texts: Project Euler #5 - Smallest multiple using Factor Table

texts:
This is a problem from Project Euler and on Hackerrank (here)-

  2520 is the smallest number that can be divided by each of the numbers
  from 1 to  10 without any remainder.

  What is the smallest positive number that is evenly divisible
  (divisible with no remainder) by all of the numbers from 1 to N?

  Input Format First line contains  that denotes the number of test cases. This is followed by  lines, each containing an integer, .

  Output Format  Print the required answer for each test case.

  Constraints

    1 <= T <= 10
    1 <= N <= 40

  Sample Input

    2
    3
    10

  Sample Output

    6
    2520

Here is the code I wrote. My approach was to first create a table of prime factors and use them to generate a number that is divisible by all numbers below N. Is there a better approach? Is there something that I am doing here that is very sub-optimal?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int T,N,i,j,k,q,M[40],p;
    scanf("%d",&T);
    M[0]=1;
    M[1]=2;
    M[2]=3;
    for (i=3;i<40;i++){
        q=i+1;
        for (j=1;j<i;j++){
            if (q%M[j]==0){
                q/=M[j];
            }
        }
        M[i]=q;
    }
    for (i=0;i<T;i++){
        scanf("%d",&N);
        p=1;
        for (j=0;j<N;j++){
            p*=M[j];
        }
        printf("%d\n",p);
    }
    return 0;
}


texts: How to improve the way I handle greping in this script

texts:
What my script does is:

Append data to a file on a continuous basis.
If an error pattern is observed, then do something.

I need feedback on the way I am grepping for patterns in the continuously appended file. For grep, I am creating a pattern file first and then using it with -f option to grep. Can I do this better? Any other better way I can write my over all logic.

Here's my script

#!/bin/bash
# List of error patterns to look for. Add more patterns to this list
p1='pattern1'
p2='pattern2'
p3='pattern3'
p4='pattern4'

PATTERNFILE=~/patternfile
FILETOCHECK=~/filetocheck

captureFileToCheck()
{
   //appends data into filetocheck &

}
createPatternFile()
{

    for i in `seq 100` # hopefully 100 is all we will need
    do
        if [ ! "x$p{$i}" = "x" ]
        then
            echo $p{$i} >> $PATTERNFILE
        else
            break
        fi
    done
}

createPatternFile
captureFileToCheck

while [ 1 ]
do

    if grep -f $PATTERNFILE $FILETOCHECK
    then
        echo "something starting"

          #doSometing

        echo "something complete"

        break
    fi

done


texts: Binary search: first/last/random occurrence

texts:
I've written some code to "binary search" a list, and return the first occurrence of the target:

def bsearch(a, left, right, target, first_or_last = 'first'):
    """
    Use binary search to find the first, last, or random index
    of target.

    >>> a = [1,1,1,1,1,1]
    >>> bsearch(a, 0, len(a)-1, 1, 'first')
    0
    """

    if left > right:
        return -1

    mid = (left + right)//2
    val = a[mid]

    if val == target:
        first_occur = mid
        if first_or_last == 'first'
            later_occur = bsearch(a, left, mid - 1, target)  # check if there's an earlier occurrence in the left sub-list
            if later_occur != -1:
                return later_occur
            else:
                return first_occur

        elif first_or_last == 'last':
            later_occur = bsearch(a, mid + 1, right, target)
            if later_occur != -1:
                return later_occur
            else:
                return first_occur
        else:
            return first_occur

    if target < val:
        return bsearch(a, left, mid - 1,  target)
    if target > val:
        return bsearch(a, mid + 1, right, target)

Is there a more elegant/cleaner way to give this function the ability to find the first, last, or random occurrence of the target, without use of a string to represent the cases (as I've done)? Suggestions would be great.


texts: What is the potential risk with this code?

texts:
I am trying to implement a distinct counter to detect if all tasks that is added to the ThreadPool has completed and want to use it as a barrier. So, when a function that is added to the ThreadPool is completed, workDone will be called, and count will be decreased. The main thread will be locked by calling waitForALL() method until the count is cleared to 0. Is this implementation reasonable and what risk does it have from the concurrency perspective?

I am still using .net 3.5, code has been updated as below.

public class BarrierCount
{
    private static volatile BarrierCount INSTANCE = new BarrierCount();
    private int count = 0;
    private static volatile Object o = new Object();

    public static BarrierCount getInstance()
    {
        return INSTANCE;
    }

    private BarrierCount() { }
    public void increaseCount()
    {
        lock (o)
        {
            count = count + 1;
        }
    }

    public void workDone()
    {
        lock (o)
        {
            count = count - 1;
        }
    }

    public void WaitForAll()
    {
        while(true)
        {
            lock (o)
            {
                if (count == 0)
                {
                    break;
                }
            }

            Thread.SpinWait(100);
        }
    }
}


texts: Optimize 950k+ lookups in pandas dataframe

texts:
I'm currently working on a project where I'm dealing with somewhat large data sets. I have a dataframe transactions and another users.
Iterating through the transactions dataframe is no problem. I used timeit and it takes just under a minute to do so. My second dataframe users has 1,000 rows. Both of these dataframes have a column email. Essentially what i'm trying to do is get the userId in the row in users that matches the email in each transactions row. My current approach looks like this:
for row in transactions.itertuples():
    userId = users[users['email'] == getattr(row, 'email')]['userId'].values[0]

This simple lookup works, however it's too slow for my use case. I kept it running for over an hour and it still wasn't finished running. I'm wondering if there's potentially a faster way to do this lookup (maybe get the runtime down to minutes instead of hours)?
Appreciate any help in advance!


texts: Knowing which way to iterate the for loop C

texts:
I want the code to automatically know which way to iterate through the loop without manually adding the '>' or '<' sign.
I am using the logic that if the setup part of the loop is smaller than the value in the  test expression, then the sign used will '<' and will be '>' vice versa.

The current way I have gone around this is by wrapping the for loop in an if statement, however this looks incredibly bulky and I feel there must be a better way.

The following is the code I am currently using:

i = -1;

if ((i*i*i)<(i * i * (i + i + i + i + i))){
    for (integer = i * i * i; integer < i * i * (i + i + i + i + i);integer += i * i * i * i * i) {
        printf("%d",integer);
        printf("\n");
    }
}
else {
    for (integer = i * i * i; integer > i * i * (i + i + i + i + i);integer += i * i * i * i * i) {
        printf("%d",integer);
        printf("\n");
    }
}

And here is an example which looks simpler:

if (-1<-5){
for (integer = -1; integer < -5;integer += -1) {
    printf("%d",integer);
    printf("\n");
}
}

else{
    for (integer = -1; integer > -5;integer += -1) {
        printf("%d",integer);
        printf("\n");
    }
}


texts:
Kindly accept my apologies as Java is something my mind cannot digest no matter what I do. At the moment I have an assignment and have written a piece of code and have used Constructor (I think so) but not sure if I have used it correctly and if Yes then will need some guidance in order to refactor the code.

Anyhow I am writing code for a Booking System where user is given option to input value and create a new Show along with date. I have achieved this in the below code but note sure that I have used the constructor properly or not.

import java.io.*;
import java.util.*;

public class LocalPlay extends Play {

    private static String playName;
    private static String playDate;

    private LocalPlay(String playName, String playDate) {
        this.playName = playName;
        this.playDate = playDate;
    }

    public String getShowName() {
        return playName;
    }

    public String getShowDate() {
        return playDate;
    }

    public void setShowName(String value) {
        this.playName = value;
    }

    public void setShowDate(String date) {
        this.playDate = date;
    }

    public static void lPlayDetails() {
        try {
            int selection = 0;
            Scanner option = new Scanner(System.in);
            System.out.println();
            System.out.println("Press 1 to Add a New Play/ Show: ");
            System.out.println("Press 2 to View existing Play: ");
            System.out.println("Press 3 to delete existing Play: ");
            System.out.println("Press 4 for Previous Menu: ");
            System.out.println();
            System.out.print("Kindly make the selection: ");
            selection = option.nextInt();
            if (selection == 1) {
                addPlay();
            } else if (selection == 2) {
                viewPlay();
            } else if (selection == 3) {
                deletePlay();
            } else if (selection == 4) {
                managePlay();
            } else
                while (selection != 1 || selection != 2 || selection != 3) {
                    System.out.println();
                    System.out.println(selection + " is not a valid option. ");
                    managePlay();

                }
        } catch (InputMismatchException ime) {
            System.out.println("Invalid option selected.");
            System.out.println("Try again");
            lPlayDetails();
        }
    }

    private static void addPlay() {
        String name;
        String date;
        Scanner option = new Scanner(System.in);
        System.out.print("Enter name of Play: ");
        name = option.nextLine();
        System.out.print("Enter date of Play: ");
        date = option.nextLine();
        LocalPlay lp = new LocalPlay(name, date);
        System.out.println("The name of play is " + playDate + " date played is " + playDate);
        lPlayDetails();
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter("play.txt"));
            writer.write(name + " " + date);

        } catch (IOException e) {
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
            }
        }
        return;
    }

    private static void deletePlay() {
        System.out.println("Method not implemented");
        lPlayDetails();

    }

    private static void viewPlay() {
        System.out.println("Method not implemented");
        lPlayDetails();

    }

}


texts:
In my system I frequently require data by Ajax requests. For example, different lists, content of modal dialogs, etc. This data can't be changed after request, so I wrote cache mechanism which stores Ajax result and then before Ajax request checks is there stored data.
Here is example:

YFeX.cache = { }; // YFex is my own namespace

$('#account_modal_button').click(function () {
    if (YFeX.cache.account_modal !== undefined) {
        YFeX.modal(YFeX.cache.account_modal.title, YFeX.cache.account_modal.body);
    } else {
        $.ajax({
            type:'GET',
            url:'/?/login',
            dataType:'json',
            context:$(this),
            success:function (data) {
                YFeX.cache.account_modal = data.modal;
                // YFeX.modal will be called automatically
            }
        });
    }
    return false;
});

Are there any 'bad' parts in my solution?


texts: Calculating the interest on a series of loans

texts:
I am a college student and started my first week of C++ and we were given an assignment to convert a Java program that calculate the interest on a series of loans given the amount of the principal, the annual interest rate, and the number of days in a sentinel loop into C++.

Here is what we were given:

import java.util.Scanner;
public class ex311
{
public static void main(String[] args)
{
    double principle, rate, interest;
    int days;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter principle (-1 to end):  ");
    principle = sc.nextDouble();
    while (principle != -1)
    {
        System.out.print("Enter annual interest rate (as a decimal):  ");
        rate = sc.nextDouble();
        System.out.print("Enter number of days:  ");
        days = sc.nextInt();
        interest = principle * rate / 365 * days;
        System.out.printf("Interest is %.2f\n", interest);
        System.out.print("\nEnter principle (-1 to end):  ");
        principle = sc.nextDouble();
    }
}
}

This is what I have for the C++ converted code:

#include <iostream>

using namespace std;
void main()
{
    double principle, rate, interest;
int days;
cout << "Enter principle (-1 to end)";
cin >> principle;
while (principle != -1)
{
    cout << "Enter annual interest rate(as a decimal)";
    cin >> rate;

    cout << "Enter number of days";
    cin >> days;

    interest = principle * rate / 365 * days;
    cout << "Interest is "<< interest;
    cout << "Enter principle (-1 to end)";
    cin >> principle;
}
}

I would like to know if there is a better way to go about this, as in making my code more efficient. I am aware that I should not be using void main, but this is how we're being taught for the time being.


texts:
I tried to write my first jQuery plugin. It's a very simple Ajax file uploader.

I would appreciate a review of this code.

HTML

<input type="file" id="upload" multiple="multiple" />

Plugin

;(function ($, window, document, undefined) {

    // Function-level strict mode syntax
    'use strict';

    $.fn.ajaxUpload = function(options) {

        var defaults = {
            curr_files      : 0,
            max_files       : 18,
            max_concurrent  : 10,
            max_filesize    : 200000,
            allowed_types   : ['jpeg','jpg'],
            ajax_url        : 'action.php',
            extra_fields    : {}
        };

        var options = $.extend(defaults, options);

        return this.each(function() {

            var $this = $(this);

            $this.on('change', function() {

                var files = $this[0].files;
                var len = files.length;
                var items = 0;
                var diff_files = parseInt(defaults.max_files - defaults.curr_files - len);

                if(diff_files < 0) {
                    alert("Error!");
                    return false;
                }
                if(!maxUploadFiles(len, defaults.max_concurrent)) {
                    alert("Error!");
                    return false;
                }

                var formdata = new FormData();
                jQuery.each(files, function(i, file) {
                    if(!isOverSized(file, defaults.max_filesize)) {
                        alert("Error!");
                        return false;
                    }
                    if(!isAllowedTypes(file, defaults.allowed_types)) {
                        alert("Error!");
                        return false;
                    }
                    formdata.append('file['+i+']', file);
                    items++;
                });

                // Append extra data to formdata
                $.each(defaults.extra_fields, function(name, value) {
                    formdata.append(name, value);
                });

                // Check that files have passed all test
                if (len != items) { return false; }

                $.ajax({
                    url: defaults.ajax_url,
                    data: formdata,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function(data){
                        alert(data);
                        location.reload(true);
                    }
                });

            });
       });
    };

    function maxUploadFiles(len, max_concurrent) {
        if(len > max_concurrent) {
            return false;
        }
        return true;
    }
    function isAllowedTypes(file, allowed_types) {
        var ext = file.name.split('.').pop().toLowerCase();
        if(jQuery.inArray(ext, allowed_types) < 0) {
            return false;
        }
        return true;
    }
    function isOverSized(file, max_filesize) {
        if(file.size > max_filesize) {
            return false;
        }
        return true;
    }

})(jQuery, window, document);


texts: Checking if file is within a directory for security

texts:
I have a security manager I'm writing for a Java program, and within the checkRead method, I wish to only allow reads to files within a given directory.

The basis of it is that it will get a canonical file for the input (which is actually a string as per the method contract). It will then begin taking the file's parent repeatedly until it either matches one of the trusted directories, or becomes null (from trying to take the parent of the root directory). This check should be secure both on Unix/linux and Windows environments and styles of filenames. I don't need 100% certainty that a valid and allowed, but mangled or non-standard path would pass, but I certainly cannot rework the program's API to open files in a different, more secure manner, as my application's classloader needs to use this method to check its reads.

Are there any glaring issues (security or style) that anyone might see here?

File tested;
try {
    tested = new File(file).getCanonicalFile();
} catch (IOException e1) {
    throw new SecurityException(
            "The basedir resolution failed to resolve.");
}

File parentFile = tested;
while (parentFile != null) {
    if (basedir.equals(parentFile) || classDir.equals(parentFile)) {
        return;
    }
    parentFile = parentFile.getParentFile();
}
logger.warn("MosstestSecurityManager stopped an attempt to read a file from non-core code"
        + file);

throw new SecurityException(
        "MosstestSecurityManager stopped an attempt to read a file from non-core code");


texts: Read compressed XML file inside ZIP and parse data as fast as possible

texts:
I am trying to read and parse an XML file inside of a ZIP archive as fast as possible. The XML file is roughly 85GB in size, so I know for a fact that I/O also plays a role here, as I need to essentially read 85GB total. However, reading 85GB on a 500 MB/s SSD, means I can do this in less than 3 minutes, if we ignore CPU, decompression, and so on.
As I cannot store the ZIP file nor XML file in memory, I've streamed the content, and it works really well. Reading and parsing 100.000 XML nodes/elements (which is roughly 450.000 lines of XML) takes about 10 seconds. Don't get me wrong: Reading 400.000+ lines of XML and parsing it in ~10 seconds is fast. But it's not as fast as I want.
Multi threading this is probably not an option, but I am interested in hearing, if it's possible to speed this up.
_models is just a List<Model> that I use to keep my objects in, which gets cleared once they're saved to the database.
public static async Task Main(string[] args)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.Async = true;

    using (var stream = new ZipInputStream(File.OpenRead($@"C:\file.zip")))
    {
        // this is fine, as we know there is only 1 file in the ZIP
        stream.GetNextEntry();

        using (XmlReader reader = XmlReader.Create(stream, settings))
        {
            reader.MoveToContent();

            while (await reader.ReadAsync())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "ns:ElementName")
                    {
                        await ExtractModel(reader);
                    }
                }
            }
        }
    }

    // await save to database
}

private static async Task ExtractModel(XmlReader reader)
{
    XElement el = XNode.ReadFrom(reader) as XElement;

    var serializer = new XmlSerializer(typeof(Model));

    var model = (Model)serializer.Deserialize(el.CreateReader());

    _models.Add(model);

    // save 100.000 models to database
    if (_models.Count == 100000)
    {
        //await save to database
        _models.Clear();
    }
}
```


texts: Referring to nested arrays and array_merge (php)

texts:
In such an array:

$arr = Array (
    [key0] => Array (
        [subkey0] => Array (
            [0] => "value0"
            [1] => "value1"
        )
        [subkey1] => Array (
            [0] => "value0"
            [1] => "value1"
        )
    )
    [key1] => Array (
        [subkey0] => Array (
            [0] => "value0"
            [1] => "value1"
        )
        [subkey1] => Array (
            [0] => "value0"
            [1] => "value1"
        )
    )
)

In order to add $varX to the end of $arr[keyX][subkeyX] as [X] => $varX, I use, inside a loop, the following:

$arr[$key] = array(
    "subkey0" => array_merge((array)$arr[$key]["subkey0"], (array)$var1),
    "subkey1" => array_merge((array)$arr[$key]["subkey1"], (array)$var2)
    ...
)

And I might be working with even more nested arrays, so I was wondering if there was a way for subkey0 to refer to itself, or if I could do something like:

"subkeyX" =>+ (array)$varX

Or use array_merge() in a different way to add $varX to the end of subkeyX as [X] => $varX.


texts:
I'm having trouble testing some code. It's laid out in such a way that the business logic relies on the persistence layer.

Some classes require that an object be saved to a database. Some classes re-read the object they were working to get the "original" version of it. All of this tends to happen in what's been labeled the business logic layer.

This a WCF application where the business logic layer manipulates objects from the DAL

Code sample below.

public class WCFService : IWCFService
{

    public OrderHeader GetOrder(int id)
    {
        var om = new OrderManager();
        return om.Read(id);
    }

}

[DataContract]
public class OrderHeader
{
    [DataMember]
    public int id { get; set; }

    public OrderHeader Read(int id)
    {
        // ADO.NET calls
        return new OrderHeader();
    }

    public void CreateUpdate()
    {
        // ADO.NET calls
        this.id = GetSqlOutputParam();
    }

    private int GetSqlOutputParam()
    {
        // get the identity supplied by the executed stored proc
    }
}

public class OrderManager
{

    public OrderHeader Read(int id)
    {
        OrderHeader oh = new OrderHeader();
        return oh.Read(id);
    }

    public bool SaveOrder(OrderHeader order)
    {
        // do lots of complex stuff
        order.CreateUpdate(); // update here because some other class is going to want to do a fresh read
        // instantiate other "manager" classes
        order = order.Read(order.id); // make sure we get the latest record from the database in case other manager classes changed my order
        // do more complex stuff
        order.CreateUpdate();

        return true;

    }
}

Firstly and unfortunately, there isn't an immediate plan to replace the entity specific ADO.NET with an ORM.

I would like to start by making the code a little more testable by removing all persistence calls from the business logic layer, or separating the actual logic away from these calls while keeping them in the same layer. Instead of update() and read() littered throughout those manager classes, the object would be passed around as much as needed.

To give some context, the code suffers from a lot of persistence related bugs. I feel like removing persistence from the equation would make matters easier to deal with.

Edit: I miscommunicated the intent of the GetSqlOutputParam() method. It's not just returning a const, it is pulling it from an executed SqlCommand.


texts:
I am designing a query builder, where the user can just add conditions or groups, and each group can, in turn, have conditions in it. I came up wit the below class design. Can this design be improved?

public enum RuleType
{
    Group,
    Condition
}
public enum Operator
{
    And,
    Or
}
public enum ConditonValues
{
    GreaterThan = 1,
    EqualTo = 2,
    LessThan = 3
}
public abstract class RuleParent
{
    public Guid Id { get; set; }
    public int Order { get; set; }
    public RuleType RuleType { get; set; }
}
public class RuleSet : RuleParent
{
    public ConditonValues Condition { get; set; }
    public string Field { get; set; }
    public object Data { get; set; }
}
public class MyGroup : RuleParent
{
    public Operator Operator { get; set; }
    public List<RuleParent> Rules { get; set; }
    public MyGroup()
    {
        Rules = new List<RuleParent>();
    }
}

Example usage:

var groupM = new MyGroup();
groupM.Rules.AddRange(new List<RuleParent>
{
     new RuleSet() { Condition =  ConditonValues.EqualTo, Field="name", Data ="reza" , RuleType = RuleType.Condition },
     new MyGroup() {
         Rules = new List<RuleParent>()
         {
             new RuleSet() { Condition =  ConditonValues.EqualTo, Field="category", Data ="Tools" , RuleType = RuleType.Condition  },
             new RuleSet() { Condition =  ConditonValues.GreaterThan, Field="price", Data ="100" , RuleType = RuleType.Condition  }
         }
         , RuleType = RuleType.Group
     }
});


texts: Is this a good way to create a Javascript object?

texts:
I'm building a simple quiz app and wanted to make it more scalable by putting my code into an object. The parameters list looks a bit messy to me. Is this a normal way to use an object or is there a better way?

Thanks

// above here I have a JSON object with questions:
var quiz = new question($('#quiz-container'), $('.alert'), 0, [], questions[0].level[0]);

// for debugging
console.log(quiz);

function question(quizContainer, alert, questionCounter, selection, level) {
    this.quizContainer = quizContainer;
    this.alert = alert;
    this.questionCounter = questionCounter;
    this.selection = selection;
    this.level = level;

    function createQuestion(index) {
        //TODO
    }
}


texts:
Is it possible to make this code more efficient & elegant?

int HexToDecimal(char ch)
{
    ch = tolower(ch);
    if ('a' <= ch && ch <= 'f')
    {
        return ch - 'a' + 10;
    }
    else if ('0' <= ch && ch <= '9')
    {
        return ch - '0';
    }
    printf("Error\n");
    return 0;
}

Update: Printing error could be ignored. By returning 0 I only mean to show that the input char is not a hex digit.


texts: Plugin for finding placed blocks and if they are in a certain sequence

texts:
This is for a plugin I am making for the game called Minecraft. The code is responsible for finding out the blocks placed by the player and if they are in the following sequence as shown in the picture then create an Antenna. block in block.getType() returns the block placed by the player. Also, it doesn't matter in what order the player places the blocks.

// if block placed was a jukebox and block directly above is a diamond block
// and the block above the diamond block is an iron fence
if(block.getType() == Material.JUKEBOX
        && block.getRelative(BlockFace.UP, 1).getType() == Material.DIAMOND_BLOCK
        && block.getRelative(BlockFace.UP, 2).getType() == Material.IRON_FENCE){
    System.out.println("Antenna Created");
    player.sendMessage("Antenna Created");
}

// if block placed was a diamond block and block directly above is a iron fence
// and the block below is a jukebox
if(block.getType() == Material.DIAMOND_BLOCK
        && block.getRelative(BlockFace.UP, 1).getType() == Material.IRON_FENCE
        && block.getRelative(BlockFace.DOWN, 1).getType() == Material.JUKEBOX){
    System.out.println("Antenna Created");
    player.sendMessage("Antenna Created");
}

// if block placed was an iron fence and the block directly below is a diamond block
// and the block below that is a jukebox
if(block.getType() == Material.IRON_FENCE
        && block.getRelative(BlockFace.DOWN, 1).getType() == Material.DIAMOND_BLOCK
        && block.getRelative(BlockFace.DOWN, 2).getType() == Material.JUKEBOX){
    System.out.println("Antenna Created");
    player.sendMessage("Antenna Created");
}

I am not happy with the following code and I get the feeling there is a better way to do this? I'm also wondering how would I go about designing these if Statements to allow for future extendibility?


texts: Performance of Min and Max Sum of array in C#

texts:
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers.

Stuck at understanding a hint given in question.

Hint: Beware of integer overflow! Use 64-bit Integer.

Code:

string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp, Int32.Parse);
arr = arr.OrderBy(i => i).ToArray();
int mine = arr[0];
int maxe = arr[arr.Length - 1];
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
    if(arr[i]>=1 && arr[i]<=Math.Pow(10,9))
     sum+= arr[i];
}
Console.WriteLine((sum-maxe) + " " + (sum-mine));

Note : The motive of posting here, is to improve learning over code review, solution is already on multiple blogs.


texts: Optimizing insertion sort for small amounts of data

texts:
I'm building a hybrid sort, and for that I need a fast and adaptive sort ideal for small sizes (< 65 elements).

Insertion sort immediately comes to mind, and I've been tinkering with different implementations of it. My requirement is that it takes in iterators as per C++ standard.

Linear insertion sort

template <typename Iter>
void lin_sort(Iter begin, Iter end) {
    for (auto cur = begin; cur != end; ++cur) {
        auto key = *cur;
        auto ins = cur - 1;
        for (; begin <= ins && key < *ins; --ins)
            *(ins + 1) = *ins;    // move 1 to right until correct position's found
        *(ins + 1) = key;
    }
}

Binary insertion sort

template <typename Iter>
void ins_sort(Iter begin, Iter end) {
    for (auto cur = begin; cur != end; ++cur) {
        // upper_bound is binary search for correct insertion position
        // shift everything from up to cur to the right one and insert key into right place
        std::rotate(std::upper_bound(begin, cur, *cur), cur, cur + 1);
    }
}

Alternative and equivalent binary insertion sort

template <typename Iter>
void ins_sort(Iter begin, Iter end) {
    for (auto cur = begin; cur != end; ++cur) {
        auto key = *cur;
        auto ins = std::upper_bound(begin, cur, key);
        for (auto shift = cur; shift != ins; --shift) *shift = *(shift-1);
        *ins = key;
    }
}

Some benchmarking reveals the binary version to be around 1.5 times slower than the linear version, compiling on GCC 4.8.2 with -O3

mylibs\algo>algotest s l
after: 100000 lists with 64 elements: 1.11421e+06 us    1114.21 ms  (linear insertion sort)
mylibs\algo>algotest s i
after: 100000 lists with 64 elements: 1.62741e+06 us    1627.41 ms  (binary insertion sort)

I am only concerned about its performance for under 65 elements, so the asymptotic guarantee given by binary search is irrelevant. Can anyone suggest improvements to the linear insertion sort, or a better alternative for what I'm looking for?

Benchmarking code: (full testing can be found in algotest)
Generating random data

// random number generation
class Rand_int {
public:
    Rand_int(int low, int high) : distribution{low, high} {
    }
    int operator()() {
        return distribution(engine);
    }

private:
    default_random_engine engine;
    uniform_int_distribution<> distribution;
};

vector<int> randgen(int max, int num) {
    static Rand_int die{0, max};
    vector<int> res;
    res.reserve(num);
    for (int i = 0; i < num; ++i)
        res.push_back(die());
    return res;
}

template <typename T>
vector<vector<T>> data_gen(const string& fname, int l_num = list_num, int l_size = list_size, int r = range) {
    ofstream f {fname};
    f << l_num << ' ' << l_size << ' ' << r << endl;
    vector<vector<T>> v_list;
    v_list.reserve(l_num);
    for (int i = 0; i < l_num; ++i) v_list.push_back(randgen(r, l_size));
    for (auto v : v_list) print(v, f);
    return v_list;
}

template <typename Container>
void print(const Container& v, ostream& os = cout) {
    for (auto x : v)
        os << x << ' ';
    os << '\n';
}

Timing

class Timer {
    time_point<system_clock> init, end;
    microseconds elapsed = duration_cast<microseconds>(end - init);
public:
    Timer() : init{system_clock::now()} {}
    void start() { init = system_clock::now(); }
    double tonow() {
        end = system_clock::now();
        elapsed = duration_cast<microseconds>(end - init);
        return elapsed.count();
    }
};

//... inside switch case of algotest main
    load_data(v_list);  // v_list is loaded from file
    switch (argv[2][0]) {
        // ... more sorts
        case 'i': for(auto& v : v_list) ins_sort(v.begin(), v.end()); break;
        case 'l': for(auto& v : v_list) lin_sort(v.begin(), v.end()); break;
        default: cout << "incorrect sort selection\n"; listalgos();
    }


texts: Shortening method based on an argument name

texts:
As you can see below, I have a method which executes statements based on the first letter of a component firing an ItemEvent:

public void itemStateChanged(ItemEvent ie) {
    if(ie.getSource() == rRadioButton) {
        currentScale = "r";
        ((DefaultEditor) rSpinner.getEditor()).getTextField().requestFocus();
    }
    else if(ie.getSource() == gRadioButton) {
        currentScale = "g";
        ((DefaultEditor) gSpinner.getEditor()).getTextField().requestFocus();
    }
    else if(ie.getSource() == bRadioButton) {
        currentScale = "b";
        ((DefaultEditor) bSpinner.getEditor()).getTextField().requestFocus();
    }
    //...
}

Is it possible to easily shorten the method and make it more automatic?

If the argument was an ActionEvent I could use getActionCommand to assign the value for currentScale but the same number of lines of code would be needed first to setActionCommand for every component.

I could also use setName and getName for components but this will result it the same issue as described above.

Also it would be good to be able to automatically point to a specific Spinner based on a specific RadioButton as you can see in the attached source code.

Maybe there is a possibility to use reflection for this but I don't know if this could work.


texts: Load multiple text files with same name but in different folders

texts:
I have the following code, which basically load some data files that I have in different folders, take an average of every repeat at each Temperature and then plot the results. The code works fine, and it was OK when I had only a couple of set of data. But now I have 9 different set of temperature each with 5 repeat each and the code is becoming too long in my opinion. Is there a way to consolidate it and make it more readable and efficient?

import numpy as np
import matplotlib.pyplot as plt

steps    = np.loadtxt('/home/aperego/data/HexaPaper/nvt/303K/1st/Average_MSD.txt',usecols=[0])

def load(temp,pos):
    return np.loadtxt('/home/aperego/data/HexaPaper/nvt/'+temp+'K/'+pos+'/Average_MSD.txt',usecols=[1])

# T = 303 K
msd303_1 = load('303','1st')
msd303_2 = load('303','2nd')
msd303_3 = load('303','3rd')
msd303_4 = load('303','4th')
msd303_5 = load('303','5th')

msd303 = np.vstack((msd303_1,msd303_2,msd303_3,msd303_4,msd303_5)).T
msd303_mean = np.mean(msd303,axis=1)
msd303_std = np.std(msd303,axis=1)

# T = 313 K
msd313_1 = load('313','1st')
msd313_2 = load('313','2nd')
msd313_3 = load('313','3rd')
msd313_4 = load('313','4th')
msd313_5 = load('313','5th')

msd313 = np.vstack((msd313_1,msd313_2,msd313_3,msd313_4,msd313_5)).T
msd313_mean = np.mean(msd313,axis=1)
msd313_std = np.std(msd313,axis=1)

# T = 323 K
msd323_1 = load('323','1st')
msd323_2 = load('323','2nd')
msd323_3 = load('323','3rd')
msd323_4 = load('323','4th')
msd323_5 = load('323','5th')

msd323 = np.vstack((msd323_1,msd323_2,msd323_3,msd323_4,msd323_5)).T
msd323_mean = np.mean(msd323,axis=1)
msd323_std = np.std(msd323,axis=1)
plt.yscale("log")
plt.xscale("log")
plt.plot(steps,msd303_mean,label ='303K')
plt.plot(steps,msd313_mean,label ='313K')
plt.plot(steps,msd323_mean,label ='323K')
plt.legend(loc="best")
plt.show()


texts: Unity3D Property Drawer for a MinMaxSlider

texts:
This is a bit of an interesting one. Read about custom Property Drawers in the Unity Docs. Read about MinMaxSlider in the Unity Docs.

Unity's EditorGUI tools used for building property drawers expose a default MinMaxSlider, though the standard Unity libraries do not provide a way to use that drawer without custom code. This aims to be a reusable generally-applicable way to use a MinMaxSlider where it would be most commonly appropriate: defining a range to clamp some value at run-time or to generate a random value from within that range.

I chose to follow MinMaxSlider for naming, so I have struct MinMaxPair, class MinMaxAttribute : PropertyAttribute, and class MinMaxDrawer : PropertyDrawer. I also chose to follow the C# naming conventions default to ReSharper rather than Unity's: private _camelCase, local camelCase, public TitleCase.

To use this, you put a serialized field on a MonoBehaviour (or SriptableObject) like so:

[SerializeField] [MinMax(1, 10)] private MinMaxPair _orthographicSizeRange;

And it shows in the editor like this:

Each of the semicircles are individually grabbable to move the ends of the range and the bar is grabbable to move the whole range without changing the size. Values can be entered into the fields as well, which clamp to the outside of the allowed range and to the other value. If a MinMaxAttribute is not provided, the drawer defaults to be in the range [0,1]. We hide the MinMaxPair property when in multi-edit mode, as otherwise data loss would happen because this method of custom properties does not support multi-editing.

MinMaxPair.cs (in Assembly-CSharp)

public class MinMaxAttribute : PropertyAttribute
{
    public float Min, Max;

    public MinMaxAttribute(float min, float max)
    {
        Min = min;
        Max = max;
    }
}

[Serializable]
public struct MinMaxPair
{
    public float Min, Max;

    public MinMaxPair(float min, float max)
    {
        Min = min;
        Max = max;
    }

    public float Clamp(float value)
    {
        return Mathf.Clamp(value, Min, Max);
    }

    public float RandomValue
    {
        get { return UnityEngine.Random.Range(Min, Max); }
    }
}

MinMaxDrawer.cs (in Assembly-CSharp-Editor)

[CustomPropertyDrawer(typeof(MinMaxPair))]
[CustomPropertyDrawer(typeof(MinMaxAttribute))]
public class MinMaxDrawer : PropertyDrawer
{
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        if (property.serializedObject.isEditingMultipleObjects) return 0f;
        return base.GetPropertyHeight(property, label) + 16f;
    }

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (property.serializedObject.isEditingMultipleObjects) return;

        var minProperty = property.FindPropertyRelative("Min");
        var maxProperty = property.FindPropertyRelative("Max");
        var minmax = attribute as MinMaxAttribute ?? new MinMaxAttribute(0, 1);
        position.height -= 16f;

        label = EditorGUI.BeginProperty(position, label, property);
        position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
        var min = minProperty.floatValue;
        var max = maxProperty.floatValue;

        var left = new Rect(position.x, position.y, position.width / 2 - 11f, position.height);
        var right = new Rect(position.x + position.width - left.width, position.y, left.width, position.height);
        var mid = new Rect(left.xMax, position.y, 22, position.height);
        min = Mathf.Clamp(EditorGUI.FloatField(left, min), minmax.Min, max);
        EditorGUI.LabelField(mid, " to ");
        max = Mathf.Clamp(EditorGUI.FloatField(right, max), min, minmax.Max);

        position.y += 16f;
        EditorGUI.MinMaxSlider(position, GUIContent.none, ref min, ref max, minmax.Min, minmax.Max);

        minProperty.floatValue = min;
        maxProperty.floatValue = max;
        EditorGUI.EndProperty();
    }
}


texts: Best Regular Expression for a one or two values optionally divided by a certain character

texts:
I'm looking for the most concise regex that matches one or two 4-digit years in any the following setups:

year
year-
-year
year-year

I can't think of anything slicker than this:

[\\-]?\d{4}|\d{4}\[\\-](\d{4})?


texts: Shipping calculator consisting of one field

texts:
A made a shipping calculator, which consists of one field that is validated.

jsFiddle

HTML:

Калькулятор доставки

CSS:

.not_valid{
    border: 1px solid red;
}

.valid{
    border: 1px solid #ccc;
}

JS:

window.APP = window.APP || {};

APP.CityOfDepartureModel = Backbone.Model.extend({
  defaults: {
    cityName: undefined
  },

  validate: function(attrs) {
    var errorsArr = [];

    if($.trim(attrs.cityName).length == 0) {
        errorsArr.push('Это поле не может быть пустым')
    } else {
        if(isNaN(attrs.cityName) == false) { errorsArr.push('Это поле не может быть цифрой') };
    };

    if(errorsArr.length != 0) { return errorsArr };
  }
});

APP.CalculatorView = Backbone.View.extend({

  initialize: function() {
    this.cityOfDepartureModel = new APP.CityOfDepartureModel();
    this.cityOfDepartureWidjet = new APP.CityOfDepartureView({model: this.cityOfDepartureModel});
    this.render();
  },

  el: $('#contentContainer'),

  template: _.template($('#calculatorSubmitButtonTemplate').html()),

  render: function () {
    this.$el.append(this.cityOfDepartureWidjet.render().el);
    this.$el.append(this.template());
    return this;
  },

  events:{
    'click #calculatorSubmitButton' : 'submit'
  },

  submit: function() {
    var cityName = $('#fldCityOfDeparture').val();

    this.cityOfDepartureModel.set({'cityName': cityName});

    if(this.cityOfDepartureModel.isValid()) {
      this.cityOfDepartureWidjet.validMarkAdd();
    } else {
      var errorMessagesArr = this.cityOfDepartureModel.validationError;
      this.cityOfDepartureWidjet.notValidMarkAdd(errorMessagesArr);
      this.cityOfDepartureModel.set({'cityName': undefined});
    };

    console.log('-----------------------');
    console.log('city dep: ', this.cityOfDepartureModel.get('cityName'));
  }

});

APP.CityOfDepartureView = Backbone.View.extend({

  initialize: function() {

  },

  tagName: 'div',

  className: 'city_of_departure_container',

  id: 'cityOfDepartureContainer',

  template: _.template($('#cityOfDepartureTemplate').html()),

  render: function () {
    this.$el.html(this.template());
    return this;
  },

  notValidMarkAdd: function(errorMessagesArr) {
    this.$el.find('#fldCityOfDeparture').removeClass('valid').addClass('not_valid');

    this.$el.find('#errorMessageCityOfDeparture').html('');
    for(key in errorMessagesArr) {
      this.$el.find('#errorMessageCityOfDeparture').append(errorMessagesArr[key] + '
');
    };
  },

  validMarkAdd: function() {
    this.$el.find('#fldCityOfDeparture').removeClass('not_valid').addClass('valid');
    this.$el.find('#errorMessageCityOfDeparture').html('');
  }

});

var app = new APP.CalculatorView();


texts: VBA performance with Early Bind vs. Late Bind on called Sub-procedure

texts:
I was using early bind to reference the dictionary and realised that some users might not be willing to manually add the reference to use it and just consider the macro to be 'broken'.

I looked at programmatically enabling the reference but that would still require the user to go through several steps to change their macro security level, which again would seem 'broken' to an end user.

So my solution is to offer early bind and late bind options to the user, early bind for those comfortable with the VBE, late bind if not.

My question is, would the potential efficiency/performance gain in early binding still be present in going with this method, or is it wiped out simply by having to call to another sub?

If the gain is lost, I can simply use late bind within the main sub-procedure.

Option Explicit

Public Sub MatchArraysEarlyBind()

    Dim arrayMatchDictionary As Dictionary
    Set arrayMatchDictionary = New Dictionary

    Call ContinueMatchArray(arrayMatchDictionary)

End Sub

Public Sub MatchArraysLateBind()

    Dim arrayMatchDictionary As Object
    Set arrayMatchDictionary = CreateObject("Scripting.Dictionary")

    Call ContinueMatchArray(arrayMatchDictionary)

End Sub


texts:
I have written an implementation of memcpy function and I want to know how good is it and if it gets the most out of the processor capabilities or not.

The reason for this is because I am writing my operating system (which will be of course  reviewed on parts here on Code Review) it is supposed to work efficiently on both x86_64 and x86 machines

#include <stddef.h>
#include <stdint.h>
void *memcpy(void *dest, const void *src,size_t n)
{
        if (n==0)
                return dest;
        #if defined(__x86_64__) || defined(_M_X64)
        size_t i=0;
        if(n>=8)
                while(i<n/8*8){
                        *(uint64_t*)(dest + i) = *(uint64_t*)(src+i);
                        i+=8;
                }
        if(n-i>=4){
                *(uint32_t*)(dest + i) = *(uint32_t*)(src+i);
                i+=4;
        }
        if(n-i>=2){
                *(uint16_t*)(dest+i) = *(uint16_t*)(src+i);
                i+=2;
        }
        if(n-i>=1)
                *(uint8_t*)(dest+i) = *(uint8_t*)(src+i);

        #elif defined(__i386) || defined(_M_IX86)
        size_t i=0;
        if(n>=4)
                while(i<n/4*4){
                        *(uint32_t*)(dest + i) = *(uint32_t*)(src+i);
                        i+=4;
                }
        if(n-i>=2){
                *(uint16_t*)(dest+i) = *(uint16_t*)(src+i);
                i+=2;
        }
        if(n-i>=1)
                *(uint8_t*)(dest+i) = *(uint8_t*)(src+i);

        #endif
        return dest;
}

I made some aggressive testing with memcmp() to check for correct data transmission and valgrind to check for memory leaks and It passed all the tests. I didn't post the testing code because I think it could be useless since I don't want it to be reviewed.


texts: Efficient way to sort Matrix elements into separate bins in Python

texts:
I'm sorting matrix elements into separate bins.

The approach is: If the difference of each element and the 1st element in existing list is smallest, then add it to the current list. If not, create a new list and add the element there.

Following is my code which I'm applying on a small 3X3 test matrix of random numbers, as is evident, I'm using multiple for loops and and if staements to achieve this and hence it isn't memory efficient and is consuming a lot of time to execute. Is there a better way to handle this in python? Please recommend.

import numpy as np
import sys
import matplotlib.pyplot as plt

A = np.random.random((3, 3))

#Initialize the first cluster
k1 = [A[0,0]]
#Initialize the set of clusters
K = [k1]
#Threshold value
Theta = 0.3

counter = 1

for i in range(A.shape[1]):
    for j in range(A.shape[0]):
        diff = []
        for l in K:
            diff_l = abs(A[i,j] - l[0])
            diff.append(diff_l)
            mini = min(float(s) for s in diff)
            x = diff.index(min(diff))
            if mini < Theta:
                K[x].append(A[i,j])
            else:
                counter = counter+1
                new_list = 'k'+str(counter)
                new_list= []
                new_list.append(A[i,j])
                K.append(new_list)

print len(K)


texts: Advice on taming a slow loop required for visualization of large GIS dataset

texts:
I'm working towards plotting a large GIS dataset of which I've shown a sample above of about 1/6 of the data. I'm happy with how quickly the data loads in, and bokeh renders the html nearly instantaneously.  However, I've encountered a pretty hot loop in my code that is not scaling well as I increase the 1) number of rows and 2) resolution of the polygons. I'm just getting killed in the #count points loop and am wondering if there isn't a better way of doing this?

I found the suggestion for a loop off a GIS readthedoc.io and was happy with its performance for a few thousand points a couple months ago. But now the project needs to process a GeoDataFrame with >730000 rows. Is there a better method I'm suppose to be using to count the number of points in each polygon? I'm on a modern desktop to do the computation but the project has access to Azure resources so maybe that's most people professionally do this sort of computation? I'd prefer to do the computation locally but it means my desktop might have to sit at max cpu cycles overnight or longer which isn't a thrilling prospect. I'm using Python 3.8.2 & Conda 4.3.2.

from shapely.geometry import Polygon
import pysal.viz.mapclassify as mc
import geopandas as gpd

def count_points(main_df, geo_grid, levels=5):
    """
    outputs a gdf of polygons with a columns of classifiers to be used for color mapping
    """
    pts = gpd.GeoDataFrame(main_df["geometry"]).copy()

    #counts points
    pts_in_polys = []
    for i, poly in geo_grid.iterrows():
        pts_in_this_poly = []
        for j, pt in pts.iterrows():
            if poly.geometry.contains(pt.geometry):
                pts_in_this_poly.append(pt.geometry)
                pts = pts.drop([j])
        nums = len(pts_in_this_poly)
        pts_in_polys.append(nums)
    geo_grid['number of points'] = gpd.GeoSeries(pts_in_polys) #Adds number of points in each polygon

    # Adds Quantiles column
    classifier = mc.Quantiles.make(k=levels)
    geo_grid["class"] = geo_grid[["number of points"]].apply(classifier)

    # Adds Polygon grid points to new geodataframe
    geo_grid["x"] = geo_grid.apply(getPolyCoords, geom="geometry", coord_type="x", axis=1)
    geo_grid["y"] = geo_grid.apply(getPolyCoords, geom="geometry", coord_type="y", axis=1)
    polygons = geo_grid.drop("geometry", axis=1).copy()

    return polygons


texts: Calculating multiple car prices from a file

texts:
My application needs to read a file, which includes a list of cars from different factories, and calculate the prices (by this I mean mean add up their prices).

I suppose my solution is efficient.  Is there any better approach to it?

Company Price  other details
Benz   10000   x ...
BMW    3000    y ...
Benz   1000    z ...
Toyota 500     w ...

In this case the result should be

Benz 11000
BMW  3000
Toyota 500

Solution

public static final void main(String[] args) {
    List<Company> trn = new ArrayList();
    Company t = new Company();

    t.setName("Benz");
    t.setPrice(10000);
    trn.add(t);
    t = null;
    t = new Company();
    t.setName("BMW");
    t.setPrice(3000);
    trn.add(t);
    t = null;
    t = new Company();
    t.setName("Benz");
    t.setPrice(1000);
    trn.add(t);
    t = null;
    t = new Company();
    t.setName("Toyota");
    t.setPrice(500);
    trn.add(t);

    for (Company c : trn) {
        System.err.println(c.toString());
    }
    Map<String, String> map = new HashMap();
    int counter = 0;
    for (Company c : trn) {
        String name = c.getName();
        if (!map.containsKey(name)) {
            counter = 0;
            for (Company com : trn) {
                if (com.getName().equalsIgnoreCase(name)) {
                    counter += com.getPrice();
                }
            }
            map.put(name, String.valueOf(counter));
        }
    }
        System.err.println(map.get("Benz"));
        System.err.println(map.get("BMW"));
        System.err.println(map.get("Toyota"));
    }
}

Output

Company{name=Benz, price=10000}
Company{name=BMW, price=3000}
Company{name=Benz, price=1000}
Company{name=Toyota, price=500}
11000
3000
500


texts: Non blocking high performance message processor

texts:
I have some kind of high thoughput message handler receiving ordered messages. Now the task is - adding monitoring stuff in it in order to recognize wrong input messages, more exactly: it must notify about missed messages and just ignore the stale ones (with smaller order).

Due to high thoughput - it mustn't block.

So it must:

not use locks
find missing messages
find wrong ordered messages

Let's have some long counter in message for ordering - here is my initial version:

public class OrderedNonBlockingProcessor implements YetAnotherMessageHandler {
    private static Logger log = Logger.getLogger(OrderedNonBlockingProcessor.class);

    private final AtomicLong messageCounter = new AtomicLong(0);

    @Override
    public boolean onSomeHighThroughputMessage(final YetAnotherMessage message) {
        final long expected = messageCounter.getAndSet(message.getCounter()) + 1;

        if (expected == message.getCounter()) {
            processBusinessStuff(message);
            return true;
        } else if (expected > message.getCounter()) {
            /* wrong message, attempt to restore the sequence to prevent an error on next good message
             * TODO: fix ABA problem here
             */
            messageCounter.compareAndSet(message.getCounter(), expected - 1);

            log.error(String.format("messaging system ordering bug: got stale message %s while expected %s!",
                    message.getCounter(), expected));

            // some other notifying stuff...
        } else if (expected < message.getCounter()) {
            log.error(String.format("got forward message %s while expected %s, missed: %s",
                    message.getCounter(), expected, message.getCounter() - expected));

            // some other notifying stuff...
        }
        return false;
    }

    private void processBusinessStuff(YetAnotherMessage message) {
        log.info(String.format("process message %s", message.getCounter()));
        // some business logic...
    }
}

(Here is a junit for that)

How is it? Are there any races/concurrency issues I missed?

P.S. Next step is fixing ABA problem there.  I'm thinking about AtomicStampedReference[Long] for that.


texts: Finding Largest Integer Palindrome within a Set

texts:
I've "solved" Project Euler Question 4 and I was wondering if I could make my answer more efficient (I'm using Project Euler to help me learn Haskell).

The problem reads:

  Find the largest palindrome made from the product of two 3-digit numbers

Here is my solution

getMaxPalindrome = maximum[x*y | x<-[100..999], y<-[100..999], reverse(show(x*y)) ==show(x*y)]

All suggestions for improvement are appreciated!


texts:
The program is asking you to guess a number between 1-100 and if you guessed too low it says that in Swedish and the same goes for if it's too high and if it's the correct answer it says congratz you guessed right in Swedish.

I'd like comments about any aspects of my code.

public class Kidsprogram {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();
        int number = rand.nextInt(100) + 1;
        System.out.println("Gissa på ett nr mellan 1 och 100");
        for (int i = 1; i > -1; i++)
        {
            int guess;
            guess = input.nextInt();
            if (guess < number)
            {
                System.out.println("Du gissade för lågt");
            }
            else if(guess > number)
            {
                System.out.println("Du gissade för högt");
            }
            else if(guess == number)
            {
                System.out.println("Antal gissningar: " + i);
                System.out.println("Grattis du gissade rätt!");
                break;
            }
        }
    }
}


texts:
I'm after creating an insert function for a 2 4 tree in Haskell. I'm just wondering if this is the best way to implement it (especially when handling the Root4s), or is there a better way. I know it's quite bulky, but I couldn't see another way of handling the roots with 4 branches.

insertRoot :: Ord t => t -> Tree t -> Tree t

insertRoot x Empty = Root2 x Empty Empty

insertRoot x (Root2 y Empty Empty)
          | x <= y = Root3 (x,y) Empty Empty Empty
          | otherwise = Root3 (y,x) Empty Empty Empty

insertRoot x (Root3 (y,z) Empty Empty Empty)
          | x <= y = Root4 (x,y,z) Empty Empty Empty Empty
          | x > y && x <= z = Root4 (y,x,z) Empty Empty Empty Empty
          | otherwise = Root4 (y,z,x) Empty Empty Empty Empty

insertRoot x (Root2 y left right)
          | x <= y =
              case left of (Root4 (i,j,k) tree1 tree2 tree3 tree4) -> if x <= j then Root3 (j,y) (insertRoot x (Root2 i tree1 tree2)) (Root2 k tree3 tree4) right
                                                                           else Root3 (j,y) (Root2 i tree1 tree2) (insertRoot x (Root2 k tree3 tree4)) right
                           _ -> Root2 y (insertRoot x left) right
          | otherwise =
              case right of (Root4 (i,j,k) tree1 tree2 tree3 tree4) -> if x <= j then Root3 (y,j) left (insertRoot x (Root2 i tree1 tree2)) (Root2 k tree3 tree4)
                                                                            else Root3 (y,j) left (Root2 i tree1 tree2) (insertRoot x (Root2 k tree3 tree4))
                            _ ->  Root2 y left (insertRoot x right)

insertRoot x (Root3 (a,b) left middle right)
          | x <= a =
              case left of (Root4 (i,j,k) tree1 tree2 tree3 tree4) -> if x <= j then Root4 (j,a,b) (insertRoot x (Root2 i tree1 tree2)) (Root2 k tree3 tree4) middle right
                                                                           else Root4 (j,a,b) (Root2 i tree1 tree2) (insertRoot x (Root2 k tree3 tree4)) middle right
                           _ -> Root3 (a,b) (insertRoot x left) middle right
          | x > a && x <= b =
              case middle of (Root4 (i,j,k) tree1 tree2 tree3 tree4) -> if x <= j then Root4 (a,j,b) left (insertRoot x (Root2 i tree1 tree2)) (Root2 k tree3 tree4) right
                                                                             else Root4 (a,j,b) left (Root2 i tree1 tree2) (insertRoot x (Root2 k tree3 tree4)) right
                             _ -> Root3 (a,b) left (insertRoot x middle) right
          | otherwise =
              case right of (Root4 (i,j,k) tree1 tree2 tree3 tree4) -> if x <= j then Root4 (a,b,j) left middle (insertRoot x (Root2 i tree1 tree2)) (Root2 k tree3 tree4)
                                                                            else Root4 (a,b,j) left middle (Root2 i tree1 tree2) (insertRoot x (Root2 k tree3 tree4))
                            _ -> Root3 (a,b) left middle (insertRoot x right)

insertRoot x (Root4 (a,b,c) left mleft mright right)
          | x <= b = Root2 b (insertRoot x (Root2 a left mleft)) (Root2 c mright right)
          |otherwise = Root2 b (Root2 a left mleft) (insertRoot x (Root2 c mright right))


texts: Executing method on a certain interval + offset

texts:
I would like to execute a certain method at a given interval. The reason why I can't use a timer + its event handler right away is because I want to add an offset to each tick (100ms in my example below).

It seems to be working just as intented. The reason why I'm starting it manually is because if the _action(); takes more than the given tick time, I want to let it finish before starting a new "tick".

Perhaps this could be done in a much simpler way. I would like your thoughts on the code:

class RandomIntervalTask : IDisposable
{
    private readonly Timer _timer;
    private readonly int _initialInterval;
    private readonly int _range;
    private readonly Action _action;

    public RandomIntervalTask(int initialInterval, int range, Action action)
    {
        this._range = range;
        this._initialInterval = initialInterval;
        this._action = action;

        _timer = new Timer { AutoReset = false, Interval = initialInterval };
        _timer.Elapsed += TimerElapsed;
        _timer.Start();
    }

    private void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        var rnd = new Random();

        _timer.Interval = rnd.Next(_initialInterval, _initialInterval + _range);
        _action();
        _timer.Start();
    }

    public void Dispose()
    {
        _timer.Stop();
        _timer.Dispose();
    }
}

Executed like this:

var rit = new RandomIntervalTask(400, 100, DoStuff);

private void DoStuff()
{
    Debug.WriteLine("stuff");
}


texts:
The following is a class for curl wrapper.

This class will be called like:

     class curlWrapper {

private:
    CURLcode curlCode;
    CURL* curlHandle;
    struct curl_slist *header = NULL;

    MemoryStructA response;

    static std::atomic<int> numberOfCurlProcess;
    static std::atomic<bool> isGlobalInitCalled;
    static std::mutex curlGlobalkey;

public:
    curlWrapper(){

        curlGlobalkey.lock();

        if(!isGlobalInitCalled)
        {
            curl_global_init(CURL_GLOBAL_ALL); // this should be called only once in the entire program when a first object using this class.
            numberOfCurlProcess++;
        }
        else
        {
            numberOfCurlProcess++;

        }
        curlGlobalkey.unlock();

        //globalCurlInit();

        initializeMemoryStruct();

    }

    ~curlWrapper(){

        curlGlobalkey.lock();

        if(numberOfCurlProcess > 0)
        {

            numberOfCurlProcess--;
        }
        else if(numberOfCurlProcess == 0)
        {
 // this should be called only once in the entire program when a last object using this class.

            curl_global_cleanup();

        }
        curlGlobalkey.unlock();

    }

    int trace(CURL *handle, curl_infotype type,  char *data, size_t size, void *classPointer);
    int traceImpl(CURL *handle, curl_infotype type,  char *data, size_t size);

    CURL* curlInit();

    void curlClose();

    bool initializeConnection();

    bool sendRequest(const char* request);

    char* getResponse();

    void setMemorytoWrite();

    bool listen();

    void closeConnection();

    bool setURL(const char* url);

    bool setHttpHeader(const char * contentType, const char * charSet);

    void setTrace(bool trace);// If true trace will be displayd

    bool curlExec();

    void initializeMemoryStruct();

    void globalCurlInit();

    void globalCulrClean();

};

This class will be used as:

   class Accessor{
   public:
          curlWrapper *curl = new curlWrapper()

    };

main(){

   //somewhere in the main
      Accessor aa = new Accessor();
      Accessor bb = new Accessor();

     thread(aa).doProcess();
     thread(bb).dpProcess()

}

Did I call curl_global_init(CURL_GLOBAL_ALL) at first thread starts and only once? Similarly, did I call curl_global_cleanup() while the last thread ends?


texts:
Challenge:

  Given three query types simulate heap operations.

Specifications:

  1. "1 v" - Add an element v to the heap.
    2. "2 v" - Delete the element v from the heap.
    3. Print the minimum of all the elements in the
      heap.

  It is guaranteed that the element to be deleted will exist in the heap.
  Only distinct elements will be in the heap.

  The first line contains the number of queries, Q.
  Each of the next Q lines contains a single query of any one of the 3 above mentioned types.

Implementation:

import java.util.Set;

public class QHeap1 {
    int minimum = Integer.MAX_VALUE;
    Set<Integer> set = new HashSet<>();

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        QHeap1 qHeap = new QHeap1();

        for (int i = Integer.parseInt(input.nextLine()); i > 0; i--) {
            String query = input.nextLine();
            if (query.startsWith("1")) {
                qHeap.add(Integer.valueOf(query.split("\\s")[1]));
            } else if (query.startsWith("2")) {
                qHeap.remove(Integer.valueOf(query.split("\\s")[1]));
            } else {
                System.out.println(qHeap.minimum);
            }
        }
    }

    private void add(Integer value) {
        set.add(value);
        if (value < minimum) {
            minimum = value;
        }
    }

    private void remove(Integer value) {
        set.remove(value);
        if (minimum == value) {
            minimum = Integer.MAX_VALUE;
            for (Integer newMin : set) {
                if (newMin < minimum) {
                    minimum = newMin;
                }
            }
        }
    }
}

This is a challenge found on Hacker Rank. I passed all test cases, but I'm wondering if there's a way to further increase the performance of this algorithm. Especially concerning the minimum tracking. Interestingly, SortedSet implementations timeout hence the current strategy.

I considered also tracking the second minimum, but that seems a slippery slope to also tracking the second or third, but it could conceivably eliminated having to find the minimum, I'm unsure if it makes sense, generally. What do you think?


texts: Display message that content depends on variable value

texts:
I start external process and after its completion print a message to the user. The message content depends on exit code that this process returns.
I have defined this codes in enum:

public enum ExitCode {
    Success = 0,
    Warning = 1,
    Error = 2
}

I call some method only if the process exited with success.

I have 2 approaches.
First is to use switch statement

switch (process.ExitCode)
{
    case ExitCode.Success:
        Console.WriteLine("Success message.");
        CallSomeMethod();
        break;
    case ExitCode.Warning:
        Console.WriteLine("Warning message.");
        break;
    case ExitCode.Error:
        Console.WriteLine("Error message.");
        break;
    default:
        Console.WriteLine("Unknown exit code.");
        break;
}

Second way is to create dictionary with (StatusCode, messageContent) pairs

if (dictionary.TryGetValue(process.ExitCode, out msg))
{
    Console.WriteLine(msg);
    if (process.ExitCode == ExitCode.Success)
    {
        CallSomeMethod();
    }
}
else
{
    Console.WriteLine("Unknown exit code.");
}

Which version is more elegant? Feel free to reject both and propose better solution.


texts:
This piece of code is working - It gives me a lot of JSON back, which I have yet to parse, but I'd like to show my code here first to get tips on how to improve what I already have:

VenueService.swift

    class VenueService {

    private let __kVenueServiceClientID = "CLIENT_ID"
    private let __kVenueServiceClientSecret = "CLIENT_SECRET"

    func performVenueLocationRequest(location: CLLocationCoordinate2D, identifier: NSString, completion: (venues: NSDictionary?, error: NSError?) -> ()) {
        var error: NSError?
        var response: NSURLResponse?

        let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

        dispatch_async(queue, {
            if let data = NSURLConnection.sendSynchronousRequest(self.buildRequestForVenueLocation(location, identifier), returningResponse: &response, error: &error) {
                if(error == nil) {
                    let responseDictionary: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:&error)
                    if let responseDictionary = responseDictionary as? NSDictionary {
                        completion(venues: responseDictionary, error: nil)
                    }
                } else {
                    completion(venues: nil, error: error)
                }
            } else {
                println("There was a problem with the request...")
            }
        })

    }

    func todaysDate() -> NSString {
        let date = NSDate()
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyMMdd"
        return formatter.stringFromDate(date)
    }

    func buildRequestForVenueLocation(location: CLLocationCoordinate2D, _ identifier: NSString) -> NSURLRequest {
            return NSURLRequest(URL: NSURL(string: "https://api.foursquare.com/v2/venues/search?ll=\(location.latitude),\(location.longitude)&radius=500&limit=50&categoryId=\(identifier)&client_id=\(__kVenueServiceClientID)&client_secret=\(__kVenueServiceClientSecret)&v=\(self.todaysDate())")!)
    }
}

I use it like this in my ViewController:

struct Location {
    let location: CLLocationCoordinate2D

    init() {
        self.location = CLLocationCoordinate2D(latitude: 37.332331, longitude: -122.031219)
    }

}

class ViewController: UIViewController {

    let v = VenueService()
    let l = Location()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func testJSON(sender: AnyObject) {
        v.performVenueLocationRequest(l.location, identifier: "4d4b7105d754a06374d81259", completion: { dict, err in
            dispatch_async(dispatch_get_main_queue(), {
                if let err = err {
                    println("if let \(err)")
                } else {
                    if let dict = dict {
                        println("else: \(dict)")
                    }
                }
            })
        })
    }
}

One thing I'm really confused about:

Say I have an optional. I could use the if let syntax to unwrap it, but is it the same to just say if optinalVariable == nil {} else optinalVariable!?

In playground I get the same results.


texts:
I have a situation in which a program, communicating over the network, can timeout or otherwise fail to establish a connection through no fault of my application or its user. If and when this happens, an exception is thrown. The solution is obvious; simply try again a couple more times, and if multiple tries don't work then this is really a problem.

I've accomplished this by wrapping the original try-catch in a while loop with a retry counter, producing the following basic pattern:

var retryCount = 0;
while(true)
{
   try
   {
      AttemptToConnect();
      break;
   }
   catch(TimeoutException tex)
   {
      if(++retryCount < 3) continue;

      throw; //or handle error and break/return
   }
}

Do any of you see any problems? The biggest smell, prompting me to ask in the first place, is the conditionless loop, which would be infinite except that the "happy path" breaks out of the loop manually, while the terminating error will throw out. This has been called out before as a potential bug generator, if it's ever modified in the future (for instance to catch a second type of exception, or to do something else that could throw an exception).


texts:
I'm using this method from my Downloads() class in a back-end admin system, where these can upload some files, which must be .rar or .zip I'm not to concern about filesize, yet. Eventually, these compressed files, will be holding only .mp3 files.

Well, here's the code. As you can see, I'm checking mimetype against an array of the ones allowed, which I got them from Stack Overflow, but I'm still not sure if I'm not missing any.

Then, I'm checking against the file extension in case mimetype is faked (not sure how accurate this check is).

Are those conditionals OK? I mean, I wouldn't want the file to be uploaded, but the query not to be done, or vice-versa.

//Handle file upload process
    public function uploadFile($titulo,$file) {
        $accepted_types = array(
                        'application/zip',
                        'application/x-zip-compressed',
                        'multipart/x-zip',
                        'application/x-compressed',
                        'application/x-rar-compressed',
                );
        if (isset($file['name'])) {
            $filename = str_replace(' ', '_',$file["name"]);
            $tmp_name = $file["tmp_name"];
            $type = $file["type"];
            $name = explode(".", $filename);
            foreach($accepted_types as $mime_type) {
                if($mime_type == $type) {
                        $okay = true;
                        break;
                }
            }
            //Check mimeType
            $continue = (strtolower($name[1]) == 'zip') || (strtolower($name[1]) == 'rar') ? true : false;
            if(!$continue) {
                    return false;
            }
            $finalPath = DOWNLOAD_PATH.$filename;
            if (file_exists($finalPath)) {
                $newname=  Utility::file_newname(DWONLOAD_PATH,$filename);
                $finalPath= DWONLOAD_PATH.$newname;
            }

            if (move_uploaded_file($tmp_name, $finalPath)) {
                $fileSize = filesize($finalPath);
                $query = "INSERT INTO descargas (titulo,size,src,filename) VALUES
                    ('$titulo','$fileSize','$finalPath','$filename')";
                if ($this->mysqli->query($query)) {
                    return true;
                } else {//The file's been moved, but theere was an error in the query
                    unlink($finalPath);
                    return false;
                }
            }
        }
    }


texts: Looking to simplify my first python Rock, paper, Scissors project

texts:
I recently (Yesterday) started working with python and my goal is to not use any tutorials etc where I have to follow along and make a small project. My first project I was recommended to do was a simple game of Rock, Paper, Scissors. I made it in about thirty minutes and it works fine. It goes up to 3 points for each game etc. It's super simple, but now since I'm done with it I'm hoping to find a way to simplify the code, if there is any other way. I really stretched it out since I'm using basics with no help.

# Rock Papers Scissors
import random

option = ["Rock", "Paper", "Scissor"]
game = True

def start_game():
    point_player = 0
    point_ai = 0
    game_end = True
    while game:
        rock = False
        paper = False
        scissor = False
        if point_player == 3:
            game_end = False
        elif point_ai == 3:
            game_end = False
        if game_end:
            print("Choose an option. (R,P,S)")
            selection = input()
            if selection == 'R':
                selection = 'Rock'
                rock = True
            elif selection == 'P':
                selection = 'Paper'
                paper = True
            elif selection == 'S':
                selection = 'Scissor'
                scissor = True
            else:
                print("That's not an option")
                exit()
            print("=======================")
            print("You chose " + selection)
            ai_response = random.choice(option)
            print("The A.I chose " + ai_response)
            print("=======================")
            if ai_response == "Rock":
                while rock:
                    print("Oh! That's a tie no points.")
                    break
                while scissor:
                    print("Oh, you lost :( +1 to A.I")
                    point_ai = point_ai + 1
                    break
                while paper:
                    print("Looks like you beat the A.I! +1 Point")
                    point_player = point_player + 1
                    break
            elif ai_response == "Paper":
                while rock:
                    print("Oh, you lost :( +1 to A.I")
                    point_ai = point_ai + 1
                    break
                while scissor:
                    print("Looks like you beat the A.I! +1 Point")
                    point_player = point_player + 1
                    break
                while paper:
                    print("Oh! That's a tie no points.")
                    break
            elif ai_response == "Scissor":
                while rock:
                    print("Looks like you beat the A.I! +1 Point")
                    point_player = point_player + 1
                    break
                while scissor:
                    print("Oh! That's a tie no points.")
                    break
                while paper:
                    print("Oh, you lost :( +1 to A.I")
                    point_ai = point_ai + 1
                    break
            print("You have " + str(point_player) + " points")
            print("The A.I has " + str(point_ai) + " points.")
            print("=======================")
        else:
            if point_ai > point_player:
                print("The A.I won! RIP U")
            else:
                print("Dang! You won this time.")
            exit()

print("|=========================|")
print("|    Rock Paper Scissor   |")
print("|       (R) (P) (S)       |")
print("|=========================|")
print("Would you like to start? y/n")
answer = input()
if answer == "y":
    print("Welcome to the game of Rock Paper Scissors")
    start_game()
elif answer == "n":
    print('Well ok then.. Fine leave')
    exit()
else:
    print("That's not an option.")


texts:
I'm attempting to define an abstract interface for a key value store.

Some requirements:

Once a key has been written it should never be overwritten (although it may be deleted
Transactions with multiple operations are not required

To begin with, this is the basic interface:

class KVS a where
  get :: ByteString -> a -> Maybe ByteString
  put :: ByteString -> ByteString -> a -> Maybe a
  delete :: ByteString -> a -> a

And here's an InMemory instance:

newtype InMemoryKVS = InMemoryKVS (M.Map ByteString ByteString)

instance KVS InMemoryKVS where
  get k (InMemoryKVS m) = M.lookup k m
  put k v (InMemoryKVS m)
    | M.Member k m = Nothing
    | otherwise = Just $ InMemoryKVS $ M.insert k v m
  delete k (InMemoryKVS m) = InMemoryKVS $ M.delete k m

I would also like to write instances that use the IO monad, so presumably the typeclass needs to take this into account. Here's my first attempt at that:

class IOKVS a where
  ioGet :: ByteString -> a -> IO (Maybe ByteString)
  ioPut :: ByteString -> ByteString -> a -> IO (Maybe a)
  ioDelete :: ByteString -> a -> IO a

instance IOKVS InMemoryKVS where
  ioGet k s = return $ get k s
  ioPut k v s = return $ put k v s
  ioDelete k s = return $ delete k s

Here is how I'm currently using it:

{-# LANGUAGE OverloadedStrings #-}
main :: IO()
main = do
  kvs <- return (InMemoryKVS M.empty)
  kvs' <- ioPut "foo" "bar" kvs
  maybe (putStrLn "put failed") (printKey "foo") kvs'

printKey :: IOKVS a => B.ByteString -> a -> IO()
printKey k s = do
  v <- ioGet k s
  maybe (putStrLn "doesn't exist") (\v -> B.putStrLn v) v

I feel that there is a lot of room for improvement with my design. Here are some questions that I have:

In main I'm manually keeping track of the state of kvs. Could my code be simplified by using the State monad? If so how can I manage the complexity of having IO, State and Maybe stacked?
I'm not happy with the design of the IOKVS typeclass. Specifically I don't think it will work well with concurrent access.
Can this design hide a connection pool to an external db?
Is there a more elegant way to handle the failure cases then using the maybe function? I would like to be able to compose these into higher level actions that may fail, but not have to deal with the failure case within each action.
Can you see any other areas for improvement?


texts:
I have recently created my first game in C++:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    cout<<"\tWelcome to Guess my Number!\n";
    const unsigned short kusiLower=1;
    const unsigned short kusiHigher=100;
    srand(time(0));
    unsigned short usiComp=rand()%kusiHigher+kusiLower;
    cout<<"Guess a number between 1 and 100: ";
    unsigned short usiUser;
    cin>>usiUser;
    unsigned short usiGuesses=1;
    while(usiUser!=usiComp)
    {
        cout<<((usiUser>usiComp)?"Your guess is too high.\n":"Your guess in too low\n");
        cout<<"Guess a number between 1 and 100: ";
        cin>>usiUser;
        ++usiGuesses;
    }
    cout<<"Congratulations! You guessed my number in "<<usiGuesses<<" guesses.";
}

And I came here to ask the standard question: can it be in any way optimized or improved?


texts:
The idea is to convert first 8 character from the C string to uint64_t or uint32_t, then to convert to Big Endian.

The value can be stored and compared with same values and result will be compatible with memcmp or strcmp.

The only exception is if both "strings" are 8 bytes long or 4 bytes long for uint32_t and are equal, the function must return sentinel value, e.g. std::numeric_limits<int>::max(), so caller to know he will need to compare the real strings in order to find the result.

For simplicity, I assume code runs on Little Endian machine and convert to Big Endian is done by __builtin_bswap64 (available on gcc and clang).

Here is the code + some tests

#include <cstdint>
#include <cstring>
#include <limits>

namespace sshhash_implementation{
    constexpr auto bswap(uint64_t x){
        return __builtin_bswap64(x);
    }

    constexpr auto bswap(uint32_t x){
        return __builtin_bswap32(x);
    }

    template<typename T>
    T hash(const char *src){
        constexpr auto capacity = sizeof(T);

        union{
            char    s[capacity];
            T   u = 0;
        };

        strncpy(s, src, capacity);
        return bswap(u);
    }

    template<typename T>
    constexpr T mask(){
        return bswap(T{ 0xFF } << (sizeof(T) - 1) * 8);
    }

    template<typename T>
    int sscmp(T const a, T const b){
        if (a > b)
            return +1;

        if (a < b)
            return -1;

        // equal, check size

        constexpr auto m = mask<T>();

        if ( (a | b) & m )
            return std::numeric_limits<int>::max();

        return 0;
    }
}

template<typename T>
auto sshash(const char *s){
    return sshhash_implementation::hash<T>(s);
}

auto sshash8(const char *s){
    return sshash<uint64_t>(s);
}

auto sshash4(const char *s){
    return sshash<uint32_t>(s);
}

template<typename T>
auto sscmp(T a, T b){
    return sshhash_implementation::sscmp(a, b);
}

auto sscmp8(uint64_t a, uint64_t b){
    return sscmp(a, b);
}

auto sscmp4(uint32_t a, uint32_t b){
    return sscmp(a, b);
}

#include <cstdio>

template<typename T = uint32_t>
void testC(const char *sa, const char *sb, bool const overflow){
    auto const a = sshash<T>(sa);
    auto const b = sshash<T>(sb);

    int const  x = strncmp(sa, sb, sizeof(T));
    int const  y = sscmp(a, b);

    bool const ok = [=](){
        if (overflow)
            return x == 0 && y == std::numeric_limits<int>::max();
        else
            return x == y;
    }();

    printf(
        "%-8s | %-8s | %2d | %2d | %-8s\n",
        sa,
        sb,
        x,
        y,
        ok ? "OK" : "Error"
    );
}

template<typename T = uint32_t>
void test(const char *sa, const char *sb, bool const overflow = false){
    testC(sa, sb, overflow);
    testC(sb, sa, overflow);
}

int main(){
    test("aaa"  , "aaa"     );

    test("aaa"  , "b"       );
    test("aaaa" , "b"       );
    test("aaa"  , "bbbb"    );
    test("aaaa" , "bbbb"    );

    test("aaaa" , "aaaa", true  );
}


texts: Fetching counties and localities using JSON API calls

texts:
I'm using the below code to call different methods from an API:

import requests
import json
from unidecode import unidecode
from datetime import datetime

temp_county = 'County'
temp_locality = 'Locality'

# Function - login

session = requests.Session()

def login():
    # Application header
    header = {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': '{KEY}'
    }

    # User's credentials
    body_login = {
        'username': 'user',
        'password': 'pass'
    }

    # Make the login request and return the token
    request_url = session.post(
        'https://urgentcargus.azure-api.net/api/LoginUser', json=body_login, headers=header)

    # Parse the token and remove double quotes
    token = 'Bearer ' + request_url.text.strip('"')

    return token

# Get country code. Since it's a local product, the request will return only the code for RO

def countries():
    # Application header
    header = {
        'Authorization': login(),
        'Ocp-Apim-Subscription-Key': '{KEY}'
    }
    # Make the request and return the country code
    request_url = session.get(
        'https://urgentcargus.azure-api.net/api/Countries', headers=header
    )

    countries_dictionary = request_url.json()

    for country in countries_dictionary:
        if country['Abbreviation'] == 'RO':
            countryId = str(country['CountryId'])

    return countryId

def counties():
    # Application header
    header = {
        'Authorization': login(),
        'Ocp-Apim-Subscription-Key': '{KEY}'
    }
    # Load the country id
    params = {
        'countryId': countries()
    }

    # Make the request and return the county code based on the city
    request_url = session.get(
        'https://urgentcargus.azure-api.net/api/Counties', params=params, headers=header
    )

    counties_dictionary = request_url.json()

    # Parse the city description and transliterate it to ASCII

    county = unidecode(temp_county)

   # print(county)

    # Return the county code
    for countyName in counties_dictionary:
        if countyName['Name'] == county:
            countyId = str(countyName['CountyId'])

    return countyId

def localities():
    # Application header
    header = {
        'Authorization': login(),
        'Ocp-Apim-Subscription-Key': '{KEY}'
    }
    # Load the country id and county id
    params = {
        'countryId': countries(),
        'countyId': counties()
    }

    # Make the request and return the county code based on the city
    request_url = session.get(
        'https://urgentcargus.azure-api.net/api/Localities', params=params, headers=header, stream=True
    )

    localities_dictionary = request_url.json()

    # Parse the city description and transliterate it to ASCII

    locality = unidecode(temp_locality)

    # print(county)

    # Return the locality code
    for localityName in localities_dictionary:
        if localityName['Name'] == locality:
            localityId = str(localityName['LocalityId'])

    return localityId

#
print(login())
print(countries())
print(counties())
print(localities())

The functions are working well, with no errors or something. Problem is that it require (in my opinion) lot of time to complete all functions and return what it has to return.

I have used requests.Session() in order to create one persistent session in order to save time but somehow is the same behavior.

I've monitored how much time is required and for instance, it takes about 5 - 6 seconds to complete:

print('Process start! ' + str(datetime.now()))

# here are all the functions

print('Process ended! ' + str(datetime.now()))

Terminal response:

Process start! 2019-10-18 13:26:09.796132
Bearer 8JCAOoSSevSpcNDydLHSAmZORL0RGgDXV110IUhxIRWABX0TNj
1
26
163
Process ended! 2019-10-18 13:26:14.663092

Is there any way to improve it?


texts:
There are 12 buttons, and each of them has 3 options for selecting pictures, depending on the data. It works but I think need a shorter and more intelligent decision.

import SpriteKit

class SelectEasyLevelViewController: UIViewController{

@IBOutlet weak var level_1: UIButton!
@IBOutlet weak var level_2: UIButton!
@IBOutlet weak var level_3: UIButton!
@IBOutlet weak var level_4: UIButton!
@IBOutlet weak var level_5: UIButton!
@IBOutlet weak var level_6: UIButton!
@IBOutlet weak var level_7: UIButton!
@IBOutlet weak var level_8: UIButton!
@IBOutlet weak var level_9: UIButton!
@IBOutlet weak var level_10: UIButton!
@IBOutlet weak var level_11: UIButton!
@IBOutlet weak var level_12: UIButton!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    //This thing help me to open data
    if  UserDefaults.standard.array(forKey: "levelPassed") != nil {
        Model.sharedInstance.levelPassed = UserDefaults.standard.array(forKey: "levelPassed") as! [Int]
    }

let image = UIImage(named: "levelbutton01")
let image2 = UIImage(named: "levelbutton02")
let image3 = UIImage(named: "levelbutton03")

    switch Model.sharedInstance.levelPassed[0] {
    case 1:
        level1.setBackgroundImage(image, for: .normal)
    case 2:
        level1.setBackgroundImage(image2, for: .normal)
    case 3:
        level1.setBackgroundImage(image3, for: .normal)
    default:
        break

    }

    ..........................................
    Here codes for button 2, 4, 5, 6, 7, 8, 9, 10, 12
    .........................................

    switch Model.sharedInstance.levelPassed[11] {
    case 1:
        level_12.setBackgroundImage(image, for: .normal)
    case 2:
        level_12.setBackgroundImage(image2, for: .normal)
    case 3:
        level_12.setBackgroundImage(image3, for: .normal)
    default:
        break

    }
}

Or maybe another way.


texts: Describing algorithms to implement higher level operations in terms of the lower level operations

texts:
My question concerns problem (b). This is my attempt:

def shift_left(D,k)
    for j = 0 to k:
      x_current = D.delete_first() //this remove and return first item
      D.insert_last(x_current)

    return D

The answer key was given the following for the solution. I am just trying to figure out if my solution is correct. I know this solution key uses recursion. Does my solution work as well?