texts:
I'm using C# .NET Core 2.1 and Excel lib DotnetCore.NPOI

I'm converting xls file to xlsx by loading xls and copying sheet by sheet, cell by cell to xlsx - How can I improve performance / ram usage here?

private string ConvertToXSLX(string path)
{
    using (var fs = File.OpenRead(path))
    {
        var result = XLS_to_XLSX_Converter.Convert(fs);

        // (file.xls) + x = file.xlsx
        path = $"{path}x";

        using (var fs2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
        {
            fs2.Write(result, 0, result.Length);
        }
    }
    return path;
}

public static byte[] Convert(Stream sourceStream)
{
    var source = new HSSFWorkbook(sourceStream);
    var destination = new XSSFWorkbook();

    for (int i = 0; i < source.NumberOfSheets; i++)
    {
        var hssfSheet = (HSSFSheet)source.GetSheetAt(i);

        var xssfSheet = (XSSFSheet)destination.CreateSheet(source.GetSheetAt(i).SheetName);

        CopyRows(hssfSheet, xssfSheet);
    }

    using (var ms = new MemoryStream())
    {
        destination.Write(ms);
        return ms.ToArray();
    }
}

private static void CopyRows(HSSFSheet hssfSheet, XSSFSheet destination)
{
    for (int i = 0; i < hssfSheet.PhysicalNumberOfRows; i++)
    {
        destination.CreateRow(i);

        var cells = hssfSheet.GetRow(i)?.Cells ?? new List<ICell>();

        for (int j = 0; j < cells.Count; j++)
        {
            var row = destination.GetRow(i);
            row.CreateCell(j);

            CopyCell((HSSFCell)cells[j], (XSSFCell)row.Cells[j]);
        }
    }
}

private static void CopyCell(HSSFCell oldCell, XSSFCell newCell)
{
    CopyCellValue(oldCell, newCell);
}

private static void CopyCellValue(HSSFCell oldCell, XSSFCell newCell)
{
    switch (oldCell.CellType)
    {
        case CellType.String:
            newCell.SetCellValue(oldCell.StringCellValue);
            break;
        case CellType.Numeric:
            newCell.SetCellValue(oldCell.NumericCellValue);
            break;
        case CellType.Blank:
            newCell.SetCellType(CellType.Blank);
            break;
        case CellType.Boolean:
            newCell.SetCellValue(oldCell.BooleanCellValue);
            break;
        case CellType.Error:
            newCell.SetCellErrorValue(oldCell.ErrorCellValue);
            break;
        default:
            break;
    }
}


texts: Using Java to Add the Contents of two EditText views in Android

texts:
I have a toy app that contains:

editText1 for entering a number. Uses inputType of number.
editText2 for entering a second number. Uses inputType of number.
adderButton for triggering addition.
textVeiw  for displaying the result of the addition.

I know:

The naming could be better
I should check for overflow/underflow on the addition and elsewhere.

This code is working for simple cases.

 public void adder_click(View view) {
        EditText et1 = (EditText) findViewById(R.id.editText1);
        EditText et2 = (EditText) findViewById(R.id.editText2);
        Integer s = Integer.valueOf(et1.getText().toString()) + Integer.valueOf(et2.getText().toString());
        TextView tv = (TextView) findViewById(R.id.textView);
        tv.setText(s.toString());
    }

Is there a more direct way of reading the values and performing the addition?


texts:
While writing a C++ GUI application more or less from scratch I needed some form of an event-listener system, preferably using lambdas. An event should be able to have multiple listeners and the user should not have to worry about the lifetime of the objects. I came up with this bit using shared and weak pointers to determine object lifetime:

#include <functional>
#include <list>

template <typename ... Args> struct event:public std::shared_ptr<std::list<std::function<void(Args...)>>>{

  using handler = std::function<void(Args...)>;
  using listener_list = std::list<handler>;

  struct listener{
    std::weak_ptr<listener_list> the_event;
    typename listener_list::iterator it;

    listener(){ }

    listener(event & s,handler f){
      observe(s,f);
    }

    listener(listener &&other){
      the_event = other.the_event;
      it = other.it;
      other.the_event.reset();
    }

    listener(const listener &other) = delete;

    listener & operator=(const listener &other) = delete;

    listener & operator=(listener &&other){
      reset();
      the_event = other.the_event;
      it = other.it;
      other.the_event.reset();
      return *this;
    }

    void observe(event & s,handler f){
      reset();
      the_event = s;
      it = s->insert(s->end(),f);
    }

    void reset(){
      if(!the_event.expired()) the_event.lock()->erase(it);
      the_event.reset();
    }

    ~listener(){ reset(); }
  };

  event():std::shared_ptr<listener_list>(std::make_shared<listener_list>()){ }
  event(const event &) = delete;
  event & operator=(const event &) = delete;

  void notify(Args... args){
    for(auto &f:**this) f(args...);
  }

  listener connect(handler h){
    return listener(*this,h);
  }

};

Example usage:

#include <iostream>

using click_event = event<float,float>;

struct gui_element{
  click_event click;
  void mouse_down(float x,float y){ click.notify(x, y); }
};

int main(int argc, char **argv) {
  gui_element A,B;
  click_event::listener listener_1,listener_2;

  listener_1.observe(A.click,[](float x,float y){ std::cout << "l1 : A was clicked at " << x << ", " << y << std::endl; });
  listener_2.observe(B.click,[](float x,float y){ std::cout << "l2 : B was clicked at " << x << ", " << y << std::endl; });

  {
  auto temporary_listener = A.click.connect([](float x,float y){ std::cout << "tmp: A was clicked at " << x << ", " << y << std::endl; });
  // A has two listeners, B has one listeners
  A.mouse_down(1, 0);
  B.mouse_down(0, 1);
  }

  listener_2 = std::move(listener_1);

  // A has one listener, B has no listeners
  A.mouse_down(2, 0);
  B.mouse_down(0, 2);
}

Output:

l1 : A was clicked at 1, 0
tmp: A was clicked at 1, 0
l2 : B was clicked at 0, 1
l1 : A was clicked at 2, 0

While the usage is exactly how I wanted, I am not sure the implementation is elegant or optimal. Any way how to improve this?


texts:
Here's a function for making multiple copies of a block of memory in another block of memory. It handles the case when the size of the target is smaller than or not a perfect multiple of the source pattern.

It proceeds by copying the pattern once, twice, four times, eight times, etc. until it can make a last 'massive' copy and fill the target buffer.

The protocol on this site is (apparently) to answer your own question with the improved code rather than edit original question. That makes sense otherwise other answers and feedback may be difficult to understand!

#include <string.h> //This is where memcpy() hangs out. I know! I know!

///Fills a block of memory with a specified pattern.
///The target block starts at pToFill and extends for pToFillSize bytes.
///The source pattern starts at pFillWith and extends for pFillWithSize bytes.
///Will fill the whole buffer including a trailing partial pattern at the end (if necesssary).
///pFillWithSize must not be 0. pFillWith must not be NULL.
///If Either pToFill is NULL or pToFillSize is 0, does nothing and returns without error.
///The area to fill and pattern must not overlap or behaviour is undefined.
void memcopyfill(void*const pToFill,const size_t pToFillSize,void*const  pFillWith,const size_t pFillWithSize){
    if(pToFill==NULL||pToFillSize==0){
        return;//Nothing to do.
    }
    if(pFillWith==NULL||pFillWithSize==0){
        return;//Can do nothing...
    }
    if(pToFillSize<pFillWithSize){
        memcpy(pToFill,pFillWith,pToFillSize);
        return;//Short buffer.
    }
    //The to buffer is bigger so we start with a full copy of pattern.
    //Now we keep doubling the copies by copying and copying from the target onto itself.
    char*lFillFrom=((char*)pToFill)+pFillWithSize;
    size_t lFilledSoFar=pFillWithSize;
    char*lFillEnd=((char*)pToFill)+pToFillSize;
    while(lFilledSoFar<(lFillEnd-lFillFrom)){//Overflow safe.
        memcpy(lFillFrom,pToFill,lFilledSoFar);
        lFillFrom+=lFilledSoFar;
        lFilledSoFar=lFilledSoFar<<1;//Doubling....
    }
    //No we can fill the end of the buffer in one final step. Could be half the job.
    memcpy(lFillFrom,pToFill,pToFillSize-lFilledSoFar);
}

Can it be bettered?

One use is to fill an array with a default structure.
If that is the purpose you don't need the initial fannying about with the short buffer special case.

There is no guarantee that NULL has a bit-pattern of all zeros so if you wanted to be ultra-ultra portable you ought to be doing something like this to get an array full of NULL.

I think most people use calloc(.) and don't even think about it.

If you use it for strings don't forget your null terminator!

Bonus question

Does anyone know of an extant platform where NULL doesn't have a zero filled bit-pattern?

I half remember one where it was 0xFFF...FF and that was clever because the hardware could detect overflow easily and handle all sorts of wrap-around errors gracefully. I'm damned if I can remember what it was. It may have been a hypothetical example to show why standards should give implementers freedom.


texts:
I'm not really even sure if this counts as a game. There is so little code, but it works. It is a game where you have to guess the computers number, and it tells you how many times you took to get it right. I kind of want feedback, and not ways to improve the code. I want to know ways to improve my future projects and what to avoid again.

def main():
    # Guess My Number
    #
    # The computer picks a random number between 1 and 100
    # The player tries to guess it and the computer lets
    # the player know if the guess is too high, too low
    # or right on the money

    import random

    def ask_number(question, low, high, step):
        response = None
        while response not in range(low, high):
            response = int(input(question))
        return response
        tries += step

    #Opening Remarks
    print("Welcome to 'Guess My Number'!")
    print("I'm thinking of a number between 1 and 100.")
    print("Try to guess it in as few attempts as possible.")

    # set the initial values
    the_number = random.randint(1, 100)
    # Create the priming read here
    tries = 0
    guess= 0
    while int(guess) != int(the_number):

        guess = ask_number("Enter your guess:", 1, 100, 1)

        if int(guess) == int(the_number):
            print("Your right on the money!")
        elif int(guess) > int(the_number):
            print("To high!")
        elif int(guess) < int(the_number):
            print("To low!")

        tries += 1
    #Didnt know how to make it reloop to the start...
    print("You guessed it!  The number was", the_number)
    print("And it only took you", tries, "tries!")

    #Program Closing
    input("Press the enter key to exit.")

main()


texts: Python Clean way to get whether a number is above/below two values and increment accordingly

texts:
Consider (simplified)

low_count = 0
high_count = 0
high = 10
low = 5
value = 2

What is a clean way to check a number value versus a min low and a max high, such that if value is below low low_count increments, and if value is above high high_count increments? Currently I have (code snippet)

            high_count = 0
            low_count = 0
            low = spec_df['Lower'][i]
            high = spec_df['Upper'][i]
            #Calculate results above/below limit
            for result in site_results:
                if result<low:
                    low_count+=1
                else:
                    if result>high:
                        high_count+=1

Thanks!


texts: Armstrong numbers in a given range using Java 8

texts:
Was fiddling with java-8; trying to write a program for getting all Armstrong Numbers between 1 and 10_000_000.

Following is my working solution:

public class ArmstrongNumbers {

    public static void main(String[] args) {
        IntStream.range(1, 10_000_000)
                .filter((n) -> {
                    int c = 0, temp = n;
                    while (temp > 0) {
                        c += Math.pow(temp % 10, Integer.toString(n).length());
                        temp /= 10;
                    }
                    return c == n;
                }).forEach(System.out::println);
    }

}

Output:

1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
54748
92727
93084
548834
1741725
4210818
9800817
9926315

Why I'm here:

Can this be made shorter?
Can any other Java 8 concept be used here?
Can the use of the while loop be avoided and a stream be used somehow (given that it is more elegant)?
Review overall correctness

Here is a link to a list of Armstrong Numbers for verifying the outputs.

Please note that there is a follow up question.


texts:
I cache the data and use local database in my Windows Phone app. The algorithm is very simple:

Get data from DB and show in UI
Get data from a web service and show in UI
Update data in DB from the web service

Some data need to be saved in DB, and some do not need to.

For these purposes, I have the following classes.

GYDataAccessLayer is an entry point. This class sets and changes the data source.

Example:

GYDataAccessLayer da = new GYDataAccessLayer();
da.GetInfo((result, error) =>
 {
    if (error != null) { return; } // handling exception
    GYUser user = result;
 });

public class GYDataAccessLayer
{
    public void GetUserInfo(Action<GYUser, Exception> act, string id)
    {
        GYDataSource dataSource = new GYDataSource(new GYLocalData());
        dataSource.GetUserInfo(act, id);

        dataSource.SetDataSource(new GYWebData());
        dataSource.GetUserInfo(act, id);
    }
}

public class GYDataSource
{
    IGYDataAccess _gyDataAccess;

    public GYDataSource(IGYDataAccess gyDataAccess)
    {
        _gyDataAccess = gyDataAccess;
    }

    public void SetDataSource(IGYDataAccess gyDataAccess)
    {
        _gyDataAccess = gyDataAccess;
    }

    public void GetInfo(Action<GYUser, Exception> act, string uid)
    {
        _gyDataAccess.GetUserInfo(act, uid);
    }
}

I have a two classes to work with Local and Web data source. GYWebData gets data from web and calls update method in GYLocalData.

public interface IGYDataAccess
    {
        void GetUserInfo(Action<GYUser, Exception> act, string id);
    }

public class GYWebData : IGYDataAccess
{
    public void GetUserInfo(Action<GYUser, Exception> act, string id)
    {
        GYUserAPI.GetInfo(id, (result, error) =>
            {
                if (error != null)
                {
                    act.Invoke(null, error);
                    return;
                }

                act.Invoke(result.Result, null);
                GYLocalData gyLocalData = new GYLocalData();
                gyLocalData.UpdateUserInfo(result.Result);

            });
    }
}

 public class GYLocalData : IGYDataAccess
{
    private const string ConnectionString = @"isostore:/Cache.sdf";
    CacheDataContext DataBase;
    CacheDataContextProfiles DataBaseProfiles;

    private void CheckDataBase()
    {
        using (DataBase = new CacheDataContext(ConnectionString))
        {
            if (!DataBase.DatabaseExists())
            {
                DataBase.CreateDatabase();
            }
        }
    }

    public void GetUserInfo(Action<GYUser, Exception> act, string id)
    {
        CheckDataBase();

        using (DataBaseProfiles = new CacheDataContextProfiles(ConnectionString))
        {
            try
            {
                var user = DataBaseProfiles.GetInfo(id);
                if (user != null)
                {
                    act.Invoke(user, null);
                }
            }
            catch (Exception ex)
            {

                act.Invoke(null, ex);
            }
        }
    }

   public void UpdateUserInfo(GYUser user)
    {
        CheckDataBase();

        using (DataBaseProfiles = new CacheDataContextProfiles(ConnectionString))
        {
            DataBaseProfiles.UpdatePersonProfile(user);
        }
    }
 }

With this architecture it is inconvenient to work and hard to support. You have to write a lot of code and be very attentive (eg do not forget to call the update data method in the DB). Are there good patterns for such problems? How can I improve this code?


texts: Python multiprocessing for tasks depending on each other

texts:
I have a simulation that runs a process on a tree structure, where the slow processes down processes are separate from each other. This looked like a thing that would be a prime candidate for multiprocessing to me, so I tried to wrap my head around the python multiprocessing module and its locks, pools etc. and wrote a toy example that walks down a length-annotated tree, where each branch of the tree waits for its parent.

import multiprocessing
import time
import newick

t = newick.loads("((A:2,B:2)C:2,D:4)E:1")[0]

manager = multiprocessing.Manager()
generated_languages = manager.dict()
# The root should be allowed to start computation immediately. The parent of
# the root is `None`, initialize it with some starting state of the
# simulation which is not false.
generated_languages[None] = True
# Processes will want to write results to file. This can take some time,
# provide a lock around the file access.
io_lock = manager.Lock()

def mp_worker(node):
    """Run the simulation on the branch leading to `node`.

    That process takes time proportional to the branch length.

    """
    def parent_done():
        """Check whether the parent node has been generated yet."""
        print("Parent {:} generated: {:}".format(
            parent, generated_languages.get(parent)))
        return generated_languages.get(parent)

    name = node.name
    # We cannot have duplicate names, and we cannot have unnamed nodes.
    assert name not in generated_languages
    parent = None if node.ancestor is None else node.ancestor.name

    print("Process {:s}\tWaiting for parent {:}".format(name, parent))
    start_from = parent_done()
    while not start_from:
        time.sleep(1)
        start_from = parent_done()

    print("Process {:}\t‘running the simulation’ (ie., waiting {:}s)".format(
        (node.name, node.length))
    time.sleep(int(node.length))
    result = start_from

    generated_languages[name] = result

    # Write result to file.
    io_lock.acquire()
    print("Process {:}\tDONE with result {:}".format(
        name, result))
    io_lock.release()

    return result

p = multiprocessing.Pool(2)

for result in p.imap(mp_worker, t.walk()):
    print(result)

Now this works, it generates the expected output (tree nodes in pre-order, with no node process started before its parent is finished) but it does not look like good code to me. I noticed a few problems myself which I don't know how to do cleanly

I think manager should be used in a context manager, but mp_worker can only get one argument from pool.imap, so I want mp_worker to be a closure on manager, which means it must be valid at definition-time as well as at run-time of mp_worker, which feels wrong.
The waiting loop should obviously replaced by something else. Should it be one Condition? One Condition for each Node? Something else entirely? How?
With its current structure, a long branch is likely to block its children when the simulation could be continued somewhere else in the tree. The heuristic way around this is to sort nodes by their distance from the root and iterate them in highest-first-order, which is possible with my structure here. A cleverer way might involve a queue of nodes still waiting for their parent, what would be the best pattern (instead of pool.imap) to implement that?
The bounding factors for writing to a file will be different from the ones for running the simulation. Writing to a file may take seconds, running the simulation on one branch hours. I assume it is fine to have one blocking process doing both, given these different orders of magnitudes?


texts:
I'm trying to avoid manually updating a whitelist of pages, so I wrote the following that I might use, but I'd like my fellow, more experienced, developers to let me know if this is safe. By safe, I mean that it won't allow the inclusion or execution of arbitrary code. Is it safe from directory traversal and other similar vectors?

<?php
$current_page = 'default_page';
//Get list of acceptable pagenames:
$found_pages = [];
if ($handle = opendir('pages')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $found_pages[]= $entry;
        }
    }
    closedir($handle);
}

if(isset($_GET)){
  $requested_page=reset($_GET); //just need value of first GET element, regardless of name.
  if(in_array($requested_page.'.php',$found_pages)){
    $current_page=$requested_page;
  }
}

include('pages/' . $current_page . '.php');


texts:
For the time being, I am not interested in any recursive solution. The code is not modularized; the whole body is inside the main function.

#include<iostream.h>
#include<stdlib.h>
/*This code is written by NF between any time of 120711 and 210711;modified at 231211*/

int main()
{
    int length=0,min_heapified=0,start_length=0,index=0;
    cout<<"Enter Array Length:";
    cin>>length;
    int array[length];
    for(int i=0;i<length;i++)
    {
        array[i]=rand()%100;
    }
    cout<<"Array is filled now with random elements";
    cout<<"\nSorted Array:"<<endl;
    do
    {
            do
            {
                min_heapified=0;
                for(int root=0;root<length/2;root++)/*As the leaf nodes have no child they should not be in a consideration while swapping so looping upto length/2 is enough*/
                {

                    int left=((2*root)+1);
                    int right=((2*root)+2);

                    if(left<length)
                    {
                           if(array[left]<array[root])
                           {
                                int swap=array[left];
                                array[left]=array[root];
                                array[root]=swap;
                                min_heapified=1;
                           }
                     }
                    if(right<length)
                     {
                            if(array[right]<array[root])
                            {
                                 int swap=array[right];
                                 array[right]=array[root];
                                 array[root]=swap;
                                 min_heapified=1;
                             }
                      }

                  }

             }while(min_heapified>0);

            int swap=array[0];
            array[0]=array[--length];/*modification done at this point to avoid keeping the sorted elements into another array;and swapping done between the 0th and last element*/
            array[length]=swap;
            cout<<array[length]<<" ";

 }while(length>0);

  return 0;

}


texts:
I need to know if the following lines of code represent a valid implementation of Strategy Pattern in Java 8:

public interface AIStrategy {
    void play();
}

public class AIPlayer {

    private AIStrategy aiStrategy;

    public AIPlayer() {
    }

    public AIPlayer(AIStrategy aiStrategy) {
        this.aiStrategy = aiStrategy;
    }

    public void changeStrategy(AIStrategy aiStrategy) {
        this.aiStrategy = aiStrategy;
    }

    public void fight() {
        aiStrategy.play();
    }
}

public class App {

    public static void main(String[] args) {
        AIPlayer aiPlayer = new AIPlayer();
        String difficulty;

        Scanner sc = new Scanner(System.in);
        difficulty = sc.next();

        switch (difficulty) {
            case "chill":
                aiPlayer = new AIPlayer(()
                        -> System.out.println("The opponent is playing a chill strategy..."));
                aiPlayer.fight();
                break;
            case "calculated":
                aiPlayer = new AIPlayer(()
                        -> System.out.println("The opponent is playing a calculated strategy..."));
                aiPlayer.fight();
                break;
        }

        System.out.println("Is the opponent hurt?");
        boolean isHurted = sc.nextBoolean();
        if (isHurted) {
            aiPlayer.changeStrategy(()
                    -> System.out.println("The opponent changed his strategy. Now he is having a holy rage!!"));
            aiPlayer.fight();
        }
    }
}


texts: JUnit - Test whether object was persisted or not

texts:
I am using Hibernate 4 and Spring Framework 4. I wrote a simple test to check whether object was persisted or not.

All set values in confirmationEntity are required.

In this test I relly on that, that after a new object is persisted, then it is given a new id automatically.

Is this correct way how to determine if the object was persisted or not? Or is there better way?

@Test
public void testCreated(){
    ConfirmationTypeEntity confirmationTypeEntity = confirmationTypeDao.find(1L);
    UserEntity userEntity = userDao.find(1L);

    ConfirmationEntity confirmationEntity = new ConfirmationEntity();
    confirmationEntity.setConfirmationTypeEntity(confirmationTypeEntity);
    confirmationEntity.setUserEntity(userEntity);
    confirmationEntity.setConfirmationString("5374a74e9542f");
    confirmationEntity.setConfirmationStringValidUntil(new LocalDateTime());

    confirmationDao.create(confirmationEntity);
    confirmationDao.flush();

    Assert.assertNotNull("Expected not null value.", confirmationEntity.getId());
}


texts:
I've made my attempt to code timer entirely by hand using jQuery. No external libraries to manage time at all.

$(document).ready(function() {
 var setSessionMinutes = 5,
  setBreakMinutes = 5,
  sessionMinutes = setSessionMinutes,
  breakMinutes = setBreakMinutes,
  counterSeconds = -1,
  countTimeout,
  runState = false;

 function setClockValues() {
  $('#break').html(setBreakMinutes);
  $('#session').html(setSessionMinutes);
  $('#time').html(formatTime(setSessionMinutes, 0));
  sessionMinutes = setSessionMinutes;
  breakMinutes = setBreakMinutes;
  counterSeconds = -1;
 };
 setClockValues();

 function formatTime(minutes, seconds) {
  minutes = minutes >= 10 ? minutes : '0' + minutes;
  seconds = seconds >= 10 ? seconds : '0' + seconds;
  return minutes + ':' + seconds;
 }

 //change values by buttons
 $('#minusbreak').click(function() {
  $('#break').html(setBreakMinutes > 0 ? --setBreakMinutes : 0);
  breakMinutes = setBreakMinutes;
 });
 $('#plusbreak').click(function() {
  $('#break').html(++setBreakMinutes);
  breakMinutes = setBreakMinutes;
 });
 $('#minusSession').click(function() {
  $('#session').html(setSessionMinutes > 0 ? --setSessionMinutes : 0);
  $('#time').html(formatTime(setSessionMinutes, 0));
  sessionMinutes = setSessionMinutes;
 });
 $('#plusSession').click(function() {
  $('#session').html(++setSessionMinutes);
  $('#time').html(formatTime(setSessionMinutes, 0));
  sessionMinutes = setSessionMinutes;
 });

 function countDown() {
  if (counterSeconds < 0 && sessionMinutes >= 0) {
   --sessionMinutes;
   counterSeconds = 59;
  }
  $('#time').html(formatTime(sessionMinutes, counterSeconds));
  --counterSeconds;
  if (counterSeconds >= 0 && sessionMinutes >= 0)
   countTimeout = setTimeout(countDown, 1000);
  else {
   $('#finish').get(0).play();
   setTimeout(countDownBreak, 1000);
  }
 }

 function countDownBreak() {
  if (counterSeconds < 0 && breakMinutes >= 0) {
   --breakMinutes;
   counterSeconds = 59;
  }
  $('#time').html(formatTime(breakMinutes, counterSeconds));
  --counterSeconds;
  if (counterSeconds >= 0 && breakMinutes >= 0)
   countTimeout = setTimeout(countDownBreak, 1000);
  else {
   stopCountDown();
   $('#status').html('start');
   runState = false;
   $('#finish').get(0).play();
  }
 }
 function stopCountDown() {
  clearTimeout(countTimeout);
  setClockValues();
 }

 //   start/stop timer
 $('#status').click(function() {
  switch (runState) {
   case false:
    $('#status').html('reset');
    countDown();
    runState = true;
    break;
   case true:
    $('#status').html('start');
    stopCountDown();
    runState = false;
    break;
  }
 });

});

You can also see it on CodePen.io.

I realise this code should be 3/4 or even half current length, more DRY etc., but I'd like to get some opinions about code without much optimization to know better where I currently am with my progress. After all, I could spend 12 hours to make it beautiful (which I eventually will), but that would destroy purpose of this post.

About setTimeout instead of setInterval: I did it on purpose because of this.


texts: C# static class holding list of member class instances

texts:
I was wondering if such a design was a bad idea in C#. Here I have a static class EventLog which holds a list of instances of Event class. This is a simple event log of actions players can do in a game. What can I be doing in a better way?

public class EventLog
{
    private const int maxEventsInLog = 50;
    private static List<Event> events = new List<Event>();
    private static string[] eventDescriptions = new string[8]
    {
        "<fromUnit> walked",
        "<fromUnit> waited",
        "<fromUnit> inquired",
        "<fromUnit> allured <toUnit>",
        "<fromUnit> persuaded <toUnit>",
        "<fromUnit> bribed <toUnit>",
        "<fromUnit> hired <toUnit>",
        "<fromUnit> attacked <toUnit>",
    };

public static void AddEvent(GameObject _fromUnit, GameObject _toUnit, Utils.ActionType _actionType)
{
    events.Add(new Event(_fromUnit, _toUnit, _actionType));

    if (events.Count > maxEventsInLog)
    {
        while (events.Count > maxEventsInLog)
        {
            events.RemoveAt(0);
        }
    }
}

public static int NumEventsInLog()
{
    return events.Count;
}

public static string GetEventDescription(int eventIndex)
{
    if (eventIndex < 0 || eventIndex > events.Count - 1)
        return null;

    return events[eventIndex].description;
}

private class Event
{
    private GameObject fromUnit;
    private GameObject toUnit;
    private Utils.ActionType actionType;
    public string description;

    public Event(GameObject _fromUnit, GameObject _toUnit, Utils.ActionType _actionType)
    {
        fromUnit = _fromUnit;
        toUnit = _toUnit;
        actionType = _actionType;

        description = eventDescriptions[(int)_actionType];
        description = description.Replace("<fromUnit>", _fromUnit.GetComponent<UnitData>().firstName + " " + _fromUnit.GetComponent<UnitData>().lastName);
        description = description.Replace("<toUnit>", _toUnit.GetComponent<UnitData>().firstName + " " + _toUnit.GetComponent<UnitData>().lastName);
    }
}


texts: Using an asynchronous function without directly using its callback

texts:
I hate functions and re-writing callbacks by "intercepting" them and passing the original along. This is simple: it uses an existing function, exec, and doesn't open it up. Its callback arguments are passed into results.exec. There's just a lot of overhead here. I was wondering if there's an easier way, using the async library or not.

function execModify(command, manipulators, callback) {
  var exec = childProcess.exec;
  return async.auto({
    "exec": async.apply(exec, command),
  }, function(err, results) {
    if (err) return callback(err);
    var value = results.exec[0];
    if (typeof manipulators == "function") return manipulators(null, value);
    if (manipulators.length == 0) return callback(null, value);
    _.each(manipulators, function(manipulator) {
      value = manipulator(value);
    });
    return callback(null, value);
  });
};


texts: Registering multiple keypresses simultaneously, very slow

texts:
I'm working on a Pong game and right now I'm working on being able to register multiple KeyDown presses simulatenously. I used the Win32 native method GetKeyBoardState first to loop through all of the virtual keys and see if any of the keys matched the game input keys. Now this worked just fine but in the interest of optimization I figured that it would be quicker to use GetKeyState since there are only 4 valid input keys and then simply check if any of those keys are pressed down.

Surprisingly it is incredibly slow and choppy, a lot worse than GetKeyBoardState so I'm wondering if there's something in my code that's slowing it down. Here's the complete implementation

NativeMethods.cs

internal static class NativeMethods
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetKeyboardState(byte[] lpKeyState);

        [DllImport("user32.dll")]
        internal static extern short GetKeyState(int nVirtKey);
    }

Keyboard.cs

static class Keyboard
{
    public static bool GetKeyState(Keys vKey)
    {
        short results = NativeMethods.GetKeyState((int)vKey);
        // We're only going to use this to look for arrow keys so
        // No need to differntiate results based on low or high order bits
        switch (results)
        {
            case 0: //KEY STATE: NOT PRESSED
                return false;
            case -127: //KEY STATE: PRESSED
                return true;
        }
        return false;
    }

GameForm.cs

 private void GameForm_KeyDown(object sender, KeyEventArgs e)
        {
            var movementData = new Tuple<int, Move>(-1, Pong.Move.Down);

            //Check how many keys that are pressed down (for example both players might be moving their paddles simulatenously)
            var pressedKeys = inputKeys.Where(key => Keyboard.GetKeyState(key));

            //Check if pressed key equals any of the player assigned keys.. If so call MovePaddle()

            foreach (Keys key in pressedKeys)
            {
                switch (key)
                {
                    case Keys.Up:
                        movementData = Tuple.Create(0, Pong.Move.Up);
                        break;
                    case Keys.Down:
                        movementData = Tuple.Create(0, Pong.Move.Down);
                        break;
                    case Keys.W:
                        movementData = Tuple.Create(1, Pong.Move.Up);
                        break;
                    case Keys.S:
                        movementData = Tuple.Create(1, Pong.Move.Down);
                        break;
                }
                gameController.MovePaddle(movementData.Item1, movementData.Item2);
            }
        }


texts: Dirty Bash hack to run the ssh connections in the Parallel mode

texts:
A Few years back I used to opt the below method to run the shell program in a Parallel way to open multiple ssh session at a time to get a quick result.
I know there are various other good utilities available, however due to some pressing needs I've to use this way, this dirty piece of code works well however I would like to know if there are some suggestion to improve it further considering the fact I have to use it for some compelling reasons over other better tools.
#!/bin/bash
echo "$(date) Starting the SSH Connection Check...."
#set -x

read -rsp $'Please Enter password below: ' SSHPASS
export SSHPASS
SSH_Connection () {
    hostTarget=${1}
    sshpass -e ssh -q "${hostTarget}" "true" -o StrictHostKeyChecking=no -o ConnectTimeout=60 2>>/dev/null
    if [[ $? -eq 0 ]]
    then
        echo  "$CurrntTime $MachineName   : SSH connection is Up"
    elif [[ $? -eq 255 ]]
        then
        echo  "$CurrntTime $MachineName   : SSH Authentication Failed"
    elif [[ $? -eq 2 ]]
        then
        echo  "$CurrntTime $MachineName   : SSH connection is Down"
    elif [[ $? -eq 1 ]]
        then
        echo  "$CurrntTime $MachineName   : SSH Authentication Failed"
    else
        echo  "$CurrntTime $MachineName   : SSH connection is Down"
    fi
}

HostList=$(<~/host2)

CurrntTime=$(date +'%m/%d/%Y %T')

for MachineName in ${HostList}
do
    SSH_Connection "${MachineName}" &
done
# wait for all outstanding background jobs to complete before continuing
wait
# at last clear the exported variable containing the password
unset SSHPASS


texts: Shopify monitor that utilizes redis for caching each product

texts:
This is just a simple monitor for shopify products for an array of sites. It involves parsing the /products.json of the site, checking if each product ID is already stored as a key in redis and if it isn't it needs to notify a group of discord members (haven't implemented yet). Really appreciate any feedback given!

const axios = require('axios'),
      fs = require('fs'),
      redis = require('redis');

const client = redis.createClient();

let trackingF = fs.readFileSync("../tracking.json");
let proxiesF = fs.readFileSync("../proxies.json");

let keywords = JSON.parse(trackingF).keywords.map(x => {
     return x.toLowerCase();
});

let sites = JSON.parse(trackingF).sites.map(x => {
    return x.toLowerCase();
});

let proxies = JSON.parse(proxiesF).proxies;

const getProducts = (url) => {
    return new Promise((resolve, reject) => {
        axios.get(`${url}/products.json`, rProxy()).then(response => {
           resolve(response.data.products);
        }).catch(err => {reject(err)});
    });
 }

const cache = (product) => {
    client.get(product.id, (err, reply) => {
       if (err) console.log(err);
       if (!reply) {
           client.set(product.id, JSON.stringify(product));
           console.log("NEW PRODUCT: " + product.id);
           return;
       }
    });
}

const rProxy = () => {
    return proxies[Math.floor(Math.random() * Math.floor(proxies.length))];
}

const checkStock = () => {
    console.log("[MONITOR] CHECKING");
    for (let i = 0; i < sites.length; i++) {
        getProducts(sites[i]).then(products => {
           products.forEach(product => {
               cache(product)
           });
        }).catch(err => console.log(err));
    }
}

setInterval(() => checkStock(), 5000);


texts: JavaScript function to convert an array to an array of strings (formatted)

texts:
Input

categories - an array of categories

[
    { id: 1, title: 'Smartphones' },
    { id: 2, title: 'Laptops' }
]

products - an array of products, linked to categories

[
    { id: 1, title: 'iPhone X', category_id: 1, price_min: 1200, price_max: 1700 },
    { id: 2, title: 'MacBook Pro Retina 13', category_id: 2, price_min: 1500, price_max: 4500 },
    { id: 3, title: 'Samsung Galaxy S8', category_id: 1, price_min: 0, price_max: 0 }
]

Output

[
    "*Smartphones*\niPhone X\n ($1200 - $1700)\nSamsung Galaxy S8 (free)",
    "*Laptops*\nMacBook Pro Retina 13 ($1500 - $4500)"
]

Current implementation

function printPriceList (categories, products) {
    return categories.map(category => {
        const pcontent = products
            .filter(product => product.category_id === category.id)
            .map(product => {
                const samePrice = product.price_min === product.price_max
                const price = samePrice ? product.price_min : `${product.price_min} - ${product.price_max}`

                if (price === 0) {
                    return `${product.title} (free)`
                }

                return `${product.title} ($${price})`
            })
        return [`*${category.title}*`].concat(pcontent)
    }).map(cat => cat.join('\n'))
}

I'd like to find out a way to refactor it to be more readable, easy to understand and efficient.

What can we use?

all the modern JS features, like a spread operator (...smth)
lodash


texts: Python - username and password authentication

texts:
How can I reduce the amount of if statements in this program to make it more robust and any other tips for improvement would be grateful.

# importing pickle
import pickle

# defining variables
create_username = 0
create_password = 0
password = 0
username = 0

# this variable allows the user or denies the user to the rest of the program (will only run if access is 1)
access = 0

# creates a users dictionary
with open('users.pickle', 'rb') as f:
    users = pickle.load(f)

print(users)

# sign up (creating new account)
while username not in users and username != 'signup':
    username = input("enter username(type signup to create an account): ")

    # add new user to dictionary
    if username == "signup" or username == "Signup":
        create_username = input("enter a new username: ")
        create_password = input("enter a new password (Your password cannot be the same as your username !!!!!!!): ")

    if create_password in users:
        create_password = input("password taken re-enter: ")
    # then adds the new username to the users dictionary
    if username == 'signup':
        users[create_username] = create_password

if username in users:
    password = input("enter password: ")

if password in users:
    print("access granted")

    access = 1
if username not in users and username != 'signup':
    username = input("enter username: ")

    if username in users:
        password = input("enter password")

    if password in users:
        print("access granted")
        access = 1

if password not in users:
    print("access denied")

with open('users.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(users, f, pickle.HIGHEST_PROTOCOL)

print(users)


texts: Lookup country codes with a JavaScript ES6 Map Object

texts:
In my application, a country code may be passed from the client as a URL query string or in a header. If there is no country in the URL or headers, then it will default to the United States. The application uses both Alpha-2 and Alpha-3 codes, and with the header there are special cases for Canada and Great Britain.

const countries = {
  UNITED_STATES: ['US', 'USA'],
  UNITED_KINGDOM: ['UK', 'GBR'],
  CANADA: ['CA', 'CAN'],
  AUSTRALIA: ['AU', 'AUS'],
  PUERTO_RICO: ['PR', 'PRI'],
  GREAT_BRITAIN: ['GB', 'GBR']
};

function lookupCountry(obj, country) {
  return Object.keys(obj).map((el) => obj[el])
         .filter((countryArr) => countryArr.includes(country.toUpperCase()));
}

function getCountry(i18nHeader, i18nQuery) {
  if (i18nQuery) {
    return lookupCountry(countries, i18nQuery);
  } else {
    if (!i18nHeader || !i18nHeader.length) {
      return countries.UNITED_STATES;
    } else {
      if (i18nHeader.toUpperCase() === countries.GREAT_BRITAIN[0]) {
        return countries.UNITED_KINGDOM;
      }
      if (i18nHeader.toUpperCase() === countries.CANADA[0]) {
        return countries.UNITED_STATES;
      }
    }
    return lookupCountry(countries, i18nHeader);
  }
}

I would like to take advantage of new ES6 language features and use the Map object. I'm thinking this Map structure could be initialized and structured like this:

 const countries = new Map([
      ['UNITED_STATES', ['US', 'USA']],
      [ 'GREAT_BRITAIN', ['GB', 'UK']]...
  ]);

I could then use counteries.get('GREAT_BRITAIN') to retrieve the array of country codes.


texts: C-style generic stack implementation in C#

texts:
I saw a nice generic stack implemented in C, in Stanford's CS107 Programming Paradigms course, so I tried to rewrite it in C#:

public unsafe static class NativeMemory
{
    [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern  void* memcpy(void* dest, void* src, UIntPtr count);

    [DllImport("msvcrt.dll", EntryPoint = "malloc", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern  void* malloc(UIntPtr count);

    [DllImport("msvcrt.dll", EntryPoint = "realloc", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern  void* realloc(void* src, UIntPtr count);

    [DllImport("msvcrt.dll", EntryPoint = "free", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern void free(void* src);
}

public unsafe delegate void FreeFunction(void* elemAddr);

public unsafe struct Stack : IDisposable
{
    private readonly int elemSize;
    private readonly FreeFunction freeFunction;
    private int alloclength;
    private void* elems;

    public Stack(int elemSize, FreeFunction freeFunction)
        : this()
    {
        this.elemSize = elemSize;
        this.freeFunction = freeFunction;
        alloclength = 4;
        elems = NativeMemory.malloc((UIntPtr) (elemSize * alloclength));
    }

    public int Count { get; set; }

    public void Push(void* elemAddr)
    {
        if (alloclength == Count)
        {
            Grow();
        }
        NativeMemory.memcpy(((byte*)elems + Count* elemSize), elemAddr, (UIntPtr) elemSize);
        Count++;
    }

    public void Pop(void* elemAddr)
    {
        void* source = ((byte*) elems + (--Count* elemSize));
        NativeMemory.memcpy(elemAddr, source, (UIntPtr)elemSize);
    }

    private void Grow()
    {
        alloclength *= 2;
        elems = NativeMemory.realloc(elems, (UIntPtr) (alloclength* elemSize));
    }

    public void Dispose()
    {
        if (freeFunction != null)
        {
            for (int i = 0; i < Count; i++)
            {
                void* elemAddr = ((byte*) elems + (elemSize * i));
                freeFunction(elemAddr);
            }
        }
        NativeMemory.free(elems);
    }
}

public class Program
{
    private unsafe static void Main(string[] args)
    {
        using (Stack s = new Stack(sizeof (char*), null))
        {
            string[] names = {"rezo", "jack", "andrew"};
            foreach (string n in names)
            {
                fixed (char* ptr = n)
                {
                    char* name = ptr;
                    s.Push(&name);
                }
            }

            while (s.Count > 0)
            {
                char* name;
                s.Pop(&name);
                Console.WriteLine(new string(name));
            }
        }
    }
}

Example of how to store managed objects:

private unsafe static void Main(string[] args)
{
    var names = new[] {"Brad", "Andrew", "Jon","Melissa"};

    using (Stack stack = new Stack(sizeof(GCHandle), (ptr) =>
    {
        GCHandle handle = GCHandle.FromIntPtr(new IntPtr(ptr));
        handle.Free();
    }))
    {
        foreach (var name in names)
        {
            GCHandle handle = GCHandle.Alloc(name);
            stack.Push(&handle);
        }

        while (stack.Count > 0)
        {
            GCHandle objHandle;
            stack.Pop(&objHandle);
            Console.WriteLine((string)objHandle.Target);
        }
    }
}

What do you think about this? Is there a better way to implement a C-style generic stack in C#?


texts:
I would like to ask for code review for my Python histogram word counter.

# Given a body of text, return a hash table of the frequency of each word.

"""

# I use a hash map as my data structure to create the histogram
# and add words into the dictionary
# if words are not in the dictionary, then I add those word into the dictionary
# final output is that we return the dictionary
"""

# Word Counter

# Given an body of text, return a hash table of the frequency of each word.

# Parameters
# Input: text {String}
# Output: {Hash Table}

# Constraints
# Capital and lower case versions of the same word should be counted is the same word.
# Remove punctuations from all words.
# Time: O(N)
# Space: O(N)
# Where N is the number of characters in the string.

# Examples
# 'The cat and the hat.' --> '{ the: 2, cat: 1, and: 1, hat: 1 }'`
# 'As soon as possible.' --> '{ as: 2, soon: 1, possible: 1 }'`
# 'It's a man, it's a plane, it's superman!' --> '{ its: 3, a: 2, man: 1, plane: 1, superman: 1 }'`

def word_count(sentence):
    word_counter = {}
    wordlist = sentence.lower().split()
    for word in wordlist:
        word = re.sub('[.,:*! ]', '', word)

        if word in word_counter:
            word_counter[word] += 1
        else:
            word_counter[word] = 1
    return word_counter

example = word_count("It's a man, it's a plane, it's superman!")


texts: Representing a combatant's equipment using the decorator pattern

texts:
Is this a valid implementation of Decorator Pattern? Are there any possible improvements? Also, it is possible to remove decorations in a simple way?

 public interface Enemy {
    void fight();

    String shoutIdentity();
}

public class UnarmedEnemy implements Enemy {

    @Override
    public void fight() {
        System.out.println("I'm fighting with you!");
    }

    @Override
    public String shoutIdentity() {
        return "I'm your enemy! ";
    }
}

public class EnemyDecorator implements Enemy {

    private Enemy enemy;

    public EnemyDecorator(Enemy enemy) {
        this.enemy = enemy;
    }

    @Override
    public void fight() {
        enemy.fight();
    }

    @Override
    public String shoutIdentity() {
        return enemy.shoutIdentity();
    }
}

public class BowDecorator extends EnemyDecorator {

    public BowDecorator(Enemy enemy) {
        super(enemy);
    }

    @Override
    public void fight() {
        super.fight();
    }

    @Override
    public String shoutIdentity() {
        return super.shoutIdentity() + "I have a bow! ";
    }
}

public class ShieldDecorator extends EnemyDecorator {

    public ShieldDecorator(Enemy enemy) {
        super(enemy);
    }

    @Override
    public void fight() {
        super.fight();
    }

    @Override
    public String shoutIdentity() {
        return super.shoutIdentity() + "I have a shield! ";
    }
}

public class SwordDecorator extends EnemyDecorator {

    public SwordDecorator(Enemy enemy) {
        super(enemy);
    }

    @Override
    public void fight() {
        super.fight();
    }

    @Override
    public String shoutIdentity() {
        return super.shoutIdentity() + "I have a sword! ";
    }
}

public class HorseDecorator extends EnemyDecorator {

    public HorseDecorator(Enemy enemy) {
        super(enemy);
    }

    @Override
    public void fight() {
        System.out.println("I'm NOT fighting with you!");
    }

    @Override
    public String shoutIdentity() {
        return super.shoutIdentity() + "I have a horse! I'm fleeing! ";
    }
}

public class App {
    public static void main(String[] args) {
        Enemy enemy = new UnarmedEnemy();
        System.out.println(enemy.shoutIdentity());
        enemy.fight();
        System.out.println("\nYour enemy found a shield..\n");
        enemy = new ShieldDecorator(enemy);
        System.out.println(enemy.shoutIdentity());
        enemy.fight();
        System.out.println("\nYour enemy found a bow..\n");
        enemy = new  BowDecorator(enemy);
        System.out.println(enemy.shoutIdentity());
        enemy.fight();
        System.out.println("\nYour enemy found a sword..\n");
        enemy = new SwordDecorator(enemy);
        System.out.println(enemy.shoutIdentity());
        enemy.fight();
        System.out.println("\nYour enemy found a horse..\n");
        enemy =  new HorseDecorator(enemy);
        System.out.println(enemy.shoutIdentity());
        enemy.fight();
    }
}


texts: A counterexample in balanced parentheses

texts:
In this program I had to analyse if the parenthesis given are well balanced. For instance, input (()) is correct and input ())(() is incorrect. I've tested with other similar inputs, so my question is: can my code fail with some weird expression (using parentheses) or will it always work correctly?

public class Main {

public static void main(String[] args) {
    Scanner x = new Scanner(System.in);
    Stack<String> parenthesis = new Stack<>();

    System.out.println("Introduce the length of your expression");
    int l = x.nextInt();
    System.out.println("Introduce your expression");

    x.nextLine();
    for (int i = 0; i < l; i++) {
        System.out.println("Introduce an element");
       String e = x.next();
        parenthesis.push(e);
    }

    analysis(parenthesis);
}

public static void analysis(Stack<String> st) {

    Stack<String> closed = new Stack<>();//only for parentesis like this: )

    int ww = 0;
    while (!st.isEmpty() && ww != 1) {
        String s =st.pop();
        if (0 == s.compareTo("(") && !closed.isEmpty()) {
            closed.pop();
        } else if ((0 == s.compareTo("(")) && closed.isEmpty()) {
            System.out.println("incorrect expression.");
            ww = 1;
        } else {
            closed.push(s);
        }
    }
    if (ww == 1) {
        System.out.println();
    } else if (!closed.isEmpty()) {
        System.out.println("incorrect espression");
    } else {
        System.out.println("correct");
    }

}
  }


texts: Display PHP Menu Stored in an Array and Looped

texts:
I'm creating a PHP website for a non-profit. They have some restrictions (no MySQL or pre-installed CMS) so I'm creating a CSS menu displayed by an unordered list where all of the elements are stored in a multi-dimensional array.

I've gotten it to work but being new to PHP, I'm certain it's not optimized to run as smoothly as possible. Also, I feel I've hacked my way through the first and last elements.

Here's the array:

<?php
$siteURL = "http://www.mysite.org/";

$menu = array
   (
   //"Name","URL",ID,Level,Seq,Under,Target,Display
   //First Menu
   array("TOP1",$siteURL."top1.php",1,1,1,0,0,true),
   array("SUB1a",$siteURL."sub1a.php",2,2,1,1,0,true),
   array("SUB1b",$siteURL."sub1b.php",3,2,2,1,0,true),
   array("SUB1c",$siteURL."sub1c.php",4,2,3,1,0,true),
   array("SUB1d","http://www.externalsite.org/",5,2,4,1,1,true),
   array("SUB1e","http://www.externalsite.org/",6,2,5,1,1,true),
   array("SUB1f",$siteURL."sub1f.php",7,2,6,1,0,true),

   //Second Menu
   array("TOP2",$siteURL."top2.php",8,1,2,0,0,true),
   array("SUB2a","http://www.externalsite.org/",9,2,1,8,1,true),
   array("SUB2b",$siteURL."sub2b.php",10,2,2,8,0,true),
   array("SUB2c","http://www.externalsite.org/",11,2,3,8,1,true),
   array("SUB2d","http://www.externalsite.org/",12,2,4,8,1,true),

   //Third Menu
   array("TOP3",$siteURL."top3.php",13,1,3,0,0,true),
   array("SUB3a","http://www.externalsite.org/",14,2,1,13,1,true),
   array("SUB3b","http://www.externalsite.org/",15,2,2,13,1,true),
   array("SUB3c","http://www.externalsite.org/",16,2,3,13,1,true),
   array("SUB3d","http://www.externalsite.org/",17,2,4,13,1,true),

   //Fourth Menu
   array("TOP4",$siteURL."top4.php",18,1,4,0,0,true),
   array("SUB4a",$siteURL."downloads/sub4a.pdf",19,2,1,18,0,true),
   array("SUB4b",$siteURL."sub4b.php",20,2,2,18,0,true),

   //Fifth Menu
   array("TOP5",$siteURL."top5.php",21,1,5,0,0,true),

   //Sixth Menu
   array("TOP6",$siteURL."top6.php",22,1,6,0,0,false),

   //Seventh Menu
   array("TOP7",$siteURL."top7.php",23,1,7,0,0,false),

   //Eighth Menu
   array("TOP8","http://www.externalsite.org/",24,1,8,0,1,true),

   );
?>

And here's the logic:

<?php
$count = count($menu);
$i = 0;
while ($i < $count) {
    if (($menu[$i][3]===1) && ($menu[$i][7]===true)) {
        if ($menu[$i][6]===1) {
            echo "
".$menu[$i][0]."
\n";
        }
        else {
            echo "
".$menu[$i][0]."
\n";
        }
        for ($j = 0; $j < $count; $j++){
            if (($menu[$j][5]===$menu[$i][2]) && ($menu[$j][7]===true)) {
                if ($menu[$j][6]===1) {
                    echo "
".$menu[$j][0]."
\n";
                }
                else {
                    echo "
".$menu[$j][0]."
\n";
                }
            }
        }
        echo '

';
    }
    $i++;
}
?>

I had a hard time finding a relevant post. I'd appreciate some help or even just validation that I'm doing this correctly.


texts: Multiple jQuery events on one element with different functions and target selectors

texts:
According to this two questions: [1] and [2]

I need a way to combine these two methods of handling the event attachment in jQuery.

$('selector').on({
    mouseenter: function() {},
    mouseleave: function() {},
    mousedown:  function() {},
    mouseup:    function() {}
});

I prefer the previous method but need something like the following to work with "live"-events. (The problem is, that the next pattern kills the clarity if the code will be a bit larger and even if there're comments between the handlers, it breaks the code.):

$(document).on('mouseenter', 'selector1', function(){})
           .on('mouseleave', 'selector2', function(){})
           // this comment breaks the chain
           .on('mousedown',  'selector3', function(){})
           .on('mouseup',    'selector4', function(){});

However, since there's no real world example to do it like this?:

$(document).on({
    mouseenter: 'selector1': function() {},
    mouseleave: 'selector2': function() {},
    mousedown:  'selector3': function() {},
    mouseup:    'selector4': function() {}
});

...I've ended up with this simple on-wrapper function: https://gist.github.com/4191657

;(function($) {
    $.fn.act = function() {
        var args = arguments;
        return this.each(function() {
            for (var i = args.length; i--;) {
                $(this).on(args[i][0], args[i][1], args[i][2]);
            }
        });
    };
})(jQuery);

Now the usage is quite simpler:

$(document).act(
    ['mouseenter', 'selector1', function() {}],
    ['mouseleave', 'selector2', function() {}],
    ['mousedown', 'selector3', function() {}],
    ['mouseup', 'selector4', function() {}]
);

As @Joonas said that this funtion improves anything. I had the need to came up here with a new question.

So my question, have you any thoughts, suggestions or improvements to this function? Or is there maybe a better solution to handle this problem?


texts:
This is a pattern in SQL queries that I've found myself repeating recently:

SELECT
    w,
    x,
    y,
    (w + x) / y as z
FROM
  (SELECT
      <some gigantic and complicated query> as w,
      a + b as x,
      a - b as y
   FROM
      basetable) somealias;

The issue is:

a select query that does some complex operations, resulting in a column with a new name
directly reusing the "new" column doesn't work in MySQL (unsure about other RDBMS's)

This code fails:

SELECT
    <some gigantic and complicated query> as w,
    a + b as x,
    a - b as y,
    (w + x) / y as z
FROM
    basetable;

Because MySQL doesn't allow column aliases (x and y) to be re-used in the same select query.

The solution I'm using:

wrap the select in a subquery
this renames the columns
use the new column names from the outer query

I'm unsure whether it's a best practice, or a common practice, and thus easily understandable for other programmers.


texts: python segment tree - count of smaller numbers after self

texts:
I am trying to solve this question https://leetcode.com/problems/count-of-smaller-numbers-after-self/

  You are given an integer array nums and you have to return a new
  counts array. The counts array has the property where counts[i] is the
  number of smaller elements to the right of nums[i].

My code:

import bisect

from functools import lru_cache

def merge(a, b):
    i, j = 0, 0
    res = []
    while i < len(a) and j < len(b):
        if a[i] < b[j]:
            res.append(a[i])
            i += 1
        else:
            res.append(b[j])
            j += 1
    while i < len(a):
        res.append(a[i])
        i += 1
    while j < len(b):
        res.append(b[j])
        j += 1
    return res

class SegmentTree:
    def __init__(self, nums):
        self.nums = nums
        self.tree = [0] * (len(nums)*4)
        if len(nums)>0:
            self._build()

    def _build(self):
        def build(l, r, index):
            if l == r:
                self.tree[index] = [self.nums[l]]
                return self.tree[index]
            else:
                mid = (l+r)//2
                left_set = build(l, mid, index*2)
                right_set = build(mid+1, r, index*2+1)
                m = merge(left_set, right_set)
                self.tree[index] = m
                return m
        build(0, len(self.nums)-1, 1)

    def get_range(self, l, r):

        @lru_cache(maxsize=None)
        def get_range(left_boundary, right_boudndary, index, l, r):
            if l > r:
                return []
            if left_boundary == right_boudndary:
                return self.tree[index]
            if left_boundary == l and right_boudndary == r:
                return self.tree[index]
            else:
                mid = (left_boundary + right_boudndary)//2
                left = get_range(left_boundary, mid, index*2, l, min(r, mid))
                right = get_range(mid+1, right_boudndary,
                                index*2+1, max(l, mid+1), r)
                return merge(left, right)

        return get_range(0, len(self.nums)-1, 1, l, r)

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        s = SegmentTree(nums)
        result = []
        for i in range(len(nums)):
            res  = s.get_range(i+1, len(nums)-1)
            ans = bisect.bisect(res, nums[i]-1)
            result.append(ans)
        return result

Sadly this times out on the last case :(

How do I speed this up?

(To be clear: I am looking for a faster solution with segment trees, not fenwick tree)


texts: Optimization of Barnes-Hut Multithread Insertion algorithm

texts:
I'm currently working on optimizing a Barnes-Hut implementation (connected to a previous post I did) and I need help to optimize it further.

After some testing, the main problem appears to be in the Insertion algorithm, which takes roughly 3-10 times as long as the second longest part of the program.

The basis of the program are a number of threads that each act as a worker that does the following when building the tree:

//particle[] is a list that is set in the constructor
public void run(){
    boolean run = true;

    while(run){
        i = barnesHut.getIndex();

        if(i < particle.length){ tree.insertThreaded(particle[i], thread); }
        else{ run = false; }
    }
}

the getIndex function can be found in the BarnesHut class which handles the start of the program and the insertion algorithm. It's synchronized to work as a

public synchronized int getIndex(){
    return index++;
}

Now, the insertion algorithm looks like this:

//entryLock and quadLock are two atomic mutex locks
//childs[][] are the leaves to the tree structur that makes up a Barnes-Hut

public void insertThreaded(BHBody body, int threadID){
    entryLock.lock();
    numberOfParticles++;

    if(numberOfParticles == 1){
        existingParticle = body;
        entryLock.unlock();
    }
    else if(numberOfParticles == 2){
        quadLock.lock();

        entryLock.unlock();
        int[] position = getQuadForBody(existingParticle);
        if(childs[position[0]][position[1]] == null){
            startQuad(position[0],position[1]);
        }
        quadLock.unlock();

        childs[ position[0] ][ position[1] ].insertThreaded(existingParticle, threadID);

        quadLock.lock();
        position = getQuadForBody(body);
        if(childs[position[0]][position[1]] == null){
            startQuad(position[0],position[1]);
        }
        quadLock.unlock();

        childs[ position[0] ][ position[1] ].insertThreaded(body, threadID);
    }
    else if(numberOfParticles > 2){
        entryLock.unlock();

        quadLock.lock();
        int[] position = getQuadForBody(body);
        if(childs[position[0]][position[1]] == null){
            startQuad(position[0],position[1]);
        }
        quadLock.unlock();

        childs[position[0]][position[1]].insertThreaded(body, threadID);
    }
}

The locks are to make sure that no other thread gets into the way of the thread when it's creating something vital, such as a new leaf or even trying to update the number of particles.

The startQuad() function which creates a new leaf for the current node:

public void startQuad(int x, int y){
    if(x == 0 && y == 0)
        childs[0][0] = new BHnode(xStart,xMid,yMid,yEnd, debug, range,correction);
    if(x == 0 && y == 1)
        childs[0][1] = new BHnode(xStart,xMid,yStart,yMid, debug, range,correction);
    if(x == 1 && y == 0)
        childs[1][0] = new BHnode(xMid,xEnd, yMid,yEnd, debug, range,correction);
    if(x == 1 && y == 1)
        childs[1][1] = new BHnode(xMid,xEnd,yStart,yMid, debug, range,correction);
}

The getQuad() function which returns the quad for the body to be inserted into:

public int[] getQuadForBody(BHBody body){
    int x = 0, y = 0;
    if( body.getX() > xMid ){
        x++;
    }
    if( body.getY() < yMid ){
        y++;
    }
    int[] a = {x,y};
    if(debug){
        System.out.println("setting ("+body.getX()+","+body.getY()+") at ("+x+","+y+") with mid " +xMid+","+yMid);
        helper.sleepSeconds(2);
    }
    return a;
}

If anyone has any suggestions on how to improve this code I would be grateful. I've tried a lot of different things, from completly rewriting parts of the code to making things in a different order.


texts:
I try to program a stopwatch/countdown clock in FORTH with Gforth (and using Gforth-specific words).

I'm  a complete beginner and the following code is the basic stuff (going to add an alarm function / countdown option and more).

For now the stopwatch counts from 00:00:00 (hh:mm:ss) up to 24:00:00 and

pressing space pauses the clock, pressing it again resumes the clock
pressing j/k sets the clock back/ahead one minute
pressing J/K sets the clock back/ahead one hour
pressing q quits the program

Does my code follow best practices? Is it bad style for words like move-clock-seconds-back to return flags because they will be used in a begin ... until statement?

1000000 constant million

: sextal  ( -- )
   6 base ! ;

: hhmmss.  ( ud --  )
   drop million /  0 <# decimal # sextal # [char] : hold decimal # sextal # [char] : hold decimal # sextal # decimal #> TYPE ;

: pause-clock  ( ud -- ud f )
   utime
   begin
      50 ms
      key? if
         key bl = ( pause is released )
      else
        false ( clock keeps pausing )
      then
   until
   utime d- d-
   false ;

: move-clock-seconds-ahead  ( u ud -- ud f )
    million * 0 d-
    false ;

: move-clock-seconds-back  ( u ud -- ud f )
    million * 0 d+
    utime dmin
    false ;

: get-elapsed-time  ( ud -- ud )
    2dup
    utime
    2swap d- ;

: 24-hours-elapsed?  ( ud -- f )
    get-elapsed-time ( elapsed time fits in single integer )
    drop 24 60 * 60 * million * u> ;

: run-clock  ( -- )
    page ( clears the terminal )
    utime ( returns a ud timestamp in microseconds )
    begin
       50 ms ( sleep for 50 ms )
       get-elapsed-time
       5 0 at-xy ( coordinates where to print output )
       hhmmss.
       key? if
       key case
       bl of pause-clock endof
          [char] j of 60 move-clock-seconds-back endof
          [char] k of 60 move-clock-seconds-ahead endof
          [char] J of 60 60 * move-clock-seconds-back endof
          [char] K of 60 60 * move-clock-seconds-ahead endof
          [char] q of true endof
          false swap ( the char is now on top of the stack, will be dropped by endcase )
       endcase
       else 24-hours-elapsed? if
          CR
          ." 24 hours elapsed."
          true
       else
          false
       then then
    until ;

run-clock

bye


texts:
I created a simple command line calculator, and then after some reading I made a few tweaks and then remade it with a friends idea to make it more simpler. I'm wondering if this can be more optimized or if any part of the code can be done "better"?

I recently started learning Java and wanted for this first project of mine to end up the "best possible" written, so I can start learning on what is a "good code".

One of the things that was changed over time was the use of the Scanner.

Firstly I had it create a new one on each iteration of kalkulator(); but that was obviously a unnecessary waste.
Then I had a static scanner static Scanner scanMe = new Scanner(System.in); but somewhere I read It was better to pass it as an argument, because something that doesn't belong anywhere doesn't have place in a good code unless it is really necessary.

Here is what I ended up with so far:

"Main" Method:

public class SimpleCalculator {

public static void main(String[] args) {

    Scanner scanMe = new Scanner(System.in);

    kalkulator(scanMe);
}

"Helper" Methods:

static double scanDouble(Scanner scan){
    while (!scan.hasNextDouble()){

        System.out.println("Invalid number! Please try again.");
        scan.nextLine();
    }

    return scan.nextDouble();
}

static String scanOperator(Scanner scan){
    String In = scan.next();

    while (!(In.equals("+") || In.equals("-") || In.equals("*") || In.equals("/") || In.equals("end"))) {

        System.out.println("Invalid operator! Please select either: +,-,*,/");
        In = scan.next();
    }

    return In;
}

The Main Method:

    public static void kalkulator(Scanner scan) {

    double prviB = 0, drugiB = 0, rezultat = 0;
    String operator;

    System.out.println("Enter the 1st number: ");
    prviB = scanDouble(scan);

    System.out.println("Enter the 2nd number: ");
    drugiB = scanDouble(scan);

    System.out.println("Select an operator: (+,-,*,/) , or type 'end' for termination: ");
    operator = scanOperator(scan);

    switch (operator) {
    case "+":
        rezultat = prviB + drugiB;
        break;

    case "-":
        rezultat = prviB - drugiB;
        break;

    case "*":
        rezultat = prviB * drugiB;
        break;

    case "/":
        rezultat = prviB / drugiB;
        break;

    case "end":
        System.out.println("Terminated.");
        scan.close();
        System.exit(0);
        break;

    default:
        break;
    }

    System.out.println("Result: " + rezultat);
    System.out.println("");

    kalkulator(scan);
}


texts:
I built my code according to the algorithm provided in this YouTube video. Please review it and help me find any problems. It definitely takes a lot longer than the qsort() function in C++. But the algorithm I use should be just as fast. Can anyone find problems?

#include <iostream>
#include <time.h>

using namespace std;

void randomize( int* array, int size );
void qsort( int* array, int leftbound , int rightbound );
void swap( int &a, int &b );
void output( int* array, int size );

int main()
{
    //declare array
    int array[100];

    //get size of the array
    int size = sizeof(array)/sizeof(int);

    //randomize value
    randomize(array, size);

    //start the quicksort algorithm
    qsort(array, 0, size-1 );

    //output the array
    output(array, size);

    return 0;
}

void randomize( int* array, int size )
{
    srand((int)(time(0)));
    for ( int i = 0 ; i < size ; i++ ) {
        array[i] = rand();
    }
}

void output( int* array, int size )
{
    for ( int i = 0 ; i < size ; i++ ) {
        cout << array[i] << endl;
    }
}

void qsort( int* array, int leftbound , int rightbound )
{
    if (rightbound > leftbound) {
        int pivot = array[leftbound + (rand() % (rightbound - leftbound + 1))];
        int leftposition = leftbound;
        int rightposition = rightbound;
        while ( leftposition != rightposition ) {
            while ( array[leftposition] < pivot ) {
                leftposition++;
            }
            while ( array[rightposition] > pivot ) {
                rightposition--;
            }
            swap ( array[leftposition], array[rightposition] );
        }
        qsort( array, 0, leftposition - 1 );
        qsort( array, leftposition + 1, rightbound );
    }
}

void swap(int &a, int &b)
{
    int tmp = a;
    a = b;
    b = tmp;
}


texts: Conditionally eliminating one of two colliding bodies

texts:
I like to explicit return function even for void functions to reduce the use of if-elses, like this code snippet:

private void processContactBetweenPlayers(Contact contact) {
    final Body bodyA = contact.getFixtureA().getBody();
    final Body bodyB = contact.getFixtureB().getBody();
    if (!isPlayer(bodyA) || !isPlayer(bodyB)) {
        return;
    }
    final float vx_a = Math.abs(bodyA.getLinearVelocity().x);
    final float vx_b = Math.abs(bodyB.getLinearVelocity().x);
    final float vy_a = Math.abs(bodyA.getLinearVelocity().y);
    final float vy_b = Math.abs(bodyB.getLinearVelocity().y);
    final float a_power = vx_a + vy_a;
    final float b_power = vx_b + vy_b;
    if ((a_power > b_power)) {
        if (save(bodyB)) return;
        markForDestroy(bodyB);
    } else {
        if (save(bodyA)) return;
        markForDestroy(bodyA);
    }
}

The function returns if both bodies are not players. But doing maybe this practice reduces the code readability. What do you think?


texts:
I've just taken the codility test on finding perfect squares in a range. I thought it was pretty straightforward, but on submitting, I got that a 50% on correctness and 66% on performance.

The spec also mentioned that range will be between [-2147483648 ... 2147483647], expected worst-case time complexity is O(sqrt(abs(B))) and expected worst-case space complexity is O(1).

This is my code:

Solution1.java

public class Solution1 {

    public int solution(int A, int B) {
        int upperLimit = (int) Math.sqrt(B);
        int squares = 0;
        for (int i = 1; i <= upperLimit; i++) {
            if (i * i >= A && i * i <= B) {
                squares++;
            }
        }
        return squares;
    }
}

Solution1Test.java

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class Solution1Test {

    private final Solution1 solution1 = new Solution1();

    @Test
    public void given4_17_return3() {
        assertEquals(3, solution1.solution(4, 17));
    }

    @Test
    public void given1_17_return4() {
        assertEquals(4, solution1.solution(1, 17));
    }

    @Test
    public void given1_35_return5() {
        assertEquals(5, solution1.solution(1, 35));
    }

    @Test
    public void given1_36_return6() {
        assertEquals(6, solution1.solution(1, 36));
    }

    @Test
    public void given9_49_return5() {
        assertEquals(5, solution1.solution(9, 49));
    }

    @Test
    public void given3000_3300_return3() {
        assertEquals(3, solution1.solution(3000, 3300));
    }
}

I'm specially concerned (and confused) about the 50% on correctness.

PS: it this is off-topic just let me know and I'll ask on stackoverflow.


texts:
Excuse the pun in the title, the project this is for is called "Cheddar" (a type of cheese).

Github

I have recently been writing a language, in which I was using grunt. Grunt was very slow for me, and had a lot more problems for me, so I switched my tasks over to makefile. Most of my makefile knowledge is based off examples, googling, and brief tutorials, which is why I want to ask here on how it could be improved.

PREFIX=./node_modules/.bin
## Compiler
# The compiler to use for the ES7 -> ES5 transformation
JC=$(PREFIX)/babel
# Location of files
SRC=src/
OUT=dist/
# The flags to pass to the compiler
JCFLAGS=$(SRC) -d $(OUT)
# The binary files to copy
BIN=cli/cheddar
EXE=cheddar
BIN_MAKE=$(foreach BIN_FILE,$(BIN),chmod 755 $(SRC)$(BIN_FILE) && cp $(SRC)$(BIN_FILE) $(OUT)$(BIN_FILE)${\n});\
         ln -s $(OUT)cli/$(EXE) ./$(EXE)

## Tests
TESTRUNNER=$(PREFIX)/babel-node
COVERAGE=$(PREFIX)/babel-istanbul
TEST=$(PREFIX)/_mocha
TFLAGS=cover $(TEST)

## Rules
all: default

# The default task
# The **production** build
default: $(JC) $(SRC)
    $(JC) $(JCFLAGS) --minified
    $(BIN_MAKE)
# Development build task
# This builds and includes source maps
build: $(JC) $(SRC)
    $(JC) $(JCFLAGS) --sourceMaps="inline"
    $(BIN_MAKE)

# Runs install with default method
install: ./bin/install
    ./bin/install --method=path

# Performs testing, including coverage
# At the moment uses mocha for testing
# and babel-istanbul for coverage
test: $(TESTRUNNER) $(COVERAGE) $(TEST)
    $(TESTRUNNER) $(COVERAGE) $(TFLAGS)
clean:
    rm -rf ./dist/
 .PHONY: test

Essentially what this does is it defined a couple of tasks:

default: This is the default task. It runs babel, a compiler I need to compile the code from the src/ directory to the output dist/ directory.  It passes the --minified flag because this is a production build so we don't want big unminified code.
Following is BIN_MAKE. This runs code to chmod 755 a list of binary files stored in the BIN variable. It then moves these files from the source dir src/ to the destination/output dir dist/.

Lastly, it symlinks the executable to start the program from deep within the dist/ directory to the root for easy-access.
build:: This is a development build. It compiled the same as above, but instead of --minify passes a --sourceMap arg to create source maps
install: This runs an install script to install the application into the user's computer. The script's contents is located in an external file.
test: This runs a file to simply test the application. If you know Mocha or Istanbul, this just runs that. _mocha and babel-istanbul are in variables as they are located in ./node_modules/.bin/.
clean: This removes the dist/ dir which is the location of the output of the build.


texts: Batch upload users to nextcloud on docker with bash csv

texts:
I have this bash script that adds users to NextCloud from a csv file. It expects to be run from the same directory as the docker-compose.yml file.

I'm pretty new to bash scripting and I'm wondering if I am doing things correctly or if there are pieces that could be improved in terms of efficiency, correctness, style? Any comments are appreciated really.

Thanks in advance!

#!/bin/bash

# Handle printing errors
die () {
  printf '%s\n' "$1" >&2
  exit 1
}

usage () {
  echo ""
  echo "batch_users.sh"
  echo "SYNOPSIS"
  echo "batch_users [-p] [file]"
  echo "DESCRIPTION"
  echo "The batch_users script adds a batch of users to an instance of NextCloud running inside of a docker container by reading a list from a csv file."
  echo ""
  echo "-p, --password    Set users password. If no option is passed, the default password is nomoremonkeysjumpingonthebed ."
  echo ""
  echo "csv file should be formatted in one of the following configurations."
  echo "username,Display Name,group,email@address.domain,"
  echo "username,Display Name,group,"
  echo "username,Display Name,"
  echo "username,"
  echo ""
  echo "EXAMPLES"
  echo "The command:"
  echo "batch_users.sh -p 123password321 foobar.csv"
  echo "will add the users from foobar.csv and assign them the password 123password321"
  echo "The command:"
  echo "batch_users.sh foobar.csv"
  echo "will add the users from foobar.csv and assign them the default password."
  echo ""
  echo "batch_users will return 0 on success and a positive number on failure."
  echo ""
}
# flags
password=nomoremonkeysjumpingonthebed
while :; do
  case $1 in
    -h|-\?|--help)
      usage # Display a usage synopsis.
      exit
      ;;
    -p|--password)
      if [ "$2" ]; then
        password=$2
        shift
      else
        die 'Error: "--password" requires a non-empty option argument.'
      fi
      ;;
    --password=?*)
      password=${1#*=} # Delete everything up to = and assign the remainder.
      ;;
    --password=) # Handle the case of empty --password=
      die 'Error: "--password" requires a non-empty option argument.'
      ;;
    --)
      shift
      break
      ;;
    -?*)
      printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
      ;;
    *) # Default case. No more options, so break out of the loop
      break
  esac
  shift
done

# Check to see if there was at least one argument passed.
# If not, print error and exit.
if [[ $# -eq  0 ]]
then
  die 'Error: Expected at least one argument, but no arguments were supplied.'
fi

# Check to see if the file passed in exists.
# If not, print error and exit.
if [[ ! -e $1 ]]
then
  die "Couldn't find file ${1}."
  exit 1
fi

input_file="$1"

while IFS=, read -r f1 f2 f3 f4
do
  # check --password flag
  # f1, f2, f3 exist?
  if [[ -n $f1  && -n $f2 && -n $f3 ]]
  then

    sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \
      user:add --password-from-env --display-name=\"${f2}\" --group=\"${f3}\" \"$f1\" " < /dev/null

  elif [[ -n $f1 && -n $f2 ]]
  then
    # f1 and f2

    sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \
      user:add --password-from-env --display-name=\"${f2}\" \"$f1\" " < /dev/null

  elif [[ -n $f1 ]]
  then
    #only f1

    sh -c "docker-compose exec -T --env OC_PASS=${password} --user www-data app php occ \
      user:add --password-from-env \"$f1\" " < /dev/null

  else
    #error
    die "Expected at least one field, but none were supplied."
  fi

  # If there is a fourth value in the csv, use it to set the user email.
  if [[ -z ${f4+x} ]]
  then
    break
  else
    sh -c "docker-compose exec -T --user www-data app php occ\
      user:setting \"$f1\" settings email \"${f4}\" " < /dev/null
  fi
done <"$input_file"
exit 0


texts: Data Explorer query that makes bar graphs

texts:
I wrote a query for SEDE that I think is pretty cool. It uses the currently available graphing capabilities (scatter plots) to create a bar graph. I have used it as the subject for a self-answer on MSE.

This query finds potential "recommendation questions" based on the words in the title.

The graph looks like this when I ran the query for Super User:

Side note: they are planning to expand the graphing capabilities in the future. Right now they're very limited, so I had to work within the limitations of the system. I'm also aware that my bar graph looks a lot different from the "average" bar graph, but I'm ok with it.

My code right now isn't very long or complex because I'm just starting to teach myself SQL (mostly to make SEDE queries).

The main things I want to know are:

Can I refactor it so that the list of when like then statements occurs only once? (Preferably without complicating the code too much.)

Right now, the first time, it assigns the number for the X axis. The second time, it orders it so that all of the points for each bar are continuous.
Are there any optimizations I can make? So far, I've been using top # statements to keep things from taking too long.

I have prettied up my code for review, but most of the comments are from when I posted it to MSE. Because of the large number of "non-programmers" there (and people without SQL experience), I included a lot of details that are superfluous if you know the basics of SQL (ignore it if you want).

--This limits the results to the first 500
--It's sorting by the bar number,
-- so the query may get cut off like this one,
-- which has 4 bars instead of 6.
select top 500

--Here is the X axis.
--Each number is the bar that the result will be put in.
(case
    when lower(title) like '%open source%' then 0
    when lower(title) like '%recommend%'   then 1
    when lower(title) like '%free%'        then 2
    when lower(title) like '%good%'        then 2
    when lower(title) like '%best%'        then 2
    when lower(title) like '%better%'      then 2
    when lower(title) like '%any%'         then 2
    when lower(title) like '%what%should%' then 3
    when lower(title) like '%which%should%'then 3
    when lower(title) like '%is there%'    then 3
    when lower(title) like '%looking for%' then 4
    else 5 end
)

--This is the first 25 characters of the title
,left(title,25)

--Here is the Y axis. It sorts by the X axis,
-- and then just numbers upwards
,row_number() over (order by
  (case
    when lower(title) like '%open source%' then 0
    when lower(title) like '%recommend%'   then 1
    when lower(title) like '%free%'        then 2
    when lower(title) like '%good%'        then 2
    when lower(title) like '%best%'        then 2
    when lower(title) like '%better%'      then 2
    when lower(title) like '%any%'         then 2
    when lower(title) like '%what%should%' then 3
    when lower(title) like '%which%should%'then 3
    when lower(title) like '%is there%'    then 3
    when lower(title) like '%looking for%' then 4
    else 5 end
  )
) as Number

--This query searches posts
from posts

--This provides stricter criteria for the graph as a whole
where (title like '%library%'
    or title like '%tool%'
    or title like '%book%'
    or title like '%tutorial%')
and closeddate   is null
and deletiondate is null ;


texts:
How can I write a better database query wrapper?

//code for connection
exports.connect = function(callback) {
    client.connect(function(err, conInfo){
        if (err) callback(err);
        conInfo = "Connection at " + client.host + ":" + client.port + "/"
            + client.database + " used by " + client.user;
        callback(null, conInfo);
    });
};

//for queries that do not return realation
exports.runQuery = function(query_str, columns, params, callback) {
    var sqlQuery = query_str + " " + columns;
    client.query(sqlQuery, params, function(err) {
        console.log("NEW QUERY____________________");
        console.log(sqlQuery);
        console.log(params);
        if (err) throw err;
        callback(null);
    });
};

//for select queries
exports.executeQuery = function(query_str, callback) {
    var query = client.query(query_str, function(err){
        console.log("NEW QUERY____________________");
        console.log(query_str);
        if (err) throw err;
        query.on("row", function(row, result) {
            result.addRow(row);
        });
        query.on("end", function (result) {
            callback(null, result.rows);
        });
    });
};


texts: Given n input strings and m query strings, find each query frequency in the list of input strings

texts:
I'm doing questions on HackerRank to brush up on Java & CS.

Problem

This problem is called Sparse Arrays in HackerRank.

  There is a collection of input strings and a collection of query
  strings. For each query string, determine how many times it occurs in
  the list of input strings.

  For example, given input strings = ['ab', 'ab', 'bc'] and queries =
  ['ab', 'abc', 'bc'], result is [2, 1, 0]

  Full Question

Solution

static int[] matchingStrings(String[] strings, String[] queries) {
    Map<String, Integer> counter = new HashMap<>();
    for (String current: strings) {
        counter.put(current, counter.getOrDefault(current, 0) + 1);
    }

    int[] result = new int[queries.length];
    for (int i = 0; i < queries.length; i++) {
        result[i] = counter.getOrDefault(queries[i], 0);
    }
    return result;
}

This passes all the test cases.

Can I do it in a better way?
Can this be simplified in Java-8, 11 or later?


texts: Choosing structure of fields validation module in Swift

texts:
I've implemented abstract module for fields validation according to this MVP clean architecture repo.
In a nutshell I've created ValidationGateway protocol containing signatures for validate methods. Then created ValidationUseCase protocol and implementation to wrap called exact method on validationGateway like this:

typealias ValidationUseCaseCompletionHandler = (_ result: ValidationResult<Void>) -> Void

protocol ValidateFieldsUseCase {
    ...
    func validatePassword(password: String, completionHandler: @escaping ValidationUseCaseCompletionHandler)
    ...
}

class ValidateFieldsUseCaseImplementation: ValidateFieldsUseCase {
    let validationGateway: ValidationGateway

    init(validationGateway: ValidationGateway) {
        self.validationGateway = validationGateway
    }

...

func validatePassword(password: String, completionHandler: @escaping ValidationUseCaseCompletionHandler) {
        self.validationGateway.validatePassword(password: password) { (result) in
            completionHandler(result)
        }
    }

...

And of course created implementation for gateway, eg.

class LocalValidationGateway: ValidationGateway {
...
  func validatePassword(password: String, completionHandler: @escaping ValidationGatewayCompletionHandler) {
        if password.isEmpty {
            completionHandler(.failure(PasswordValidationError.passwordIsEmpty))

        } else if isLengthTooShort(password, min: FieldLengths.minPasswordLength) {
            completionHandler(.failure(PasswordValidationError.passwordTooShort))
...

In a result I've got an abstract module that can be injected in any presenter and used for field validation like this:

...
let fieldValidatorGateway = LocalValidationGateway()
let fieldValidationUseCase = ValidateFieldsUseCaseImplementation(validationGateway: fieldValidatorGateway)

let presenter = ChangePasswordPresenterImplementation(view: changePasswordViewController,
                                                           account: account,
                                                           changeCredentialsUseCase: changeCredentialsUseCase,
                                                           fieldValidatorUseCase: fieldValidationUseCase)
...

And used in presenter like this:

...
func updatePassword(currentPassword: String, newPassword: String, newPasswordRepeat: String) {
    fieldValidatorUseCase.validatePassword(password: currentPassword) { (result) in
        switch result {
        case .success():
            self.checkNewPassword(currentPassword, newPassword, newPasswordRepeat)
        case let .failure(error): break
        //                self.view.displayCurrentPasswordError(errorType: error)
        default: break
        }
    }
}

func checkNewPassword(_ currentPassword: String,_ newPassword: String,_ newPasswordRepeat: String) {
    fieldValidatorUseCase.validatePassword(password: newPassword) { (result) in
        switch result {
        case .success():
            self.checkPasswordRepeat(currentPassword, newPassword, newPasswordRepeat)
        case let .failure(error): break
        //                self.view.displayNewPasswordError(errorType: error)
        default: break
        }
    }
}
...

My problem is that according to that solution every field that needs to be checked has to be wrapped like this and have completion handler served/implemented. From one point of view this is very readable, it's easy to find what does happen on success and failure, what fields are checked, code is divided in nice blocks of code. But from another, when you check more than a 3-4 fields it really starts to look like boilerplate code.

I like the module part of this solution, and not going to resign from it anytime soon, but question is is there some better solution to handle these fileds? Some kind of generic collection of textfields? Or do/try/catch where everything could be passed into one "do" block and catched error passed directly to view for display?

Sorry for long post, I hope everything is clear.


texts:
Here is the problem: Verilog code and testbench for detecting the range of the input given number. If input number is between 12 to 49 then output is '1' else '0'. Range should be easily programmable.
I'm using EDA playground, cadence xcelium 20.09 simulator and EP wave is also present. Is it the appropriate code for the question asked? and also-
Does Verilog read integers normally? for example if I'm inputting a binary number then I should mention the number of bits and then the binary bit like 4b'0011. I directly inputted 12 in the if loop, so it automatically detects that it is an integer?
Here is the link: https://www.edaplayground.com/x/7sQM
Design
module range_detect(y,x);
  input [9:0]x;
  output reg y;
  always @(x)
    begin
      if(x>=12 && x<=49)
        begin
        y=1;
          $display("Input: %d lies between 12 and 49",x);
        end
      else
        begin
        y=0;
          $display("Input: %d does not lie between 12 and 49",x);
        end
    end
endmodule

Testbench
module testbench;
  reg [9:0]in;
  wire out;
  range_detect rd(out,in);
  initial
    begin
      $dumpfile("dump.vcd");
      $dumpvars(1,testbench);
      in=12;
      #2 in=11;
      #2 in=51;
      #2 in=34;
      #2 in=61;
      #2 in=19;
      #2 in=18;
      #2 $stop;
    end
endmodule


texts:
I have no idea if I'm doing this efficiently, or ideally, but I've written what I think is a factory. Please help me understand if this is good practice, or if there is another direction I should take this. There's no particular project in mind with this, I'm just farting around. (Written in PHP)

class Factory
{
    private function __construct(){}

/**
 * @param $obj    Object to Create.
 * @param $params Params (use array for multiple parameters) to be passed.
 */
    public static function build($obj, $params=null) {
        switch ($obj) {
            case 'db': return new DB($params);
            default:   return null;
        }
    }
}

This lets me do something like $db = Factory::build("db","test_database_name"); The DB class just builds a PDO connection using appropriate parameters based on the database I'm trying to access, which is useful for me because I deal with MySQL and MS SQL all day long, and I don't want to have to remember all the connection strings, users, and passwords (stored in the DB class). That's kind of besides the point, I just intend this to be expanded as I develop more useful classes, so...

I just want to get some opinions on the the topic of a Factory. Is this a good method? are there others that are considered superior? If so, what have I overlooked?


texts: Powershell script to save user credentials in a xml file

texts:
I have a power shell script that when run will prompt the user to:

Select a folder location
select a file name
enter credentials

This then exports those credentials in a xml file. Although this requires 3 prompts to the user before is complete. Looking to find if there is a better way to approach this. For example, having a single prompt for the user.

###########################################################
# Create a file containing encrypted credentials
###########################################################

clear

Function Get-Folder($initialDirectory)
{
    #User selected folder location
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null

    $path = New-Object System.Windows.Forms.FolderBrowserDialog
    $path.Description = "Select a folder"
    $path.rootfolder = "MyComputer"

    if($path.ShowDialog() -eq "OK")
    {
        $location += $path.SelectedPath
    }

    #User selected file name
    [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

    $title = 'File Name'
    $msg   = 'Please enter your file name'

    $text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)

    #Open prompt for user to enter credentials and export to xml file
    Get-Credential | Export-Clixml "$location\Credentials-$text.xml"

}

Get-Folder


texts: Generating readable text in a human language from machine-readable data

texts:
I have been generating English-language text from some machine-readable data, but now I want internationalization of my script to be relatively easy. The challenge is that some data might be missing and thus should be omitted from the output, possibly precluding any approach involving just "plugging in" numbers.

Currently, I have functions like these, the output concatenated together in the main program:

function UserinfoJsFormatQty(qty, singular, plural) {
    return String(qty).replace(/\d{1,3}(?=(\d{3})+(?!\d))/g, "$&,") + "\u00a0" + (qty == 1 ? singular : plural);
}

function UserinfoJsFormatDateRel(old) {
    // The code below requires the computer's clock to be set correctly.
    var age = new Date().getTime() - old.getTime();
    var ageNumber, ageRemainder, ageWords;
    if(age < 60000) {
        // less than one minute old
        ageNumber = Math.floor(age / 1000);
        ageWords = UserinfoJsFormatQty(ageNumber, "second", "seconds");
    } else if(age < 3600000) {
        // less than one hour old
        ageNumber = Math.floor(age / 60000);
        ageWords = UserinfoJsFormatQty(ageNumber, "minute", "minutes");
    } else if(age < 86400000) {
        // less than one day old
        ageNumber = Math.floor(age / 3600000);
        ageWords = UserinfoJsFormatQty(ageNumber, "hour", "hours");
        ageRemainder = Math.floor((age - ageNumber * 3600000) / 60000);
    } else if(age < 604800000) {
        // less than one week old
        ageNumber = Math.floor(age / 86400000);
        ageWords = UserinfoJsFormatQty(ageNumber, "day", "days");
    } // ...
    return ageWords;
}

It is supposed to generate output like:

  A reviewer and rollbacker, 2 years 9 months old, with 8,624 edits. Last edited 7 hours ago.

The age, edit count, date of last edit, or all of them could be missing. How could I improve my current design without resorting to a tabular display format? (All the information needs to nicely fit into a single status line.)


texts:
As suggested here, I'm using Boost multi-index to implement orderbook. So far my code looks like this:

"CommonsNative.h" contains typedef int64_t myDecimal; and enum Side { Buy, Sell };

#pragma once

#include "CommonsNative.h"
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>

using boost::multi_index_container;
using namespace boost::multi_index;

struct OrderBookItem {
    myDecimal price;
    int32_t lots;
    OrderBookItem(myDecimal price_) :price(price_), lots(0) {

    }
};

typedef multi_index_container
    <OrderBookItem, indexed_by<

    hashed_unique<
    BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price)
    >,

    ordered_unique<
    BOOST_MULTI_INDEX_MEMBER(OrderBookItem,myDecimal,price),
    std::greater<myDecimal> /* sorted beginning with most frequent */
    >

    >> OrderBookContainer;

class OrderBook
{
public:
    OrderBook(void);
    ~OrderBook(void);
    void Add(Side side_, myDecimal price_, int lots_)
    {
        if (side_ == Buy) {
            // inserts or returns existent
            OrderBookContainer::iterator it = buyContainer.insert(price_).first;
            // how to add lots i.e. OrderBookItem.lots += lots_?
            // auto curLevel = buyContainer.get<name>(price);
            // curLevel.lots += Lots;
        } else if (side_ == Sell) {
            // inserts or returns existent
            OrderBookContainer::iterator it = sellContainer.insert(price_).first;
        }
    }
private:
    OrderBookContainer buyContainer;
    OrderBookContainer sellContainer;
};

I have the following questions:

For here:

OrderBookContainer::iterator it = buyContainer.insert(price_).first;

If I already have an item with price = price_ I receive it in \$O(1)\$ (from hashtable). If such a level doesn't exist, then is it added in \$O(log n)\$? If I'm wrong, then what should I write to get an item if it exists (in \$O(1)\$) otherwise add it (in \$O(log n)\$)?
Once I have an item, how can I modify lots to something like this?

OrderBookItem.lots += lots_