texts: Renames file-name references inside files in a directory

texts:
The filenames.txt contains all the names of the files that you want to change in a given directory.
It is generated by:

import os

walk = os.walk("./app/")

for dirpath, dirs, files in walk:
    for filename in files:
        fpath = os.path.join(dirpath, filename)
        with open("filenames.txt", "a") as f:
            f.write(filename + "\n")

The Test directory is the directory whose files you are targeting.

"""Rename files.
Rename file references containing `-` with `_`
"""
import os

# Directory to traverse
walk = os.walk('./Test/')

# A file containing filenames that you want to change.
# Already generated
with open("filenames.txt") as filenames_to_change:
    names = filenames_to_change.read().splitlines()

for dirpath, dirs, files in walk:
    for filename in files:
        fpath = os.path.join(dirpath, filename)

        for name in names:
            old_name = name
            new_name = name.replace('-', '_')
            print("{} >>> {}".format(old_name, new_name))

            with open(fpath) as f:
                s = f.read()
            s = s.replace(old_name, new_name)
            with open(fpath, "w") as f:
                f.write(s)


texts: Java implementing task on another thread with javascript-like promise resolve-reject

texts:
Background:

I have a TCP online multiplayer game server, which the player requests to log-in. However, the game server does not handle the authentication part of the login process, instead, it uses an outer micro-service which is an HTTP server to see if the user can authenticate with the given credentials.

Now why is that a problem? - Well I use netty.io networking framework, which is a non-blocking framework, it handles all connections in a sequence on the same thread. Since I don't want to cause any delays, I will not send an HTTP request on the same thread because I don't want to stop it.

Instead I followed a pattern of callbacks like java script promise resolve-reject, and I Would like to hear what you think, and if it could be done better.

Don't mind the generic types, just take the basic idea of it:

First of all this is my ServiceProvider, the point of this class is to provide a singleton of each service that interacts with microservices such as UserService which is an HTTP server to handle everything related to user (authentication, data, etc):

public class ServiceProvider {

    private static ExecutorService executorService = Executors.newFixedThreadPool(ServicesConfig.SERVICES_THREAD_POOL_CAPACITY);

    private static UserService userService;

    /**
     * Provdes an user service singleton instance
     * @return  The user service
     */
    public static UserService getUserService() {
        if (userService == null) {
            userService = new UserService();
            userService.setBaseUrl(ServicesConfig.USER_SERVICE_BASE_URL);
        }
        return userService;
    }

    public static void submitServiceTask(ServicePromise task) {
        executorService.submit(task);
    }
}

Secondly is my UserService for example:

public class UserService extends HeroesHttpService {

    /**
     * Authenticates an user
     * @param username  The username
     * @param password  The password
     * @return  ?
     */
    public ServicePromise<?> authenticateUser(String username, String password) {

        ServicePromise<HttpResponse> promise = new ServicePromise<HttpResponse>() {
            @Override
            public void run() {
                HttpClient client = HttpClients.createDefault();

                HttpGet request = new HttpGet(getBaseUrl() + "/user/authenticate");
                try {
                    HttpResponse response = client.execute(request);
                    resolve(response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        ServiceProvider.submitServiceTask(promise);
        return promise;
    }
}

Now this is my promise interface:

public abstract class ServicePromise<T> implements Runnable {

    private ServicePromiseCallback<T> callback;

    public ServicePromise<T> then(ServicePromiseCallback<T> cb) {
        this.callback = cb;
        return this;
    }

    @Override
    public void run() {
    }

    public void resolve(T data) {
        if (this.callback == null) {
            return;
        }
        this.callback.onResolve(data);
    }

    public void reject(T data) {
        if (this.callback == null) {
            return;
        }
        this.callback.onReject(data);
    }
}

And that's the callback interface:

public interface ServicePromiseCallback<T> {
    void onResolve(T response);
    void onReject(T response);
}

And finally, thats how I use it:

    ServiceProvider.getUserService().authenticateUser(player.playerName, player.playerPass).then(new ServicePromiseCallback<?> () {
        @Override
        public void onResolve(Object response) {

        }

        @Override
        public void onReject(Object response) {

        }
    });

Again, don't mind the types in resolve/reject, it's going to definitely be AuthenticateUserResponseDto and so on, but it doesn't matter right now


texts: Parallel brute-force solution for Project Euler 4 (Largest palindrome product)

texts:
The pe4Concurrent.go file given below is my first attempt at writing a concurrent programme, pe4.go is a non-concurrent implementation of the same algorithm for comparison purposes.

The algorithm itself is a simple, brute force solution to one of the Project Euler problems.

Basically, I'm very new to both Go and concurrency and would appreciated any suggestions as to how the efficiency or elegance of my use of channels and goroutines in pe4Concurrent.go might be improved.

Non-concurrent brute force solution (included for comparison purposes):

pe4.go

//Project Euler: Problem 4

//Largest palindrome product

//A palindromic number reads the same both ways. The largest
//palindrome made from the product of two 2-digit numbers is
//9009 = 91 × 99.

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

package main

import "fmt"
import "time"

func isPalindrome(s string) bool {
    if len(s) <= 1 {
        return true
    }
    if s[0] != s[len(s)-1] {
        return false
    }
    s = s[:len(s)-1]
    s = s[1:]
    return isPalindrome(s)
}

func main() {

    start := time.Now()

    highestPal := 0

    lowerLimit := 100

    upperLimit := 1000

    for i := upperLimit - 1; i >= lowerLimit; i-- {

        for j := i - 1; j > 0; j-- {

            candidate := i * j

            s := fmt.Sprintf("%d", candidate)

            if isPalindrome(s) {

                if candidate > highestPal {

                    highestPal = candidate
                }
            }
        }
    }

    elapsed := time.Since(start)

    //num := 1000 * 999
    //s := fmt.Sprintf("%d", num)
    //output := isPalindrome(s)
    //fmt.Println(output)
    //output = isPalindrome("101")
    //fmt.Println(output)
    //output = isPalindrome("9")
    fmt.Println(highestPal)
    fmt.Println("Programme execution time %s", elapsed)
}

Concurrent brute force solution:

pe4Concurrent.go

//Project Euler: Problem 4

//Largest palindrome product

//A palindromic number reads the same both ways. The largest
//palindrome made from the product of two 2-digit numbers is
//9009 = 91 × 99.

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

// Note:
// Brute force solution launching 900 goroutines outperforms
// the same algorithms without goroutines by a factor of
// five: 14 ms vs. 72 ms.

package main

import "fmt"
import "time"

func isPalindrome(s string) bool {
    if len(s) <= 1 {
        return true
    }
    if s[0] != s[len(s)-1] {
        return false
    }
    s = s[:len(s)-1]
    s = s[1:]
    return isPalindrome(s)
}

func getHighestPal(i int, c chan int) {

    for j := i - 1; j > 0; j-- {

        candidate := i * j

        s := fmt.Sprintf("%d", candidate)

        if isPalindrome(s) {

            c <- candidate
        }
    }
}

func main() {

    start := time.Now()

    highestPal := 0

    lowerLimit := 100

    upperLimit := 1000

    c := make(chan int)

    for i := upperLimit - 1; i >= lowerLimit; i-- {

        go getHighestPal(i, c)
    }

    for i := 0; i < upperLimit-lowerLimit; i++ {

        candidate := <-c

        if candidate > highestPal {

            highestPal = candidate
        }
    }

    elapsed := time.Since(start)
    fmt.Println(highestPal)
    fmt.Println("Programme execution time %s", elapsed)
}


texts:
I have the below C# code for parsing. Do you think this is most optimized or  should I use a generic method in these functions themselves?

public static bool GetDBBool(object value)
{
    var result = false;

    if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
        bool.TryParse(value.ToString(), out result);

    return result;
}

public static int GetDBInt(object value)
{
    var result = -999;

    if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
        int.TryParse(value.ToString(), out result);

    return result;
}

public static double GetDBDouble(object value)
{
    var result = -999.00;

    if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
        double.TryParse(value.ToString(), out result);

    return result;
}

public static DateTime GetDBDate(object value)
{
    var result = DateTime.Now;

    if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
        DateTime.TryParse(value.ToString(), out result);

    return result;
}

public static DateTime? GetDBNullableDate(object value)
{
    DateTime date;
    if (value != null && string.IsNullOrEmpty(value.ToString()) == false)
        return DateTime.TryParse(value.ToString(), out date) ? date : (DateTime?)null;
    else
        return null;
}


texts: Is this a correct way to utilize classes and methods in JAVA?

texts:
I am currently learning JAVA. I barely have any coding experience. I wrote a program which asks a user for a sentence. It then swaps the words of the sentence (first with last, second with second to last, etc.). Program will then output the new sentence.

I know that this is not the most optimal way this task could be solved so please ignore that.
My question is: "Do I use classes and methods correctly? If not, how would I adjust them in this code? In particular, I feel my main method looks weird (the way parameters are added to the methods)."

The code compiles and works as intended. My question is more in regards to style.

I add the code, in 2 classes

main class:

package com.test;

public class ND2_Task1 {

    public static void main(String[] args) {

        ND2_Task1_Core run = new ND2_Task1_Core();

        run.getInput(); // gets userSentence
        run.getWordCount(run.getUserSentence());
        run.checkValidity(run.getWordCount());
        run.toArray(run.getUserSentence()); // transforms String into an array
        run.reverseArray(run.getSeperatedSentence());
        run.showResult(run.getSeperatedSentence());

    }

}

2nd. class:

package com.test;

import java.util.Arrays;
import java.util.Scanner;

public class ND2_Task1_Core {

    private static String userSentence;
    private static int wordCount;
    private static String[] seperatedSentence;
    private static String[] reversedSentence;

    public void getInput() {
        System.out.println(
                "Please enter a sentence.\nFirst word will be swapped with the last one.\nSecond word will be swapped with second to last\netc.");
        setUserSentence(new Scanner(System.in).nextLine());

    }

    public void getWordCount(String userSentence) {
        wordCount = 1;
        for (int i = 0; i < userSentence.length(); i++) {
            if (userSentence.charAt(i) == ' ') {
                wordCount++;
            }
        }

    }

    public void checkValidity(int wordCount) {
        if (wordCount < 2) {
            System.out.println(
                    "You have entered an insufficient number of words. Enter at least 2 words for program to swap them");
            System.out.println("Exiting now");
            System.exit(0);
        }

    }

    public void toArray(String userSentence) {
        setSeperatedSentence(userSentence.split(" "));

    }

    public void reverseArray(String[] seperatedSentence) {
        reversedSentence = new String[seperatedSentence.length];

        reversedSentence = seperatedSentence;

        for (int i = 0; i < reversedSentence.length / 2; i++) {
            String temp = reversedSentence[i];
            reversedSentence[i] = reversedSentence[reversedSentence.length - i - 1];
            reversedSentence[reversedSentence.length - 1 - i] = temp;
        }

    }

    public void showResult(String[] reversedSentence) {
        System.out.println(Arrays.toString(reversedSentence));

    }

    public String getUserSentence() {
        return userSentence;
    }

    public void setUserSentence(String userSentence) {
        ND2_Task1_Core.userSentence = userSentence;
    }

    public String[] getSeperatedSentence() {
        return seperatedSentence;
    }

    public void setSeperatedSentence(String[] seperatedSentence) {
        ND2_Task1_Core.seperatedSentence = seperatedSentence;
    }

    public int getWordCount() {
        return wordCount;
    }

    public void setWordCount(int wordCount) {
        ND2_Task1_Core.wordCount = wordCount;
    }

}
```


texts: Returning substrings (motifs) and original strings (sequences) from a file of strings (sequences)

texts:
I would like to get some help/tips on writing better and more pythonic code, as well as variable naming.

Code info:

.backtranscribe() is just a method to convert the U's in the sequence to T's (ATUG -> ACTG)
a - 1-based index where substring starts
b - size of substring
c - text input of names of sequences to get substrings of (the data/sorted...fa file has hundreds of name/sequence pairs)

def comp(a, b, c):
    mirna_set = set(c.data.splitlines())
    motif_size = b
    results = []
    motif_set = set()
    handle = open("data/sorted.human.mature.fa", "rU")
    for record in SeqIO.parse(handle, "fasta"):
        if record.id in mirna_set: # check if db mirna is one in user input
            index_5p = a-1
            flag_motif_unique = False
            motif = ""
            while(flag_motif_unique == False):
                motif = record.seq.back_transcribe()[index_5p:index_5p+motif_size]
                if motif not in motif_set:
                    flag_motif_unique = True
                    motif_set.add(motif)
                index_5p += 1
            pos = "pos:" + str(index_5p) + "-" + str(index_5p+10)
            results.append(">" + record.id + " " + motif + " " + pos)
            results.append(record.seq.back_transcribe())
        else:
            continue
    handle.close()
    return(results)

Full app here (with input/output)


texts: Finding binary combinations based on substitute wildcards

texts:
I am given a string containing the possible characters of : 0, 1, and ?, iterating over possibilities, replacing the wildcard ? with either 0 or 1.

For example; given "1?00?101", the outcome would be: ["10000101", "10001101", "11000101", "11001101"].

My code seems to work, I tested with two wildcards and three wildcards, but is there a better way to solve this.

class MainClass
    {
        static void BinaryString(char [] word, int a, int b, int count){
            if (count == 0) {
                Console.WriteLine (word);
            } else {
                for (int i = a; i < b; i++) {
                    if (word [i].Equals ('?')) {
                        word [i] = '0';
                        count--;
                        BinaryString (word, i, word.Length - 1, count);
                        word [i] = '1';
                        BinaryString (word, i, word.Length - 1, count);
                        word [i] = '?';
                        count++;
                    }
                }
            }
        }
        public static void Main (string[] args)
        {
            string binary = "1?00?1?1";
            char[] bi = binary.ToCharArray ();
            int count = 0;
            for (int i = 0; i < bi.Length; i++) {
                if (bi [i].Equals ('?')) {
                    count++;
                }
            }
            BinaryString (bi, 0, bi.Length - 1, count);
        }
    }


texts: Create HttpClient using PoolingHttpClientConnectionManager

texts:
I have a java service class which will call a REST service and get response back.
It is working fine in developer environment where less requests are made, but I still wanted to get a review.

My service method call is like:

private String getResponse(Object request, String cUri) {
String responseStr = StringUtils.EMPTY;
    try {

        Gson requestJson = new GsonBuilder().disableHtmlEscaping().create();
        String inputJson =  requestJson.toJson(request);
        logger.debug("Input JSON : " + inputJson);

        responseStr = connect.getResponse(cUri, inputJson,config.getHttpClient());
        logger.debug("Outut JSON for provided request" + responseStr);

    } catch (Exception e) {
        logger.error("Exception while getting response from service : " + e,e);
    }
    return responseStr;
}

Here config.getHttpClient()); is as follows:

public class Test {

    private static CloseableHttpClient httpClient;
    private static PoolingHttpClientConnectionManager connectionManager;

    public CloseableHttpClient getHttpClient() {

        if(httpClient != null){
            return httpClient;
        }

        try {

            SSLContext sslContext = getSSLContext();

            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                    sslContext == null
                    ? SSLContext.getDefault() : sslContext
                            ,new String[] { "TLSv1", "TLSv1.2", "TLSv1.1" }
                            ,null
                            ,NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry= RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", trustSelfSignedSocketFactory)
                    .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

            connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            connectionManager.setMaxTotal(Integer.parseInt(props.getProperty(Constants._CONNECTION_COUNT)));
            connectionManager.setDefaultMaxPerRoute(Integer.valueOf(props.getProperty(Constants._MAX_PER_ROUTE)));

            httpClient = HttpClientBuilder
                    .create()
                    .setConnectionManager(connectionManager)
                    .setConnectionManagerShared(true)
                    .build();

        } catch (Exception e) {
            logger.error("Error in getting rest server connection" + e, e);
        }

        return httpClient;

    }

    private SSLContext getSSLContext(){
        //return sslContext;
    }

}

And this Test class is initialized as Singleton bean.

And public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) is as follows:

public class ConnectionHelper{

    public String getResponse(String uri, String inputJson, CloseableHttpClient httpClient) throws Exception{

        String responseStr = StringUtils.EMPTY;
        HttpPost request = new HttpPost(uri);
        StringEntity params = new StringEntity(inputJson);
        request.addHeader("Content-type", "application/json");
        request.setEntity(params);

        try(final CloseableHttpResponse response= httpClient.execute(request)){
            responseStr = EntityUtils.toString(response.getEntity(),"UTF-8");
        }catch(Exception e){
            logger.error("Error while exeucting on request " + e,e);
        }finally {
            httpClient.close();
        }

        return responseStr;
    }

}


texts: An iterable implementation of LinkedList

texts:
I am curious as to what improvements to my code can be suggested.

package concepts;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<M> implements Iterable<LinkedListNode<M>> {

    public static class LinkedListIterator<O> implements Iterator<LinkedListNode<O>> {
        private LinkedListNode<O> curNode;

        public LinkedListIterator(LinkedList<O> linkedList) {
            curNode = linkedList.head;
        }

        @Override
        public boolean hasNext() {
            if (curNode != null) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public LinkedListNode<O> next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            } else {
                LinkedListNode<O> temp = curNode;
                curNode = curNode.next;
                return temp;
            }

        }

    }

    public LinkedListNode<M> head;

    public boolean add(M newData) {
        LinkedListNode<M> newNode = new LinkedListNode<M>();
        newNode.data = newData;
        if (head == null) {
            head = newNode;
        } else {
            LinkedListIterator<M> it = new LinkedListIterator<M>(this);
            LinkedListNode<M> lastNode = null;
            while (it.hasNext()) {
                lastNode = it.next();
            }
            if (lastNode != null) {
                lastNode.next = newNode;
            } else {
                throw new IllegalStateException();
            }
        }
        return true;
    }

    @Override
    public Iterator<LinkedListNode<M>> iterator() {
        return new LinkedListIterator<M>(this);
    }

}

Here is the LinkedListNode implementation:

package concepts;

public class LinkedListNode<N> {
    public N data;
    public LinkedListNode<N> next;
}


texts:
I'm somewhat curious on peoples opinion about such a method. I Actually didn't find anything similar in librarys I use on regular bases so far.

This is my implementation:

Object.map = function _map( obj, transform ) {
    if( typeof obj === 'object' && typeof transform === 'function' ) {
        Object.keys( obj ).forEach(function _forEach( key ) {
            (function _mapping( oldkey, transmuted ) {
                if( transmuted && transmuted.length ) {
                    obj[ transmuted[ 0 ] || oldkey ] = transmuted[ 1 ];

                    if( transmuted[ 0 ] && oldkey !== transmuted[ 0 ] ) {
                        delete obj[ oldkey ];
                    }
                }
            }( key, transform.apply( obj, [ key, obj[ key ]] ) ));
        });
    }
};

I normally put it on the Object object and not the prototype. However, usage is like this

var foo = {
    someProp: 5,
    bar: 10,
    moar: 20
};

Object.map( foo, function(key, value) {
    return [ key.toUpperCase(), value*2 ];
});

result:

Object { SOMEPROP=10, BAR=20, MOAR=40}

I most often use it to translate CSS properties (to vendor prefixes). But I don't see people use an approach like this often in ECMAscript. Any thoughts?


texts: Pythonic way to flatten lists or arbitrary depth using assignment expressions

texts:
I'm working through the classic "99 problems in prolog" collection. But trying to do them Pythonically. Flatten a list is problem 07.
I am flattening a list of lists of arbitrary depth. I have two solutions below. Which is more Pythonic?
# helper function
def isList( x ): return isinstance( x, list )

def flatten3_h( *xs ):
  if ( len(xs) == 0 ): return [] # base case, empty list/tuple
  hd, tl = xs[ 0 ], xs[ 1: ]
  if ( not(isList( hd ))): return [ hd ] + flatten3_h( *tl )
  return flatten3_h( *hd ) + flatten3_h( *tl )

def flatten4( *xs ):
  acc = []
  [ acc := acc + [x] if not(isList( x )) else acc + flatten4( *x ) for x in xs ]
  return acc

Here is example usage:
flatten4([ [] , [1, [2, [3, [], 4]], 5]] ) # => [1, 2, 3, 4, 5]

I'm guessing flatten4 is more Pythonic as it uses list comprehensions.
But I'm not sure since it uses an assignment expression which I just learned about. As it's a new feature in python3.8.
Any feedback is appreciated.


texts: Cleaning sensitive information returned from a REST API

texts:
I am working with an API of coupons from sites like Groupon. There are 2 fields in the JSON response (url and imgUrl) that return a url which directs them to the actual coupon and a picture of the business, respectively. Problem is that they contain sensitive information (my API KEY).
Below is my service (using spring boot) which "cleans" the API key from the urls before servicing them to the client:
@Service
public class SanitationService {

public List<Deal> cleanApiKeys(List<Deal> deals) {
    List<Deal> cleanList = new ArrayList<>();
    deals.forEach(item -> {
        //Catching "dirty" URLs containing API keys
        List<String> dirtyUrls = Arrays.asList(item.getUrl(), item.getImageUrl()); //maybe map?
        List<String> cleanUrls = cleanUrls(dirtyUrls);
        cleanList.add(cleanDeal(item ,cleanUrls));
    });
    return cleanList;
}
public Deal cleanDeal(Deal deal, List<String> cleanUrls) {
    deal.setUrl(cleanUrls.get(0));
    deal.setImageUrl(cleanUrls.get(1));
    return deal;
}
public List<String> cleanUrls(List<String> urls) {
    return urls.stream()
            .map(url -> url =  url.split("\\?")[0])
            .collect(Collectors.toList());
}
//Helper method for other services to extract a list of Deal from the DealWrapper JSON
public List<Deal> dealUnwrap(List<DealWrapper> dealWrappers) {
    return dealWrappers.stream()
            .map(DealWrapper::getDeal)
            .collect(Collectors.toList());
}

}
Here is the code I use to test the service (still figuring out how to mock a list of Deal)
@SpringBootTest
class SanitationServiceTest {
@Autowired
private SanitationService service;

@Test
void cleanUrls() {
    List<String> dirtyUrls = Arrays.asList("https://api.discountapi.com/v2/deals/1988753/click?api_key=secret",
            "https://api.discountapi.com/v2/deals/1988753/click?api_key=secret");
    assertTrue(service.cleanUrls(dirtyUrls).stream()
                .noneMatch(url -> url.contains("api_key")));
}

}
What is the quality of my code? Is my testing headed in a good direction? Is my code readable and concise?


texts: How to decrease memory usage in codeeval Road Trip challenge

texts:
I'm solving easy CodeEval challenges in Python 2.7. Usually my solutions use around 256 bytes of memory according to CodeEval. With Road Trip however while time used is still low (30-40ms), memory is >5881866 bytes.  As I'm somewhat of a beginner, is there an easy way to decrease memory usage?

For each test case, which consists of one line of input that lists cities and their locations on a line, the task is to find the incremental distances when visiting them all.  Input follows the template ("city_name", distance;"city_name", distance;):

Rkbs,5453; Wdqiz,1245; Rwds,3890; Ujma,5589; Tbzmo,1303;
Vgdfz,70; Mgknxpi,3958; Nsptghk,2626; Wuzp,2559; Jcdwi,3761;
Yvnzjwk,5363; Pkabj,5999; Xznvb,3584; Jfksvx,1240; Inwm,5720;
Ramytdb,2683; Voclqmb,5236;

The data set is pretty big for this challenge:

The route length is an integer in range [10000, 30000]
The number of cities is in range [500, 600]

My solution is as follows:

test_cases = open(file)
for line in test_cases:
    line = line.strip()
    if line == "": continue
    line = line.replace(';', ' ').replace(',', ' ').split()
    distances = sorted(map(int, [line[i] for i in range(1, len(line), 2)]))
    result = [distances[i] - distances[i-1] for i in range(1, len(distances))]
    result.insert(0, distances[0])
    print ','.join(map(str, result))


texts: Find out the 2 numbers which gives the highest product

texts:
Input given is an int array, which may or may not contain positive, negative or zero values. Write a
  program to find out the two numbers which gives the highest product.
  (Both numbers should be positive or negative.)

Below is my code whose time complexity is O(n2), I believe. Is there any improvement I can make to the code?

public class FindLargestProduct{

    public static void main(String[] args) {
        int[] arr = { 52, 12, 34, 10, 6, 40, 0, 12, 40, 52, -56, -78, -99, 68 };
        int firstMax = 0, secondMax = 0;
        int firstNegMax = 0, secondNegMax = 0;

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

            if (arr[i] > 0) {
                if (arr[i] > firstMax) {
                    secondMax = firstMax;
                    firstMax = arr[i];
                } else if (arr[i] > secondMax) {
                    secondMax = arr[i];
                }
            }

            if (arr[i] < 0) {
                secondNegMax = firstNegMax;
                firstNegMax = arr[i];
                if (arr[i] > firstNegMax) {
                    secondNegMax = firstNegMax;
                    firstMax = arr[i];
                } else if (arr[i] > secondNegMax) {
                    secondNegMax = arr[i];
                }

            }
        }

        int proPositive = firstMax * secondMax;
        int proNegative = firstNegMax * secondNegMax;

        if (proPositive > proNegative) {
            System.out.println(proPositive);
        } else {
            System.out.println(proNegative);
        }
    }
}


texts:
I was trying this problem and I was wondering if there is a way to check for the edge cases inside the for-loop.

The problem statement:

  We'll say that a lowercase 'g' in a string is "happy" if there is another 'g' immediately to its left or right. Return true if all the g's in the given string are happy.

Here I am starting the loop from index 1 as I need to look back and I don't want an ArrayIndexOutOfBounds exception. The same applies for the end edge case where I need to look the following index.

To avoid this problem I'm checking these cases right after I've checked all the others, but it doesn't feel quite right. Is there a way to do it in a more compact way?

public boolean gHappy(String str) {

   if(str.length() == 1 && str.charAt(0) == 'g') return false;
   if(str.length() == 0) return true;

   for(int i = 1; i < str.length() - 1; i ++) {
     if(str.charAt(i) == 'g') {
       if(str.charAt(i - 1) != 'g' && str.charAt(i + 1) != 'g') return false;
     }
   }
 // edge cases (start-end)
 if(str.charAt(0) == 'g' && str.charAt(1) != 'g') return false;
 if(str.charAt(str.length() - 1) == 'g' && str.charAt(str.length() - 2) != 'g') return false;

 return true;
}


texts:
I'm new to Go and have a use-case for periodically executing an async work-function.  I want the interval between work-function executions to be constant (not the time between one finishing and the next starting).  I also want this work-function to be executed some number of times.  This translates to "run work N times, once per M ms".
This is what I have.  I've tried to write schedule to be generic for any work-function.  I've also written it so that the first time work is executed is at time 0 (as opposed to waiting for the first tick).
package main

import (
    "fmt"
    "sync"
    "time"
)

func work() {
    fmt.Printf("work %s\n", time.Now())
}

func schedule(duration time.Duration, max int, work func()) {
    ticker := time.NewTicker(duration)
    defer ticker.Stop()
    var wg sync.WaitGroup
    var i = 0
    for {
        wg.Add(1)
        go func() {
            defer wg.Done()
            work()
        }()
        i++
        if i >= max {
            wg.Wait()
            return
        }
        <-ticker.C
    }
}

func main() {
    fmt.Printf("main begin %s\n", time.Now())
    schedule(1*time.Second, 3, work)
    fmt.Printf("main end %s\n", time.Now())
}

Any advice for simplifying and making this code more idiomatic is welcome :)


texts: Read bits, write bits data to arbitrary position in char array

texts:
I created functions to read bit data from arbitrary bit position of a char array to long long int, and I also created a function to write data to a char array from vector bool.

However, I do not really like my implementation since I think it has a burdensome implementation when reading and writing bits. Can anyone see my implementation and enlighten me on a better implementation?

Here is my implementation to write bit data from vector<bool> bitdataForModification.

unsigned char*& str is the original char array.
int startBitLocation is an arbitrary bit position to read from.
int sizeToModify is the size in bits for modification.

void setBitDataToBitPosition(unsigned char*& str, int startBitLocation, int sizeToModify, std::vector<bool>& bitdataForModification){
    int endBitLocation = startBitLocation + sizeToModify-1;
    int sizeChar = (endBitLocation - startBitLocation)/8;

    //Save leftover data
    int startCharPosition = startBitLocation/8;
    int startLeftOverBits = startBitLocation%8;

    //endPosition
    int endCharPosition = endBitLocation/8;
    int endLeftOverBits = 7-(endBitLocation%8);

    unsigned char tempChar = str[startCharPosition];
    unsigned char tempLastChar = str[endCharPosition]; // store last char

    int posBitdata = 0;
    for(int i = 0 ; i < startLeftOverBits; i++){
        str[startCharPosition] <<= 1;
        str[startCharPosition] = (str[startCharPosition] | ((tempChar >> (7-i)) & 0x1));
    }

    for(int i = startCharPosition*8 + startLeftOverBits ; i <= endBitLocation ; i++){
        str[i/8] <<= 1;
        if(posBitdata <= endBitLocation){
            str[i/8] = (str[i/8] | ((bitdataForModification[posBitdata]) & 0x1));
            posBitdata++;
        }
    }

    for(int i = 0 ; i < endLeftOverBits ; i++){
        str[endCharPosition] <<= 1;
        str[endCharPosition] = (str[endCharPosition] | ((tempChar >> i) & 0x1));
    }

}

I do not like this function because it copies from the original char[] to a temp char[] and copies back the bits I need.

Following is my read function I implemented. It reads from a char array and copies the data to long long int data.

void getBitDataFromBitPosition(unsigned char* str, int startBitLocation, int sizeToRead, unsigned long long* data){
    int endBitLocation = startBitLocation + sizeToRead;
    int sizeChar = (endBitLocation - startBitLocation)/8;

    int startCharPosition = startBitLocation/8;
    int endCharPosition = endBitLocation/8 +1;

    vector<bool> bitData;

    int bitCnt = 0;
    for(int i = startCharPosition; i < endCharPosition; i++){
        unsigned char tempChar = str[i];

        for(int j = 7 ; j >= 0 ; j--){
            int curLoc = ((i*8)+(bitCnt%8));
            if(curLoc >= startBitLocation){
                if(curLoc < endBitLocation){

                    bool temp = ((str[i] >> j) & 0x1);
                    bitData.push_back(temp);
                }
            }
            bitCnt++;
        }
    }

    for(int i = bitData.size() -1 ; i >= 0 ; i--){
        *data <<= 1;
        *data = (*data | bitData[bitData.size()-i-1]);
    }
}

I think it is a burden to copy to a bool vector and copy back to long long int. Can anyone provide a better solution for me?


texts:
In a web application I'm working on I have a class that Map objects to other (different) objects. It is implemented with something like:

public interface IMapper
{
    object Map<T>(T item);
}

public class Mapper
{
    private static ConcurrentDictionary<Type, Delegate> cache = new ConcurrentDictionary<Type, Delegate>();

    public Mapper()
    {
        // dependencies are injected in the constructor
        // not shown here for simplicity
    }

    public object Map<T>(T item)
    {
        if (cache.ContainsKey(typeof(T)))
            return (cache[typeof(T)] as Func<T, object>)(item);

        var method = typeof(Mapper).GetMethod("Map", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(T) }, null);

        var @delegate = (Func<T, object>)Delegate.CreateDelegate(typeof(Func<T, object>), this, method);
        cache.TryAdd(typeof(T), @delegate);

        return @delegate(item);

        // I'm trying not to use this
        //return method.Invoke(this, new object[] { item });
    }

    public object Map(Guid item) { return new object(); }
}

In order to assess what I believe should be a performance gain (compared to the .Invoke() solution) I tried to generate ten million objects (tested with strings) and then I ran the mapper for all of them and printed out the time elapsed. The results are.

Direct call: 1.67 s
Reflection: 14.09 s
Optimized Reflection: 2.62 s

which is not bad actually but I wonder if I'm testing this correctly.

Test code

 var guidList = new List<Guid>();
        for(int i = 0; i < 10000000; i++)
        {
            guidList.Add(Guid.NewGuid());
        }

        var mapper = new Mapper();

        var sw = new Stopwatch();
        sw.Start();
        var result = guidList.Select(_ => mapper.Map<Guid>(_)).ToList();
        sw.Stop();

(Obviously, when I tested the direct method call I changed the select lambda expression to _ => mapper.Map(_))

Am I doing it right?

On a side note: I declared the ConcurrentDictionary as ConcurrentDictionary<Type, Delegate> and so I have to "cast" the delegate part like this (cache[typeof(T)] as Func<T, object>)(item) when I'm using it. Is there a better way to do this?


texts:
I am attempting to complete the coin flip streaks problem from automate the boring stuff with python.
My code works fine but my only concern is the phrasing of the task.
Does the question want us to find the number of samples (100 flips) that contain at least one streak and divide that by the total number of samples (10,000)
Or are we supposed to find the total number of streaks (6H or 6T) in all samples and divide that by 10,000?
My solution was for the first option but I make no distinction between one streak and several.
My code and the question are listed below.
Coin Flip Streaks

For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.
Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.

import random
import re

totalRuns = 0
streakScore = 0

def coinFips():
    global streakScore,totalRuns
    # Return results into a single string for regular expressions
    results = ''
    for i in range(100):
      value = random.randint(0, 1)
      if value == 0:
        results += "H"
      elif value == 1:
        results += "T"
    # Use regular expressions to check results sting
    match = re.findall(r'(HHHHHH|TTTTTT)', results)
    if len(match) > 0:
      streakScore = streakScore +  1
    totalRuns = totalRuns + 1

for i in range(10000):
  coinFips()

print("The Chance of a streak is: {}%".format(round(streakScore/totalRuns * 100)))


texts: Randomly split a vector into N bins of random lengths

texts:
As the title says, I want a function that takes a vector, as well as the number of bins, and splits the vector in that number of bins, with a minimum length of 1 for each bin.

def split_into_bins(nbin, vector):
    """
    Randomly split vector into nbin number of bins, each of random size
    """
    permutation = list(np.random.permutation(vector))

    # Location of the splits
    splits = sorted(np.random.choice(range(1,len(vector)), nbin-1, replace=False))

    # Initializing empty bins
    bins = [[]]*nbin

    start = 0
    end = splits[0]

    for i in range(nbin):
        bins[i] = permutation[start:end]
        start = end
        try:
            end = splits[i+1]
        except IndexError:
            end = len(vector)

    return bins

I'm wondering if there's a cleaner way to split the vector into bins besides randomly selecting split locations. My method of splitting up the list given the location of the splits also seems pretty messy. Performance does matter, so I'm wondering if I should initialize the empty bins outside of the function.

I also don't want there to be any bias with regards to the size of the bins; they should all have the same size on average. I'm pretty sure this method isn't biased, however.


texts: Speeding up Python program that converts DOCX to PDF in Windows

texts:
This is meant to be a performance-centric question as this type of conversion is obviously very common. I'm wondering about the possibilities for making this process faster.
I have a program that creates several thousand QR codes from a list, embeds them in an MS Word docx template, and then converts the docx files to pdf. Problem is, what I've designed is very slow. When creating several thousand pdf files, it takes hours on a local machine.
What can I do to speed this program up? Is there a way to multithread it? (Total newb to that topic). Or, what about my program design is inherently flawed?
Repeatable program below, meant to be run in local Windows 10 directory:
import pyqrcode
import pandas as pd
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
import glob
import os
from docx2pdf import convert

def make_folder():
    os.mkdir("codes")
    os.mkdir("docs")

def create_qr_code():
    for index, values in df.iterrows():
        data = barcode = values["barcode"]
        image = pyqrcode.create(data)
        image.png("codes\\"+f"{barcode}.png", scale=3)

def embed_qr_code():
    qr_images = glob.glob("codes\\"+"*.png")
    for image in qr_images:
        image_name = os.path.basename(image)
        doc = Document()
        doc.add_picture(image)
        last_paragraph = doc.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        doc.save("docs\\"+f"{image_name}.docx")
        convert("docs\\"+f"{image_name}.docx")

def clean_file_names():
    paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk("docs\\")
        for filename in filenames)
    for path in paths:
        newname = path.replace(".png", "")
        if newname != path:
            os.rename(path, newname)

data = {'barcode': ['teconec', 'tegovec', 'teconvec', 'wettrot', 'wetocen']}
df = pd.DataFrame(data)

make_folder()
create_qr_code()
embed_qr_code()
clean_file_names()

Thank you!


texts: Comparator based on Double values in Java

texts:
I have class point that represents point in 2D and I want to sort these points once based on their x-coordinate and second based on their y coordinate. Since x and y are double values my code looks like this:

public static class Point{
    int id;
    public double x;
    public double y;
    Point(int id, double x, double y){
        this.id = id;
        this.x = x;
        this.y = y;
    }
    public static Comparator<Point> xComparator = new Comparator<Point>(){
        @Override
        public int compare(Point t1, Point t2) {
            // TODO Auto-generated method stub
            if (t1.x > t2.x){
                return 1;
            }
            if (t1.x < t2.x){
                return -1;
            }
            else{
                return 0;
            }
        }
    };
    public static Comparator<Point> yComparator = new Comparator<Point>(){
            public int compare(Point t1, Point t2) {
                // TODO Auto-generated method stub
                if (t1.x > t2.x){
                    return 1;
                }
                if (t1.x < t2.x){
                    return -1;
                }
                else{
                    return 0;
                }
            }
        };
}

Is this a good way for defining Comparator? Is there better solution for sorting based on x and on y coordinate? Is this the only way to deal with compare method based on two double values?


texts:
Could I code differently to slim down the point of this Python source code? The point of the program is to get the user's total amount and add it to the shipping cost. The shipping cost is determined by both country (Canada or USA) and price of product: The shipping of a product that is $125.00 in Canada is $12.00.

input ('Please press "Enter" to begin')

while True: print('This will calculate shipping cost and your grand total.')

totalAmount = int(float(input('Enter your total amount: ').replace(',', '').replace('$', '')))
Country = str(input('Type "Canada" for Canada and "USA" for USA: '))

usa = "USA"
canada = "Canada"
lessFifty = totalAmount <= 50
fiftyHundred = totalAmount >= 50.01 and totalAmount <= 100
hundredFifty = totalAmount >= 100.01 and totalAmount <= 150
twoHundred = totalAmount

if Country == "USA":
    if lessFifty:
        print('Your shipping is: $6.00')
        print('Your grand total is: $',totalAmount + 6)
    elif fiftyHundred:
        print('Your shipping is: $8.00')
        print('Your grand total is: $',totalAmount + 8)
    elif hundredFifty:
        print('Your shipping is: $10.00')
        print('Your grand total is: $',totalAmount + 10)
    elif twoHundred:
        print('Your shipping is free!')
        print('Your grand total is: $',totalAmount)

if Country == "Canada":
    if lessFifty:
        print('Your shipping is: $8.00')
        print('Your grand total is: $',totalAmount + 8)
    elif fiftyHundred:
        print('Your shipping is: $10.00')
        print('Your grand total is: $',totalAmount + 10)
    elif hundredFifty:
        print('Your shipping is: $12.00')
        print('Your grand total is: $',totalAmount + 12)
    elif twoHundred:
        print('Your shipping is free!')
        print('Your grand total is: $',totalAmount)

endProgram = input ('Do you want to restart the program?')
if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):
    break


texts:
I made a few recursive functions for learning purposes which do a variety of tasks. Here is my current and functioning code:

def separate(p,l):
    ''' recursive function when is passed a predicate and a list returns a 2-tuple
    whose 0 index is a list of all the values in the argument list for which the
    predicate returns True,and whose 1 index is a list of all the values in the
    argument list for which the predicate returns False.'''
    if len(l) == 0:
        return ([],[])
    else:
        (true_list, false_list) = separate(p,l[1:])
        if p(l[0]):
            return ([l[0]] + true_list, false_list)
        else:
            return (true_list, [l[0]] + false_list)

def is_sorted(s):
    ''' recursive function when passed a list returns a bool telling whether or not
    the values in the list are in non-descending order: lowest to highest allowing
    repetitions. '''
    if len(s) <= 1:
        return True
    elif s[0] < s[1]:
        return is_sorted(s[1:])
    else:
        return False

def sort(l):
    ''' recursive function when passed a list; it returns a new list (not mutating
    the passed one) with every value in the original list, but ordered in non-
    descending order. '''
    if len(l) == 0:
        return []
    else:
        (before, after) = separate(lambda i: i < l[0], l[1:])
        return sort(before) + [l[0]] + sort(after)

def compare(a,b):
    ''' a recursive function when is passed two str arguments; it returns one of
    three str values: '<’, '=’, or '>’ which indicates the relationship between the
    first and second parameter.'''
    if a == '' and b == '':
        return '='
    if a == '' and b != '':
        return '<'
    if a != '' and b == '':
        return '>'
    if a[0] > b[0]:
        return '>'
    if a[0] < b[0]:
        return '<'
    else:
        return compare(a[1:],b[1:])

Is there a way to write these recursive functions in a cleaner/concise way? Any help would be great.


texts:
In my attempts to grasp Existential Types in Haskell I decided to implement an integer-based fixed-length vector data type. I'm using ghc 7.8.3.

Specifically I wanted to write a program which asks the user for a possible new value to append to a fixed-length vector and then displays the resulting vector.

First I wrote a first version of the program like this:

{-# LANGUAGE GADTs                     #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE Rank2Types                #-}

import System.IO (hFlush, stdout)

data Z
data S n

data Vect n where
    ZV :: Vect Z
    CV :: Int -> Vect n -> Vect (S n)

data AnyVect = forall n. AnyVect (Vect n)

instance Show (Vect n) where
    show ZV = "Nil"
    show (CV x v) = show x ++ " : " ++ show v

vecAppend :: Int -> Vect n -> Vect (S n)
vecAppend x ZV = CV x ZV
vecAppend x v = CV x v

appendElem :: AnyVect -> IO AnyVect
appendElem (AnyVect v) = do
    putStr "> "
    hFlush stdout
    x <- readLn

    return $ if x == 0 then AnyVect v else AnyVect $ vecAppend x v

main = do
    AnyVect v <- appendElem $ AnyVect ZV
    putStrLn $ show v

Which works as expected. Then I decided to get rid of the unecessary AnyVect:

{-# LANGUAGE GADTs                     #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE Rank2Types                #-}

import System.IO (hFlush, stdout)

data Z
data S n

data Vect n where
    ZV :: Vect Z
    CV :: Int -> Vect n -> Vect (S n)

instance Show (Vect n) where
    show ZV = "Nil"
    show (CV x v) = show x ++ " : " ++ show v

vecAppend :: Int -> Vect n -> Vect (S n)
vecAppend x ZV = CV x ZV
vecAppend x v = CV x v

appendElem :: Vect n -> (forall n. Vect n -> a) -> IO a
appendElem v f = do
    putStr "> "
    hFlush stdout
    x <- readLn

    return $ if x == 0 then f v else f $ vecAppend x v

main = do
    appendElem ZV show >>= putStrLn

Which works as well, even if I don't really like the way main is written.

Is there any other simpler/cleaner way to write it?


texts:
I have this function that searches for stock moves that have the same product, and if it finds them then it searches for lots in those lines, and if it finds the same lots then UserError is raised.
The thing is I think this method can be rewritten in a more elegant way. Maybe someone can help me with that.
def check_for_duplicates(self):
    exist_product_list = {}
    duplicates = {}
    for line in picking.move_lines:
        if line.product_id.id in exist_product_list:
            duplicates[line.id] = line.product_id.id
            for product, line_id in exist_product_list.items():
                if product == line.product_id.id and line.id != line_id:
                    duplicates[line.id] = line.product_id.id
                    duplicates[line_id] = product
        exist_product_list[line.product_id.id] = line.id
    duplicate_lots = []
    if duplicates:
        for line in self.env['stock.move'].browse(duplicates.keys()):
            lots = line.mapped('lot_ids')
            for lot in lots:
                if lot in duplicate_lots:
                    raise UserError(
                        _('You have few lines with same product %s and same lot in it') % line.product_id.name)
                duplicate_lots.append(lot)


texts: Declaring a large number of 2D arrays to be used as 2D graphic sprites

texts:
I'm creating a Space Invaders game, and graphics sprites in it are defined as 2D arrays of colors.

It seems like it's going to be cumbersome declaring these arrays the way I currently am:

//This creates an inverting red/blue cross animation
public Sprite myFirstAnimation()
{
    Sprite frame1 = new Sprite(new Color[,]
                    {{Color.Red, Color.Blue, Color.Red},
                        {Color.Blue, Color.Blue, Color.Blue},
                        {Color.Red, Color.Blue, Color.Red}});

    Sprite frame2 = new Sprite(new Color[,]
                    {{Color.Blue, Color.Red, Color.Blue},
                        {Color.Red, Color.Red, Color.Red},
                        {Color.Blue, Color.Red, Color.Blue}});

    AnimatedSprite myAnimatedSprite = new AnimatedSprite(new Sprite[] { frame1, frame2 });
    return myAnimatedSprite;
}

Can you point me the the direction for a nicer way of doing this, as to make it more maintainable and readable, and less arduous?


texts:
This code is for a simple language quiz.  It fetches two words and related audio files via a JSON call, presents the user with an image that matches one of the words, and challenges the user to make the match.  My code works but it's a little repetitious and ugly.  I'd like to see how the experts would propose rewriting this.

function getNewWords() {
        {
            var Category = "animals";
            var BaseURL = "http://localhost:61741/VocabGame/play?cat=";
            var URL = BaseURL + Category;

            $.getJSON(URL, {
                tagmode: "any",
                format: "json"
            }, function (data) {
                var choiceA = data.nouns[0].Pinyin;
                var choiceB = data.nouns[1].Pinyin;
                $('#ChoiceA').html(choiceA);
                $('#ChoiceB').html(choiceB);

                var root = "../../Content/Audio/";
                var mp31 = root + data.nouns[0].Audio1 + ".mp3";
                var ogg1 = root + data.nouns[0].Audio1 + ".ogg";
                var mp32 = root + data.nouns[1].Audio1 + ".mp3";
                var ogg2 = root + data.nouns[1].Audio1 + ".ogg";

                attachMouseEnter(mp31, ogg1, mp32, ogg2);

                var random = Math.random();
                if (random >= 0.5) {
                    correctAnswer = "ChoiceA";
                    Search(data.nouns[0].English);
                }
                else {
                    correctAnswer = "ChoiceB"
                    Search(data.nouns[1].English);
                }

            });
        }

    };

    function playAudio1(mp31, ogg1) {
        var mp3_src = mp31;
        var oga_src = ogg1;

        $('#jquery_jplayer_1').jPlayer('setMedia', {
            oga: oga_src,
            mp3: mp3_src
        });

        $('#jquery_jplayer_1').jPlayer("play");
    };

    function playAudio2(mp32, ogg2) {
        var mp3_src = mp32;
        var oga_src = ogg2;

        $('#jquery_jplayer_1').jPlayer('setMedia', {
            oga: oga_src,
            mp3: mp3_src
        });

        $('#jquery_jplayer_1').jPlayer("play");
    };
        function attachMouseEnter(mp31, ogg1, mp32, ogg2) {
            $('#ChoiceA').die('mouseenter.audio1event');
            $('#ChoiceA').live('mouseenter.audio1event', function () {
                playAudio1(mp31, ogg1);
            });

            $('#ChoiceB').die('mouseenter.audio2event');
            $('#ChoiceB').live('mouseenter.audio2event', function () {
                playAudio2(mp32, ogg2);
            });
    }


texts: Validating multiple parameters by regex and length

texts:
I have a set of validation functions which return a response code along with an error message if the validation fails. Requests can be of three types, and each of them contains a different type of values to be validated. My question is what are the options to avoid the repetitive code, particularly in the message assignment?

const Validation = (function() {

  const isParameterOneLengthValid = (data) => {
    return data.length >= 5 && data.length <= 10;
  };

  const isParameterOneValid = (data) => {
    return !(/[^A-Za-z\-0-9\,\.]/.test(data));
  };

  const isParameterTwoLengthValid = (data) => {
    return data.length >= 1 && data.length <= 5;
  };

  const isParameterTwoValid = (data) => {
    return !(/[^0-9]/.test(data));
  };

  function Validation() {}

  Validation.prototype.validateFirstTypeRequest= (data) => {
      if (!isParameterOneLengthValid(data.parameterOne)) {
        data.code = 0;
        data.message = 'Length of the parameter one is invalid';
        return data;
      } else if (!isParameterOneValid(data.parameterOne)) {
        data.resStatus = 1;
        data.resMessage = 'Parameter one is invalid';
        return data;
      }

      if (!isParameterTwoLengthValid(data.parameterTwo)) {
        data.code = 3;
        data.message = 'Length of the parameter two is invalid';
        return data;
      } else if (!isParameterTwoValid(data.parameterTwo)) {
        data.resStatus = 4;
        data.resMessage = 'Parameter two is invalid';
        return data;
      }

      return data;
  };

  Validation.prototype.validateSecondTypeRequest= (data) => {
      if (!isParameterOneLengthValid(data.parameterOne)) {
        data.code = 0;
        data.message = 'Length of the parameter one is invalid';
        return data;
      } else if (!isParameterOneValid(data.parameterOne)) {
        data.resStatus = 1;
        data.resMessage = 'Parameter one is invalid';
        return data;
      }

      return data;
  };

  Validation.prototype.validateThirdTypeRequest= (data) => {
      if (!isParameterTwoLengthValid(data.parameterTwo)) {
        data.code = 3;
        data.message = 'Length of the parameter two is invalid';
        return data;
      } else if (!isParameterTwoValid(data.parameterTwo)) {
        data.resStatus = 4;
        data.resMessage = 'Parameter two is invalid';
        return data;
      }

      return data;
  };

  module.exports = new Validation();

  return Validation;
})();


texts: Simulating gravitational attraction between bodies - follow up

texts:
I've decided to revisit a chunk of code I wrote a while back, and see what I could do to make some changes. As a result, I know have slow, but working piece of code which is able to simulate gravitational attractions between \$n\$ amount of bodies. Like usual, I'm using the formula described in Newton's Law of Gravitation, as seen below:

$$F=G\frac{m_1m_2}{r^2}$$

using UnityEngine;

/// <summary>
/// Gravity component.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class GravityComponent : MonoBehaviour
{
    public float gravityConstant = 1;
    public Vector3 startingForce;

    /// <summary>
    /// Applies attraction to the object.
    /// </summary>
    public void ApplyAttraction()
    {
        foreach(GameObject body in GameObject.FindGameObjectsWithTag("body"))
        {
            Vector3 force = body.transform.position - this.transform.position;
            float attraction =
                  (this.gravityConstant * this.rigidbody.mass * body.rigidbody.mass)
                / (Mathf.Pow(force.magnitude, 2));
            this.rigidbody.AddForce(force * attraction);
        }
    }

    public void Start()
    { this.rigidbody.AddForce(this.startingForce); }

    public void FixedUpdate()
    { this.ApplyAttraction(); }
}

Ideally, I'd like to know the following things:

Can the performance be better? Right now it runs at an okay speed with about 10 bodies on my laptop, but once it starts getting past that, it begins to slow down rather drastically.
Am I doing anything wrong Unity3d-wise?
Is my code written in an idiomatic manner?
Anything else?

For anyone who might be interested, you can find the repository on GitHub here.


texts:
The goal of this module is to take in a string (user input, someone copy and pasting a large list of proxies) and parse it into an array of objects.
I appreciate any and all feedback, but I'm specifically interested in improving the stringToProxy function.
Namely I'm unsure about mutating the string parameter, seems like there could be a better solution. And the way I'm declaring the proxy at the beginning of the function feels wrong to me (using As) but I couldn't think of any better solution. I also feel as though I may be overusing string.split().
Thanks for your time!
Edit:
Incorporated the url module as Nazar recommended. I'm happy with this solution but still taking feedback.
const { URL } = require("url");

interface Proxy {
    host: string;
    port: number;
    protocol: string;
    auth?: {
        username: string;
        password: string;
    };
}

function parse(string: string): Proxy[] {
    const rawArray = stringToArray(string);
    const fixedArray = rawArray.map((string) => fixProxyString(string));
    const proxyArray = fixedArray.map((string) => stringToProxy(string));
    return proxyArray;
}

function stringToArray(string: string): string[] {
    return string.trim().replace(/[ ,\n]+/g, ",").split(",");
}

function fixProxyString(string: string): string {
    return string.includes("://") ? string : `http://${string}`; //if user doesnt specify a protocol, default to http
}

function stringToProxy(string: string): Proxy {
    const url = new URL(string);
    return {
        host: url.hostname,
        port: url.port ? parseInt(url.port) : 80, //if proxy is 80 url will ignore it so i need to explicitly add it
        protocol: url.protocol.slice(0, -1), //removing the colon
        auth: url.username ? { username: url.username, password: url.password } : undefined
    };
}

export = parse;

Before edit:
interface Proxy {
    host: string;
    port: number;
    auth?: {
        username: string;
        password: string;
    };
    protocol?: string;
}

function parse(string: string): Proxy[] {
    const rawArray = stringToArray(string);
    const proxyArray = rawArray.map((string) => stringToProxy(string));
    return proxyArray;
}

function stringToArray(string: string): string[] {
    return string.trim().replace(/[ ,\n]+/g, ",").split(",");
}

function stringToProxy(string: string) {
    const proxy = {} as Proxy;

    if (string.includes("://")) {
        const [protocol, remainder] = string.split("://");
        proxy.protocol = protocol;
        string = remainder;
    }
    if (string.includes("@")) {
        const [auth, remainder] = string.split("@");
        const [username, password] = auth.split(":");
        proxy.auth = { username, password };
        string = remainder;
    }
    const [host, port] = string.split(":");
    proxy.port = parseInt(port);
    proxy.host = host;

    return proxy;
}

export = parse;

Usage:
const parse = require("parse-proxy");

parse(`1.1.1.1:80, 2.2.2.2:80, 3.3.3.3:80`)

//result
[
  { host: '1.1.1.1', port: 80 },
  { host: '2.2.2.2', port: 80 },
  { host: '3.3.3.3', port: 80 }
]

parse(`https://user:pass@104.236.55.48:8080\nhttps://user:pass@213.105.29.14:3128`)

//result
[
  {
    protocol: 'https',
    auth: { username: 'user', password: 'pass' },
    host: '104.236.55.48',
    port: 8080
  },
  {
    protocol: 'https',
    auth: { username: 'user', password: 'pass' },
    host: '213.105.29.14',
    port: 3128
  }
]


texts: Snaplogic Script to group key-value pairs based on a certain ID field

texts:
Following is the script I'm using to group key-value pairs based on an ID field viz. interface_id:

// Ensure compatibility with both JDK 7 and 8 JSR-223 Script Engines
try { load("nashorn:mozilla_compat.js"); } catch(e) { }

// Import the interface required by the Script snap.
importPackage(com.snaplogic.scripting.language);

// Import the Java utility classes.
importPackage(java.util);

/**
 * Create an object that implements the methods defined by the "ScriptHook"
 * interface.  We'll be passing this object to the constructor for the
 * ScriptHook interface.
 */
var impl = {
    /*
     * These variables (input, output, error, log) are defined by the
     * ExecuteScript snap when evaluating this script.
     */
    input : input,
    output : output,
    error : error,
    log : log,

    /**
     * The "execute()" method is called once when the pipeline is started
     * and allowed to process its inputs or just send data to its outputs.
     *
     * Exceptions are automatically caught and sent to the error view.
     */
    execute : function () {
        var interfaceIds = new java.util.ArrayList();
        var interfaceParams = new java.util.ArrayList();
        while (this.input.hasNext()) {
            var doc = this.input.next();

            var interfaceId = doc.interface_id;
            var paramName = doc.param_name;
            var paramValue = doc.param_value;

            var index = -1;

            if(!interfaceIds.contains(interfaceId)) {
                interfaceIds.add(interfaceId);
                var interfaceMap = new java.util.LinkedHashMap();
                interfaceMap.put("interface_id", interfaceId);
                interfaceParams.add(interfaceMap);
            }

            index = interfaceIds.indexOf(interfaceId);
            if(index >= 0) {
                interfaceParams.get(index).put(paramName,paramValue);
            }
        }

        for(var i=0; i<interfaceParams.size(); i++) {
            this.output.write(interfaceParams.get(i));
        }
    }
};

/**
 * The Script Snap will look for a ScriptHook object in the "hook"
 * variable.  The snap will then call the hook's "execute" method.
 */
var hook = new com.snaplogic.scripting.language.ScriptHook(impl);

The Pipeline

Input

Output

In the above script, since I'm more comfortable with Java, I used ArrayList and LinkedHashMap. Is it the correct way to do this? If yes, please do review the overall correctness and efficiency of the code. If not, is there a way to do this only using the scripting language and not using Java's collections framework. My understanding is that, for large datasets, it is better to avoid collections framework (ideally, avoiding the script altogether is a better option). Any other approach is also welcome.

PS: I did not find a tag for snaplogic so I'm tagging it under JavaScript and Java. This is because, I've set the scripting language to JavaScript and I'm using Java's collections framework in it.


texts: Producer/Consumer implementation using condition_variable

texts:
Trying to implement producer/consumer problem in C++. I have one question: should I use nofify_all or notify_one method here? Also any feedback is welcome

template <class T>
class Stack
{
public:
    Stack(size_t size) : size_(size)
    {
        arr_ = new T[size_];
        init();
    }

    ~Stack()
    {
        delete[] arr_;
    }

    void init()
    {
        top_ = -1;
    }

    int capacity()
    {
        return static_cast<int>(size_) - top_ - 1;
    }

    void set(T num)
    {
        std::unique_lock<std::mutex> locker(mu);

        cond.wait(locker, [this](){ return top_ < static_cast<int>(size_) - 1; });
        top_++;
        arr_[top_] = num;
        std::cout << "Setting num: " << num << " Capacity: " << this->capacity() << std::endl;
        locker.unlock();
        cond.notify_one();
    }

    Т get()
    {
        std::unique_lock<std::mutex> locker(mu);
        T top_value;

        cond.wait(locker, [this](){ return top_ != -1; });
        top_value = arr_[top_];
        top_--;
        std::cout << "Getting num: " << top_value << " Capacity: " << this->capacity() << std::endl;
        locker.unlock();
        cond.notify_one();

        return top_value;
    }

private:
    size_t size_;
    T* arr_;
    int top_;
    std::mutex mu;
    std::condition_variable cond;
};

main:

int main()
{
    Stack<int> stack(10);
    std::vector<std::thread> producers;
    std::vector<std::thread> consumers;

    for (int i = 0; i <= 20; i++)
    {
        consumers.push_back(std::thread([&](){
            stack.get();
        }));
    }

    for (int i = 1; i <= 20; i++)
    {
        producers.push_back(std::thread([&](){
            stack.set(i);
        }));
    }

    for (auto& th : producers)
    {
        th.join();
    }

    for (auto& th : consumers)
    {
        th.join();
    }

    return 0;
}


texts:
I have been learning webdevelopment at Freecodcamp and have therefore been writing a lot of javascript by myself. They have a code-review chatroom, but the people in that chatroom seem to review the final product and not the code itself.

So, I am searching for some constructive criticism about the structure and style of my code.

The code shown below is a class from a Game of Life game as part of the Freecodecamp course and does work. It is written in Javascript and uses React. There is more code for this project, but I don't think it is necessary to show all of the code, for you to critique my code structure and style. If it the rest of the code is required I can of course post it as well.

class GameOfLife extends Component {
  constructor(props) {
    super(props)
    this.toggleGameState = this.toggleGameState.bind(this);
    this.stepGame = this.stepGame.bind(this);
    this.squareClicked = this.squareClicked.bind(this);
    this.clearGrid = this.clearGrid.bind(this);
    this.generateRandomGrid = this.generateRandomGrid.bind(this);
    this.toggleSpeed = this.toggleSpeed.bind(this);
    this.state = {
      cellRows: generateRandomCellDistribution({height: 50, width: 50}),
      size: {height:50, width:50},
      gameState: 'playing', speed: 1,
      generation: 0
    };
  }

  componentDidMount() {
    this.setState({gamteState: 'playing', interval: setInterval(this.stepGame, 200/this.state.speed)});
  }

  toggleGameState() {
    var newState = this.state.gameState === 'playing' ? 'paused' : 'playing';
    if(newState === 'playing') {
      this.setState({gameState: newState, interval: setInterval(this.stepGame, 200/this.state.speed)});
    } else {
      this.setState({'gameState': newState});
      clearInterval(this.state.interval);
    }
  }

  squareClicked(row, column) {
    var cellRows = this.state.cellRows.slice();
    var newState = cellRows[row][column].state === 'alive' ? 'dead' : 'alive';
    cellRows[row][column] = {state: newState};
    this.setState({cellRows: cellRows});
  }

  generateRandomGrid() {
    this.setState({cellRows: generateRandomCellDistribution(this.state.size), generation: 0})
  }

  clearGrid() {
    this.setState({cellRows: getBlankCellRows(this.state.size), generation: 0});
  }

  toggleSpeed(){
    var newSpeed = this.state.speed < 4 ? this.state.speed+1 : 1;
    clearInterval(this.state.interval);
    this.setState({speed: newSpeed, interval: setInterval(this.stepGame, 200/newSpeed)});
  }

  stepGame() {
    var newCellRows = getBlankCellRows(this.state.size);
    var currentCellRows = this.state.cellRows.slice();
    var aliveNeighbours = getAliveNeighbours(currentCellRows);

    for(var i = 0; i < currentCellRows.length; i++) {
      for(var q = 0; q < currentCellRows[i].length; q++) {
        newCellRows[i][q].state = getNewState(currentCellRows[i][q].state, getAliveNeighbours(currentCellRows, i, q));
      }
    }

    this.setState({cellRows: newCellRows, generation: this.state.generation + 1});
  }

  render(){
    return(

          <button className="button-theme" onClick={this.toggleGameState}>{this.state.gameState === 'playing' ? 'Pause' : 'Start'}</button>
          <button className="button-theme" onClick={this.clearGrid}>Clear grid</button>
          <button className="button-theme" onClick={this.generateRandomGrid}>Random</button>
          <button className="button-theme" onClick={this.toggleSpeed}>Speed: {this.state.speed}x</button>

Generation: {this.state.generation}

        <Grid
          gameState={this.state.gameState}
          size={this.state.size}
          cellRows={this.state.cellRows}
          squareClicked={this.squareClicked}
        />

    );
  }
}


texts:
I was just wondering if my code below is a good way of populating data from database. I have had no issues with this really but I am being taught this and just wondering if it is the best practice.

 Public Sub LoadProperty()
    '**Finds the Current Property Data

    'Error Checking
    ' On Error GoTo Err_LoadProperty
    Try

        Dim uRecSnap As ADODB.Recordset

        ' Check For Open Connection
        If uDBase Is Nothing Then
            OpenConnection()
            bConnection = True
        End If

        ' Run Stored Procedure - Load Property Record
        uCommand = New ADODB.Command
        With uCommand
            .ActiveConnection = uDBase
            .CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
            .CommandTimeout = 0
                 uCommand.Parameters.Append(uCommand.CreateParameter("@PropertyID", ADODB.DataTypeEnum.adInteger, ADODB.ParameterDirectionEnum.adParamInput, , Val(lblPropertyIDValue.Text)))
            .CommandText = "PropertyMaster_LoadRecord"

            uRecSnap = .Execute
        End With

        ' Store Data Values
        Do Until uRecSnap.EOF
            lblPropertyIDValue.Text = If(IsDBNull(uRecSnap("PropertyID").Value), "", uRecSnap("PropertyID").Value)
            lblSPMReferenceValue.Text = If(IsDBNull(uRecSnap("SPMReference").Value), "", uRecSnap("SPMReference").Value)
            cmbPropertyManager.Text = If(IsDBNull(uRecSnap("PropertyManager").Value), "", uRecSnap("PropertyManager").Value)
            txtAddress1.Text = If(IsDBNull(uRecSnap("AddressLine1").Value), "", uRecSnap("AddressLine1").Value)
            txtAddress2.Text = If(IsDBNull(uRecSnap("AddressLine2").Value), "", uRecSnap("AddressLine2").Value)
            txtAddress3.Text = If(IsDBNull(uRecSnap("AddressLine3").Value), "", uRecSnap("AddressLine3").Value)
            txtTown.Text = If(IsDBNull(uRecSnap("Town").Value), "", uRecSnap("Town").Value)
            txtPostCode.Text = If(IsDBNull(uRecSnap("PostCode").Value), "", uRecSnap("PostCode").Value)
            chkAvailable.Checked = If(IsDBNull(uRecSnap("Availabilty").Value), "", uRecSnap("Availabilty").Value)
            dtpAvailable.Value = If(IsDBNull(uRecSnap("Available").Value), "1/1/1900", uRecSnap("Available").Value)
            chkFactored.Checked = If(IsDBNull(uRecSnap("Factored").Value), 0, uRecSnap("Factored").Value)
            txtFactorName.Text = If(IsDBNull(uRecSnap("FactorsName").Value), "", uRecSnap("FactorsName").Value)
            txtFactorsEmail.Text = If(IsDBNull(uRecSnap("FactorsEmail").Value), "", uRecSnap("FactorsEmail").Value)
            dtpPropertyBuilt.Value = If(IsDBNull(uRecSnap("PropertyBuilt").Value), "1/1/1900", uRecSnap("PropertyBuilt").Value)
            txtPropertyValue.Text = If(IsDBNull(uRecSnap("PropertyValue").Value), "", uRecSnap("PropertyValue").Value)
            txtMinimumFee.Text = If(IsDBNull(uRecSnap("MimimumFee").Value), "", uRecSnap("MimimumFee").Value)
            txtCostAuthorisationAmount.Text = If(IsDBNull(uRecSnap("CostSuthorisationAmount").Value), "", uRecSnap("CostSuthorisationAmount").Value)
            txtCommision.Text = If(IsDBNull(uRecSnap("Commission").Value), "", uRecSnap("Commission").Value)
            chkVacant.Checked = If(IsDBNull(uRecSnap("Vacant").Value), 0, uRecSnap("Vacant").Value)
            dtpVacant.Value = If(IsDBNull(uRecSnap("VacantDate").Value), "1/1/1900", uRecSnap("VacantDate").Value)
            txtStartingRent.Text = If(IsDBNull(uRecSnap("StartingRent").Value), "", uRecSnap("StartingRent").Value)

            uRecSnap.MoveNext()
        Loop

        ' Close Connection
        uRecSnap.Close()
        If bConnection Then CloseConnection()
        uRecSnap = Nothing

    Catch ex As Exception
        MsgBox(vbCrLf & ex.Message & vbCrLf & "Source---" & vbCrLf & ex.Source & vbCrLf & "Problem---" & vbCrLf & ex.StackTrace, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "SouthSide- Error Reporting")

    End Try

End Sub


texts: Windows Like Security Screen for Linux (mockup)

texts:
Ubuntu and other Linux variants do not have a Windows like CTRL + ALT + DEL screen, so I figured I'll make one myself. My plan is to make a HTML version, render that with the PyQt Web engine, and then when the keys CTRL + ALT + DEL are pressed the program launches.
Preview it:
https://codepen.io/aangeletakis/pen/YzprZxX?editors=1100
How could I improve on it before I start on the application portion?

<button>Lock</button>

<button>Switch user</button>

<button>Sign out</button>

<button>System manager</button>

    <button class="cancelBtn">Cancel</button>


texts: How to create a simple stateless cache class in PHP

texts:
i need to create a cache class to avoid making the same calculations more than needed. My idea was something really basic like

class transient_cache {
    static private $cache = array();
    static public function get_value( array $obj, $key ) {
        // $obj is an array( $object, $method )
        $classname = get_class( $obj[0] );
        $method = $obj[1];
        if( ! isset( self::$cache[$classname] ) ) {
            self::$cache[$classname] = array();
        }
        if( ! isset( self::$cache[$classname][$method] ) ) {
            self::$cache[$classname][$method] = array();
        }
        if( ! isset( self::$cache[$classname][$method][$key] ) ) {
            self::$cache[$classname][$method][$key] = call_user_func( $obj );
        }
        return  self::$cache[$classname][$method][$key];
    }
}

Do you think this approach is correct or would you suggest something better?


texts:
I am trying to learn Mongodb and decided to build a simple blog application using Zend Framework and Mongodb (using Shanty for ZF).

I have the following document for Post

class App_Model_Post extends Shanty_Mongo_Document
{
    protected static $_db = 'blog';
    protected static $_collection = 'posts';
    protected static $_requirements = array(
        'Title' => 'Required',
        'Content' => 'Required',
        'CreatedOn' => 'Required',
        'Author' => array('Document:App_Model_User', 'Required', 'AsReference'),
        'Slug' => 'Required',
    );

    public function preSave()
    {
       $title = $this->Title;
       $this->Slug = strtolower($title);
    }
}

Document for Comment:

class App_Model_Comment extends Shanty_Mongo_Document
{
    protected static $_db = 'blog';
    protected static $_collection = 'comments';
    protected static $_requirements = array(
        'Content' => 'Required',
        'Author' => array('Required', 'Document:App_Model_User', 'AsReference'),
        'Post' => array('Required', 'Document:App_Model_Post'),
    );
}

In my controller I do the following to get the Post and Comments for this Post:

public function viewAction()
{
    $slug = $this->_getParam('id');
    $post = App_Model_Post::one(array('Slug' => $slug));
    $this->view->post = $post;
    $this->view->title = 'Post Title : ' . $post->Title;

    $comments = App_Model_Comment::all(array('Post.Slug' => $post->Slug))->skip(0)->limit(10);
    $this->view->comments = $comments;
}

I wonder if this is a good way to accomplish this.  Is it good practice to reference to Post in the Comment or should I inject Comment documents to Post document?


texts:
I tried to solve a programming contest problem in Scala, but I have a feeling, that it could be done in a more functional way. I compared it with the solution written in imperative style and it is not shorter or less complex at all. Do you have any idea how to "impove" or approach the problem in a more functional way?

Here is my solution:

object Sunshine extends App {

  def tanning(bedNumber:Int, part1 : List[Char], part2: List[Char], inBed: List[Char], tanned:Int, walkedAway: Int) : Int  = {

     val actCustomer =part2.head
     val tanningTuple=(part1.indexOf(actCustomer),inBed.indexOf(actCustomer),bedNumber>inBed.length,part2.tail)

     tanningTuple  match {
      case(_,_,_,Nil)  => walkedAway
        // enter,can be tanned
      case (-1,-1,true,_) =>
        tanning(bedNumber,actCustomer::part1,part2.tail,actCustomer::inBed,tanned,walkedAway)
        // enter, can not be tanned
      case (-1,-1,false,_) =>
        tanning(bedNumber,actCustomer::part1,part2.tail,inBed,tanned,walkedAway)
        //leave, not in bed
      case (x ,-1,_,_) if x>=0 =>
        tanning(bedNumber,actCustomer::part1,part2.tail,inBed,tanned,walkedAway+1)
      //leave, in bed
      case (x,y,_,_) if x>=0 && y>=0 =>
        tanning(bedNumber,actCustomer::part1,part2.tail,inBed-actCustomer,tanned+1,walkedAway)
    }
  }

  println(tanning(2,List(),"ABBAJJKZKZ".toList,List(),0,0))
  println(tanning(3,List(),"GACCBDDBAGEE".toList,List(),0,0))
  println(tanning(3,List(),"GACCBGDDBAEE".toList,List(),0,0))
  println(tanning(1,List(),"ABCBCA".toList,List(),0,0))
}


texts: In DRY Python code, when should I catch/raise exceptions?

texts:
Given python's principle of duck-typing, when is it best to raise exceptions?

In a simplified case below, say I want to code a couple functions to return booleans based on an input object product. Rather than catching an exception if an unexpected object was entered, I'm splitting functionality to keep things DRY.

However, should I also be catching the raised exception in functions that call the abstracted code?

For the options below, which would be the better approach? Are there better approaches still?

Option 1

TAX_RATE = 0.2

def calculate_price_after_tax(product):
    """Returns Decimal"""
    try:
        net_price = product.price
    except AttributeError:
        raise TypeError('Expected an input of type Product, but received: {0}.'.format(type(product))
    return net_price * TAX_RATE

def is_price_above_100(product):
    """Returns bool"""
    return calculate_price_after_tax(product) > 100

def is_price_above_200(product):
    """Returns bool"""
    return calculate_price_after_tax(product) > 200

Option 2

TAX_RATE = 0.2

def calculate_price_after_tax(product):
    """Returns Decimal"""
    try:
        net_price = product.price
    except AttributeError:
        raise TypeError('Expected an input of type Product, but received: {0}.'.format(type(product))
    return net_price * TAX_RATE

def is_price_above_100(product):
    """Returns bool"""
    try:
        calculate_price_after_tax(product) > 100
    except TypeError as e:
        raise TypeError(e)

def is_price_above_200(product):
    """Returns bool"""
    try:
        calculate_price_after_tax(product) > 200
    except TypeError as e:
        raise TypeError(e)


texts:
Wikipedia uses Infoboxes for many of its articles. They contain basic information in a structured form about the topic. Take for example the articles about Stack Overflow and donkeys.

Their structure is something like:

Title
Icon or Image
One or more sections

Each containing on or more key value pairs
or a text

Wikipedia uses for Infoboxes Tables.

My approach in HTML5 is:

Donkey

Conservation status

    Domesticated

Scientific classification

Kingdom

Animalia

Phylum

Chordata

Class

Mammalia

Order

Perissodactyla

Family

Equidae

Genus

Equus

Subgenus

Asinus

Species

E. africanus

ubspecies

E. a. asinus

Trinomial name

    quus africanus asinus
    Linnaeus, 1758

Is this HTML correct and useful? Are there better ways to write it?

This question is not only about Wikipedia but on how to write such constructs like infoboxes, that are used on other sites as well.


texts: Get average post score of TOP 10 tags on StackOverflow using Stack Exchange Data Explorer

texts:
I want to use the Stack exchange data explorer in order to display some basic information about the top tags.

The query should print the number of questions and answers, the average number of answers per question and the average score of posts(questions and answers under such questions). The query is ordered by the total number of questions.

This is my SQL code:

SELECT TOP(10)
  Tags.TagName,
  COUNT(DISTINCT Questions.Id) AS 'Number of Questions',
  COUNT(Answers.Id) AS 'Number of Answers',
  (COUNT(Answers.Id)+0.0)/COUNT(DISTINCT Questions.Id) AS 'Answers per question',
  (
    SELECT AVG(post.Score+0.0)
    FROM Posts post,PostTags tag
    WHERE
      (
      post.Id=tag.PostId
      OR post.ParentId=tag.PostId
      )
      AND tag.TagId=Tags.Id
      ) AS 'average score of posts under this tag(questions and answers)'
FROM Posts Questions
LEFT JOIN Posts Answers
  ON Answers.ParentId = Questions.Id
INNER JOIN PostTags
  ON Questions.Id=PostTags.PostId
INNER JOIN Tags
  ON PostTags.TagId=Tags.Id
GROUP BY Tags.Id,Tags.TagName
ORDER BY COUNT(*) DESC

You can look at the script in the data explorer here.

The problem is that the script times out(in around 100 seconds). If I remove the OR post.ParentId=tag.PostId, it still takes around 25 seconds to run (for Stack Overflow) but it does not time out.

If I run my script on Super User, it does not time out. (It runs around 4 seconds, I think it is because Super User is smaller than Stack Overflow)

Is there a way to run optimize the script so that it does not time out on Stack Overflow without losing functionality and why does that simple OR decrease the performance that much?

The OR is that answers do also count for the average score.

I've added the execution plan files here.


texts: Performance problem: Ranking with ties and skipping rows on passmark condition

texts:
I am using the following code for calculating ranking and it is working great for not large data. But when it comes to large data, processing time takes almost a minute. Please can anyone suggest a better way or atleast a faster way to put the same mysql statement?

 SELECT id, Names, TOTALSCORE, Rank
 FROM
 (
 SELECT t.*,
     IF(@p = TOTALSCORE, @n, @n := @n + 1) AS Rank,
     @p := TOTALSCORE
  FROM(
  SELECT id, Names,SUM(score) TOTALSCORE
     FROM exam e1, (SELECT @n := 0, @p := 0) n
     WHERE NOT EXISTS(
        SELECT null FROM exam e2
        WHERE e1.id = e2.id
        AND e2.score/e2.Fullmark < 0.33
      )
     GROUP BY id
     ORDER BY TOTALSCORE DESC
  ) t
 ) r
 ;

Fiddle is here:ranking with ties and skipping rows on passmark condition


texts: Refactoring APEX to keep all database calls outside of for loops

texts:
I have the following APEX code. I have been trying for hours to try and refactor it so that the SOQL query is outside of the for loop without any luck. Any ideas?

public static void ErrorIfWorklogsOverlap(List<Worklog__c> worklogs) {
        for (Worklog__c worklog : worklogs) {
            List<Worklog__c> timesheetWorklogs = [
                    SELECT
                            Id
                    FROM Worklog__c
                    WHERE Timesheet__c IN (
                            SELECT
                                    Id
                            FROM Timesheet__c
                    )
            ];
            DateTime worklogStartTime = worklog.Start_Time__c;
            DateTime worklogEndTime = worklog.End_Time__c;
            for (Worklog__c checkLog : timesheetWorklogs) {
                DateTime checkLogStart = checkLog.Start_Time__c;
                DateTime checkLogEnd = checkLog.End_Time__c;
                if (worklogStartTime > checkLogStart && worklogStartTime < checkLogEnd) {
                    worklog.Start_Time__c.addError('Worklog\'s start time is within the bounds of another worklog');
                } else if (worklogEndTime < checkLogEnd && worklogEndTime > checkLogStart) {
                    worklog.End_Time__c.addError('Worklog\'s end time is within the bounds of another worklog');
                } else if (worklogStartTime < checkLogStart && worklogEndTime > checkLogEnd) {
                    worklog.addError('Worklog overlaps another worklog');
                }
            }
        }
    }

A Worklog belongs to a Timesheet. This code is supposed to be checking if any of the Worklogs in the list worklogs overlaps another Worklog in the same Timesheet.


texts:
I'm making a old-school Final Fantasy type game and I made a tile map class a while back and posted it on here (Is this a good way to implement a tile map from a text file?) But, when I got to collision, it was a nightmare. So I've updated it to make it more collision friendly and I was wondering what the community's thoughts were on this code.

Tile.java

import java.awt.image.BufferedImage;

public class Tile
{
    public int texKey;  //number to represent texture
    public BufferedImage texture;
    public boolean collidable;

    public Tile(int texKey, BufferedImage texture, boolean collidable)
    {
        this.texKey = texKey;
        this.texture = texture;
        this.collidable = collidable;
    }
}

TileMaker.java

import com.stardust.rpgtest2.gfx.Assets;

public class TileMaker
{
    public Tile[] tileArray= new Tile[28];

    public TileMaker()
    {

    }

    public void setTile()
    {
        for(int i = 0; i <= tileArray.length; i++)
        {
            switch(i)
            {
                case 0:
                {
                    tileArray[i] = new Tile(i, Assets.grass, false);
                    break;
                }
                case 1:
                {
                    tileArray[i] = new Tile(i, Assets.dirt, false);
                    break;
                }
                case 2:
                {
                    tileArray[i] = new Tile(i, Assets.water, false);
                    break;
                }
                //this goes up to 27 at the moment
                default:
                {
                    break;
                }
            }

        }
    }

    public Tile[] getTileArray()
    {
        return tileArray;
    }
}

TileMap.java

import com.stardust.rpgtest2.Game;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TileMap
{
    int posX, posY, x, y, sx, sy, mapSize;
    public String filename;

    public int[][] tilemap;

    public TileMap(int posX, int posY, int mapSize, String filename)
    {
        this.mapSize = mapSize;
        tilemap = new int[mapSize][mapSize];
        this.posX = posX;
        this.posY = posY;
        this.sx = mapSize;
        this.sy = mapSize;
        this.filename = filename;
    }

    public void render(Graphics g)
    {
        for(int y = 0; y < tilemap.length; y++)
        {
            for(int x = 0; x < tilemap.length; x++)
            {
                int textureType = tilemap[x][y];
                BufferedImage texture = Game.tileMaker.getTileArray()[textureType].texture;
                g.drawImage(texture, posX, posY, null);
                posY += 32;
            }
            posX += 32;
            posY = Game.mapY;
        }
        posX = Game.mapX;
        posY = Game.mapY;
    }

    public void fileParser() throws IOException
    {
        BufferedReader in = new BufferedReader(new FileReader(filename));

        String line;

        while((line = in.readLine()) != null)
        {
            String[] values = line.split(",");

            for(String str : values)
            {
                int str_int = Integer.parseInt(str);
                tilemap[x][y] = str_int;
                ++y;
            }
            ++x;
            y = 0;
        }
        x = 0;

        in.close();
    }
}

I call the TileMaker.setTile() and TileMap.fileParser() methods both in the initialization method in the main game class, and everything behaves as needed so far.


texts: Parsing n lines to count vowels - HackerEarth

texts:
I have written a haskell program for the following 'Code Monk' Challenge at HackerEarth.
Here is the challenge description. Basically, we are looking for the number of vowels in a string. The first input n is the number of string to parse, followed by n number of random strings.

And here is my implementation:

import Data.Char
main = do
    numberOfTestCases <- getLine
    processLine (read numberOfTestCases :: Int)

processLine 0 = return()
processLine n = do
    line <- getLine
    print $ countVowels line
    processLine (n-1)

countVowels :: String -> Int
countVowels line = length $ filter (`elem` ['a','e','i','o','u']) $ map toLower line

My code is working correctly but as I'm fairly new to functional programming and Haskell I would like some comments about my code. More specifically, I would like the processLine function to not have a side effect, but I don't know how can I do that. Any other tips or comments would be greatly appreciated!


texts:
I'm attempting to implement a calculator-like application in C#. But the way I've currently implemented it seems a little messy and inefficient. It works, but it's just I'm pretty sure it can be achieved in a more elegant solution.

I looked to see if I could factor out any repeating code, such as the switch statement - but without having numerous parameters in the method, I don't think it'll make things much better.

Here's the main portion of the code:

private double Calculate()
{

    double answer = 0.0;
    foreach (double number in this.numbers)
    {
        int index = this.numbers.IndexOf(number);

        if (index != this.numbers.Count() - 1)
        {
            if (answer != 0.0)
            {
                switch ((int)operators[index])
                {
                    case (int)Operator.Plus:
                        answer = (double)(answer + numbers[index + 1]);
                        break;

                    case (int)Operator.Minus:
                        answer = (double)answer - numbers[index + 1];
                        break;

                    case (int)Operator.Divide:
                        answer = (double)answer / numbers[index + 1];
                        break;

                    case (int)Operator.Multiply:
                        answer = (double)answer * numbers[index + 1];
                        break;
                }
            }
            else
            {
                switch ((int)operators[index])
                {
                    case (int)Operator.Plus:
                        answer += (double)(number + numbers[index + 1]);
                        break;

                    case (int)Operator.Minus:
                        answer += (double)number - numbers[index + 1];
                        break;

                    case (int)Operator.Divide:
                        answer += (double)number / numbers[index + 1];
                        break;

                    case (int)Operator.Multiply:
                        answer += (double)number * numbers[index + 1];
                        break;
                }
            }
        }

    }

    return answer;
}

Just for reference, Operators is an ENUM that's defined as:

private enum Operator
{
    Plus = 1,
    Minus = 2,
    Multiply = 3,
    Divide = 4,
}

and the two lists:

private List<double> numbers;
private List<Operator> operators;

Any ideas on how I could improve this?


texts: Helper extension to release Windsor component; not sure if it's over-kill

texts:
One of the tenets of Windsor IoC (probably applies to all IoC containers too) is to "release what you explicitly resolve", which admittedly should occur rarely.  But we have a fair few UsingFactoryMethod setups in our installers, which are resolving directly (which appears to be a valid case for explicit resolution).

However, remembering to call Dispose() on those resolved things is something I doubt a lot of people will remember, so I came up with a helper method in order to be able to wrap that logic away (always a good thing, right?).  However, I'm not sure if it's just a bit overkill in this case.

namespace Castle.Windsor {
    using System;
    using Castle.MicroKernel;

    public static class KernelExtensions {

        public static ResolvedResult<TInstance> ResolveDispose<TInstance>(this IKernel kernel) {
            return new ResolvedKernelResult<TInstance>(kernel);
        }

        public static ResolvedResult<TInstance> ResolveDispose<TInstance>(this IWindsorContainer container) {
            return new ResolvedContainerResult<TInstance>(container);
        }

        public abstract class ResolvedResult<T> : IDisposable {

            public T Instance { get; private set; }

            protected ResolvedResult(Func<T> resolver, Action<object> releaser) {
                this.Instance = resolver();
                this._Releaser = releaser;
            }

            #region IDisposable Members

            public void Dispose() {
                if (null == _Releaser) {
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                //Dis-associate the resolved instance, can't null assign as T isn't typed
                Instance = default(T);

                _Releaser(Instance);
                _Releaser = null;
            }

            #endregion

            private Action<object> _Releaser;

            public static implicit operator T(ResolvedResult<T> res) {
                return res.Instance;
            }
        }

        private sealed class ResolvedKernelResult<T> : ResolvedResult<T> {
            internal ResolvedKernelResult(IKernel kernel) : base(kernel.Resolve<T>, kernel.ReleaseComponent) { }
        }

        private sealed class ResolvedContainerResult<T> : ResolvedResult<T> {
            internal ResolvedContainerResult(IWindsorContainer container) : base(container.Resolve<T>, container.Release) { }
        }
    }
}

Usage

Before:

container.Register(
    //...

    Component.For<MyComponentType>()
        .UsingFactoryMethod(k => {
            var altComponent = k.Resolve<SomeAlternativeComponent>();

            var component = new ImplementingComponentType(altComponent.RandomProperty);

            k.ReleaseComponent(altComponent);

            return component;
        })
)

After:

container.Register(
    //...

    Component.For<MyComponentType>()
        .UsingFactoryMethod(k => {
            using(var altComponent = k.ResolveDispose<SomeAlternativeComponent>()) {
                return new ImplementingComponentType(altComponent.Instance.RandomProperty);
            }
        })
)