texts:
I have this code, which I think can be optimized even more, but I can't think of a way of optimizing the main loop to make it faster and more comprehesive. Here's the code:

#include <iostream>
#include <cstdlib>
#include <cmath>

template <class Integral>
bool IsPrime (const Integral &n){
   // Get rid of base cases
   if (n==2 || n==3) return true;

   // Initialize the boolean to an intuitive correct value
   bool is_prime = n%2 != 0 && n%3 != 0;
   unsigned long top = (unsigned long) sqrt(n)+1;

   // This is the loop I want to optimize
   for (unsigned long i=3; i<top && is_prime; i+=6){
      is_prime = (n%(i+2) != 0) && (n%(i+4) != 0);  // kind of loop unrolling...
   }

   return is_prime;
}

// Main program
int main (int argc, char* argv[]){
   // Check passed arguments
   if (argc != 2){
      std::cerr << "Format: " << argv[0] << " <integer>" << std::endl;
      return -1;
   }

   if (IsPrime(strtoul(argv[1], NULL, 0))) return 0;
   else return 1;
}

As you can see, I could reduce the amount of iterations by six times, but going further was worthless.

For the biggest 64-bit unsigned prime number, 18446744073709551557, it spends about 15-17 seconds in an i5, 1.70 GHz processor (which I think can be optimized more).


texts: Using Delegates and BeginInvoke with .NET 2.0 WebServices

texts:
I'm attempting to implement a simple long-polling/comet/reverse AJAX solution, and came across the concept of delegates, specifically with the BeginInvoke and EndInvoke methods. I've built a Web Service that uses these concepts, but, having never used these, they make me a little nervous, and I have my doubts as to whether they are actually what I want.

The goal, of course, is to offload the actual processing from IIS processes onto other framework processes, for a reduction in server load when waiting on a long-poll request for data. I can't have gotten this right, but I want to know why and at least get some direction in how it might be better accomplished (not necessarily a solution, but maybe an article or some documentation).

The Web Service code:

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Threading
Imports System.Runtime.InteropServices

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Dim threadId As Integer
        Dim thing As New Things
        Dim caller As New AsyncDoStuff(AddressOf thing.doStuff)
        Dim result As IAsyncResult = caller.BeginInvoke(3000, threadId, Nothing, Nothing)

        result.AsyncWaitHandle.WaitOne()

        Dim returnValue As String = caller.EndInvoke(threadId, result)

        result.AsyncWaitHandle.Close()

        Return returnValue
    End Function
End Class

Public Class Things
    Public Function doStuff(ByVal callDuration As Integer, <Out()> ByRef threadId As Integer) As String
        ' Imagine this method was accessing a database, looking for new information, and returning when it found some
        Thread.Sleep(callDuration)
        threadId = Thread.CurrentThread.ManagedThreadId()
        Return String.Format("My call time was {0}.", callDuration.ToString())
    End Function
End Class

Public Delegate Function AsyncDoStuff(ByVal callDuration As Integer, <Out()> ByRef threadID As Integer) As String


texts: Method that fetches rows from database and maps it to a Model class with SqlDataReader

texts:
So, I have a project that has a lot of methods that look alike.
In the below method as you can see it just fetches a bunch of rows from database and maps it to a model class.

In this  case ParkingSlipDetails class.
There are several such methods in the project that do the exact same thing only with a different set of data and a different model class. There is no complicated business logic here. Just pure fetching data and mapping it to a model.

Something like this:

  public CustomReturn < List < ParkingSlipDetails >> GetAllParkingSlips(int offset, int fetch)
    {
        SqlConnection sqlConnection = null;
        try
        {
            List < ParkingSlipDetails > ParkingSlipDetailsList = new List < ParkingSlipDetails > ();
            sqlConnection = (SqlConnection) sqlHelper.CreateConnection(); //sqlHelper is a nugget and not in my control
            sqlConnection.Open();
            SqlCommand cmd = new SqlCommand(Constants.GetAllParkingSlips, sqlConnection);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add("@CreatedBy", SqlDbType.NVarChar).Value = gepservice.GetUserContext().UserId;
            cmd.Parameters.Add("@OffsetRows", SqlDbType.NVarChar).Value = offset;
            cmd.Parameters.Add("@FetchRows", SqlDbType.NVarChar).Value = fetch;
            var refCountdr = (RefCountingDataReader) sqlHelper.ExecuteReader(cmd);
            var sqlDr = (SqlDataReader) refCountdr.InnerReader;
            if (sqlDr != null)
            {
                while (sqlDr.Read())
                {
                    ParkingSlipDetails ParkingSlipDetails = new ParkingSlipDetails();
                    ParkingSlipDetails.Id = Convert.ToInt32(sqlDr[FileUploadConstants.Id]);
                    ParkingSlipDetails.FileName = Convert.ToString(sqlDr[FileUploadConstants.FileName]);
                    ParkingSlipDetails.FileUri = Convert.ToString(sqlDr[FileUploadConstants.FileURI]);
                    ParkingSlipDetails.PONumber = Convert.ToString(sqlDr[FileUploadConstants.DocumentNumber]);
                    ParkingSlipDetails.UploadDate = Convert.IsDBNull(sqlDr[FileUploadConstants.UploadDate]) ? DateTime.UtcNow: Convert.ToDateTime(sqlDr[FileUploadConstants.UploadDate]);
                    ParkingSlipDetails.FileStatus = (Status)(Convert.ToInt16(sqlDr[FileUploadConstants.FileStatus]));
                    ParkingSlipDetails.ReceiptNumber = Convert.ToString(sqlDr[FileUploadConstants.RecieptNumber].ToString());
                    ParkingSlipDetails.TotalRows = Convert.ToInt32(sqlDr[FileUploadConstants.TotalRows]);
                    ParkingSlipDetails.CreatedBy = gepservice.GetUserContext().UserId;
                    ParkingSlipDetailsList.Add(ParkingSlipDetails);
                }
            }
            return new CustomReturn < List < ParkingSlipDetails >> (ParkingSlipDetailsList);
        }
        catch(Exception ex)
        {
            LogError("ManageParkingSlipDataAccess", "GetAllParkingSlips", "Error", ex);
            return null
        }
        finally
        {
            if (sqlConnection != null)
            sqlConnection.Close();
        }
    }

I think there is a lot of scope for refactoring here since there is a lot of places where I would repeat :

sqlConnection = (SqlConnection)sqlHelper.CreateConnection();
sqlConnection.Open();

and

var refCountdr = (RefCountingDataReader) sqlHelper.ExecuteReader(cmd);

var sqlDr = (SqlDataReader) refCountdr.InnerReader;
if (sqlDr != null) {
  while (sqlDr.Read())
  {

  }
}

And I also think the looping is repetitive for each method. Each such method has a loop that maps object to cmd.Parameters

How do I separate the looping and mapping? Should I create an extension method on ParkingSlipDetails Class that takes SqlDataReader and returns an instance of ParkingSlipDetails? Even then I will be repeating reader creation and lopping in each model class.


texts:
I've created a tiny (723 bytes compressed + gzip) animation library. Is this a good way of animating arbitrary numbers?

const map = (value, x1, x2, y1, y2) => (value - x1) * (y2 - y1) / (x2 - x1) + y1;
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);

// Courtesy of @gre from https://gist.github.com/gre/1650294
const Easing = {
  // no easing, no acceleration
  linear: t => t,
  // acceleration until halfway, then deceleration
  easeInOutQuad: t => t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
};

function Animation(settings) {
  if (typeof settings !== 'object' || (typeof settings === 'object' && settings instanceof Array)) {
    throw new Error('The settings passed to Animation must be an object');
  }

  if (!settings.hasOwnProperty('duration')) {
    throw new Error('The settings passed to Animation must have a "duration" property set');
  }

  if (!settings.hasOwnProperty('from')) {
    throw new Error('The settings passed to Animation must have a "from" property set');
  }

  if (!settings.hasOwnProperty('to')) {
    throw new Error('The settings passed to Animation must have a "to" property set');
  }

  if (settings.hasOwnProperty('easing') && typeof settings.easing !== 'function') {
    throw new Error('Invalid easing function passed to settings. Easing function must be one of the functions provided in the Easing object, e.g. Easing.linear');
  }

  const duration = settings.duration;
  const easing = settings.easing || Easing.linear;
  const timestamps = {
    start: 0,
    finish: 0,
  };
  const value = {
    from: settings.from,
    to: settings.to,
  };

  let nextFrame, tickCallback;

  const setTimestamps = currentTimestamp => {
    timestamps.start = currentTimestamp;
    timestamps.finish = currentTimestamp + duration;
  };

  const tick = () => {
    nextFrame = requestAnimationFrame(tick);

    const currentTimestamp = Date.now();

    if (timestamps.start + timestamps.finish === 0) {
      setTimestamps(currentTimestamp);
    }

    const normal = easing(map(currentTimestamp, timestamps.start, timestamps.finish, 0, 1));
    const delta = clamp(normal, 0, 1);

    tickCallback(map(delta, 0, 1, value.from, value.to));

    if (delta === 1) {
      cancelAnimationFrame(nextFrame);
    }
  };

  this.animate = fn => {
    if (typeof fn !== 'function') {
      throw new Error('The given callback is not a function. A valid function callback must be provided');
    }

    nextFrame = requestAnimationFrame(tick);
    tickCallback = fn;
  };

  return this;
}

Example of animating a number from -50 to 50 over 5000, starting slow and finishing slow:

const animation = new Animation({
  duration: 5000,
  from: -50,
  to: 50,
  easing: Easing.easeInOutQuad,
});

animation.animate(value => {
  document.body.innerText = String(Math.round(value));
});

I know there are many tiny animation libraries out there already, but I only need a small sub-set of their functionality.

Demo on JS Bin.


texts: A Java class for calculating size of iterable/array

texts:
Another exercise of Java generics:

import java.util.Collection;

/**
 * Created by IDEA on 16/11/14.
 */
public class Size {
    public static <T, I extends Iterable<T>> int size(I data) {
        final int size;
        if (data instanceof Collection) {
            size = ((Collection<T>) data).size();
        } else {
            int counter = 0;
            for(Object i : data) {
                counter++;
            }
            size = counter;
        }
        return size;
    }

    public static int size(int[] data) {
        return data.length;
    }

    public static int size(double[] data) {
        return data.length;
    }

    public static int size(String[] data) {
        return data.length;
    }
}

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IDEA on 16/11/14.
 */
public class TestSize {
    public static void main(String[] args) {
        int[] x = {1, 2, 3};
        List<Integer> y = new ArrayList<>();
        y.add(1);
        y.add(2);
        System.out.println(Size.size(x));
        System.out.println(Size.size(y));
    }
}


texts: Simple File Manager with recursion in C#

texts:
Simple class to simpify runtime file loading of ressources. The class reads all files from a given directory including all subdirectories and stores the name together with the path in a simple struct. If a file needs to be used by the program just pass the name to GetPath() and the class returns the location of the file.

Any suggestions/improvements about my implementation of this? Im especially not sure if making this static is the right choice.

using System.IO;
using System.Collections.Generic;

namespace Sample
{
    struct File
    {
        public string Name;
        public string Path;
    }

    static class FileManager
    {
        private static List<File> Files = new List<File>();

        public static void AddFiles(string directory)
        {
            foreach(string file in  Directory.GetFiles(directory))
            {
                Files.Add(new File() { Name = Path.GetFileName(file), Path = directory });
            }

            foreach(string subdirectory in Directory.GetDirectories(directory))
            {
                AddFiles(subdirectory);
            }
        }

        public static string GetPath(string filename)
        {
            var File = Files.Find(x => x.Name == filename);

            return File.Path;
        }

        public static void ClearFiles()
        {
            Files.Clear();
        }
    }
}


texts:
I just want to know if my PHP code is secure and if it's as clean as it can be. I'm trying to make a blog system and I want to make sure all my users information is safe and secure, although this is just an install script.

 <?php
ob_start();
if (isset($_POST['submit'])) {

    ### SQL INFO CHECK ###
    $db_host = $_POST['hostname'];
    $db_user = $_POST['host_username'];
    $db_pass = $_POST['host_password'];
    $db_name = $_POST['database'];
    ### CREATE ACCOUNT CHECK ###
    $username = $_POST['username'];
    $password = $_POST['password'];
    $email = $_POST['email'];
    $block = $_POST['block'];
    ### SITE INFO CHECK ###
    $site_name = $_POST['site_name'];
    $site_slogan = $_POST['site_slogan'];

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $email_verify = 1;
    } else {
        $email_verify = 0;
    }

    if (!$_POST['hostname'] || !$_POST['host_username'] || !$_POST['host_password'] || !$_POST['database']|| !$_POST['username'] || !$_POST['password'] || !$_POST['site_name'] || !$_POST['site_slogan']) {
        echo '
';
        echo 'You\'ve left some fields empty.';
        echo '
';
    }

    elseif (strlen($username) > 30) {
        echo '
';
        echo 'The username is too long, it must be 30 or less characters';
        echo '
';
    }

    elseif (strlen($password) > 10) {
        echo '
';
        echo 'The password is too long, it must be 10 or less characters';
        echo '
';
    }

    elseif (strlen($site_slogan) > 30) {
        echo '
';
        echo 'The site slogan is too long, it must be 30 or less characters';
        echo '
';
    }

    elseif (strlen($site_name) > 20) {
        echo '
';
        echo 'The site name is too long, it must be 20 or less characters';
        echo '
';
    }

    elseif (!$db = @mysqli_connect($db_host, $db_user, $db_pass, $db_name)) {
        echo '
';
        echo 'Unable to connect to MySQL. Error Code (2002)';
        echo '
';
    } else
    if ($email_verify == 0){
        echo '
';
        echo 'The E-mail address is incorrect';
        echo '
';
    } else {
        $conf = file_get_contents("../inc/conf.php");
        $conf = str_replace("localhost", $db_host, $conf);
        $conf = str_replace("replace_u", $db_user, $conf);
        $conf = str_replace("replace_p", $db_pass, $conf);
        $conf = str_replace("replace_n", $db_name, $conf);
        $conf = str_replace("Site Name", $site_name, $conf);
        $conf = str_replace("The best blog in town!", $site_slogan, $conf);
        file_put_contents("../inc/conf.php", $conf);
    }

    $query = file_get_contents("install.sql");

    if (mysqli_multi_query($db, $query)) {
        ### Add install functions here.
    }

}
ob_flush();
?>


texts:
I often use a similar scheme work with an API project. Can it be made easier, or is there a standard approach?

This class creates an API request:

public class ApiRequestCreator {

     private static String TEST_API_REQUEST = "http://jsonplaceholder.typicode.com/posts";

     public static Request createTestApiRequest(){
         return new Request.Builder()
                .url(TEST_API_REQUEST)
                .build();
     }
}

This class execute the request:

 public class ApiRequestExecutor {

     private final OkHttpClient client = new OkHttpClient();

     public void run(final Request request, final ApiMethodListener apiMethodListener) {

         new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void ...voids) {
                try {
                     Response response = client.newCall(request).execute();
                     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                     return response.body().string();
                } catch (IOException e) {
                     e.printStackTrace();
                     return null;
                }
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                apiMethodListener.result(result);
            }

        }.execute();

    }
}

For all of this to start:

new ApiRequestExecutor().run(ApiRequestCreator.createTestApiRequest(), call_back_interface_here);


texts: A trait class to detect whether a template is specialized for a given type

texts:
Today's question will just be about a small utility that I needed at some point for one of my projects: a template to detect whether a template is specialized for a given type. The utility uses std::void_t from C++17, but this alias template is simle enough to be implemented in you favourite C++ revision, whichever it is:

template<typename...>
struct voider
{
    using type = void;
};

template<typename... TT>
using void_t = typename voider<TT...>::type;

Here is the template utility I wrote to detect whether a template has a specialization for a given type, for SFINAE purpose:

template<
    template<typename...> class,
    typename,
    typename=void
>
struct is_specialized:
    std::false_type
{};

template<
    template<typename...> class Template,
    typename T
>
struct is_specialized<Template, T, std::void_t<decltype(Template<T>{})>>:
    std::true_type
{};

And here is a small example of how it can be used:

template<typename T>
struct foo;

template<>
struct foo<int> {};

template<>
struct foo<float> {};

int main()
{
    // Should print 1 1 0
    std::cout << is_specialized<foo, int>::value << ' '
              << is_specialized<foo, float>::value << ' '
              << is_specialized<foo, double>::value;
}

Is there any way I could improve this specialization trait? Any kind of review is welcome :)


texts:
I needed a structure that works really similar to the predefined Stack<T> but with a few extra functionalities. Examples include getting the index of value in the collection and being able to index the structure itself.

Any flaws or improvement notes are welcome!

public class StackList<T> : IEnumerable<T>
{
    private readonly List<T> _stackList = new List<T>();

    public T Pop()
    {
        if (_stackList.Count == 0)
        {
            throw new InvalidOperationException("The stack is empty");
        }
        T value = _stackList[0];
        _stackList.Remove(value);
        return value;
    }

    public void Push(T item)
    {
        _stackList.Insert(0, item);
    }

    public T Peek()
    {
        if (_stackList.Count == 0)
        {
            throw new InvalidOperationException("The stack is empty");
        }
        return _stackList[0];
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _stackList.GetEnumerator();
    }

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

    public T this[int index]
    {
        get { return _stackList[index]; }
        set { _stackList[index] = value; }
    }

    public int Count
    {
        get { return _stackList.Count; }
    }

    public void Clear()
    {
        _stackList.Clear();
    }

    public bool Contains(T item)
    {
        return _stackList.Contains(item);
    }

    public int IndexOf(T item)
    {
        return _stackList.IndexOf(item);
    }
}


texts: Optimize Application of Python Gensim Search Functions

texts:
I have a DataFrame that has a text column. I am splitting the DataFrame into two parts based on the value in another column. One of those parts is indexed into a gensim similarity model. The other part is then fed into the model to find the indexed text that is most similar. This involves a search function to enumerate over each item in the indexed part.

The goal is to compare each row in df_yes with the sims index (which consists of all rows from df_no. So the function is applied to each row in df_yes and, for each row, find the maximum similarity value and index(ices) of df_no.

With the toy data, it is fast, but with my real data, it is much too slow using apply. Here is the code example:

import pandas as pd
import gensim
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')

d = {'number': [1,2,3,4,5], 'text': ['do you like python', 'do you hate python','do you like apples','who is nelson mandela','i am not interested'], 'answer':['no','yes','no','no','yes']}
df = pd.DataFrame(data=d)

df_yes = df[df['answer']=='yes']

df_no = df[df['answer']=='no']
df_no = df_no.reset_index()

docs = df_no['text'].tolist()
genDocs = [[w.lower() for w in word_tokenize(text)] for text in docs]
dictionary = gensim.corpora.Dictionary(genDocs)
corpus = [dictionary.doc2bow(genDoc) for genDoc in genDocs]
tfidf = gensim.models.TfidfModel(corpus)
sims = gensim.similarities.MatrixSimilarity(tfidf[corpus], num_features=len(dictionary))

def get_search_results(row):
    tokenized_row = word_tokenize(row)
    query_bag_of_words = dictionary.doc2bow(tokenized_row)
    query_tfidf = tfidf[query_bag_of_words]
    search_result = sims[query_tfidf]
    max_similarity = max(search_result)
    index = [i for i, j in enumerate(search_result) if j == max_similarity]
    return max_similarity, index

df_yes = df_yes.copy()

df_yes['max_similarity'], df_yes['index'] = zip(*df_yes['text'].apply(get_search_results))

I have tried converting the operations to dask dataframes to no avail, as well as python multiprocessing. How would I make these functions more efficient? Is it possible to vectorize some/all of the functions?


texts: Showing data for a chat with another user

texts:
I have a get route to show the data for a chat with another user. If an existing chat exists I want to return that, otherwise create a new chat and return it.

/chat/user/{contra_user_id}

Should my Service or my repository be adding chat members to the chat? Currently I have my service creating each member.

class ChatService
{
    private $chatRepository;

    public function __construct(ChatRepository $chatRepository)
    {
        $this->chatRepository = $chatRepository;
    }

    public function findByUsers(User $user, User $contraUser) : Collection
    {
        $chat = $this->chatRepository->findByUsers($user, $contraUser);
        if ($chat = $chat->first()) {
            return $chat;
        }

        $chat = $this->chatRepository->create();
        $member = $this->chatMemberRepository->create($chat, $user);
        $contraMember = $this->chatMemberRepository->create($chat, $user);
        $returnChat = $this->chatRepository->find($chat->id);

        return $returnChat;
    }
}


texts:
I'm just after some sanity checking of this code:

public struct function defer(required function job, function onSuccess, function onFailure, function onError, function onTerminate){
    var threadId = "deferredThread_#createUuid()#";

    local[threadId] = "";

    try {
        cfthread.status = "Running";
        thread name=threadId action="run" attributecollection=arguments {
            try {
                successData.result = job();
                cfthread.status = "Completed";
                if (structKeyExists(attributes, "onSuccess")){
                    onSuccess(successData);
                }
            } catch (any e){
                cfthread.status = "Failed";
                if (structKeyExists(attributes, "onFailure")){
                    onFailure(e);
                }else{
                    rethrow;
                }
            }
        }
    } catch (any e){
        cfthread.status = "Errored";
        if (structKeyExists(arguments, "onError")){
            onError(e);
        }else{
            rethrow;
        }
    }
    return {
        getStatus = function(){
            return cfthread.status;
        },
        getThreadId = function(){
            return threadId;
        },
        terminate = function(){
            if (cfthread.status == "Running"){
                thread name=threadId action="terminate";
                cfthread.status = "Terminated";
                if (isDefined("onTerminate")){
                    onTerminate();
                }
            }
        }
    };
}

Blog article about it: "Threads, callbacks, closure and a pub", and tests and stuff on Github.

Here is a summary of that, copied from the article, and edited for length & situation:

  A week or so ago I encountered a feature proposition for CFML which
  was adding closure callback support to the following
  functions/operations so they can be processed natively in the
  background (non-blocking) and then call back when done:

  FileRead FileWrite etc

  Basically any operation that can block a network or local resource.
  Imagine doing this:

fileRead( file, function(contents){
    // process file here in the background once it is read.
});

  This is a reasonable idea in general, but I don't think the suggested
  approach is very good as it's too focused on specific pain points.

  My suggested approach would be more all-encompassing. Why limit this
  functionality to a subset of predetermined built-in functions? What
  about other built-in operations that might be slow, but otherwise
  doesn't need to interact with the rest of the code subsequent to it in
  the request? What about custom code that is similar? It makes little
  sense to me to "hard-code" this sort of behaviour to specific
  operations, to me.

  A better solution would be to provide a general mechanism that can be
  used by any code to background-thread its execution, and fire
  callbacks on completion, failure etc, so as to kick off the next
  process, or flag-up that the process has completed.

  Then it occurred to me that I thought I could knock a solution out to
  this using a single function. Not a very complete solution, but a
  solution nevertheless.


texts:
int Octet(double m, int Ax, int Ay, int Bx, int By)
{
    int octetNo = -1;
    double dx = Bx - Ax;
    double dy = By - Ay;

    //m = dy / dx;

    if(0<=m && m<=1)
    {
        if(Ax<Bx) octetNo = 1;
        else if(Bx<Ax) octetNo = 5;
    }
    else if(0>=m && m>=-1)
    {
        if(Bx<Ax)
            octetNo = 4;
        else if(Ax<Bx) octetNo = 8;
    }
    else if(m>1)
    {
        if(Ay<By) octetNo = 2;
        else if(By<Ay) octetNo = 6;
    }
    else if(-1>m)
    {
        if(Ay<By) octetNo = 3;
        else if(By<Ay) octetNo = 7;
    }

    return octetNo;
}

int NextDiIfDiIsGreaterThanOrEqualtoZero(double m, int di, int x1, int y1, int x2, int y2)
{
    int di_plus_1 = -1;
    int dx = x2 - x1;
    int dy = y2 - y1;

    int octet = Octet(m, x1, y1, x2, y2);

    switch(octet)
    {
    case 1:
    case 5:
        di_plus_1 = di - 2 * (dx - dy);
        break;
    case 2:
    case 6:
        di_plus_1 = di + 2 * (dx - dy);
        break;
    case 3:
    case 7:
        di_plus_1 = di - 2 * (dx + dy);
        break;
    case 4:
    case 8:
        di_plus_1 = di + 2 * (dx + dy);
        break;
    }

    return di_plus_1;
}

int NextDiIfDiIsSmallerThanZero(double m, int di, int x1, int y1, int x2, int y2)
{
    int di_plus_1 = -1;
    int dx = x2 - x1;
    int dy = y2 - y1;

    int octet = Octet(m, x1, y1, x2, y2);

    switch(octet)
    {
    case 1:
    case 5:
        di_plus_1 = di - 2 * dy;
        break;
    case 2:
    case 6:
        di_plus_1 = di + 2 * dx;
        break;
    case 3:
    case 7:
        di_plus_1 = di - 2 * dx;
        break;
    case 4:
    case 8:
        di_plus_1 = di + 2 * dy;
        break;
    }

    return di_plus_1;
}

int InitialValueOfDi(double m, int x1, int y1, int x2, int y2)
{
    int init_di = -1;
    int dx = x2 - x1;
    int dy = y2 - y1;

    int octet = Octet(m, x1, y1, x2, y2);

    switch(octet)
    {
    case 1:
    case 5:
        init_di = dx - 2 * dy;
        break;
    case 2:
    case 6:
        init_di = 2 * dx - dy;
        break;
    case 3:
    case 7:
        init_di = (-2) * dx - dy;
        break;
    case 4:
    case 8:
        init_di = 2 * dy + dx;
        break;
    }

    return init_di;
}

void BresLine(int x1, int y1, int x2, int y2, int color)
{
    int dy = y2 - y1;
    int dx = x2 - x1;
    double m = (double)dy/(double)dx;
    int di = InitialValueOfDi(m, x1, y1, x2, y2);
    int limit = ((abs(dx)>abs(dy))?abs(dx):abs(dy))/2;
    int x = x1;
    int y = y1;

    for(int i=0 ; i<=limit; i++)
    {
        PlotPixel(x, y, color);

        if(di>=0)
        {
            di = NextDiIfDiIsGreaterThanOrEqualtoZero(m, di, x1, y1, x2, y2);
            y++;
        }
        else
        {
            di = NextDiIfDiIsSmallerThanZero(m, di, x1, y1, x2, y2);
        }
        x++;
    }
}


texts:
This is my second Python beginner program done without help. I would like to receive comments on how clean does it look and if it can be done more efficiently.

def user_operation():
    return input('Type operation: ')

def user_number():
    """Return numbers used in operations"""
    n1 = input('First number: ')
    n2 = input('Second number: ')
    return (int(n1), int(n2))

#Operations
def add(x, y):
    a = x + y
    print ('%d + %d is %d' % (x, y, a))
def sub(x, y):
    s = x - y
    print ('%d - %d = %d' % (x, y, s))
def mult(x, y):
    m = x * y
    print('%d * %d is %d' % (x, y, m))
def div(x, y):
    d = x / y
    print ('%d / %d is %d' % (x, y, d))

def calculate():
    while True:
        n1, n2 = user_number()
        operation = user_operation()
        if operation.lower() == 'quit':
            return False

        elif operation == '1':
            add(n1, n2)
        elif operation == '2':
            sub(n1, n2)
        elif operation == '3':
            mult(n1, n2)
        elif operation == '4':
            div(n1, n2)
        else:
            print ("That is not an operation!!")

def main():
    print ("Calculator program by Jfelix\n"
           "Available operations:\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n"
           "Type their respective number to perform the selected operation\n"
           "If done with an operation, type 'back'\n"
           "Type 'quit' to end the program.\n"

        )
    calculate()

if __name__ == "__main__":
    main()


texts: Delete node from linked list, using offsetof to set the tail pointer

texts:
This is a follow on from this question - Delete node from singly linked list with tail pointer in C

I've attempted to implement node deletion using the offsetof() macro mentioned by the answerer and after a lot of debugging I found that I needed to cast my pointer to a char* in order to be able to increment or decrement by 1 byte instead of 1 whole unit. The relevant line is commented below as //(RELEVANT LINE)

Is this the correct way to go about achieve this with only one double pointer? Is there a better way, avoiding casting to char*? Have I missed some fundamental of pointer arithmetic and I just got lucky here that my code hasn't fallen over?

For reference offsetof(lrsll_node, next) is 8, sizeof(lrsll_node) is 16

typedef struct lrsll_node {
    char *data;
    struct lrsll_node *next;
} lrsll_node;

typedef struct lrsll_list {
    lrsll_node *head;
    lrsll_node *tail;
} lrsll_list;

 lrsll_node *lrsll_delete(lrsll_list *list, char *data) {
        lrsll_node **node = &list->head;
        while (*node && strcmp((*node)->data, data) != 0) {
            node = &(*node)->next;
        }
        if (*node == NULL)
            return NULL;
        lrsll_node *deleted = *node;
        *node = deleted->next;

        if (deleted == list->tail) {

            //RELEVANT LINE
            list->tail = (node == &list->head) ?
                    NULL : (lrsll_node*) ((char*)node - offsetof(lrsll_node, next));
        }

        return deleted;
    };


texts:
So basically, a user is prompted to input a number of stairs and a staircase when a guy on it is generated. I know this is sloppy and my variable names are rough, I'm actively working to change them now. I thought I would go ahead and post the working code though.

How can I improve on this? What can I do better to do more with less?

Note: I'm very new to Python and general programming.

def render(num, num3):
    num2 = num - 1
    white_space7 = ""

    white_space = ""
    for x in range(num):
        white_space = white_space + "       "
    c = num
    white_space5 = makeSpace(Num - num2)
    if num3 != 0:
        white_space7 = makeFloor(num3)
        print(white_space + "      *" + white_space5 + "*")
        print(white_space + "   o  *" + white_space5 + "*")
        print(white_space + "  /|\ *" + white_space5 + "*")
        print(white_space + "  / \ *" + white_space5 + "*")
        print(white_space + "*******" + white_space7 + "*")
    else:
        print(white_space + "      *" + white_space5 + "*")
        print(white_space + "   o  *" + white_space5 + "*")
        print(white_space + "  /|\ *" + white_space5 + "*")
        print(white_space + "  / \ *" + white_space5 + "*")
        print(white_space + "*******" + white_space7 + white_space5 + "*")

def makeSpace(num):
    white_space4 = ""
    for x in range(num):
        white_space4 = white_space4 + "       "
    return white_space4

def makeFloor(num):
    white_space6 = ""
    num4 = num + 1
    for x in range(num4):
        white_space6 = white_space6 + "*******"
    return white_space6

Num = raw_input("Number of Stairs:" )
Num = int(Num)

white_space2 = ""
for x in range(Num + 1):
    white_space2 = white_space2 + "       "
print(white_space2 + "*******")
y = Num

white_space2 = ""

for x in range(Num):
    if (x < Num - 1):
        render(y,0)
        y -= 1
    else:
        render(y,Num - 1)
        y -= 1


texts:
I have developed a jQuery slider and I want to implement it in WordPress (it will be a Featured Posts slider).

This is my slider logic:

If there are 1 or 3 posts, show them but hide the prev and next buttons.
If there are more than 3 posts but less than or equal to 6, or more than 6, show navigation.
If there are more than 6 posts, show navigation.
After the animation is finished, hide the next button.

In my code, there are a lot of if else statement. Is there a better way to write my slider?

You can look at the Fiddle and try to delete divs from container (slider and its navigation will remain functional...)

jQuery:

$(document).ready(function () {
  //If less than four divs Hide next button
  if ($('.container div').length < 4) {
    $('.next').hide();
  }
  //Also hide prev button
  $('.prev').hide();
  i = 0; //Click counter...
  $('.next').click(function () {
    //Prevent animation to mess up...
    if ($('.container').is(':animated')) {
      return false;
    }
    //Animate next click...
    $('.container').animate({
      marginLeft: '-=300'
    }, 1000, function () {
      i++; //Increase Var by One...
      // Animation Callback If there are LESS than 6 divs
      //hide next button
      if ($('.container div').length <= 6) {
        $('.next').hide();
      }
      // Else if there are more than 6 divs
      //show next button
      else if ($('.container div').length >= 6) {
        $('.next').show();
      }
      //If first click exists show prev button
      if (i == 1) {
        $('.prev').show();
      }
      //If second click exists hide next button
      else if (i == 2) {
        $('.next').hide();
      }
    });
  });
  //on prev button click
  $('.prev').click(function () {
    //Prevent animation to mess up...
    if ($('.container').is(':animated')) {
      return false;
    }
    //Run animation...
    $('.container').animate({
      marginLeft: '+=300'
    }, 1000, function () {
      i--; //Decrase number of clicks
      //If on prev click counter===0 hide prev button
      //and show next button
      if (i == 0) {
        $('.prev').hide();
        $('.next').show();
      }
      //Else if click===1 or click===0
      //Show next button
      else if (i == 1 || i == 0) {
        $('.next').show();
      }
    });
  });
});

HTML:

//If you delete those guys below //Slider and navigation will still work!!

Next

Prev


texts:
Interface for logger:

 public interface ILogger
        {
            void Log(Exception ex, string contextualMessage = "");

            void Log(string message);
        }

Interface for web job logger:

public interface IJobLogger : ILogger
{
    void SetWriter(TextWriter logWriter);
}

Web job logger:

 public class WebJobLogger : IJobLogger
    {
        private TextWriter writer;

        public WebJobLogger()
        {
            writer = TextWriter.Null;
        }

        public void SetWriter(TextWriter logWriter)
        {
            writer = logWriter;
        }

        public void Log(Exception ex, string contextualMessage = "")
        {
            writer.WriteLine("Logger: Exception thrown with message {0}, exception : {1}", contextualMessage, ex);
        }

        public void Log(string message)
        {
            writer.WriteLine("Logger: {0}", message);
        }
    }

Usage:

public async Task TestJob(
    [QueueTrigger(QueueName.StorageExcelImport)] StartImportCommand blobInfo,
    [Blob(Global.BlobContainerName + BlobReferenceName, FileAccess.Read)] Stream input,
    TextWriter logWriter)
{
    await logWriter.WriteLineAsync("Start");
    try
    {
        //Implemetation
    }
    catch (Exception ex)
    {
        //Set writer
        log.SetWriter(logWriter);
        //Log exception
        log.Log(ex);
    }
    await logWriter.WriteLineAsync(string.Format("File: '{0}' successfuly processed from blob to the database. ({1})", blobInfo.OriginalFileName, DateTime.UtcNow));
}

Dependency injection:

container.Register<ILogger, WebJobLogger>();

The problem with this is that I always have to call log.SetWriter(logWriter); before call  log.Log(ex);. If I forget that, then will not work. The whole point of this is to mock logger in unit test. What do you think?


texts:
I am attempting to create a Linked List where someone can enter in some movie titles and their rating for it. Here is what I have thus far:
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define TITLE_MAX 50
void mygets(char buffer[], size_t limit);

// linked list
struct film {
    char title[TITLE_MAX];
    int rating;
    struct film *next;
};

int main(void)
{
    struct film *head = NULL, *current = NULL;
    char tbuffer[TITLE_MAX];

    while (true)
    {
        printf("Enter the name of the film (empty line to stop)\n");
        mygets(tbuffer, TITLE_MAX);
        if (*tbuffer=='\0') break;

        if (!head)
            current = head = malloc (sizeof(struct film));
        else
            // assignment associates right-to-left so can do this trick
            current = current->next = malloc (sizeof(struct film));

        current->next = NULL;
        strcpy(current->title, tbuffer);
        printf("Now enter in your rating for it: ");
        scanf("%d", &(current->rating));
        for (int c; (c=getchar()) != '\n' && c != EOF; ); // clean up garbage in scanf -- should probably write a function for this
    }

    // print the Linked List
    current = head;
    for (int i=1; current != NULL; current=current->next)
        printf("Linked List Item #%d: %s (Rating: %d)\n",
                i++, current->title, current->rating
        );

    for(struct film *current=head, *next; current != NULL; current=next) {
        next = current->next;
        free(current);
    }

}

void mygets(char buffer[], size_t limit)
{
    // first non-space char until newline or EOF,
    // eating any extra chars in buffer
    // will add \0 at the end, so will get up to N-1 chars

    int c, idx=0;
    bool started=false;
    while ((c=getchar()) != EOF && c != '\n')
    {
        if (!started && isspace(c));
        if (idx < limit-1)
            buffer[idx++] = c;
    }
    buffer[idx] = '\0';

}

How does it look so far? What can be improved? Additionally, in real-world implementations of a linked list, what sort of additional metadata is stored -- for example, things like List Size and such.
Also, how does the free look in there. For a linked list does it matter which direction I free the data?


texts:
Due to some clueless soul, we have several fields in a legacy database that uses a 6-digit integer to represent a date in (YYYYmm) format. The date field is assumed to be the last day of the given month.

I have written the following method to perform the conversion from int to java.util.Date:

public Date convertIntToDate(Integer intDate) {

    if (intDate < 100000 || intDate > 999999) {
        log.warn("Unable to parse int date {}", intDate);
        return null;
    }

    int intYear = intDate/100;
    int intMonth = intDate - (intYear * 100);

    Calendar result = new GregorianCalendar();
    result.set(intYear, intMonth - 1, 1, 0, 0, 0);

    return result.getTime();
}

It seems to work, but if anyone has any suggested improvements, I'd love to hear them.


texts:
If I have a number of different classes which manage certain tests. At the moment I have to launch each test individually which results in a lot of if statements.

I wonder if there is a way of putting all of these in a loop to manage the launching of each test and retrieving of results more cleanly.  Does anyone have any advice? Can anyone improve on this? Is this use of classes optimal (I'm not a professional programmer)?

class Engine(object):
    """Class that holds information about the
tests relevant to the engine"""

    def __init__(self):
        self.run = True # Flag to run the test or not
        self.kg = 20.5 # Some information required by this test
        self.ok = 'Not run' # Final result to say if the test was passed

class Wheels(object):
    """Class that holds information about the
tests relevant to the wheels"""

    def __init__(self):
        self.run = True
        self.number = 4
        self.ok = 'Not run'

class Door(object):
    """Class that holds information about the
tests relevant to the doors"""

    def __init__(self):
        self.run = True
        self.colour = 'red'
        self.ok = 'Not run'

class Car(object):
    """Class that holds information about the
different tests available"""

    def __init__(self):
        self.engine = Engine()
        self.wheels = Wheels()
        self.door = Door()

motor = Car()

if motor.engine.on is True:
    import engine_tests # An external file containing everything about engine tests
    motor.engine.ok = engine_tests.launch(weight=motor.engine.kg) # Return success/failure of tests

if motor.wheels.on is True:
    import wheel_tests
    motor.wheels.ok = wheel_tests.launch(nwheels=motor.wheels.number)

if motor.door.on is True:
    import door_tests
    motor.door.ok = door_tests.launch(shading=motor.door.colour)

print 'Tests completed'
print 'Engine: ', motor.engine.ok
print 'Wheels: ', motor.wheels.ok
print 'Door: ', motor.door.ok


texts: Helper class for ASP.net to return data from SQL server

texts:
My goal is to create a class that I can call from my webpages like this. Similar to a data access layer?

string sql = "SELECT EMPLOYEE_ID, FIRST, LAST, HIRE_DATE " +
             "FROM EMPLOYEES ";
DataTable dtEmployees = SqlConnectionHelpers.TimeManagementDataTable(sql);

The class itself looks like this and is working so far (it's in the AppCode, folder on my website), but my boss has me questioning whether it will work in all cases or with a bunch of users accessing the webpages.

public static class SqlConnectionHelpers
{
    private static SqlConnection timeManagementCon= new SqlConnection("Data Source=XXX.XXX.XXX.XXX\\TM;Initial Catalog=TimeManagement;User ID=payroll;Password=*****");

    #region TimeManagement
    public static DataTable TimeManagementDataTable(string sql)
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter(sql, SqlConTimeManagement());
        adapter.Fill(dt);
        return dt;
    }

    public static string TimeManagementCommand(string sql)
    {
        SqlCommand command = new SqlCommand(sql, SqlConTimeManagement());

        var result = command.ExecuteScalar();

        if (result != null)
            return result.ToString();
        else
            return "Success";
    }

    private static SqlConnection SqlConTimeManagement()
    {
        if (timeManagementCon.State == ConnectionState.Open)
            return timeManagementCon;
        else
            timeManagementCon.Open();
        return timeManagementCon;
    }
    #endregion
}

So my questions are

Is this thread safe? This is a word that comes up a lot when I was
looking  into this problem. Say 10 people have this open in 10
different tabs, are they all accessing the same static page? If so
does this cause issues with multiple people trying to grab the same
connection concurrently?
Does this cost a lot of needless overhead, when I could just code it
every time I needed it?
Is this bad practice? If so how can I fix it?


texts: Declaring JavaScript variable and then overwriting it multiple times

texts:
I'm wondering if I am doing this in the most efficient way.

So I'm declaring my function el which is equal to a macro (Google Tag Manager), then I reassign or overwrite that previously-defined var which grabs the innerText/textContent of the element.  It then converts the string to lowerCase and then capitalizes the first letter of the string, before finally returning the 'cleaned-up' element.

   function() {
      var el = {{element}}
      el = (el.innerText || el.textContent);
      el = el.toLowerCase();
      el = el.charAt(0).toUpperCase() + el.slice(1);

      return el;

    }


texts: command-line binary/hex conversion program in python

texts:
I'm just learning the ropes to programming, so bear with me here. I wanted a simple command-line program to quickly convert decimal numbers into either binary or hexadecimal. This is what I came up with, but I know it can be improved.
while True:
    while True:
        conv_type = input("Hexadecimal or Binary?: ").lower()
        if "b" not in conv_type and "h" not in conv_type:
            print("Invalid Input")
            continue
        else:
            break

    while True:
        try:
            dec_num = int(input("Decimal Number: "))
        except ValueError:
            print("Invalid Input")
            continue
        break

    if "h" in conv_type:
        print("   ", dec_num, "=", hex(dec_num), "in hexadecimal")

    if "b" in conv_type:
        print("   ", dec_num, "=", bin(dec_num).replace("0b", ""), "in binary")

How would you improve this? I feel a bit weird using three while True loops in the same program, but I couldn't think of a better solution on the fly. Any feedback is greatly appreciated!


texts:
I was hoping that someone could review this code.

My main concern is that the contents of main() are difficult to read. I thought about extracting some segments of code into functions (to aid comprehension) but it felt unnecessary because these segments are not completely repeated.

#include <SFML/Graphics.hpp>
#include <random>

// Maps input in the range [0..1] to an output in the range [0..1].
// Represents the piecewise function:
// y(x) = 2*x^2             when x < 0.5
//      = -2*x^2 + 4*t - 1  when x >= 0.5
float easeInOutQuad(float normalisedTime)
{
  auto & t = normalisedTime;
  return t < 0.5 ? 2*t*t : 2*t*(2 - t) - 1;
}

struct Tween
{
  float begin;
  float change;
  float time{0};
  float duration;
  float current() const
  {
    return begin + change*easeInOutQuad(time/duration);
  }
};

int main()
{
  sf::RenderWindow window{sf::VideoMode{500, 500}, "Snow"};
  auto const inverseFramerate = 1.f/60;
  window.setFramerateLimit(static_cast<unsigned>(1/inverseFramerate));
  auto const numberOfSnowflakes = 200;
  Tween tweens[numberOfSnowflakes];
  float yPositions[numberOfSnowflakes];
  auto generator = std::mt19937{};
  // Returns a normally distributed random number.
  auto randomChangeInX = [&generator]()
  {
    static auto distribution = std::normal_distribution<float>{0.f, 10.f};
    return distribution(generator);
  };
  // Returns a uniformly distributed random number in the range [min..max).
  auto randomBetween = [&generator](float min, float max)
  {
    return std::generate_canonical<float, 10>(generator)*(max - min) + min;
  };
  for (auto i = 0; i < numberOfSnowflakes; ++i)
  {
    tweens[i].begin = randomBetween(0, window.getSize().x);
    tweens[i].change = randomChangeInX();
    tweens[i].duration = randomBetween(1, 5);
    yPositions[i] = randomBetween(-20, window.getSize().y);
  }
  auto const defaultRadius = 5.f;
  auto circle = sf::CircleShape{};
  while (window.isOpen())
  {
    auto event = sf::Event{};
    while (window.pollEvent(event))
    {
      if (event.type == sf::Event::Closed)
      {
        window.close();
      }
    }
    for (auto i = 0; i < numberOfSnowflakes; ++i)
    {
      tweens[i].time += inverseFramerate;
      if (tweens[i].time > tweens[i].duration)
      {
        tweens[i].begin += tweens[i].change;
        tweens[i].change = randomChangeInX();
        tweens[i].time = 0;
      }

      yPositions[i] += 1/tweens[i].duration;
      if (yPositions[i] > window.getSize().y)
      {
        yPositions[i] = -defaultRadius*2;
        tweens[i].begin = randomBetween(0, window.getSize().x);
        tweens[i].change = randomChangeInX();
        tweens[i].time = 0;
      }
    }
    window.clear();
    for (auto i = 0; i < numberOfSnowflakes; ++i)
    {
      circle.setPosition(tweens[i].current(), yPositions[i]);
      circle.setRadius(defaultRadius/tweens[i].duration);
      window.draw(circle);
    }
    window.display();
  }
}


texts:
I have a tv show I created a MySQL database for. I am trying to get my code to group and order correctly the seasons and episodes within their respective season.

Current Code

if (!($result = mysql_query("SELECT season_num, sub_season_num, esp_num, title, descrip FROM season ORDER BY season_num, sub_season_num", $link))) showerror();
$season_one = 1;
$season_two = 2;
echo "Season 1
";
while ($row = mysql_fetch_array($result))
{
if(season_num !== $season_one){
echo "Episode {$row["esp_num"]}
";
echo "Title {$row["title"]}
";
echo "Description {$row["descrip"]}
";
}}
echo "Season 2
";
while ($row = mysql_fetch_array($result))
{
if(season_num !== $season_two){
echo "Episode {$row["esp_num"]}
";
echo "Title {$row["title"]}
";
echo "Description {$row["descrip"]}
";
}}
?>

Example
Season 1
Eps 1
Eps 2
Eps 3
Season 2
Eps 1
Eps 2
Ect..

Any code help would be greatly appreciated.


texts: Looping Strategy: Change behaviour after first iteration

texts:
I have often encountered the following situation. I want to call a method in a Loop, but want to skip the call at the first run. It do not have to be a method, it also can be some lines of code that I want to skip. Here is one example:

I have a file which looks like that.

headline:headline1
content:lorem ipsum dolor sit amet
content2:lorem ipsum dolor sit amet
content3:lorem ipsum dolor sit amet
headline:headline2
content1:lorem ipsum dolor sit amet
.
.
.

I iterate through the lines and generate following html:

 headline1

 lorem ipsum dolor sit amet

 lorem ipsum dolor sit amet

 lorem ipsum dolor sit amet

 headline2

 lorem ipsum dolor sit amet

  .
  .
  .

My Code looks like that:

private String createList(String file) {
        StringBuilder output = new StringBuilder();
        String[] lines = file.split("\n");

        int headlineCounter = 0;
        for (String line : lines) {
            String[] fields = line.split(":");
            if (fields[0].equals("headline")) {
                if (headlineCounter > 0) {
                    output.append("
");
                }
                output.append("
").append(fields[1]).append("
");
                output.append("
");
                headlineCounter++;
            } else {
                output.append("
").append(fields[1]).append("
");
            }
        }
        output.append("
");
        return output.toString();
    }

The content always is wrapped with an
 tag. When a new headline appears the content of the last headline is at the end and has to be closed with
 except it's the first headline of course, because there is no content before, that has to be closed.

In my example I am using a counter. On this way it works, but there are other and better ways I think. How would you solve this problem? This is just an example there are of course other and better ways to generate html, I just wanted to show you an example to my question.


texts:
The data bellow shows part of my dataset, that is used to detect anomalies

    describe_file   data_numbers    index
0   gkivdotqvj      7309.0          0
1   hpwgzodlky      2731.0          1
2   dgaecubawx      0.0             2
3   NaN             0.0             3
4   lnpeyxsrrc      0.0             4

I used One Class SVM algorithm to detect anomalies

from pyod.models.ocsvm import OCSVM
random_state = np.random.RandomState(42)
outliers_fraction = 0.05
classifiers = {
        'One Classify SVM (SVM)':OCSVM(kernel='rbf', degree=3, gamma='auto', coef0=0.0, tol=0.001, nu=0.5, shrinking=True, cache_size=200, verbose=False, max_iter=-1, contamination=outliers_fraction)
}

X = data['data_numbers'].values.reshape(-1,1)

for i, (clf_name, clf) in enumerate(classifiers.items()):
    clf.fit(X)
    # predict raw anomaly score
    scores_pred = clf.decision_function(X) * -1

    # prediction of a datapoint category outlier or inlier
    y_pred = clf.predict(X)
    n_inliers = len(y_pred) - np.count_nonzero(y_pred)
    n_outliers = np.count_nonzero(y_pred == 1)

    # copy of dataframe
    dfx = data[['index', 'data_numbers']]
    dfx['outlier'] = y_pred.tolist()
    IX1 =  np.array(dfx['data_numbers'][dfx['outlier'] == 0]).reshape(-1,1)
    OX1 =  dfx['data_numbers'][dfx['outlier'] == 1].values.reshape(-1,1)
    print('OUTLIERS : ',n_outliers,'INLIERS : ',n_inliers, clf_name)
    # threshold value to consider a datapoint inlier or outlier
    threshold = stats.scoreatpercentile(scores_pred,100 * outliers_fraction)

tOut = stats.scoreatpercentile(dfx[dfx['outlier'] == 1]['data_numbers'], np.abs(threshold))

y = dfx['outlier'].values.reshape(-1,1)
def severity_validation():
    tOUT10 = tOut+(tOut*0.10)
    tOUT23 = tOut+(tOut*0.23)
    tOUT45 = tOut+(tOut*0.45)
    dfx['test_severity'] = "None"
    for i, row in dfx.iterrows():
        if row['outlier']==1:
            if row['data_numbers'] <=tOUT10:
                dfx['test_severity'][i] = "Low Severity"
            elif row['data_numbers'] <=tOUT23:
                dfx['test_severity'][i] = "Medium Severity"
            elif row['data_numbers'] <=tOUT45:
                dfx['test_severity'][i] = "High Severity"
            else:
                dfx['test_severity'][i] = "Ultra High Severity"

severity_validation()

from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(dfx[['index','data_numbers']], dfx.outlier, test_size=0.25,
                                                    stratify=dfx.outlier, random_state=30)

#Instantiate Classifier
normer = preprocessing.Normalizer()
svm1 = svm.SVC(probability=True, class_weight={1: 10})

cached = mkdtemp()
memory = Memory(cachedir=cached, verbose=3)
pipe_1 = Pipeline(steps=[('normalization', normer), ('svm', svm1)], memory=memory)

cv = skl.model_selection.KFold(n_splits=5, shuffle=True, random_state=42)

param_grid = [ {"svm__kernel": ["linear"], "svm__C": [0.5]}, {"svm__kernel": ["rbf"], "svm__C": [0.5], "svm__gamma": [5]} ]
grd = GridSearchCV(pipe_1, param_grid, scoring='roc_auc', cv=cv)

#Training
y_pred = grd.fit(X_train, Y_train).predict(X_test)
rmtree(cached)

#Evaluation
confmatrix = skl.metrics.confusion_matrix(Y_test, y_pred)
print(confmatrix)
Y_pred = grd.fit(X_train, Y_train).predict_proba(X_test)[:,1]
def plot_roc(y_test, y_pred):
    fpr, tpr, thresholds = skl.metrics.roc_curve(y_test, y_pred, pos_label=1)
    roc_auc = skl.metrics.auc(fpr, tpr)
    plt.figure()
    lw = 2
    plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area ={0:.2f})'.format(roc_auc))
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic example')
    plt.legend(loc="lower right")
    plt.show();
plot_roc(Y_test, Y_pred)

The code works just fine, however it just takes too long so I am hoping to maybe get some advice to optimize is so I runs faster.


texts: Running parallel tasks until they're done

texts:
The General Idea

I wish to simulate something which works like Java's ThreadExecutor, but as a first step, I would like to run a fixed number of identical tasks in parallel.
The next step should be queuing different tasks.

The method in question

public static async Task RunTasks(Func<Task<bool>> action, int tasks, int retries, string method)
{
    // Its just a source in order to use the library.
    byte[] source = new byte[tasks];

    // Wrapping the method with a retry mechanism
    async Task NewAction(byte _)
    {
        await DoWithRetries(async () => await action(), retries, method);
    }

    // Running everything
    await source.ParallelForEachAsync(NewAction, tasks);
}

private static async Task<bool> DoWithRetries(Func<Task<bool>> action, int retryCount, string method)
{
    while (true)
    {
        if (retryCount <= 0)
            return false;

        try
        {
            bool res = await action();
            if (res)
                return true;
        }
        catch (Exception e)
        {
            LogFactory.General.Fatal(e, method);
        }

        retryCount--;
        await Task.Delay(200);
    }
}

External Libraries

I used the AsyncEnumerator Nuget (which allows the ParallelForEachAsync call)

Code Execution

int page = -1;
int tasks = 10;
long count = 0;

await RetryComponent.RunTasks(async () =>
{
    int localPage = Interlocked.Increment(ref page);
    int results = -1;

    while (results != 0)
    {
        Console.WriteLine($"Page: {localPage}");

        // req.IsSuccess holds if the request processed well
        // mData contains the data returned from db (List)
        var req = await FetchSomeListFromDb();
        if (!req.IsSuccess)
            continue;

        foreach (var item in req.mData)
        {
            // simluate some IO..
            Interlocked.Increment(ref count);
        }

        // shuts down if zero
        results = req.mData.Count;

        // next page
        localPage = Interlocked.Increment(ref page);
    }

    return true;

}, tasks, 1, MethodBase.GetCurrentMethod().Name);

The issues I have with this code:

It seems like someone 100% did it already in the past, but I couldn't find anything like that or like the Java's ThreadsExecutor I mentioned
It seems like the execution code (The code I used to run everything) is large and seems like it will repeat itself..especially the page increment and the while handling (the last 2 statements at the end of the while block)

I will be glad to get a feedback on it or suggestions if the code exists somewhere (Either my implemetation or something similar to Java's ThreadsExecutor)


texts:
In my current project I have objects of the following structure:

CanvasBundle - Object

Some elements...
gridCanvas
axesCanvas
functions[] (contains unknown number of functionCanvases)
overlayCanvas

I'd like to write an iterator which would iterative over all the canvases (grid/axes/func/func1/func2/.../overlay).

I've currently implemented it like this:

function makeCanvasBundleIterator(canvasBundle) {
  var nextIndex = 0;
  var functionIndex = 0;

  return {
    next: function() {
      var value;

      switch (nextIndex) {
      case 0:
        value = canvasBundle.grid;
        break;
      case 1:
        value = canvasBundle.axes;
        break;
      case 2:
        value = canvasBundle.functions[functionIndex];
        break;
      case 3:
        value = canvasBundle.overlay;
        break;
      default:
        break;
      }

      if (nextIndex != 2 || functionIndex == canvasBundle.functions.length -1) {
        nextIndex++;
      } else {
        functionIndex++
      }

      return nextIndex <= 4 ?
        {value: value, done: false} :
        {done: true};
    }
  };
}

This allows me to do the following:

var it = makeCanvasBundleIterator(canvasBundle);

var next;
while (!(next = it.next()).done) {
  console.log(next.value);
}

Coming from C, this code does not look clean at all. Since I'm a real JS beginner, I'd like a review with suggestions/advice how I can clean it up. Maybe there even is a completely different/better approach.


texts:
I'm trying to write as simple I/O library in x64 using linux syscalls

section .text
strlen:
  xor rdx, rdx
  .loop:
  cmp [rsi + rdx], 0
  je .exit
  inc rdx
  jmp .loop
  .exit:
  ret ; value in rdx

puts:
  ; string passed through rsi
  mov rax, 1
  call strlen
  syscall


texts: Calculating minima values for each column of given data

texts:
Can anyone help make this perform faster?

import numpy as np
from scipy import signal

d0 = np.random.random_integers(10, 12, (5,5))
d1 = np.random.random_integers(1, 3, (5,5))
d2 = np.random.random_integers(4, 6, (5,5))
d3 = np.random.random_integers(7, 9, (5,5))
d4 = np.random.random_integers(1, 3, (5,5))
d5 = np.random.random_integers(13, 15, (5,5))

data = np.array([d0,d1,d2,d3,d4,d5])  ####THIS SHAPE IS GIVEN, WHICH CAN NOT BE CHANGED.
data = data.reshape(6,25)

data = data.T
minimas=[]
for x in data:
    minima = signal.argrelmin(x, axis=0)
    minimas.append(x[minima])

print minimas    ####THIS SHAPE IS GIVEN, WHICH CAN NOT BE CHANGED.


texts: Function outcome: consistent approach and easy logging

texts:
My goal is to make a consistent and easy way to determine how a function fails/succeeds. I'm looking for code review of my Status class for any bad practices, code that isn't thread-safe and general improvements and changes.

For logging and debugging I always needed to know how a function failed and print this out as readable text. The solution I usually employed was using enumerations - enum ERROR_CODE {..}; - which is fine except they cannot be expanded/overridden - I'm making an API so enums don't allow the user to expand/add custom error codes. They also don't print out nicely to describe what error actually occurred - they just print out as numbers. So I made a status class.

Main features:

Allows creation of error/states wherever & whenever (runtime, compile time):

static const Status S_SUCCESS         = CStatus::registerState("Success");
static const Status S_EMPTY_CONTAINER = CStatus::registerState("Empty rectangle vectors");

General usage:

Status unionRectangles(const vector<Rect>& left, vector<Rect>& right)
{
  if (left.size() <= 0 || right.size() <= 0)
     return S_EMPTY_CONTAINER;

  ...

  return S_SUCCESS;
}

Print out descriptive errors without requiring conversion:

vector<Rect> v1, v2;
Status myStatus = unionRects(v1, v2)
cout << myStatus << end; // "Empty rectangle vectors"

Easily and efficiently compare objects without conversion:

if (myStatus == S_SUCCESS) // for eg; resolves to if (1 == 9), ie, not string comparison
    // do something

Easy to inline check error:

if (!unionRects(v1, v2))
    // do something

Full implementation:

#ifndef STATUS_H
#define STATUS_H

#include <iostream>
#include <hash_map>

typedef int STATE;
typedef std::hash_map<STATE, tstring>::iterator StateIterator;
typedef class CStatus;
typedef const CStatus Status;

#ifndef S_SUCCESS
#define S_SUCCESS CStatus::CS_SUCCESS
#endif // S_SUCCESS

#ifndef S_UNDEFINED_ERROR
#define S_UNDEFINED_ERROR CStatus::CS_UNDEFINED_ERROR
#endif // S_SUCCESS

class CStatus
{
public:
    // Static Properties//
    static Status CS_SUCCESS;
    static Status CS_UNDEFINED_ERROR;

    // Static Functions //
    static Status registerState(const tstring &stateMsg)
    {
        // Post:

        int nextStateTmp = nextState + 1;
        std::pair<StateIterator, BOOL> res = states.emplace(std::make_pair(nextStateTmp, stateMsg));

        // if state has been inserted
        if (res.second)
            return Status(++nextState);

        // return existing state id
        return Status(res.first->first);
    }

    // Properties //
    const STATE state;

    // Functions //
    CStatus(const STATE &state)  : state(state) {}
    virtual ~CStatus() {}

    const tstring& toString() const
    {
        return (states.find(state) == states.end()) ? states[state] : _T("Undefined");
    }

    operator tstring() const
    {
        return toString();
    }

    operator int() const
    {
        return state;
    }

    bool operator==(const CStatus& obj) const
    {
        return state == obj.state;
    }

    bool operator!=(const CStatus& obj) const
    {
        return state != obj.state;
    }

    bool operator!() const
    {
        return *this != S_SUCCESS;
    }

    std::ostream& operator <<(std::ostream &stream, const CStatus& obj)
    {
        return stream << obj.toString().c_str();
    }

    friend std::ostream& operator<<(std::ostream& stream, const CStatus& obj);

private:
    static std::hash_map<STATE, tstring> states;
    static STATE nextState;

protected:

};

//static Status S_SUCCESS         = CStatus::registerState(_T("Success"));
//static Status S_UNDEFINED_ERROR = CStatus::registerState(_T("Undefined Error"));

#endif // STATUS_H


texts: Finding an index in an array of objects with 3 possible outcomes

texts:
currentUserPosts will have a post object with an id that either matches a tempId, an Id, or nothing.

If there's a tempId match there won't be an id match and vice versa.

This code works but there's something about it I don't like. How can it be refactored?

let postIndex;
postIndex = currentUserPosts.findIndex(post => post.id === upsertParams.tempId);
if (postIndex === -1) {
  postIndex = currentUserPosts.findIndex(post => post.id === upsertParams.id);
}
if (postIndex === -1) {
  currentUserPosts.push(upsertParams);
} else {
  currentUserPosts[postIndex] = upsertParams;
}

Complete function:

const upsertIntoApolloCache = (upsertParams) => {
  try {
    const data = client.readQuery({
      query: USER_POSTS_QUERY,
    });
    const currentUserPosts = data.currentUser.posts;

    const postIndex = currentUserPosts.findIndex(
      post => post.id === upsertParams.tempId || post.id === upsertParams.id
    );
    if (postIndex === -1) {
      currentUserPosts.push(upsertParams);
    } else {
      currentUserPosts[postIndex] = upsertParams;
    }

    client.writeQuery({
      query: USER_POSTS_QUERY,
      data,
    });
  } catch (error) {
    console.log('!!ERROR in upsertIntoApolloCache!!', error);
  }
};


texts: Project Euler Problem 6: sum of squares and square of sums

texts:
This is a very simple task, but I'm curious if there is a better, more 'Pythonic' way to solve this.

"""The sum of the squares of the first ten natural numbers is,

1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)^2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers
and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural
numbers and the square of the sum."""

square = 0
s = 0

for i in range(1, 101):
    square += i**2
    s += i

s = s**2

print(s - square)


texts:
I'm timing out on Codewars' Prime Streaming kata. Below is my code:

"use strict";

let _base = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71];
let _bufferSize = 1000

class Primes {
   static get base() {
      return _base;
   }

   static get bufferSize() {
      return _bufferSize;
   }

   static set bufferSize (value) {
      _bufferSize = value;
   }

   static sieve(array) {
      for (let p of Primes.base) {
         array = array.filter(n => n % p !== 0);
      }
      return array;
   }

   static sieve_2(array) {

   }

   static * stream() {
      const candidates = [];
      for (let i = 73; i < 5001; i += 2)
         candidates.push(i);
      Primes.base.push(...Primes.sieve(candidates));
      const buffer = Primes.base.slice();

      while (true) {
         let current;
         while (buffer.length > 0) {
            current = buffer.shift();
            yield current;
         }
         let [lower, upper] = [current + 2, current + Primes.bufferSize];
         let basket = [];
         for (let i = lower; i <= upper; i += 2)
            basket.push(i);
         buffer.push(...Primes.sieve(basket));
      }
   }
}

As far as I can tell, changing the buffer size affected nothing. I first generate primes less than 5001 because their upper bound on primes they test is somewhere below 16 million, and I wasn't enthused about doing the investigation work to find a precise bound, so I just went with a loose one.


texts: Refactor Ruby method for getting domain?

texts:
How do I make this more Ruby like? I want to return the host, for example
if the URL is "http://www.facebook.com" then I want to get 'facebook.com'.

Any other sub-domains without 'www' should give the subdomin as well.
If  the URL is "http://gist.github.com" then I want 'gist.github.com':

def get_domain
  a = @url.split('.')
  a[-1] =  a[-1].gsub(/\//,'')
  if a[0][-3..-1] == "www"
    a.delete_at(0)
  else
    a[0] = a[0].gsub(/https?:\/\//,'')
  end
  domain = a.join('.')
  domain
rescue => e
  puts e.message
end #end of get_domain


texts:
Here is a simple calculator for calculating the tax and tip of a transaction. I have tried to add input verification. I am wondering if there are more elegant ways of doing some simple tasks that are required for this calculator, such as getting the total. Are my naming conventions correct, function use correct, variable (tax) convention correct (should it be static somewhere else?), and clearing/updating of fields as input is being entered into the form. Thank you!!

''' <summary>
''' Author:    Brandon Finley
''' Date:      10/5/2017
''' Purpose:   Calculate the tax and tip of a sale.
''' Status:    Works as intended. I tried to be as clear and consistant as possible.
''' </summary>

Public Class MainForum
    Dim tax As Double = 0.08

    ' Validates and updates tax and total boxes in dollar value.
    Private Sub CalcButton_Click(sender As Object, e As EventArgs) Handles CalcButton.Click
        If PriceBox.Text.Trim = "" Then
            ' If the PriceBox is empty, a value that isn't a number, or negative move cursor to PriceBox and give user reason.
            MsgBox("Enter a price.",
            MsgBoxStyle.Information, "Missing Information")
            PriceBox.Focus()
        ElseIf IsNumeric(PriceBox.Text) = False Then
            MsgBox("Must enter a number.",
            MsgBoxStyle.Information, "Verify")
            PriceBox.Focus()
        ElseIf PriceBox.Text < 0 Then
            MsgBox("Please enter a positive value into the Price field.",
            MsgBoxStyle.Information, "Verify")
            PriceBox.Focus()
        Else
            TaxBox.Text = Format(GetTax(), "currency")
            TotalBox.Text = Format(CalcTotal(), "currency")
        End If
    End Sub

    ' Returns the tax based on the tax multiplied by the price.
    Function GetTax() As Double
        Return PriceBox.Text * tax
    End Function

Private Function GetTip(PercentTip As GroupBox) As Double
    For Each ctrl As RadioButton In PercentTip.Controls
        If ctrl.Checked Then Return PriceBox.Text * (Microsoft.VisualBasic.Left(ctrl.Text, 2) / 100)
    Next
End Function

        ' Returns the total sales formatted to look like currency.
Private Function GetTotal(IsTipPercent As Boolean) As String
    ' Radio buttons do not return total until CalcButton has been pressed.
    If IsTipPercent = False Or (IsTipPercent = True And TotalBox.Text <> "") Then
        Return Format(CalcTotal(), "currency")
    End If
End Function

' Returns the total of price + tax + tip.
Private Function CalcTotal() As Double
    Return PriceBox.Text + GetTax() + GetTip()
End Function

' Updates price if tip amount changes (only after calculating total first).
' Updates price if tip amount changes (only after calculating total first).
Private Sub Tip15_CheckedChanged(sender As Object, e As EventArgs) Handles Tip15.CheckedChanged, Tip20.CheckedChanged, Tip25.CheckedChanged
    TotalBox.Text = GetTotal(True)
End Sub

    ' Clears the tax and tip fields if original price has been changed. bump
    Private Sub PriceBox_TextChanged(sender As Object, e As EventArgs) Handles PriceBox.TextChanged
        If TotalBox.Text <> "" And PriceBox.Text.Trim <> "" Then
            TaxBox.Text = ""
            TotalBox.Text = ""
        End If
    End Sub

    ' Exits application.
    Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
        Me.Close()
    End Sub

End Class


texts: Determine whether path A→B→C on a plane constitutes a left or right turn

texts:
I have recently started learning functional programming and Haskell. I have encountered this problem:

  Consider three two-dimensional points a, b, and c. If we look at the angle formed by the line segment from a to b and the line segment from b to c, it either turns left, turns right, or forms a straight line. Define a Direction data type that lets you represent these possibilities. Write a function that calculates the turn made by three 2D points and returns a Direction.

I have heard that one of the goals of the Haskell language is to create elegant solutions.

This is my solution:

data Direction = LeftTurn | RightTurn | Straight deriving Show

findDirection (x, y) (x1, y1) (x2, y2)
    | (x, y) == (x1, y1)          = Straight
    | (x1, y1) == (x2, y2)        = Straight
    | (x, y) == (x2, y2)          = Straight
    | x == x1 && x1 == x2         = Straight
    | x1 == x && y1 > y && x2 > x = RightTurn
    | x1 == x && y1 > y && x2 < x = LeftTurn
    | x1 == x && y1 < y && x2 < x = RightTurn
    | x1 == x && y1 < y && x2 > x = LeftTurn
    | x1 > x && y2 > y_on_line    = LeftTurn
    | x1 > x && y2 < y_on_line    = RightTurn
    | x1 > x && y2 == y_on_line   = Straight
    | x1 < x && y2 > y_on_line    = RightTurn
    | x1 < x && y2 < y_on_line    = LeftTurn
    | x1 < x && y2 == y_on_line   = Straight
   where y_on_line   = slope * x2 + y_intercept
         slope       = (y1 - y) / (x1 - x)
         y_intercept = y - slope * x

This looks like it is too long to be considered an elegant solution.


texts:
I fetch a bunch of categories for a DropDown tree, and have to implement search in this dropdown. If there is a match in one of the elements, it should also get all parents to display in the dropdown hierarchy. The number of childnodes is unknown, and can be changed at any given time (example has only 3 levels but can be 5 also).

The search applies on every ScrapCategory description.

I get the expected result but I would love to see this in \$O(N)\$.

public sealed class ScrapCategory
{
    public int Id { get; set; }

    public bool IsActive { get; set; }

    public string Description { get; set; }

    public int Level { get; set; }

    public int ParentId { get; set; }
}

public ScrapCategory[] Filter(ScrapCategory[] categories, string searchString)
{
    var result = new List<ScrapCategory>();

    foreach (ScrapCategory category in categories)
    {
        if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
            result.Add(category);

        if (category.ParentId > 0)
        {
            int parentId = category.ParentId;

            while (parentId > 0)
            {
                var parent = categories.Where(x => x.Id == parentId)?.First();
                if (!result.Contains(parent))
                    result.Add(parent);
                parentId = parent.ParentId;
            }
        }
    }

    return result.OrderBy(x => x.Level).ToArray();
}


texts:
I have a Timer:

var QueryReportTimer = new Timer(QueryReportTimerCallback, null, TimeSpan.Zero, TimeSpan.FromSeconds(15));

The important part here is the method QueryReportTimerCallback.

I have a few doubts here:

Is it ok to have an async void method? In general it is not, but how can I avoid this when the timer callback is delegate public delegate void TimerCallback(object state);?
Is it ok to have await inside Parallel.ForEach?

Method QueryReportTimerCallback:

private async void QueryReportTimerCallback(object state)
{
    if (await semaphoreQueryReportSlim.WaitAsync(10))
    {
        try
        {
            if (machineConfigurations != null)
            {
                await Task.Factory.StartNew(() =>
                    Parallel.ForEach(machineConfigurations.Where(x => x.QueryReport), async (configuration) =>
                    {
                        if (configuration.IsConnectionValid)
                        {
                            var queryReport = new QueryReport(configuration, ReportConfigurations, fileContainer, applicationConfiguration, logger);
                            await QueryAReport(configuration, queryReport);
                        }
                    })
                );
            }
        }
        catch (Exception e)
        {
            logger.LogError(e, e.Message);
        }
        finally
        {
            semaphoreQueryReportSlim.Release();
        }
    }
}


texts: Merge values of the objects properties with the same name into array

texts:
I have such input:

[ { name: 'timezone', value: 'EST' },
  { name: 'interval', value: 'day' },
  { name: 'metrics[]', value: 1},
  { name: 'metrics[]', value: 2} ]

As you may already notice - these are parameters from POST request.

What I need to do is to get such output:

[ { name: 'timezone', value: 'EST' },
  { name: 'interval', value: 'day' },
  { name: 'metrics[]', value: [ 1, 2 ] },
  { name: 'metrics[]', value: [ 1, 2 ] } ]

My code does everything it needs to do, but I'm not sure if it is written in the optimal way, am I overlooking some bugs, etc.

arrayify = (params) ->
  arrayifiedParams = {}

  for param in params
    paramName = param.name

    arrayifiedParams[paramName] = arrayifiedParams[paramName] || []
    arrayifiedParams[paramName].push param.value

  params.map (param) ->
    paramName = param.name
    if arrayifiedParams[paramName].length > 1
      param.value = arrayifiedParams[paramName]
    param

Here is the corresponding JSFiddle.


texts:
I'd like to know what you think of my insertion sort version. I tried to be pythonic and avoid while loops with "ugly" index-management:
def sort(a):
    for i, x in enumerate(a):
        for j, y in enumerate(a):
            if y >= x:
                a.insert(j, a.pop(i))
                break

On lists of 1000 random numbers, it seems to be about four times faster (23 ms vs 96 ms) than the implementation from the top-voted answer for the top result for searching [python] insertion sort.
Benchmark code:
from random import random
from time import perf_counter as timer
from statistics import median

n = 1000
repeat = 50

def insertionSort(lst):
    for index in range(1, len(lst)):

        currentvalue = lst[index]
        position = index

        while position > 0 and lst[position - 1] > currentvalue:
            lst[position] = lst[position - 1]
            position = position - 1

        lst[position] = currentvalue

def sort(a):
    for i, x in enumerate(a):
        for j, y in enumerate(a):
            if y >= x:
                a.insert(j, a.pop(i))
                break

solutions = insertionSort, sort

for r in range(1, 6):
    print('Round %d:' % r, end='')
    a = [random() for _ in range(n)]
    for solution in solutions:
        times = []
        for _ in range(repeat):
            copy = a.copy()
            t0 = timer()
            solution(copy)
            times.append(timer() - t0)
            assert copy == sorted(a)
        print('   %6.2f ms' % (median(times) * 1e3), end='')
    print()


texts:
Follow up of - Dynamically-sized stack - follow-up 2

I've took the tips given to me, and what I did now is:

Use same case type for type stack and it's functions
Returning 1 if push failed due to an OOM exception otherwise return 0 if succeeded.
push could now only return a pointer to null due to OOM exception and not because of allocating 0 bytes, in stack_initialize capacitiyIncrement is set to 1 if it's 0 preventing newStackSize being 0 if trying to push elements. Only occurrence where newStackSize will be 0 is if trying to shrink the stack size and there're no elements left in the stack.
Made a stack_realloc() function to deal with all stack reallocations.
stack_destroy() function is now freeing the memory of the elements saved in the stack and not the actual stack object.

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

typedef struct
{
    int *elementData;
    unsigned int stackSize;
    unsigned int capacityIncrement;
    unsigned int elementCount;
} stack;

void stack_initialize(stack*, unsigned int);
int stack_push(stack*, int);
void stack_pop(stack*);
int stack_peek(const stack*);
static int stack_realloc(stack*, unsigned int);
void stack_destroy(stack*);
bool stack_isEmpty(const stack*);
void stack_setCapacityIncrement(stack*, unsigned int);
unsigned int stack_getCapacityIncrement(const stack*);
unsigned int stack_getNumberOfElements(const stack*);
unsigned int stack_getSize(const stack*);

int main()
{
    stack s;
    stack_initialize(&s, 4);
    for(int i = 0; i < 25; i++)
    {
        stack_push(&s, i + 1);
    }
    stack_pop(&s);
    stack_push(&s, 88);
    stack_push(&s, 25);
    while (!stack_isEmpty(&s))
    {
        printf("The top of the stack is %d.\n", stack_peek(&s));
        stack_pop(&s);
        printf("The size of the stack is %u.\n", s.stackSize);
    }
}

void stack_initialize(stack *p, unsigned int capacityIncrement)
{
    p->elementData = NULL;
    p->stackSize = 0;
    if (capacityIncrement == 0)
    {
        capacityIncrement++;
    }
    p->capacityIncrement = capacityIncrement;
    p->elementCount = 0;
}

int stack_push(stack *p, int value)
{
    if(p->elementCount == p->stackSize)
    {
        if(stack_realloc(p, p->stackSize + p->capacityIncrement) == 1)
        {
            return 1;
        }
    }
    p->elementData[p->elementCount] = value;
    p->elementCount++;
    return 0;
}

void stack_pop(stack *p)
{
    if(!stack_isEmpty(p))
    {
        p->elementCount--;
        if(p->elementCount == 0 || p->stackSize - p->elementCount >= p->capacityIncrement / 2 + p->capacityIncrement)
        {
            stack_realloc(p, p->stackSize - p->capacityIncrement);
        }
    }
}

int stack_peek(const stack *p)
{
    if(!stack_isEmpty(p))
    {
        return p->elementData[p->elementCount - 1];
    }
    return 0;
}

static int stack_realloc(stack *p, unsigned int newStackSize)
{
    if (newStackSize > 0)
    {
        void *temp = realloc(p->elementData, sizeof(*p->elementData) * newStackSize);
        if(temp == NULL)
        {
            return 1;
        }
        p->elementData = temp;
    }
    else
    {
        stack_destroy(p);
    }
    p->stackSize = newStackSize;
    return 0;
}

void stack_destroy(stack *p)
{
    free(p->elementData);
    p->elementData = NULL;
}

bool stack_isEmpty(const stack *p)
{
    return p->elementCount == 0;
}

void stack_setCapacityIncrement(stack *p, unsigned int capacityIncrement)
{
    p->capacityIncrement = capacityIncrement;
}

unsigned int stack_getCapacityIncrement(const stack *p)
{
    return p->capacityIncrement;
}

unsigned int stack_getNumberOfElements(const stack *p)
{
    return p->elementCount;
}

unsigned int stack_getSize(const stack *p)
{
    return p->stackSize;
}


texts:
The goal for this project was to:

  Write a program that continues to asks the user to enter any number other than 5 until the user enters the number 5.
  Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.

  ★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.

  Requires:

  variables, data types, and numerical operators
  basic input/output
  logic (if statements, switch statements)
  loops (for, while, do-while)

(I'm not doing the 2 stars one yet)

My questions are:

How can I optimize my code in every possible way? (efficiency, readability, etc)
How can I improve the code syntax?

#include <iostream>
using std::cout;
using std::cin;

int main()
{

    int UserNumber = 0;
    int k = 1;
    while (k < 11)
    {
        cout << "\nEnter any number other than 5: ";
        cin >> UserNumber;

        if (UserNumber == 5)
        {
            cout << "\n\n\nHey! You weren't supposed to enter 5!\n\n\n";
            exit(0);
        }

        else if (k == 10)
        {
            cout << "Wow, you're more patient then I am, you win.\n\n\n";
            exit(0);
        }
        k++;
    }

}


texts:
Concise Problem Specification

Given an integer \$n\$ and a function \$f : X \to X \$ where \$X = \{1,2,3,..,n\}\$ Determine whether the given function is a bijective function or not.

Definition:

According to Wikipedia:

  In mathematics, a bijection, bijective function or one-to-one correspondence is a function between the elements of two sets, where each element of one set is paired with exactly one element of the other set, and each element of the other set is paired with exactly one element of the first set.

Constraints

\$1\le n \le 20 \$

Input format

There are  lines in the input.
The first line contains a single positive integer \$n\$.
The second line contains  space separated integers, the values of \$f(1)\$ , \$f(2)\$ ... ,  \$f(n)\$, respectively.

Output Format

On a single line, output "YES" if  is bijective. Otherwise, output "NO".

Solution

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Solution {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int n = in.nextInt();

        Set<Integer> codomain = new HashSet<Integer>();

        for (int i = 0; i < n; i++) {
            int y = in.nextInt();
            codomain.add(y);
        }

        System.out.println(codomain.size() == n ? "YES" : "NO");

        in.close();

    }

}

Comments

I am still relatively new to Java and would appreciate any comments on the above regarding improvements to my code.


texts: Storing Temporal Message Lists in ASP.NET MVC TempData

texts:
I've been using the following the code to store temporal error messages in TempData, to be displayed from my master page on production sites without any problems, but is this a good way of doing it?

The controller helper code:

namespace System.Web.Mvc
{
    public static class Controllers
    {
        public static void SetMessage(this ControllerBase controller, string message)
        {
            List<string> messages = controller.TempData["Messages"] as List<string> ?? new List<string>();
            messages.Add(message);
            controller.TempData["Messages"] = messages;
        }
        public static void SetErrorMessage(this ControllerBase controller, string errorMessage)
        {
            List<string> messages = controller.TempData["ErrorMessages"] as List<string> ?? new List<string>();
            messages.Add(errorMessage);
            controller.TempData["ErrorMessages"] = messages;
        }
    }
}

Example Use:

public ActionResult Edit()
{
    // .. do stuff
    this.SetMessage("You edited X.");
    return View();
}

Here is the rendering code:

<%
    if (TempData["ErrorMessages"] != null)
    {
    %>
        Error Messages
        <%
        foreach (string s in TempData["ErrorMessages"] as List<string>)
        {
            %><%=s%><%
        }
    }

    if (TempData["Messages"] != null)
    {
    %>
        Messages
        <%
        foreach (string s in TempData["Messages"] as List<string>)
        {
            %><%=s%><%
        }
    }
%>

Can you spot any issues?


texts: Nested loop in lisp to process a 2d array - what's good style (with and/or without loop macro)?

texts:
Code below is answer to an exercise in Paul Graham's ANSI Common Lisp (ex. 4.1). The challenge is to rotate an array by 90 degrees. I found an example solution which I've commented below.

It seems ok'ish and I'm enjoying learning how to use do, but in this particular case it seems actually more verbose than the familir c-style nested for loops to process a 2d array. I'm wondering if the below is good style or if it can be improved upon?

Is the answer going to be the loop macro?
I'm avoiding that at the moment while learning, waiting till I have better mastery of the basics. Yet would like to not pick up bad habits. Hence this question about style regarding the below.

(defun quarter-turn (arr)
  (let* ((dim (array-dimensions arr))  ; let* sets sequentially, not in parallel.
         (row (first dim))
         (col (second dim))
         (n row)  ; initialise n to row, just to organise
         new-arr) ; shorthand for (new-arr nil)
    (cond ((not (= row col))
           (format t "The arg is not a square array.~%"))
          (t (setf new-arr (make-array dim :initial-element nil))
             (do ((i 0 (+ i 1)))  ; Q. surprisingly, lisp's 'do' here looks more
                 ((= i n))        ; verbose than c-style 'for'. Is this good style?
                 (do ((j 0 (+ j 1)))
                     ((= j n))
                     (setf (aref new-arr j i) (aref arr (- n i 1) j))))
             new-arr))))

Source for the above code: http://www.cs.uml.edu/~lhao/ai/lisp/ansi-common-lisp/solution-ch04.htm


texts:
So I've read numerous tutorials on handling game states in XNA, and to each tutorial I've been read, it was different from the others. Now I want to ask which way is more efficient? I've created my own ScreenManager and what not, but it wasn't satisfying to me because it was inefficient since I didn't unload any unused content.

My question is: What is an efficient way to manage your screens and its content? Is using an enum fine? Or...?

Here's my current code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Menu
{
    public class ScreenManager
    {
        // Variables
        List<GameScreen> gameScreens = new List<GameScreen>();

        // Constructors
        public ScreenManager()
        {
            gameScreens.Add(new Splashscreen());
            gameScreens.Add(new Mainscreen());
            gameScreens.Add(new Playscreen());
            gameScreens.Add(new Pausescreen());
        }

        // Public Properties
        public List<GameScreen> Screens
        {
            get { return gameScreens; }
            set { gameScreens = value; }
        }

        // Public Methods
        public void Add(GameScreen screen)
        {
            gameScreens.Add(screen);
        }

        public void LoadContent(ContentManager Content)
        {
            foreach (GameScreen screen in gameScreens)
            {
                screen.LoadContent(Content);
            }
        }

        public void Update(GameTime gameTime)
        {
            foreach (GameScreen screen in gameScreens)
            {
                screen.Update(gameTime);
            }
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            switch (ScreenState.Instance.CurrentState)
            {
                case State.Splashscreen:
                    gameScreens[0].Draw(spriteBatch);
                    break;
                case State.Menu:
                    gameScreens[1].Draw(spriteBatch);
                    break;
                case State.Play:
                    gameScreens[2].Draw(spriteBatch);
                    break;
                case State.Pause:
                    gameScreens[3].Draw(spriteBatch);
                    break;
            }
        }
    }
}


texts: Object pool pattern for asynchronous socket operations

texts:
I have written my own object pool class called ObjectPool<T> which uses SpinLock and Stack<T>:

public class ObjectPool<T> where T : class
{
    private int _size;
    private Func<T> _factory;
    private SpinLock _spinLock;

    // storage for the pool objects.
    // the first item is expected to be most often case.
    private T _firstItem;
    private Stack<T> _cache; //Use Queue<T> for first-in-first-out (FIFO)

    public ObjectPool(Func<T> factory) : this(factory, Environment.ProcessorCount * 2) { }

    public ObjectPool(Func<T> factory, int size)
    {
        _factory = factory;
        _size = size;
        _cache = new Stack<T>();
        _spinLock = new SpinLock(false);
    }

    /// <summary>
    /// Produces an instance.
    /// </summary>
    public T Rent()
    {
        bool lockTaken = false;
        _spinLock.Enter(ref lockTaken);

        try
        {
            T instance = _firstItem;
            if (instance == null || instance != Interlocked.CompareExchange(ref _firstItem, null, instance))
            {
                instance = RentFromCache();
            }

            return instance;
        }
        finally
        {
            if (lockTaken)
            {
                _spinLock.Exit(false);
            }
        }
    }

    private T RentFromCache()
    {
        var cache = _cache;

        if (cache.Count > 0)
        {
            T instance = _cache.Pop();

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

        return CreateInstance();
    }

    private T CreateInstance()
    {
        var instance = _factory();
        return instance;
    }

    /// <summary>
    /// Returns objects to the pool.
    /// </summary>
    public void Return(T obj)
    {
        bool lockTaken = false;
        _spinLock.Enter(ref lockTaken);

        try
        {
            if (_firstItem == null)
            {
                // worst case scenario: two objects may be stored into same slot.
                _firstItem = obj;
            }
            else
            {
                ReturnToCache(obj);
            }
        }
        finally
        {
            if (lockTaken)
            {
                _spinLock.Exit(false);
            }
        }
    }

    private void ReturnToCache(T obj)
    {
        var cache = _cache;

        if (cache.Count >= _size)
        {
            // not a big fan of doing it this way
            return;
        }

        // worst case scenario: two objects may be stored into same slot.
        cache.Push(obj);
    }
}

I'm currently using this object pool to get high performance out of a Socket by making a pool of asynchronous socket operations (ObjectPool<SocketAsyncEventArgs>).

Note: I'm receiving UDP packets, which might help illustrate why some quirks exist (that won't work well for some generic-cases) in this object pool's design, such as using a LIFO pool.

It's working great so far. However, I'd appreciate some expert code review. I am hoping for advice on where it can be improved, further optimized, or if I have missed something important.

Additional Questions:

I'm wondering if ConcurrentStack<T> would provide me with any added benefits?


texts: Add a newline to a String if not empty in Java

texts:
This should be really simple. I'm searching for the cleanest & shortest way to add a newline to a non-null String if it is not empty, i.e. myString.isEmpty() is true. I know of a number of ways to do this, but none of them are as elegant as I would like them to.

For context, the string I'm working on will essentially be a list of key-value pairs that is filled with a loop. Every key-value-pair needs to have a newline appended after it, though not if it is the last one. An example for the end value of myString might be the following:

Boss : Julia
Worker : Louis
Intern : Tom

I could do

myString += myString.isEmpty() ? "" : "\n";

but is this really the best way to do this?

I also thought of

if(!myString.isEmpty()) myString += "\n";

Which way would be preferable, and why?
Are there better alternatives?


texts:
I am using 2 nested SortedDictionaries to construct sparse matrix

Here is the custom simularity(sim) function I wrote . Now it has O(n^2) complexity. I looking for suggestions to improve robustness and efficiency.Thanks for any help.

       double
            a = 0, b = 0,
            sqrta = 0,
            sqrtb = 0,
            sim = 0;

        foreach (var word_i in dict)
        {
            foreach (var word_j in dict)
            {
                if (word_i.Key == word_j.Key) continue;

                sim=a=b=sqrta=sqrtb=0;
                foreach (var term in word_j.Value.Keys)
                {
                    if (word_i.Value.ContainsKey(term))
                    {
                        word_i.Value.TryGetValue(term,out a);
                        word_j.Value.TryGetValue(term,out b);
                        sim += a * b;
                        sqrta += Math.Pow(a,2);
                        sqrtb += Math.Pow(b,2);
                    }

                }

                sim /= Math.Sqrt(sqrta) * Math.Sqrt(sqrtb);

            }
        }