texts:
Problem statement:

  Working from left-to-right if no digit is exceeded by the digit to its
  left it is called an increasing number; for example, 134468.

  Similarly if no digit is exceeded by the digit to its right it is
  called a decreasing number; for example, 66420.

  We shall call a positive integer that is neither increasing nor
  decreasing a "bouncy" number; for example, 155349.

  Clearly there cannot be any bouncy numbers below one-hundred, but just
  over half of the numbers below one-thousand (525) are bouncy. In fact,
  the least number for which the proportion of bouncy numbers first
  reaches 50% is 538.

  Surprisingly, bouncy numbers become more and more common and by the
  time we reach 21780 the proportion of bouncy numbers is equal to 90%.

  Find the least number for which the proportion of bouncy numbers is
  exactly 99%.

My code:

import time
start = time.time()

def bouncy(N):
    '''Function determines whether arbitrary number N is a bouncy number.'''
    number = list(str(N))
    n1 = list(str(N))
    n2 = list(str(N))
    n1.sort()
    n2.sort(reverse=True)
    if (number != n1 and number != n2):
        return True
    else:
        return False

def find():
    start = 1
    total = 0
    bou = 0
    while True:
        total += 1
        if bouncy(start):
            bou += 1
        if bou/total >= 0.99:
            break
        start += 1
    return start
print(find())
print(time.time() - start)

What can be improved?


texts:
I have a Visual Studio 2008 C++03 project where I need a timer. I have an implementation that works well, but I'd like any general suggestions from the community on how to improve it. (More generic, lower cost of creating timers, etc...)

class Timer
{
public:
    typedef boost::function< void( ) > OnTimer;

    Timer( const OnTimer& f, DWORD timeout )
        : cancel_event_( ::CreateEvent( NULL, FALSE, FALSE, NULL ), ::CloseHandle ),
          timer_thread_( boost::bind( &Timer::TimerThread, cancel_event_.get(), f, timeout ) ),
          timeout_( timeout )
    {
    };

    ~Timer() { ::SetEvent( cancel_event_.get() ); };

    DWORD Timeout() const { return timeout_; };

private:

    static void TimerThread( HANDLE cancel_event, const OnTimer& f, DWORD timeout )
    {
        if( WAIT_OBJECT_0 != ::WaitForSingleObject( cancel_event, timeout ) )
            f();
    };

    /// time to wait for the timer to fire
    UINT timeout_;
    /// event signaled when the timer should be canceled
    boost::shared_ptr< void > cancel_event_;
    /// thread that runs the timer (similar to boost::thread, but doesn't require `localtime`, `gmtime`, or `abort`)
    util::CThread timer_thread_;
}; // class Timer

Preemptive:

My project does not have a window message pump so SetTimer is unsuitable.
I do not want to incur the cost of importing the mmtimer library.
I can only use boost header libraries, therefore boost::timer is unsuitable.
I would prefer to keep the discussion limited to this block of code.


texts: Implementation of inheritable pImpl idiom and MVC pattern

texts:
I am trying to write an object "template" that use pImpl and MVC pattern to encapsulate everything not specific to the object. The following is how I tried to attempt it. I am sure that the code smells (if not stinks) but can't tell what's wrong with the design.

I would like to know what better alternatives with which I can do this.

#include <iostream>

using namespace std;

class Ancestor{}; //every object using the "template" inherits this class

//use a template as the type of IMPL is only known at compile time
template <typename IMPL> class Obj : public Ancestor {
    public:
        //dependency injection for easy TDD
        Obj(IMPL *impl = new IMPL()) : m_pImpl(impl) {};
        ~Obj() {delete m_pImpl; m_pImpl = nullptr;};
    protected:
        IMPL *m_pImpl;
};

// well a template is used for the same reason as for Obj<>
template <typename MODEL> struct MVCController {
    MODEL *m_pModel;
};

// same reason for a template
template <typename MODEL, typename CONTROLLER> struct MVCImpl {
    MODEL *m_pModel;
    CONTROLLER *m_pController;
    // leave alone the View for simplicity

    //constructor
    MVCImpl(MODEL *m = new MODEL(), CONTROLLER *c = new CONTROLLER()) :
    m_pModel(m), m_pController(c) {m_pController->m_pModel = m;};
};

struct someBaseModel{};

If I want to create an object called myObj with a public API void foo():

struct myModel : someBaseModel {
    // POD
};

struct myController : public MVCController<myModel> {
    void foo() {cout << "myController: foo" << endl;};
};

struct myImpl : public MVCImpl<myModel, myController> {};

class myObj : public Obj<myImpl> {
    public:
        // inherit myBaseObj to call its default ctor/dtor if no customization is needed
        myObj(myImpl *impl = new myImpl()) : Obj<myImpl>(impl) {};
        void foo();
};

void myObj::foo() {m_pImpl->m_pController->foo();};

If I want myDerivedObj to inherit myObj and add a void bar():

struct myDerivedController : public myController {
    void bar() {cout<<"myDerivedController: bar"<<endl;};
};

struct myDerivedImpl : public MVCImpl<myModel, myDerivedController> {};

// virtual inheritance is used as both inherited class inherits from Ancestor
class myDerivedObj : virtual public myObj, virtual public Obj<myDerivedImpl> {
    using Obj<myDerivedImpl>::m_pImpl;
    public:
        myDerivedObj(myDerivedImpl *impl = new myDerivedImpl()) :
            Obj<myDerivedImpl>(impl) {};
        // add any new API here
    void bar();
};

void myDerivedObj::bar() {m_pImpl->m_pController->bar();};

int main() {
    auto m2 = new myDerivedObj();
    m2->foo();
    m2->bar();

    return 0;
}

Output:

myController: foo
myDerivedController: bar

By using the above implementation I am trying to

hide all pImpl and MVC specific code in the templates
hide all generic "object behaviors" in Ancestor
leave the possibility for inheritance


texts: Mutex implementation for a uniprocessor bare metal embedded OS

texts:
I wrote this recently for one of my projects. Are there any error you can spot or a feature which could be implemented without eating up resources or some optimisations? Also, this isn't meant for multi-cores.

/*******************************************************************************
 * @file    mutex.c
 * @date    31st August 2012
 * @brief   Generic implementation of mutex, read /notes/thread-safety
 ******************************************************************************/

#include <mutex.h>

OS_ERR mutex_acquire_try(mutex_t *mutex)
{
    if(unlikely(cpu_atomic_cmpxchg(&mutex->lock, OS_UNLOCKED, OS_LOCKED) != OS_OKAY))
    {
        if(mutex->owner == current_thread)
            goto recursive;

        return OS_EBUSY;
    }

    mutex->owner = current_thread;

recursive:
    mutex->recnt++;
    return OS_OKAY;
}

static inline OS_ERR mutex_acquire_helper(mutex_t *mutex, time_t timeout)
{
    while(unlikely(cpu_atomic_cmpxchg(&mutex->lock, OS_UNLOCKED, OS_LOCKED) != OS_OKAY))
    {
        if(mutex->owner == current_thread)
            goto recursive;

        if(mutex->lock == OS_DEAD)
            return OS_EINVAL;

        if(current_thread->priority >= mutex->owner->priority)
            thread_boost(mutex->owner);

        if(thread_queue_block(&mutex->queue, timeout) != OS_OKAY)
            return OS_ETIMEOUT;
    }

    mutex->owner = current_thread;

recursive:
    mutex->recnt++;
    return OS_OKAY;
}

OS_ERR mutex_acquire_timeout(mutex_t *mutex, time_t timeout)
{
    return mutex_acquire_helper(mutex, timeout);
}

OS_ERR mutex_acquire(mutex_t *mutex)
{
    return mutex_acquire_helper(mutex, OS_TIME_INFINITE);
}

OS_ERR mutex_release(mutex_t *mutex)
{
    if(mutex->owner != current_thread)
        return OS_EINVAL;

    if(--mutex->recnt)
        goto exit;

    thread_deboost(mutex->owner);
    mutex->owner = NULL;
    cpu_atomic_set(&mutex->lock, OS_UNLOCKED);
    thread_queue_wake_one_now(&mutex->queue);

exit:
    return OS_OKAY;
}

void mutex_init(mutex_t *mutex)
{
    mutex->recnt = 0;
    mutex->owner = NULL;
    thread_queue_init(&mutex->queue);
    cpu_atomic_set(&mutex->lock, OS_UNLOCKED);
}

void mutex_deinit(mutex_t *mutex)
{
    if(mutex->owner == current_thread)
    {
        if(mutex->recnt > 1)
            LOGE("Mutex: Deinit called on recursive lock @ %p\n", mutex);

        mutex_release(mutex);
    }

    do {
        while(thread_queue_count(&mutex->queue))
            thread_yield();
    } while(cpu_atomic_cmpxchg(&mutex->lock, OS_DEAD, OS_UNLOCKED) != OS_OKAY);
}


texts:
The aim is to have that:

list ["Hello", "World", "in", "a", "frame"]

And make it printed like this:

*********
* Hello *
* World *
* in    *
* a     *
* frame *
*********

I did this and it works fine:

a = 0
for nb in listA:
    if a == 0:
        print("*"*10).center(20)
    a += 1
    if len(nb) == 2:
        print("*   " + nb + "   *").center(20)
    elif len(nb) == 1:
        print("*   " + nb + "    *").center(20)
    else:
        print("* " + nb + "  *").center(20)
    if a == len(listA):
        listA[-1]
        print("*"*10).center(20)

Still, I feel it is very cumbersome. Do you have any ideas how I can improve it, please?


texts: Increasing performance and accuracy in multithreaded loop

texts:
I was wondering if the following set up will return consistent result, i.e. no thread function call will be skipped. Also, is there any way to improve the threaded loop?

Note the first loop is the multithread version and the results are out of order and this is okay but I was hoping to find a way to get them in order. The second loop is the regular version non threaded.

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

public class Example
 {

public static int[] LoopPoints = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
public static Stack<int> StackLoopPoints;
public static void Main()
{
    StackLoopPoints = new Stack<int>();
    StackLoopPoints.Push(1);
    StackLoopPoints.Push(2);
    StackLoopPoints.Push(3);
    StackLoopPoints.Push(4);
    StackLoopPoints.Push(5);
    StackLoopPoints.Push(6);
    StackLoopPoints.Push(7);
    StackLoopPoints.Push(8);
    StackLoopPoints.Push(9);
    StackLoopPoints.Push(10);
    StackLoopPoints.Push(11);
    StackLoopPoints.Push(12);
    StackLoopPoints.Push(13);
    StackLoopPoints.Push(14);
    StackLoopPoints.Push(15);
    StackLoopPoints.Push(16);
    StackLoopPoints.Push(17);
    StackLoopPoints.Push(18);
    StackLoopPoints.Push(19);
    StackLoopPoints.Push(20);

    //Array
    List<Task> tasks = new List<Task>();
    for (int ctr = 1; ctr <= 20; ctr++)
    {
        tasks.Add(Task.Factory.StartNew(() => { Console.Write(DoStuffStack(ctr)); }));
    }
    Task.WaitAll(tasks.ToArray());

    Console.WriteLine("");

  // Normal
  for (int ctr = 21; ctr <= 40; ctr++)
  {
      Console.Write(DoStuffNormal(ctr));
  }

  Console.Read();
}

 private static string DoStuffNormal(int ctr)
  {
   Thread.Sleep(TimeSpan.FromSeconds(1d));
   return " " + ctr.ToString() + " ";
  }

  private static string DoStuffStack(int ctr)
  {
   Thread.Sleep(TimeSpan.FromSeconds(1d));
   return " " + StackLoopPoints.Pop().ToString() + " ";
  }

 }


texts:
Problem

Write a program that can calculate the Hamming difference between two DNA strands.
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^  ^ ^    ^^

Code
object Hamming {
  def compute(s1: String, s2: String): Int = {
    if (s1.length != s2.length)
      throw new IllegalArgumentException()
    (s1.toList).zip(s2.toList)
               .filter(current => current._1 != current._2)
               .length
  }
}

Test Suite
import org.scalatest._

class HammingSpecs extends FlatSpec with Matchers {
  it should "detect no difference between empty strands" in {
    Hamming.compute("", "") should be (0)
  }

  it should "detect no difference between identical strands" in {
    Hamming.compute("GGACTGA", "GGACTGA") should be (0)
  }

  it should "detect complete hamming distance in small strand" in {
    Hamming.compute("ACT", "GGA") should be (3)
  }

  it should "give hamming distance in off by one strand" in {
    Hamming.compute("GGACGGATTCTG", "AGGACGGATTCT") should be (9)
  }

  it should "give small hamming distance in middle somewhere" in {
    Hamming.compute("GGACG", "GGTCG") should be (1)
  }

  it should "give a larger distance" in {
    Hamming.compute("ACCAGGG", "ACTATGG") should be (2)
  }

  it should "be undefined for strands of unequal length" in {
    an[IllegalArgumentException] should be thrownBy {
      Hamming.compute("AAACTAGGGG", "AGGCTAGCGGTAGGAC")
    }
  }
}

Source


texts:
I have made a function to drop a row in a pandas.DataFrame. Since, in general, the input dataframe of a function is just a reference to the dataframe. So any change made in that function to the dataframe will be preserved outside that function. Therefore, there are two choices when designing the function:

simply make the change without returning the dataframe.
or, make the change and return the dataframe.

See my code below (function change_df_1 and change_df_2). Could you please let me know which one is better or do you prefer? My concern is readability/clarity of the code.
import pandas as pd

def get_df():
    df = pd.DataFrame({'A': [10, 20, 30], 'B':[100, 200, 300]})
    return df

def change_df_1(df: pd.DataFrame):
    df.drop(index=[1], inplace=True)

def change_df_2(df: pd.DataFrame) -> pd.DataFrame:
    df.drop(index=[1], inplace=True)
    return df

def main():
    df = get_df()
    print(f'Original {df=}')

    change_df_1(df=df)
    print(f'Changed_with 1: {df=}')

    # change_df_2(df=df)
    # print(f'Changed_with 2: {df=}')

if __name__ == '__main__':
    main()
```


texts:
I have little knowledge about java (I'm just starting). I have issues in my generate excel file code. It takes some time to generate the file. Could you please take a look at it?

private void generateExcelFile(String fileName)
{
    logger.debug("Start creating excel file name " + fileName);
    try
    {
        Map<Integer, Rep_Column> columns = createFileColumnsMap();
        int count = columns.size();
        ScrollData<String[]> scroller = createReportScroller(FILE_NUMBER_OF_READ_ROWS);
        List<String> filters = createParamsValueForFile();
        int filterSize = filters.size();
        Excel excel = Excel.createInstanceExcel2007("Testowy", fileName);
        int startDocumentRow = 5 + filterSize;
        if (filterSize > 0)
            startDocumentRow += 2;
        else
            startDocumentRow++;

        excel.startDocument(startDocumentRow, 1);
        excel.createHeadersLayout(columns);
        excel.writeText(1, 1, report.getName(), excel.createStyle(Excel.ALIGN_LEFT, Excel.BLACK, (short) 11, true));

        excel.writeText(2, 1, Utility.getJSFMessage(getResourceBundle(), "fileGeneratedByUser", getUserSession().getUser().getUser().getEmployee().getName() + " " + getUserSession().getUser().getUser().getEmployee().getSurname()), excel.createStyle(Excel.ALIGN_LEFT, Excel.BLACK, (short) 10, true));
        excel.writeText(3, 1, Utility.getJSFMessage(getResourceBundle(), "fileGeneratedDate", (Utility.getDateFormat(getLocale()))), excel.createStyle(Excel.ALIGN_LEFT, Excel.BLACK, (short) 10, true));
        excel.writeText(4, 1, Utility.getJSFMessage(getResourceBundle(), "fileSetText", findActiveSet()), excel.createStyle(Excel.ALIGN_LEFT, Excel.BLACK, (short) 10, true));

        if (!filters.isEmpty())
        {

            excel.writeText(5, 1, Utility.getJSFMessage(getResourceBundle(), "fileFilterText"), excel.createStyle(Excel.ALIGN_LEFT, Excel.BLACK, (short) 10, true));

            for (int i = 0; i < filterSize; i++)
            {
                excel.writeText(6 + i, 1, filters.get(i), excel.createStyle(Excel.ALIGN_LEFT, Excel.BLACK, (short) 10, false));

            }
        }

        excel.startDataLayout(scroller, columns);
        excel.writeText(excel.getLastRow() + 2, 1, Utility.getJSFMessage(getResourceBundle(), "fileGeneratedBy"), excel.createStyle(Excel.ALIGN_RIGHT, Excel.ORANGE, (short) 7, true));
        excel.endData();
        excel.startCreateMargin();
        excel.createMargin(1, 1, count);
        excel.createMargin(2, 1, count);
        excel.createMargin(3, 1, count);
        excel.createMargin(4, 1, count);

        if (filterSize > 0)
        {
            excel.createMargin(5, 1, count);

            for (int i = 0; i < filterSize; i++)
            {
                excel.createMargin(6 + i, 1, count);
            }
        }

        excel.createMargin(excel.getLastRow() + 2, 1, count);
        excel.endCreateMargin();
        excel.endSaveDocument();

        this.downloadFilePath = fileName;
        this.downloadFileName = report.getName() + ".xlsx";

        logger.debug("Generated file=" + fileName);
    }
    catch (Exception e)
    {
        logger.error("Error", e);
    }
}


texts:
I have already done many of the Project Euler questions in other languages before, but whenever learning a new language, I like to do the problems again in that language.

Here is my elixir version of

  Find the sum of all Fibonacci numbers below 4,000,000.

stream = Stream.unfold({0,1}, fn {a, b} -> {a, {b, a + b}} end)
Enum.reduce_while(stream, 0, &(
    cond do
        &1 < 4000000 and rem(&1, 2) == 0 ->
            {:cont, &2 + &1}
        &1 < 4000000 ->
            {:cont, &2}
        true ->
            {:halt, &2}
    end
))

Can anyone spot a way to make my code fit the elixir paradigm more? Are there things I could improve?


texts:
I have the following jQuery which applies a class to my fixed header to shrink it when the user is scrolled any distance down the page:

$(window).scroll(function() {
if ($(this).scrollTop() > 1){
    $('div.single-level-nav').addClass("shrunk");
  }
  else{
    $('div.single-level-nav').removeClass("shrunk");
  }
});

This is working, but of course is constantly firing whenever the user is scrolling. This seems a bit of overkill, and not a great use of resources.

What I have may be the best way of achieving what I want, but I was wondering if there was a better way.


texts: Looking for performance improvement of my custom dataframe aggregation function (Python/Pandas)

texts:
I would like to aggregate rows of my dataframe together, following those rules:

Rows are grouped by "Id", and sorted by anticipation
One row can only be aggregated with rows next to it, with the same "Id"
The "Anticipation" of the new row is the weighted mean of the "Anticipation" (weighted by "Size") of aggregated rows
One row will be included in a group of rows to be aggregated to if, without the new row, the sum of "Size" is inferior or equal to "max_size"

In other words, with this dataframe as input:

   Anticipation   Id  Size
0            10  foo    10
1             9  foo    11
2             8  foo    30
3            10  bar    10
4             9  bar     9
5             8  bar    10
6            10  baz     7

and max_size = 10, the function should return this:

    Id  Size  Anticipation
0  bar    19      9.526316
1  bar    10      8.000000
2  baz     7     10.000000
3  foo    21      9.476190
4  foo    30      8.000000

I'm looking for an improvement of my function's performance (through a more idiomatic pandas coding?).

Here is my current code

import pandas as pd
records = [{"Id": "foo", "Size": 10, "Anticipation":10},
{"Id": "foo", "Size": 11, "Anticipation":9},
{"Id": "foo", "Size": 30, "Anticipation":8},
{"Id": "bar", "Size": 10, "Anticipation":10},
{"Id": "bar", "Size": 9, "Anticipation":9},
{"Id": "bar", "Size": 10, "Anticipation":8},
{"Id": "baz", "Size": 7, "Anticipation":10}]

df = pd.DataFrame(records)
max_size = 10

def assembly_lines(df, max_size):

    df.sort_values("Anticipation", ascending=False)
    df["Cumsum"] = df[["Id", "Size"]].groupby(["Id"]).cumsum()
    df["Anticipation*Size"] = df["Anticipation"] * df["Size"]

    L_fin = [] # L_fin stores aggregated rows.

    for name, group in df.groupby(["Id"]): # Group "foo", "bar", "baz" together
        i = 0
        L = [] # L will temporarly stores rows before aggregation

        for index, row in group.iterrows():

            L.append(row.to_dict()) # Stores row in L

            if row["Cumsum"] > i + max_size: # If cumulated size of all rows in L is above maximal size authorized

                i = row["Cumsum"]
                temp = pd.DataFrame.from_dict(L).drop(["Cumsum", "Anticipation"], axis=1) \
                    .groupby("Id") \
                    .agg({"Size": "sum", "Anticipation*Size": "sum"}) #  Then rows are aggregated
                temp["Anticipation"] = temp["Anticipation*Size"] / temp["Size"] # Mean anticipation is calculated
                L_fin.append(temp) # Aggregated row is added to aggregated rows list
                L = [] # Bucket is emptyied

        if L: # If no rows remains in the grouped df

            temp = pd.DataFrame.from_dict(L).drop(["Cumsum", "Anticipation"], axis=1) \
                .groupby(["Id"]) \
                .agg({"Size": "sum", "Anticipation*Size": "sum"}) # Rows in the bucket are aggregated
            temp["Anticipation"] = temp["Anticipation*Size"] / temp["Size"]
            L_fin.append(temp) # And added to L_fin

    df = pd.concat(L_fin).drop(["Anticipation*Size"], axis=1).reset_index()

    return df


texts: Making multiple HTTP requests to Twitter

texts:
I need to make multiple http requests very fast.  I've currently use this method.

import queue as Queue
import threading
from threading import Thread
import os
import requests

Lock = threading.Lock()
Queue = Queue.Queue(maxsize=0)
for i in range(1000):
    Queue.put((i,i+1)) # These Are Examples

Task_Done = 0
Task_Total = 1000
os.system("title Task Done : {}".format(Task_Done))

class MultiThreading(threading.Thread):
    def __init__(self,Queue):
        threading.Thread.__init__(self)
        self.Queue = Queue
    def run(self):
        global Lock
        global Task_Done
        TaskLeft = self.Queue.get()
        Part1,Part2 = TaskLeft
        try:
            A = requests.get("https://twitter.com/{}{}".format(Part1,Part2))
            B = A.text
            Task_Done += 1
            with Lock:
                os.system("title Task Done : {}".format(Task_Done))
        except:
            self.Queue.put((Part1,Part2))
        self.Queue.task_done()

while not (Task_Total == Task_Done):
    for i in range(100):
        try:
            t = MultiThreading(Queue)
            t.setDaemon(True)
            t.start()
        except:
            time.sleep(5)

I'm currently new to this so excuse my messy code. I want to know what's the most efficient, best, and fastest way of sending HTTP requests.


texts: Better or more idiomatic way to apply a sequence of functions in Haskell

texts:
This is one of my Haskell solutions to a variation of the N-Queens problem, where the queens can move like knights in addition to their normal moves.  It has been optimized somewhat to avoid investigating redundant combinations.

place :: Int -> [[Int]]
place 0 = [[]]
place n = go $ take n $ repeat [1..n]
    where go [] = [[]]
          go (row:rest) = do
                q <- row
                qs <- go $ safe q rest
                return (q : qs)
          safe q = notK q . notD q . notC q
          notC q = map (filter (/= q))
          notD q = (map (\(x, r) -> filter (\y -> abs(y - q) /= x) r)) . (zip [1..])
          notK q = map (\(f, r) -> filter f r) . (zip (kFilters q))
          kFilters q = (\x -> abs (x - q) /= 2) : (\x -> abs (x - q) > 1) : (repeat (const True))

solutions = length . place

main = do
    n <- readLn
    putStrLn $ show $ solutions n

I am satisfied with the performance, but I feel there must be a more elegant way to apply a series of functions (in this case, filters) to a list.

In each iteration of the recursive function go, the top row of the board is selected and then for each position in sequence a queen is positioned and the function recurs with a filtered copy of the rest of the board, so that each iteration has only safe squares to choose from.  The safe function applies three filters to the board:

notC removes all spaces in the same column as the new queen.
notD removes any spaces on a diagonal from the new queen.
notK removes knight moves from the next two lines.

I feel that notK in particular could be implemented more cleanly and idiomatically but I couldn't see a better way to apply one function to the first item of a list, another to the second and something else to the rest.  And using zip does save me from having to check for the end of the board.

I wouldn't be surprised if there is a better way to write notD.  So I am looking for more expressive ways to apply a sequence of varying functions to successive list items.

UPDATE:

I realise that I can use uncurry to clean up notK...

        notK q = map (uncurry filter) . (zip (kFilters q))

and the two filters in Kfilters can be written in dot notation...

        ((/= 2) . abs . subtract q) : ((/= 1) . abs . subtract q) : ...

which allows the kFilters line to be rendered as

        kFilters = (f 2) : (f 1) : (repeat (const True))

but this doesn't actually change my original question.  I'm still looking for a better mechanism for applying a varying sequence of functions to a list.


texts: Converting javax.security.cert.X509Certificate[] to java.security.cert.X509Certificate[] keeping order

texts:
I have got an array of javax.security.cert.X509Certificate and need to convert it into an array of java.security.cert.X509Certificate.

My thoughts when I implemented the following code was that I must keep the order of the certificate thus I used a LinkedList. In the first step I am converting all of them into the new data type and appending it to the LinkedList. Afterwards I create temporary array of a size which equals the amount of certificates in LinkedList. Iterating over the LinkedList allows me to put each single certificate into the temp array and finally I can set my my private java.security.cert.X509Certificate array field. I have got the feeling that it is unnecessarily verbose and not efficient and could be shorter.

private X509Certificate[] x509Certificates;

private void setX509Certificates(javax.security.cert.X509Certificate[] certs)
{
  LinkedList<X509Certificate> x509CertificateLinkedList = new LinkedList<>();

  try
  {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

    for (javax.security.cert.X509Certificate cert : certs)
    {
      try
      {
        ByteArrayInputStream bais = new ByteArrayInputStream(cert.getEncoded());
        X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(bais);
        x509CertificateLinkedList.add(x509Certificate);
      }
      catch (CertificateEncodingException e)
      {
        e.printStackTrace();
      }
    }

    X509Certificate[] tempX509Certificates = new X509Certificate[x509CertificateLinkedList.size()];

    for (int i = 0; i < x509CertificateLinkedList.toArray().length; i++)
    {
      if (x509CertificateLinkedList.get(i) != null)
      {
        tempX509Certificates[i] = x509CertificateLinkedList.get(i);
      }
    }

    this.x509Certificates = tempX509Certificates;
  }
  catch (CertificateException e)
  {
    e.printStackTrace();
  }
}


texts: F# method to insert, update, or delete events in a dictionary

texts:
I have the following code:

    member this.ProcessEvent(sourceStream: OrderResponse) =
       match sourceStream.Action with
        | Action.Partial
        | Action.Insert ->
            sourceStream.Data
            |> Seq.iter (fun x -> this.orderState.[x.OrderId] <- this.ConvertFullOrder x)
        | Action.Update ->
            sourceStream.Data
            |> Seq.iter (fun x -> this.orderState.[x.OrderId] <- this.UpdateOrder x this.orderState.[x.OrderId])
        | Action.Delete ->
            sourceStream.Data
            |> Seq.iter (fun x -> this.orderState.Remove(x.OrderId) |> ignore)
        | _ -> ()

It is processing a list of events and an action. The data is processed and stored in a dictionary. The action tells to insert, update or delete some of the records and applies to all the events received in the same message.

For each case, I iterate through the sourceStream.Data list.

Is there a better / more readable way where I can declare I am going to process that list and then, based on the Action, have different code? this would allow to remove the multiple sourceStream.Data |> bits and specify it only once.


texts: VBA Excel loop with offset for extended range

texts:
Good morning,
I've made the loop for the range, which is copied from one sheet to another. However I have no solution for trimming my code down, which looks like this:
 Sub sunrise()
  Dim i As Single
  With Worksheets("7")
 .UsedRange.Clear
 .Range("a1").Value = "Latitude"
 .Range("b1").Value = "-18"
 .Range("c1").Value = "-17"
 .Range("d1").Value = "-16"
 .Range("e1").Value = "-15"
 .Range("f1").Value = "-14"
 .Range("g1").Value = "-13"
 .Range("h1").Value = "-12"
 .Range("i1").Value = "-11"
 .Range("j1").Value = "-10"
 .Range("k1").Value = "-9"
 .Range("l1").Value = "-8"
 .Range("m1").Value = "-7"
 .Range("n1").Value = "-6"
 .Range("o1").Value = "-5"
 .Range("p1").Value = "-4"
 .Range("q1").Value = "-3"
 .Range("r1").Value = "-2"
 .Range("s1").Value = "-1"
 .Range("t1").Value = "-0.85"
 .Range("u1").Value = "0.6"
 .Range("v1").Value = "1.7"
 .Range("w1").Value = "2.76"
 .Range("x1").Value = "3.84"

  For i = 0 To 10 Step 0.25
    Worksheets("1. GENERAL").Range("A2").Value = i '* (-1)
    With .Cells(Rows.Count, 1).End(xlUp)
    .Offset(1, 0).Value = i
    .Offset(1, 1).Value = Worksheets("1. GENERAL").Range("E742").Value
    .Offset(1, 2).Value = Worksheets("1. GENERAL").Range("F742").Value
    .Offset(1, 3).Value = Worksheets("1. GENERAL").Range("G742").Value
    .Offset(1, 4).Value = Worksheets("1. GENERAL").Range("H742").Value
    .Offset(1, 5).Value = Worksheets("1. GENERAL").Range("I742").Value
    .Offset(1, 6).Value = Worksheets("1. GENERAL").Range("J742").Value
    .Offset(1, 7).Value = Worksheets("1. GENERAL").Range("K742").Value
    .Offset(1, 8).Value = Worksheets("1. GENERAL").Range("L742").Value
    .Offset(1, 9).Value = Worksheets("1. GENERAL").Range("M742").Value
    .Offset(1, 10).Value = Worksheets("1. GENERAL").Range("N742").Value
    .Offset(1, 11).Value = Worksheets("1. GENERAL").Range("O742").Value
    .Offset(1, 12).Value = Worksheets("1. GENERAL").Range("P742").Value
    .Offset(1, 13).Value = Worksheets("1. GENERAL").Range("Q742").Value
    .Offset(1, 14).Value = Worksheets("1. GENERAL").Range("R742").Value
    .Offset(1, 15).Value = Worksheets("1. GENERAL").Range("S742").Value
    .Offset(1, 16).Value = Worksheets("1. GENERAL").Range("T742").Value
    .Offset(1, 17).Value = Worksheets("1. GENERAL").Range("U742").Value
    .Offset(1, 18).Value = Worksheets("1. GENERAL").Range("V742").Value
    .Offset(1, 19).Value = Worksheets("1. GENERAL").Range("W742").Value
    .Offset(1, 20).Value = Worksheets("1. GENERAL").Range("X742").Value
    .Offset(1, 21).Value = Worksheets("1. GENERAL").Range("Y742").Value
    .Offset(1, 22).Value = Worksheets("1. GENERAL").Range("Z742").Value
    .Offset(1, 23).Value = Worksheets("1. GENERAL").Range("AA742").Value
    End With
   Next I
  End With
  End Sub

I would rather populate this code as a range.
I know, that it could be sth like this;
     .Offset(1, 1).Value = Worksheets("1. GENERAL").Range("E742:AA742").Value

Regrettably, only the value from E742 is copied to the B column. Is there a way to expand the range of my offset?


texts:
I wrote a JavaScript source which regrouping by new key i.e. following JSON to the other:

{
    "items" : [
        {
            "company" : "A"
            , "name" : "Prod_A01"
        }
        , {
            "company" : "A"
            , "name" : "Prod_A02"
        }
        , {
            "company" : "B"
            , "name" : "Prod_B01"
        }
    ]
}

to:

{
    "A" : [
        {
            "company" : "A"
            , "name" : "Prod_A01"
        }
        , {
            "company" : "A"
            , "name" : "Prod_A02"
        }
    ]

    , "B" : [
        {
            "company" : "B"
            , "name" : "Prod_B01"
        }
    ]
}

And here is logic:

function regroup(collection, key){
    var novo_obj = {};
    var type = typeof collection;
    var keyGroup = [];

    getKeyGroup(collection, key, keyGroup);

    for(var i = 0; i < keyGroup.length; i++) {
        novo_obj[keyGroup[i]] = [];
        gatherElements(collection, key, keyGroup[i], novo_obj[keyGroup[i]]);
        //console.log(novo_obj);
    }
    console.log(JSON.stringify(novo_obj));
    return novo_obj;
}

function gatherElements(collection, key, value, arr){
    //console.log(collection);
    if(typeof collection == 'object'){
        var targetValue = collection[key];
        if(typeof targetValue != 'undefined' && targetValue == value){
            arr.push(collection);
        }else{
            for(var elem in collection){
                gatherElements(collection[elem], key, value, arr);
            }
        }
    }else if(typeof collection == 'array'){
        for(var i = 0; i < collection.length; i++) {
            getKeyGroup(collection[i], key, value, arr);
        }
    }
}

function getKeyGroup(collection, key, keygroup){
    var targetValue = '';
    if(typeof collection == 'object'){
        targetValue = collection[key];
        if(typeof targetValue != 'undefined'){
            keygroup.push(targetValue);
        }else{
            for(var elem in collection){
                getKeyGroup(collection[elem], key, keygroup);
            }
        }
    }else if(typeof collection == 'array'){
        console.log('isArr');
        for(var i = 0; i < collection.length; i++) {
            getKeyGroup(collection[i], key, keygroup);
        }
    }
    return keygroup;
}

function main(){
    var test = {
        items : [
            {
                company : "A"
                , name : "Prod_A01"
            }
            , {
                company : "A"
                , name : "Prod_A02"
            }
            , {
                company : "B"
                , name : "Prod_B01"
            }
        ]
    }
    regroup(test, "company");
}

However, I think looping every time does not look so good. I need to improve this source code.


texts: Filtering JSON objects from array of values

texts:
My code works, but it seems to be running exceptionally slow.

I have an array of values to search, and I have a JSON that I'm filtering.

var JSONPull;
var FilterJSON = [];
var TypeIDs = [34,35,36,37,38,39,40,11399,1230,17470,17471,1228,17463,17464,1224,17459,17460,18,17455,17456,1227,17867,17868,20,17452,17453,1226,17448,17449,21,17440,17441,1231,17444,17445,1229,17865,17866,1232,17436,17437,19,17466,17467,1225,17432,17433,1223,17428,17429,22,17425,17426,11396,17869,17870];

fetch('URL API')
    .then(res => res.json())
    .then((out) => {
        JSONPull = out;
        TypeIDs.forEach(function (index){
            FilterJSON = JSONPull.filter((element) => {
                console.log("index: "+index);
                console.log(element);
                console.log("type_id: "+ element.type_id);
                element.type_id === index;
            });
        })
    })

The console.logs are more just to watch the code while testing, but definitely shouldn't be causing these performance issues.

Thanks in advance for any help/assistance


texts: Creating tkinter widgets that can dynamically change configs

texts:
I have built a small tkinter program that I want to have a few different themes it can change between. In order to dynamically change the colours/font for each widget I have subclassed tkinter, and I am just wondering if there is any smarter way of doing this? I am aware that ttk can do something similar, but then as I understand it you are forced to use one of the ttk themes, rather than the standard tkinter widget design, which I prefer to avoid
Example for the button widget:
class Button(tk.Button):
    objects = []

    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)
        self.__class__.objects.append(self)

    @classmethod
    def set_config(cls, **val):
        for obj in cls.objects:
            obj.config(val)

    def destroy(self):
        cur_obj = next(idx for idx, x in enumerate(self.objects) if x.bindtags() == self.bindtags())
        del self.__class__.objects[cur_obj]
        super().destroy()

A full example of the running code has been included below.
This is not my current implementation, but just a minimal example to show how the color changer works in practice. NB: The tk_dynamic module contains the subclasses for each widget in the same spirit as the one for Button, shown above.
from utils import tk_dynamic as tkd
from tkinter import ttk
import tkinter as tk

themes = ['light', 'dark']
theme_map = {
    'light': {
        tkd.Tk: dict(bg='#f0f0ed'),
        tkd.Label: dict(bg='#f0f0ed', fg='black'),
        tkd.Button: dict(bg='gray85', fg='black'),
        tkd.LabelFrame: dict(bg='#f0f0ed'),
        tkd.Radiobutton: dict(bg='gray85', selectcolor='white')
    },
    'dark': {
        tkd.Tk: dict(bg='black'),
        tkd.Label: dict(bg='black', fg='#ffffff'),
        tkd.Button: dict(bg='gray47', fg='#ffffff'),
        tkd.LabelFrame: dict(bg='black'),
        tkd.Radiobutton: dict(bg='gray47', selectcolor='gray78')
    }
}

class ThemedTkinter:
    def __init__(self, theme=themes[0]):
        self.root = tkd.Tk()

        self.active_theme = theme
        self.theme_var = tk.StringVar(value=theme)
        self.make_widgets()

        self._change_theme()
        self.root.mainloop()

    def make_widgets(self):
        tkd.Label(self.root, text='This is a test application').pack()

        # Create a test row
        lf1 = tkd.LabelFrame(self.root)
        lf1.pack(expand=True, fill=tk.X)
        svar = tk.IntVar()

        tkd.Label(lf1, text='Option 1').pack(side=tk.LEFT)
        tkd.Radiobutton(lf1, text='Off', indicatoron=False, value=0, variable=svar).pack(side=tk.RIGHT)
        tkd.Radiobutton(lf1, text='On', indicatoron=False, value=1, variable=svar).pack(side=tk.RIGHT)

        # Create choice to change theme
        lf2 = tkd.LabelFrame(self.root)
        lf2.pack(expand=True, fill=tk.X)

        tkd.Label(lf2, text='Active theme').pack(side=tk.LEFT)
        theme_choices = ttk.Combobox(lf2, textvariable=self.theme_var, state='readonly', values=themes)
        theme_choices.bind("<FocusOut>", lambda e: theme_choices.selection_clear())
        theme_choices.bind("<<ComboboxSelected>>", lambda e: self._change_theme())
        theme_choices.config(width=11)
        theme_choices.pack(side=tk.RIGHT, fill=tk.X, padx=2)

    def _change_theme(self):
        if self.theme_var.get() != self.active_theme:
            self.active_theme = self.theme_var.get()
            chosen_theme = theme_map[self.active_theme]
            for k, v in chosen_theme.items():
                k.set_config(**v)

ThemedTkinter()


texts:
Recently I was thinking about the keyless entry on my car and how simple it has to be, so I wrote a C# programme to validate a StreamingPin, that is, a pin that is entered character-by-character, and resets as soon as an invalid character is input. If the correct sequence of characters is entered, then the pin is validated as correct, but if another character is entered afterwards, the pin is incorrect.

Regardless of what happens before the correct sequence of characters, as soon as the valid sequence is entered the pin is valid.

class StreamingPin
{
    public bool IsCorrect => (_lastCorrect + 1) == _pin.Length;

    private int _lastCorrect = -1;
    private string _pin;

    public StreamingPin(string pin)
    {
        if (string.IsNullOrEmpty(pin))
        {
            throw new ArgumentException($"The value provided for {nameof(pin)} cannot be null or an empty string.");
        }

        _pin = pin;
    }

    public void ProcessCharacter(char c)
    {
        var currentIndex = _lastCorrect + 1;

        if (_pin[currentIndex] == c)
        {
            _lastCorrect = currentIndex;
        }
        else if (_pin[0] == c)
        {
            _lastCorrect = 0;
        }
        else
        {
            _lastCorrect = -1;
        }
    }
}

It takes \$O(1)\$ memory, and runs in \$O(n)\$ time where \$n\$ is the number of characters processed until the correct sequence is found.

No matter now many invalid characters are entered before a valid pin, there is no lockout procedure.

Test code:

var sp = new StreamingPin("PinNumber");
var input = "p2gsvpinnumberPinNumbessfeER#VvsdinNumberPinNumberdfvlj4kF4wfV";
var lastIndex = -1;

while (!sp.IsCorrect)
{
    lastIndex++;
    Console.WriteLine(input[lastIndex]);
    sp.ProcessCharacter(input[lastIndex]);
}

Console.WriteLine("Pin found");


texts:
From the Extended Exercise beginning in section 2.1.4, you can find exercise 2.8:

  Exercise 2.8.  Using reasoning
  analogous to Alyssa's, describe how
  the difference of two intervals may be
  computed. Define a corresponding
  subtraction procedure, called
  sub-interval.

I wrote the following:

(define (sub-interval x y)
  (make-interval (- (lower-bound x) (upper-bound y))
                 (- (upper-bound x) (lower-bound y))))

What do you think?


texts: Checking referential integrity of a database schema

texts:
I am using PHP PDOs to parse the results I am receiving from MySQL queries against a database. I am now running into an issue with running out of allocated memory. Are there any suggestions on improving the efficiency of my code or another more efficient way to handle query results other than parsing PDOs?

This will return whether or not a DB has referential integrity:

function generateDSN($host, $dbname)
{
    return 'mysql:host='. $host . ';dbname=' . $dbname;
}

$dbName = $argv[2];
//Used for query construction

$dsn = generateDSN($argv[1], $argv[2]);
//create DSN

$link = new PDO($dsn, "username", "password");
//Connect to the database
//PDO($dsn, username, password)

if ($link->connect_error)
{
    die("Connection failed: " . $link->connect_error);
}
else
{
    echo "Connected successfully\n";
}
//validate database connection

$query = "SELECT TABLE_CONSTRAINTS.TABLE_NAME, KEY_COLUMN_USAGE.COLUMN_NAME, KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS RIGHT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ON INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME WHERE INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME <> 'PRIMARY' AND INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' AND INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_SCHEMA = '".$dbName."';";
//Create query to return list of tables with foreign keys
/* Query return format:
+--------------+------------------------+-----------------------+------------------------+
| TABLE_NAME   | COLUMN_NAME            | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
+--------------+------------------------+-----------------------+------------------------+
*/

$result = $link->query($query);
//Get query results

$x = 0;
$tableA = [];
$tableB = [];
//Create arrays to hold data from FK queries

while($tables = $result->fetch(PDO::FETCH_ASSOC))
{
    $test[] = $tables;
    $assoc = $test[$x];
    //assign assoc[] the value of $query (will iterate through query table row by row)

    $tableName = $assoc['TABLE_NAME'];
    $columnName = $assoc['COLUMN_NAME'];
    $refTableName = $assoc['REFERENCED_TABLE_NAME'];
    $refColumnName = $assoc['REFERENCED_COLUMN_NAME'];
    //get data values for each column

    $fkQueryA = "SELECT DISTINCT " . $columnName . " FROM " . $dbName . "." . $tableName . " ORDER BY ".$columnName." ;";
    $fkQueryB = "SELECT DISTINCT " . $refColumnName . " FROM " . $dbName . "." . $refTableName . " ORDER BY ".$refColumnName." ;";
    //A -- Table with column that is the foreign key
    //B -- Table with column that the foreign key references

    $resultA = $link->query($fkQueryA);
    $resultB = $link->query($fkQueryB);
    //Get query results

    while($var = $resultA->fetchColumn())
    {
        $tableA[] = $var;
    }
    //Push query results to table

    while($vari = $resultB->fetchColumn())
    {
        $tableB[] = $vari;
    }
    //Push query results to table

    $x++;
    //increment counter to move through $tables
}

$resultCompAB = array_diff($tableA, $tableB);
//return array with all values of A that are not in B

if(empty($resultCompAB))
{
    echo "Database ".$dbName." has referential integrity.";
}
else
{
    echo "Orphan Values in database ".$dbName.": \n";
    array_diff($tableB, $resultCompAB);
}
//print the results


texts: Basic to-do CLI app (with JSON for persistence) using Python

texts:
I’m very new to Python. I wanted to start out with a simple project: a CLI app that keeps track of my to-do’s.

The code works as intended, but is what I have written is any good?

File structure:

task.py defines the task class
task_handler.py defines a class that helps retrieve/store the tasks
command.py ties everything together and processes the command

Files:

task.py

class Task:

    def __init__(self, description):
        self.description = description
        self.completed = False

    def complete(self):
        self.completed = True

task_handler.py

import json
from task import Task

class TaskHandler:

    def __init__(self, path):
        self.path = path
        self.stored_attributes = ['description', 'completed']

    def store(self, tasks):
        data = []
        for task in tasks:
            obj = {}
            for attr in self.stored_attributes:
                obj[attr] = getattr(task, attr, None)
            data.append(obj)

        with open(self.path, 'w') as data_file:
            json.dump(data, data_file)

    def retrieve(self):
        data = []
        try:
            with open(self.path, 'r') as data_file:
                data = json.load(data_file)
        except FileNotFoundError:
            pass

        tasks = []
        for task in data:
            obj = Task(task['description'])
            for attr in self.stored_attributes:
                setattr(obj, attr, task[attr])
            tasks.append(obj)
        return tasks

command.py

import os
import sys
import argparse
from task import Task
from task_handler import TaskHandler

def parse_args(args):
    parser = argparse.ArgumentParser()
    action_parser = parser.add_subparsers(title='actions', dest='action')

    action_parser.add_parser('list')

    add_action_parser = action_parser.add_parser('add')
    add_action_parser.add_argument('description')

    complete_action_parser = action_parser.add_parser('complete')
    complete_action_parser.add_argument('index', type=int)

    purge_action_parser = action_parser.add_parser('purge')
    purge_action_parser.add_argument('index', type=int)

    return parser.parse_args(args)

def main():
    args = parse_args(sys.argv[1:])
    task_handler = TaskHandler(os.path.expanduser('~') + '/.todo.json')
    stored_tasks = task_handler.retrieve()

    if args.action == 'add':
        new_task = Task(args.description)
        stored_tasks.append(new_task)
        task_handler.store(stored_tasks)
        print('Task added')
    elif args.action == 'complete':
        try:
            stored_tasks[args.index].complete()
            task_handler.store(stored_tasks)
            print('Task marked as completed')
        except IndexError:
            print('No task with that index')
    elif args.action == 'purge':
        try:
            del stored_tasks[args.index]
            task_handler.store(stored_tasks)
            print('Task purged')
        except IndexError:
            print('No task with that index')
    else:
        if not stored_tasks:
            print('To-do list is empty')
        else:
            print('To-do:')
            for idx, task in enumerate(stored_tasks):
                completed = ' (completed)' if task.completed else ''
                print('[{}] {}{}'.format(idx, task.description, completed))

if __name__ == '__main__':
    main()

Any input would be highly appreciated! I want to focus on becoming a better programmer in any way I can.


texts: Singleton holding and notifying registered listeners

texts:
Suppose I am listening for network changes with the following listener:

interface NetListener {

    void onNetworkAvailable(boolean isWifi);

    void onNetworkUnavailable();
}

I want to have an object, accessible from anywhere within the app, holding the registered NetListeners, that can trigger the appropriate methods when necessary. The solution I came up with is this "singleton":

class NetListenerManager {

    private static List<NetListener> _listeners = new CopyOnWriteArrayList<NetListener>();

    static void addListener(final NetListener listener) {
        if (null != listener) { _listeners.add(listener); }
    }

    static void removeListener(final NetListener listener) {
        if (null != listener) { _listeners.remove(listener); }
    }

    /**
     * Called when a network connection is available.
     */
    static void notifyOnNetworkAvailable(boolean isWifi) {
        for (NetListener listener : _listeners) { listener.onNetworkAvailable(isWifi); }
    }

    /**
     * Called when a network connection becomes unavailable.
     */
    static void notifyOnNetworkUnavailable() {
        for (NetListener listener : _listeners) { listener.onNetworkUnavailable(); }
    }

    private NetListenerManager() { /* Instantiation disabled. */ }

}

So whenever e.g. a network change broadcast is received, I call NetListenerManager.notifyOnNetworkAvailable or NetListenerManager.notifyOnNetworkUnavailable,
depending on the network state.

I’m wondering if this is a good solution or if there are better ways to implement this.
Thanks!

UPDATE no.2

This is the modified listener:

interface NetListener {

    static enum NetworkType {NO_NETWORK, WIFI, MOBILE}

    void onNetworkChange(NetworkType type);

}

And the manager:

public final class NetListenerManager {

    private static final List<NetListener> NET_LISTENERS = new CopyOnWriteArrayList<NetListener>();
    private static final BlockingQueue<NetListener.NetworkType> QUEUE = new LinkedBlockingQueue<NetListener.NetworkType>();

    private static final Thread QUEUE_PROCESSOR = new Thread(new QueueProcessor());
    static { QUEUE_PROCESSOR.start(); }

    public static void addListener(final NetListener listener) {
        if (null != listener) { NET_LISTENERS.add(listener); }
    }

    public static void removeListener(final NetListener listener) {
        if (null != listener) { NET_LISTENERS.remove(listener); }
    }

    /**
     * Called when there is a network change.
     */
    public static void notifyOnNetworkChange(final NetListener.NetworkType type) {
        QUEUE.add(type);
    }

    private NetListenerManager() { /* Instantiation disabled. */ }

    /**
     * This Runnable propagates network change events to the registered NetListener listeners in a queue.
     */
    private static final class QueueProcessor implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final NetListener.NetworkType type = QUEUE.take();
                    for (NetListener listener : NET_LISTENERS) { listener.onNetworkChange(type); }
                } catch (InterruptedException ie) { /* Do nothing */ }
            }
        }
    }

}


texts: Loading GIF form on a Windows console app using threads

texts:
I have a main form which does processing for an extended period of time. Normally, progress bars are used to show either the loading status or simply show the program is still running/hasn't freezed.

For this form, I wanted to give it a more snazzy look by reusing a common loading GIF found on the web that many users would be familiar with.

This is how I implement said GIF:

ShowLoadingGif();

              //Heavy lifting

HideLoadingGif();

private void ShowLoadingGif()
{
    this.Enabled = false;

    Point formCenterPt = new Point()
    {
        X = this.Location.X + (this.Width/2),
        Y = this.Location.Y + (this.Height/2)
    };

    loadingThread = new Thread(() => ShowLoading(formCenterPt));
    loadingThread.IsBackground = true;
    loadingThread.Name = "Loading gif";
    loadingThread.Start();
}

private void HideLoadingGif()
{
    try
    {
        this.Enabled = true;
        if(loadingThread.IsAlive)
        loadingThread.Abort();
    }
    catch (Exception ex)
    {
        Log(String.Concat("Loading gif thread release failed: ",ex));
    }
}

private void ShowLoading(Point parentCenter)
{
    frmLoadingGif loading = new frmLoadingGif();

    Point offsetPt = new Point()
    {
        X = parentCenter.X - (loading.Width /2),
        Y = parentCenter.Y - (loading.Height/2)
    };

    loading.StartPosition = FormStartPosition.Manual;
    loading.Location = offsetPt;
    loading.ShowDialog();
}

What this does is produces a loading GIF (I grabbed mine from ajaxloader) in the center of the form while processing is ongoing, and also disables the form.

My question is, whether or not what I did was overkill for something as simple as an inprogresss status, or if using threads in this way is the best way to do it. I realize that using a control on the main form would have been easier, but I couldn't find a way to do so with a GIF while also making the background completely transparent.

Why have I chosen to use a form for showing the GIF?

The alternative would have been to add the picture box to the main form. However, this didn't seem the best solution because I wanted to center the GIF to the form itself, and with the TableLayoutPanel I was using, you can't simply change the location of a control in that manner (please correct me if I'm wrong here). I also wanted to keep the transparency, threading, and other attributes of the picturebox control separate from the main form so I could reuse it elsewhere.

Finally, I wanted to show the GIF loading on top of the current form, and not just in the corner/bottom in its own section like a progress bar would. As you'll see in the picture, the loading GIF is shown on top of the control behind it, a DataGridView.


texts: Normalization, division and reshaping processes on an HDF5 file

texts:
I performing a set of division operations and reshaping on a HDF5 file. As my datapoints is around 4000 in number it takes around a minute. I will be adding more data, which will further slow my overall code execution time.
How can I optimize this code to make it faster?

def pre_proc_data():
    jointMatrix = np.array([], dtype=np.float64).reshape(0, 500 * 17)
    hdf5_file = h5py.File("/home/Data.hdf5")

    for j in range(len(hdf5_file["vector"])):
        # Normalization
        norm_vec = hdf5_file["vector"][j]
        norm_vec[:, 0] = (norm_vec[:, 0] - (-3.059)) / 6.117  # W0 - Left and right
        norm_vec[:, 5] = (norm_vec[:, 5] - (-3.059)) / 6.117
        norm_vec[:, 1] = (norm_vec[:, 1] - (-1.5707)) / 3.6647  # W1
        norm_vec[:, 6] = (norm_vec[:, 6] - (-1.5707)) / 3.6647
        norm_vec[:, 2] = (norm_vec[:, 2] - (-3.059)) / 6.117  # W2
        norm_vec[:, 14] = (norm_vec[:, 14] - (-3.059)) / 6.117
        norm_vec[:, 3] = (norm_vec[:, 3] - (-1.7016)) / 3.4033  # S0
        norm_vec[:, 10] = (norm_vec[:, 10] - (-1.7016)) / 3.4033
        norm_vec[:, 4] = (norm_vec[:, 4] - (-2.147)) / 3.194  # s1
        norm_vec[:, 8] = (norm_vec[:, 8] - (-2.147)) / 3.194

        norm_vec[:, 11] = (norm_vec[:, 11] - (-3.0541)) / 6.1083  # eo
        norm_vec[:, 15] = (norm_vec[:, 15] - (-3.0541)) / 6.1083
        norm_vec[:, 12] = (norm_vec[:, 12] - (-0.05)) / 2.67  # e1
        norm_vec[:, 16] = (norm_vec[:, 16] - (-0.05)) / 2.67

        reshaped_vec = hdf5_file["vector"][j].reshape(500 * 17)
        jointMatrix = np.vstack((jointMatrix, reshaped_vec))

    return jointMatrix

jointMatrix = pre_proc_data()


texts: Variadic template class that stores a vector of each type given

texts:
I'm exploring the possibility to generalise a class of mine that stores some entities. I like it to be able to keep entities of several type, given as template arguments. To explore the possibilities I wrote the following class, that does exactly that. I'm however unsure if anything that I do here is a) save and b) as easy as it gets. I'm not very deep into metaprograming. I'm looking for tips how to improve and pitfalls.

#include <iostream>
#include <tuple>
#include <vector>

template<typename... Ts>
class A
{
    template<typename T>
    using container = std::vector<T>;

public:
    template<typename T>
    void add(T e) {
        std::get<container<T>>(m_tupel).emplace_back(e);
    }

    template<typename T>
    container<T>& get() {
        return std::get<container<T>>(m_tupel);
    }

private:
    std::tuple<container<Ts>...> m_tupel;
};

int main()
{
    A<int, bool, double, float> a;
    a.add(3);
    a.add(33);
    a.add(3.14);
    a.add(333);
    a.add(31.4);

    const auto& cDouble = a.get<double>();
    const auto& cInt = a.get<int>();

    for(auto i : cDouble)
        std::cout<<i<<" ";
    std::cout<<"\n";
    for(auto i : cInt)
        std::cout<<i<<" ";
}


texts:
Over the holidays I played around with coroutines and their use as two-in-one getter and setter methods:
#! /usr/bin/env python3
#  coroproperty.py - Coroutine-based two-in-one properties.
#
#  Copyright (C) 2020 Richard Neumann <mail at richard dash neumann period de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""Coroutine-based two-in-one decorator."""

from contextlib import suppress
from math import pi, sqrt
from typing import Any, Callable

def coroproperty(method: Callable) -> property:
    """Single decorator for getter and setter methods."""

    def getter(self) -> Any:
        """Property getter function."""
        coro = method(self)
        value = next(coro)
        coro.close()
        return value

    def setter(self, value: Any):
        """Property setter function."""
        coro = method(self)
        next(coro)
        next(coro)

        with suppress(StopIteration):
            coro.send(value)

    return property(getter, setter)

class Circle:
    """Information about a circle."""

    def __init__(self, radius: float):
        """Initializes the circle with its radius."""
        self.radius = radius

    @coroproperty
    def diameter(self):
        """Gets and sets the diameter."""
        yield self.radius * 2
        self.radius = (yield) / 2

    @coroproperty
    def circumference(self):
        """Gets and sets the circumference."""
        yield self.diameter * pi
        self.diameter = (yield) / pi

    @coroproperty
    def area(self):
        """Gets and sets the area."""
        yield pow(self.radius, 2) * pi
        self.radius = sqrt((yield) / pi)

The downsides I already discovered are, that each set access implies that an unused get is performed before. Furthermore, these decorators are significantly slower than a "classical" property with separate getter and setter methods:
Coro get: 0.2394869327545166
Classic get: 0.09408378601074219
Ratio coro / classic: 2.5454644515174247
Coro set: 0.7087152004241943
Classic set: 0.10921454429626465
Ratio coro / classic: 6.489201644257868

What other side-effects could arise when using these kind of properties?
Note that this code is not intended for use in productive environments, but is of academic interest only.


texts: Jenkins Powershell script to copy code from Github to AWS Lambda

texts:
This is a <10 line Jenkins powershell build step triggered by a git commit which zips code and copies to lambda. Seems to work fine for javascript projects. I check for the zip file and then remove it if it's there. Any commentary? What am I missing?

$sourceDir = $env:WORKSPACE;
$targetFile = $env:TEMP + "\" + $env:JOB_NAME + $env:BUILD_NUMBER+ ".zip";
if(Test-Path -Path $targetFile){
  Write-Host exists;
  Remove-Item $targetFile;
}
[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")

[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceDir , $targetfile);

aws lambda update-function-code --region us-east-1 --function-name $env:JOB_NAME --zip-file fileb://${targetFile};


texts:
I am trying to implement sentence segregation using Haskell, I have achieved a decent bulk of it using the NLP.FullStop library, but this doesn't seem to account for sentences with full stops at the end of quotes like this." or like this.', or at the end of bracketed sentences like this.) I also want to deal with the character ” much in the same way as ", as a lot of the content I am dealing with uses this character. I've been unable to get a successful regex match on this character, so have resorted to replacing it with " before the regex...

import qualified Data.ByteString.Char8 as BC
import           Data.List.Split
import qualified NLP.FullStop as FS

splitter :: String -> [String]
splitter = concatMap FS.segment . splitPunc
  where splitPunc = map unwords . split puncSplitter . words
        puncSplitter = keepDelimsR $ whenElt (\word -> BC.pack (splitPrep word) =~ puncExpr :: Bool)
        splitPrep = replace_ '”' '"'
        puncExpr = "\\.[)'\"][^w]?$" :: String

replace_ :: Eq b => b -> b -> [b] -> [b]
replace_ a b = map (\x -> if (a == x) then b else x)


texts:
I want to get the difference between arr1 and arr2 and to get the correct result. However, I think my code is a little bit redundant.

function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
  for(var i = 0;i<arr2.length;i++){
      var count = 0;
      for(var j = 0;j<arr1.length;j++){
          if(typeof arr2[i] == "number" && typeof arr1[j] == "number" && arr2[i] == arr1[j]) {
              count += 1;
          }
          if(typeof arr2[i] == "string" && typeof arr1[j] == "string" && arr2[i] === arr1[j]) {
              count += 1;
          }else{

          }

      }
      if(count == 0){
          newArr.push(arr2[i]);
      }
  }
  for(var j = 0;j<arr1.length;j++){
      var count = 0;
      for(var i = 0;i<arr2.length;i++){
          if(typeof arr2[i] == "number" && typeof arr1[j] == "number" && arr2[i] == arr1[j]) {
              count += 1;
          }
          if(typeof arr2[i] == "string" && typeof arr1[j] == "string" && arr2[i] === arr1[j]) {
              count += 1;
          }
      }
      if(count == 0){
          newArr.push(arr1[j]);
      }
  }
return newArr;
}

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);


texts:
I'm using dapper-dot-net for data access in my ASP.NET MVC application.
So in order to supply a connection string I've came up with the following pattern:

public static class ConnectionStringManager
{
    private static readonly SqlConnection conn;

    static ConnectionStringManager()
    {
        //initialize the connection with value from web.config file
        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnName"].ConnectionString);
    }

    public static SqlConnection GetOpenConnection()
    {
        if (conn.State != System.Data.ConnectionState.Open)
            conn.Open();

        return conn;
    }
}

And a sample use of it with in a query:

public Customer GetCustomerById(int id)
{
    string sql = @"select * from Customer where Id = @id";
    using (var conn = ConnectionStringManager.GetOpenConnection())
    {
        Customer cust = conn.Query<Customer>(sql, new { id }).FirstOrDefault();
        return cust;
    }
}

So my question is if this is a good approach or not, and if not, what would you suggest to do different?


texts:
I am trying a trial multiplication for factorization. This is a general example, but each sequence can be specified to pairs of sequences \${p,q}\$ for a given \$n\$. For example, if \$n\$ ended in 3, then {\$p,q\$} would be: {1,3},{3,1},{7,9} and {9,7} with sequence steps of -10 and 10 respectively.

The essence of the method is if \$pq < n\$, raise \$q\$. If \$pq > n\$, lower \$p\$ while continuing where the last \$p\$ and the last \$q\$ left off.

#Trial Multiplication
TM<- function (number){

    if (floor(sqrt(number))%%2==0)
    p_start <<- floor(sqrt(number))-1

    if (floor(sqrt(number))%%2>0)
    p_start <<- floor(sqrt(number))

    if (ceiling(sqrt(number))%%2==0)
    q_start <<- ceiling(sqrt(number))+1

    if (ceiling(sqrt(number))%%2>0)
    q_start <<- ceiling(sqrt(number))

    for (p in seq(p_start,1,-1)){
      for (q in seq(q_start,number,1)){

      #Quick primality tests for p and q...
      #if(p%%3==0 | p%%5==0 | p%%7==0 | p%%11==0 | p%%13==0 | p%%17==0 | p%%19==0) break
      #if(q%%3==0 | q%%5==0 | q%%7==0 | q%%11==0 | q%%13==0 | q%%17==0 | q%%19==0) next

      if(p*q==number)
      return(c(p,q))

      if(p*q>number) break

      q_start<<- q
      p_start<<- p

      }

  #if(q%%3==0 | q%%5==0 | q%%7==0 | q%%11==0 | q%%13==0 | q%%17==0 | q%%19==0) break
  #if(p%%3==0 | p%%5==0 | p%%7==0 | p%%11==0 | p%%13==0 | p%%17==0 | p%%19==0) next

  if(p*q==number)
  return(c(p,q))

  if(p*q<number) break

  p_start<<- p
  q_start<<- q

    }

}


texts: Fetching table using mysqli, closing statement before displaying results

texts:
I am confused if I can do like this:

$param = "%{$id}%";
$stmt = $conn->prepare("SELECT name, comp, date FROM stats WHERE date = ? AND name LIKE ? ORDER BY date DESC LIMIT 20");
$stmt->bind_param("ss", $param, $_POST['date']);
$stmt->execute();
$result = $stmt->get_result();
$count_rows = $result->num_rows;
$stmt->close(); // CAN I CLOSE IT HERE

while($row = $result->fetch_assoc()){
    echo '
    <tr>
        <td>'.$row['name'].'
        <td>'.$row['comp'].'
        <td>'.$row['date'].'
    </tr>';
}

Question is can i close $stmt->close(); where i do it now or should i close it after while loop?

I tested and it does work but is it wrong?


texts: Data mapper reuse related domain object for setting data and return a clone of the domain object

texts:
This example is simplified down to the bare minimum. No DatabaseAdapter IdentityMap or anything. No fetch() method. Just what is needed to demonstrate this.

If all your data mappers have a method:

/**
 * @return EntityType
 */
public function assign(EntityType $entity, Array $row);

You are basically creating a new blank entity each time you want to assign data to it.

I have began thinking what if all the data mappers get an entity of the related type injected into its constructor:

UserMapper::__construct(User $user)

Now the

UserMapper::assign(User $user, Array $row)

method could be changed to

UserMapper::assign(Array $row);

Since the mapper has an instance of a User object which it got when the mapper was constructed and it just assigns the row data to that.

There is a slight problem though because if I do something like the following:

$user1 = $userMapper->assign( array('username' => 'user1') );
$user2 = $userMapper->assign( array('username' => 'user2') );

// Now $user1 has the same username as $user2.
$user2->setUsername('user2_something');

Any changes I make to either user instance reflects in the other instance.

This can be solved by cloning the single user instance in the mapper when returning it in the assign method:

public function assign(Array $row) {
    $this->user->setUsername( $row['username'] );
    return clone $this->user;
}

UPDATE: Or Maybe Better...

// Now the user object in the mapper never changes, just gets cloned.
public function assign(Array $row) {

    $user = clone $this->user;
    $user->setUsername( $row['username'] );

    return $user;
}

And now the user instance you get back from the UserMapper::assign(Array $row) method does not point to the user instance inside the mapper.

I have never had to use the clone feature before so I am not too sure about it.

Is this implementation okay? Could it cause any problems?


texts: Monte Carlo Simulation of a Markov Process

texts:
A 1D binary string has the following dynamics
$$1100 \to 1010,\quad 1101\to 1011$$
each with rate \$p<1\$. That is if we see \$110\$ in the string, then we change to \$101\$ with probability \$p\$. I am interested in the count of \$00,01\$ and \$11,\$ and \$1100\$ in the binary string. For this, I have written the following code which I want to optimize (time).

This model is known as the Restricted Asymmetric Simple Exclusion Process (or RASEP), a modified version of TASEP.

import matplotlib.pyplot as plt
import numpy as np
from random import random

sweeps = 1000
n = 1000
p = 0.5
rho = 0.5
ensemble_size = 100

"""preparing 1D lattice with n number of 1s and L-n number of 0s.
Convinient to work with rho = n/L."""
def initialize(rho = 0.25, L = 100):
    config = np.array([1]*int(rho*L)+[0]*(L-int(rho*L)))
    np.random.shuffle(config)
    return config

#N0 = number of 00, N1 = number of 01 and 10, N3 = number of 11, and N12 = number of 1100
def count(state):
    n = len(state)
    n0 = n1 = n3 = n12 = 0
    for j in range(n):
        neighbour_sum = int(f"{state[j%n]}{state[(j+1)%n]}{state[(j+2)%n]}{state[(j+3)%n]}",2)
        if neighbour_sum % 4 == 0:
            n0 += 1
            if neighbour_sum == 12:
                n12 += 1
        elif neighbour_sum % 4 == 3:
            n3 += 1
    n1 = n - n0 - n3
    return n0, n1, n3, n12

"""Dynamics"""
def dynamics(state, sweeps, p):
    n = len(state)
    n0, n1, n3, n12 = count(state)
    N0, N1, N3, N12  = np.zeros(sweeps), np.zeros(sweeps), np.zeros(sweeps), np.zeros(sweeps)
    # random state indices
    J = np.random.randint(0, n, size=(sweeps, n))
    #loop
    for t in range(sweeps):
        for tt in range(n):
            # random indices
            j = J[t, tt]
            neighbour_sum = int(f"{state[j%n]}{state[(j+1)%n]}{state[(j+2)%n]}{state[(j+3)%n]}",2)
            if neighbour_sum == 12 and random() < p:
                state[(j+1)%n], state[(j+2)%n] = 0, 1
                n0 -= 1
                n1 += 2
                n3 -= 1
                n12 -= 1
            elif neighbour_sum == 13 and random() < p:
                state[(j+1)%n], state[(j+2)%n] = 0, 1
                if state[(j+4)%n] == 0 and state[(j+5)%n] == 0:
                    n12 += 1
        N0[t], N1[t], N3[t], N12[t] = n0, n1, n3, n12
    return N0/n, N1/n, N3/n, N12/n

def ensembleAvg(ensemble_size):
    ensemble = np.zeros((4, ensemble_size, sweeps))
    for _ in range(ensemble_size):
        state = initialize(rho, n)
        ensemble[0,_], ensemble[1,_], ensemble[2,_], ensemble[3,_] = dynamics(state, sweeps, p)
    return np.average(ensemble,axis = 1)

avg_ensemble = ensembleAvg(ensemble_size)
N0, N1, N3, N12 = avg_ensemble[0], avg_ensemble[1], avg_ensemble[2], avg_ensemble[3]

plt.title(f"size:{n}", color='b');

plt.plot(np.arange(sweeps), N0, color='blue', label = "00")
plt.plot(np.arange(sweeps), N1, color='darkgreen', label = "01 & 01")
plt.plot(np.arange(sweeps), N3, color='purple', label = "11")
plt.plot(np.arange(sweeps), N12, color='red', label = "1100")

plt.legend()
plt.xlabel("Sweeps", fontsize=20);
plt.ylabel("Number density", fontsize=20);
plt.axis('tight');

plt.savefig(f"{n}.pdf")
plt.show()
```


texts:
As I'm learning Rust using the second edition of the Rust book I solved the following exercise:

  Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

I could find this solution: Rust exercise department employee management (which did not receive a lot of feedback).

Do you have any feedback on my implementation? The code works, but I can imagine that some refactoring would be good. It already took me a lot of trial and error to get this working :-)

Suggestions welcome!

use std::io;
use std::collections::HashMap;

fn main() {
    let mut employees:HashMap<String, Vec<String>> = HashMap::new();
    println!("Start adding employees or type 'Done' when finished!");
    loop {
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("error: unable to read user input");
        let parsed_input = dissect_input(input.clone());
        match parsed_input {
            Ok(v) => {
                let (dept, name) = v;
                employees.entry(dept.to_string())
                    .or_insert_with(Vec::new)
                    .push(name)
            }
            Err(e) => {
                if e == "End" {
                    println!("Processed all input, good!\n\n");
                    break;
                } else {
                    println!("Input error!");
                    continue;
                }
            }
        }
    }
    println!("Type the name of a department to get its employees.");
    println!("Type 'All' to get all employees by department.");
    println!("Type 'Quit' to quit.");
    loop {
        let mut command = String::new();
        io::stdin().read_line(&mut command).expect("error: unable to read user input");
        match command.trim() {
            "Quit" => break,
            "All" => {
                for (dept, names) in &employees {
                    let mut names = names.clone();
                    names.sort();
                    for name in names {
                        println!("{}: {}", dept, name);
                    }
                }
            }
            _ => {
                match employees.get(&command.trim().to_string()) {
                    Some(names) => {
                        for name in names { println!("{}: {}", command.trim().to_string(), name); }
                    }
                    None => println!("I don't recognize that!")
                    }
                }
            }
        }
    println!("Have a nice day!");
    }

fn dissect_input(s: String) -> Result<(String, String), String> {
    match s.trim().as_ref() {
        "Done" => Err("End".to_string()),
        _ => {
            let words: Vec<&str> = s.split_whitespace().collect();
            if words.len() != 4 {
                Err("PEBCAK".to_string())
            } else {
            Ok((words[3].to_string(), words[1].to_string())) // “Add Sally to Engineering”
            }
        }
    }

}

// Using a hash map and vectors, create a text interface to allow a user
// to add employee names to a department in a company.
// For example, “Add Sally to Engineering” or “Add Amir to Sales.”
// Then let the user retrieve a list of all people in a department
// or all people in the company by department, sorted alphabetically.
```


texts:
I am creating this converter.
There are three units that can be converted: kelvin, celcius and fahrenheit.
I used two variables to check which unit is chosen.
It's cek and cek2.
Is there any way I can shorten this code,
or I just have to add all possible combination using if statements as i am doing now?

 if (cek=="celcius"&&cek2=="celcius"){
  hasil.setText(nilai.getText());
  } //celcius ke celcius

  if (cek=="celcius"&&cek2=="fahrenheit"){
  double hasil1 = (nilai1*9/5)+32;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }

  if (cek=="celcius"&&cek2=="kelvin"){
  double hasil1 = nilai1+273.15;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }

  if (cek=="fahrenheit"&&cek2=="celcius"){
  double hasil1 = (nilai1-32)*5/9;
  String hasil2 =  String.valueOf(n.format(hasil1));
  hasil.setText(hasil2);
  }
  ....................................


texts: Check smsc type of batch and submits it to the proper queue

texts:
Here, the for loop loops over a arraylist and checks smsc type of batch and submits it to the proper queue.

Is there a way to rewrite this piece of code in a better way?  Is there any way to eliminate the if/else?

for (Batch batch : input.getBatches()){
ArrayList<Messages> arrSentsms = batch.getlist();
String smsc =batch.getSmsc();
    if (smsc.equals("v")) {
            SubmitToQueueV.sendJMSMessage(arrSentsms, priority);
        } else if (smsc.equals("s")) {

            SubmitToQueueS.sendJMSMessage(arrSentsms, priority);
        } else if (smsc.equals("fake1")) {

            SubmitToQueueFake.sendJMSMessage(arrSentsms, priority);
        } else if (smsc.equals("con")) {

            SubmitToQueueCon.sendJMSMessage(arrSentsms, priority);

        } else if (smsc.equals("ce")) {

            SubmitToQueueCEcns.sendJMSMessage(arrSentsms, priority);

        } else if (smsc.equals("cli")) {

            SubmitToxQueueCli.sendJMSMessage(arrSentsms, priority);

        } else if (smsc.equals("pel")) {
            SubmitTQueuePel.sendJMSMessage(arrSentsms, priority);

        } else {
            LOG.debug("smsc" + " smsc not found");
        }
    }
}


texts: Storage class, dependency injection and singletons

texts:
In re-writing my PHP framework vervPHP, I've created the following class:

class storage {
    private static $instance;
    public $db = null; // Holds a database connection object
    public $user = null; // Holds user related information for custom auth
    public $data = array(); // Array of data for storage

    private function __construct(){
        // Create the default array in $this->data....
    }

    public static function singleton() {
        if (!isset(self::$instance)) {
            $className = __CLASS__;
            self::$instance = new $className;
        }
        return self::$instance;
    }

    // Getters, Setters and other stuff follows...
}

When my framework starts up, it looks like this:

index.php:

// Kick it off!
verv\init();

framework/verv/verv.php:

function init() {
    $verv = storage::singleton();

    loadConfig($verv);
    loadRequest($verv);
    connectDB($verv);
    authenticateUser($verv);
    loadModule($verv);
    loadTemplate($verv);
    renderPage($verv);
}

$verv is passed by reference - so any changes are saved as it moves around.

My question is, do I need the singleton portion? And basically, am I doing it "right"? The code in question works (albeit it needs a little tidying) but I want to make sure that my storage class is as robust and efficient as possible.


texts: Avoid redundant code in this simple method

texts:
I am wondering what would be an efficient way to simplify this very simple PHP method and I really lack inspiration:

public function formatToFullDate($countryCode, $hideTime = false)
{
    $format = '';
    if($hideTime === true)
    {
        switch($countryCode)
        {
            case 'us':
            case 'ca':
                $format = '%A %e %B %Y';
                break;
            case 'de':
                $format = '%A, den %e. %B %Y';
            break;
            default:
                $format = '%A %e %B %Y';
        }
    }
    else
    {
        switch($countryCode)
        {
            case 'us':
            case 'ca':
                $format = '%A %e %B %Y - %I:%M %P';
                break;
            case 'de':
                $format = '%A, den %e. %B %Y - %H:%M';
            break;
            default:
                $format = '%A %e %B %Y - %H:%M';
        }
    }

    return gmstrftime($format, $this->getTimestamp());
}


texts: Range of all variables in List in Prolog

texts:
I have a list in Prolog like this:

Puzzle = [ A1, A2, A3,
           B1, B2, B3,
           C1, C2, C3 ].

And I want every variable in the list to be a number in the range of 1 to 9.
Currently I'm doing this like so:

between(1,9, A1),
between(1,9, A2),
% ...
between(1,9, C3).

Even though this works, it's already pretty ugly even for the only 9 numbers I have so far. However I will have to expand my list to contain at least 81 numbers at first (A1 till I9), and even 405 in the end.

I would rather not 'write' 405 lines of code just to limit the range of the numbers in the list, but since I'm new to Prolog, I don't know how I can improve this.


texts:
This is considered as my second python project, I made the password generator where user has to input length of password minimum 5.

I made the code that it will guarantee at least one lowers case, one upper case and one special character is included in the password.
please review and comment.

import random

def letters():
    return list('abcdefghijklmnopqrstuvwxyz')

def upper_case():
    uppercase = []
    for x in letters():
        uppercase.append(x.upper())
    return uppercase

def special_char():
    return list('!@#$%^&*()\'\"')

def all_char():
    return letters() + upper_case() + special_char()

def create_password(password, n):
    for x in range(n):
        password += random.choice(all_char())
    return password

def check_password(password):
    nletter, nupper, nspecial = [0]*3
    for x in password:
        if x in letters():
            nletter += 1
        if x in upper_case():
            nupper += 1
        if x in special_char():
            nspecial += 1
    if nletter > 0 and nupper > 0 and nspecial > 0:
        return True
    else:
        return False

def main():
    n = 0
    while n < 5:
        n = int(input('Enter your password length (minimum 5): '))
    password = ''
    while not check_password(password):
        password = ''
        password = create_password(password, n)
        check_password(password)

    print('Generated password : {}'.format(password))

while True:
    main()


texts: Configuring a currency converter to get exchange rate feeds for for multiple currencies

texts:
I'm trying to make my function more versatile by removing hard coded data.

function get_currency_rate($currencySource) {

if (isset($currencySource)) {
        $feed = $currencySource;
    } else {
        echo 'Feed not found.  Check URL';
    }

    if (!$feed) {
        echo('Feed not found');
    }

    $xml = new SimpleXmlElement($feed);

    $rate = get_rate($xml, 15); //EUR
    if ($feed == 'http://themoneyconverter.com/rss-feed/USD/rss.xml') {
        $rate = get_rate($xml, 16); //GBP
    } else {
        $rate = get_rate($xml, 56);  //USD
    }
}

I would prefer to pass in the values 15, 16, 56 and the URL 'http://themoneyconverter.com/rss-feed/USD/rss.xml' rather than hard coding them into the function.

Below is the get_rate function.

// Get and return currency rate
// Perform regular expression to extrat numeric data
// Split title string to extract currency title
function get_rate(SimpleXMLElement $xml, $xmlTagPosition) {

    $currency['rate'] = $xml->channel->item[$xmlTagPosition]->description;
    preg_match('/([0-9]+\.[0-9]+)/', $currency['rate'], $matches);
    $rate = $matches[0];

    $title['rate'] = $xml->channel->item[$xmlTagPosition]->title;
    $title = explode('/', $title['rate']);
    $title = $title[0];

    echo $rate . ' ' . $title . '
';
}

The feed URLs are set in my cityConfig.php script as below:

// Feed URLs //
$theMoneyConverter = 'http://themoneyconverter.com/rss-feed/';

// Define arrays //
$cities = array('London', 'New York', 'Paris');
$currencyHeadings = array('London - 1 British Pound Sterling', 'New York - 1 US Dollar', 'Paris - 1 Euro');
$currencySource = array($theMoneyConverter . 'GBP/rss.xml', $theMoneyConverter . 'USD/rss.xml', $theMoneyConverter . 'EUR/rss.xml');
$currencyId = array(15, 16, 56);
?>

Notice the $currencyId array values are the same as those hard coded into the get_currency_rate function. I tried passing in a second parameter for the $currencyId to no avail. Any ideas where I'm going wrong?

I have tried the following:

Added an argument onto the end of the feed URL's e.g.

?x=15 // for EURO feed
?x=16 // for GBP feed
?x=56 // for USD feed

These numbers correspond to the position of the  XML tag as an array from the feed URL's.

$currencySource = array($theMoneyConverter . 'GBP/rss.xml?x=15', $theMoneyConverter . 'USD/rss.xml?x=16', $theMoneyConverter . 'EUR/rss.xml?x=56');

I have edited the get_rate function to parse in the URL and the PHP query.

// Get and return currency rate
// Perform regular expression to extrat numeric data
// Split title string to extract currency title
function get_rate(SimpleXMLElement $xml) {

    $vars = parse_url($xml, PHP_URL_QUERY);
    parse_str($vars);
    echo "x = " . $x;
    //$x = 15;

    $currency['rate'] = $xml->channel->item[$x]->description;
    preg_match('/([0-9]+\.[0-9]+)/', $currency['rate'], $matches);
    $rate = $matches[0];

    $title['rate'] = $xml->channel->item[$x]->title;
    $title = explode('/', $title['rate']);
    $title = $title[0];

    echo $rate . ' ' . $title . '
';
}


texts:
We were asked to implement a program that calculates the number of Fermat witnesses and liars for odd numbers greater 1. This involves Fermat’s little theorem.

Fermat’s little is used to identify whether a possible prime number is composite. It’ll find a number/numbers called Fermat witness then. The other numbers are Fermat liars unless Fermat’s little doesn’t find any witness. Then the number is possibly prime.

# coding=utf-8

"""Basic usage:
$ python fermat.py 7
(0, 0)
$ python fermat.py 9
(6, 2)
"""

import argparse

def main():
    """Prints out the results of fermat_witness_liar_count().
    fermat_witness_liar_count() takes a non-optional integer as an argument.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument('possible_prime', type=int)
    args = parser.parse_args()

    if args.possible_prime > 1 and args.possible_prime % 2 == 1:
        print(fermat_witness_liar_count(args.possible_prime))
    else:
        print("Please enter an odd integer > 1.")

def fermat_witness_liar_count(possible_prime):
    """Counts the amount of Fermat witnesses and liars
    for a number 1 <= test_num <= possible_prime.
    Basic usage:
    >>> fermat_witness_liar_count(3)
    (0, 0)
    >>> fermat_witness_liar_count(9)
    (6, 2)
    >>> fermat_witness_liar_count(31)
    (0, 0)
    >>> fermat_witness_liar_count(33)
    (28, 4)
    >>> fermat_witness_liar_count(437)
    (432, 4)
    """

    witness_count = 0
    liar_count = 0
    temp_liar_count = 0

    for test_num in range(1, possible_prime):
        if fermat_witness(test_num, possible_prime):
            witness_count += 1
        else:
            temp_liar_count += 1

    # When there are Fermat witnesses, all test_num’s that aren’t are Fermat liars
    if witness_count != 0:
        liar_count = temp_liar_count

    return witness_count, liar_count

def fermat_witness(test_num, possible_prime):
    """Basic usage:
    >>> fermat_witness(2, 3)
    False
    >>> fermat_witness(8, 9)
    False
    >>> fermat_witness(30, 31)
    False
    >>> fermat_witness(3, 33)
    True
    >>> fermat_witness(6, 437)
    True
    """

    if pow(test_num, possible_prime-1) % possible_prime != 1:
        # test_num is a Fermat witness, possible_prime composite
        return True

    # possible_prime may be prime
    return False

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    main()


texts: Are there any improvements I can make to my implementation of the strategy pattern?

texts:
I'm not sure about that if else statement in function Change().  I'm guessing there is a way to eliminate this and make better use of OOP principles.  Does anyone have any suggestions?

PS This code is functional and produces the desired result.

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

namespace ConsoleApplication1_testStrategy
{
    class Program
    {
        static void Main(string[] args)
        {
            string message = "mytext";

            Changer chng = new Changer();

            //THis is how I want the usage, I want the user to specify the string
            //and also which algorithm to invoke by specifyin the enumeration type
            string messageModified = chng.Change(message, types.type2);
        }
    }

    //ENUMERATION OF TYPES
    public enum types
    {
        type1,
        type2
    }

    //Abstact strategy
    public interface IStringModifier
    {
        string Modify(string input);
    }

    //concrete strategy 1
    class type1 : IStringModifier
    {
        public string Modify(string input)
        {
            return "hello1";
        }
    }

    //conctrete strategy 2
    class type2 : IStringModifier
    {
        public string Modify(string input)
        {
            return "hello2";
        }
    }

    //MAIN API I WANT USER TO ACCESS
    public class Changer
    {
        public Changer()
        {
        }

        private IStringModifier _stringModifier;

        public void SetStringModifier(IStringModifier stringModefier){

            this._stringModifier = stringModefier;
        }

        public string Change(string text, types type) //not sure about this part
        {
            if (type == types.type1)
            {
                SetStringModifier(new type1());
            }
            else if (type == types.type2)
            {
                SetStringModifier(new type2());
            }

            return _stringModifier.Modify(text);
        }

    }
}


texts: Quickly check whether file name is in column in an SQL Table and move to new folder

texts:
I have a table that in one of the columns exists a list of file names.  The names comes from other tables and the files in a folder.

Not all the files are used, may be attached to parcels that no longer are active.  My list is of only the active parcels.

After creating the table I want to go through the folder of files and move the files that are being used(exist in the table) to another folder.

Currently I iterate the files in the folder and test whether each file one at a time returns a record or not using an SQL command.

This works, but the consistent checking back to the database is slow.

Here is the code as it sits now:

param(
    [string] $src,
    [string] $dest,
    [string] $table
    )

$sql_instance_name = 'db'
$db_name = 'DB2'
$sql_user = 'user'
$sql_user_pswd = 'password'

Get-ChildItem -Path $src -Recurse -File | ForEach-Object  {
    $query = "select * from " + $table + " WHERE FILE_NAME Like '" + $_.BaseName + $_.Extension +  "'"
    #write-output $query

    $expcsv = invoke-sqlcmd -Username $sql_user -PASSWORD $sql_user_pswd -Database $db_name -Query $query -serverinstance $sql_instance_name
    if($expcsv -ne $null)

    {
        $nextName = Join-Path -Path $dest ( $_.BaseName  +  $_.EXTENSION)
        Write-Output $nextName
        $_ | Move-Item -Destination   $nextName
    }
}

Is there a way to load the data into memory, and search that instead of going back and forth from the database? I have to assume it would be quicker.


texts:
I read about lookups in lists and I think that is what I did. I would like to compare it to a skip list, a binary search or a B+ tree.

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

typedef struct node {
    int node_id;
    int data;
    struct node *left;
    struct node *right;
} node;

node *newNode(int data, int node_id) {
    node *new_node = (node *) malloc(sizeof(node));
    new_node->data = data;
    new_node->node_id = node_id;
    new_node->right = new_node->left = NULL;
    return new_node;
}

node *insert_node(node *root, int data, int node_id) {
    if (root == NULL)
        return newNode(data, node_id);
    else {
        node *cur;
        if (node_id < root->node_id) {
            cur = insert_node(root->left, data, node_id);
            root->left = cur;
        } else if (node_id > root->node_id) {
            cur = insert_node(root->right, data, node_id);
            root->right = cur;
        }
    }
    return root;
}

node *find_node_data(node *root, int node_id) {
    if (root == NULL)
        return NULL;
    else if (root->node_id == node_id)
        return root;
    else if (root->node_id > node_id)
        return find_node_data(root->left, node_id);
    else
        return find_node_data(root->right, node_id);
}

void print(node *np) {
    if (np) {
        print(np->left);
        printf("(%d, %d)", np->node_id, np->data);
        print(np->right);
    }
}

int main() {
    int T = 1000; //test case 1000 nodes
    int data, node_id;
    //printf("Input number of nodes:");
    //scanf("%d", &T);
    node *root = NULL;
    srand (time (NULL));
    while (T-- > 0) {
        //printf("Input data. %d:", T);
        //scanf("%d %d", &data, &node_id);
        int r = rand() % 1000;
        int r2 = rand() % 1000;
        root = insert_node(root, r, r2);
    }
    print(root);
    printf("\n");
    printf("Find data at node:", T);
    scanf("%d", &T);
    printf("node data %d", find_node_data(root, T)->data);
    return 0;
}


texts:
I have created a really simple repository for some simple data retrieval and was wondering if i was going in the right direction.  Has anyone got any thoughts on this?

interface

public interface IRepository<T> where T : class {
    IEnumerable<T> GetAll();
    T GetById(int id);
    IEnumerable<T> Filter(Expression<Func<T, bool>> filter);
    void Dispose();
}

class

public class JobRepository : IRepository<Job>, IDisposable{
    /// <summary>
    /// handles all job data retrieval
    /// crude but will suffice for now
    /// </summary>
    CentralRepositoryContainer _context = null;

    public JobRepository() {
        CentralRepositoryContainer context =
            HttpContext.Current.GetCentralRepositoryContext();
    }

    /// <summary>
    /// returns all jobs
    /// </summary>
    /// <returns>IEnumerable<Job></returns>
    public IEnumerable<Job> GetAll() {
        try {
            return this._context.Jobs;
        } catch (SqlException ex) {
            //error so dispose of context
            this.Dispose();
            //wrap and rethrow back to caller
            throw new CentralRepositoryException("Error getting all jobs", ex);
        }

    }

    /// <summary>
    /// return job
    /// </summary>
    /// <param name="id">integer to search on</param>
    /// <returns>job</returns>
    public Job GetById(int id) {
        try {
            return this._context.Jobs.SingleOrDefault(j => j.JobId == id);
        } catch (SqlException ex) {
            //error so dispose of context
            this.Dispose();
            //wrap and rethrow back to caller
            throw new CentralRepositoryException("Error getting all job by id", ex);
        }
    }

    /// <summary>
    /// filters based on parsed filter expression
    /// </summary>
    /// <param name="filter">filter to search on</param>
    /// <returns>IQueryable<Job></returns>
    public IEnumerable<Job> Filter(System.Linq.Expressions.Expression<Func<Job, bool>> filter) {
        try {
            return this._context.Jobs.Where(filter);
        } catch (SqlException ex) {
            //error so dispose of context
            this.Dispose();
            //wrap and rethrow back to caller
            throw new CentralRepositoryException("Error getting all job by filter", ex);
        }
    }

    public void Dispose() {
        if (this._context != null) {
            this._context.Dispose();
        }
    }
}


texts: Is WebClient.DownloadData acceptable for getting data from a website?

texts:
Currently on my ASP.NET website when I define a new user I write their data to a .txt file like this:

public class User
{
public string UserName;
public string PassWord;
public string Email;
public string FirstName;
public string LastName;
public string Twitter;
public string FaceBook;
public int Age;
public DateTime DateCreated;

public User(string username, string password, string email, string facebook, string twitter, string firstname, string lastname, int age, DateTime datecreated)
{
    UserName = username;
    PassWord = password;
    Email = email;
    FirstName = firstname;
    LastName = lastname;
    Age = age;
    DateCreated = datecreated;
    Twitter = twitter;
    FaceBook = facebook;

    AddToTextFile();
}

public bool CheckUsername(string username, List<User> users)
{
    for (int i = 0; i < users.Capacity; i++)
    {
        if (users[i].UserName == username) return true;

        else return false;
    }

    return false;
}

public bool CheckPassword(string username, string password, List<User> users)
{
    for (int i = 0; i < users.Capacity; i++)
    {
        if (users[i].UserName == username)
        {
            if (users[i].PassWord == password) return true;

            else return false;
        }

        else return false;
    }

    return false;
}

private void AddToTextFile()
{
    string file = "../users-information.txt";
    StreamWriter sw = new StreamWriter(@file);
    sw.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8}", UserName, PassWord, FirstName, LastName, Email, FaceBook, Twitter, Age, DateCreated);
}

Then on my C# app I use WebClient.DownloadData to get the data and write it to a file.

    private void GetUsers()
    {
        //JavaScriptSerializer serializer = new JavaScriptSerializer();
        //users = serializer.Deserialize<User[]>(Request.Form["users"]);

        WebClient client = new WebClient();
        byte[] file = client.DownloadData("http://kinected-security.com/users-information.txt");

        File.WriteAllBytes(@"../user-information/user-information.txt", file);

        string[] lines = File.ReadAllLines("../user-information/user-information.txt");

        if (lines.Length != 0)
        {
            foreach (string line in lines)
            {
                string[] splited = new string[]{ };
                splited = line.Split(new Char[] {' ' });

                users.Add(new User(splited[0], splited[1], splited[2], splited[3], splited[4], splited[5], splited[6], int.Parse(splited[7]), DateTime.Parse(splited[8])));
            }
        }
    }

Should I be using WebClient.DownloadString? Is there a more efficient way to do this?


texts:
I have implemented a recursive binary search in Python and tried to implement some verification to my code. Other than that, is there any optimization I am missing?

def isSorted(ary):
    for i in range(1, len(ary)):
        if (ary[i] < ary[i - 1]):
            return False
    return True

def binSearch(ary, elem, first, last):
    if not isSorted(ary):
        raise AssertionError("Elements are not in sorted order!")
    mid = (first + last) / 2
    if (ary[mid] < elem):
        return binSearch(ary, elem, mid + 1, last)
    elif (ary[mid] > elem):
        return binSearch(ary, elem, first, mid - 1)
    else:
        return mid

ary = (1, 2, 3, 4, 5, 6, 7)
print binSearch(ary, 5, 0, len(ary) -1)