Drawing multiple polygons in Google Maps in the same style To multiple Polygon objects in Google maps, I have to set same strokeWeight, fillColor and fillOpacity attributes. Is there a way how to add these only once or do it in a better way?

var hospitalPath = new google.maps.Polygon({
    path: hospitalPathCoords,
    strokeWeight: 0,
    fillColor: '#add78b',
    fillOpacity: 0.8
});
hospitalPath.setMap(map);

var airportPath = new google.maps.Polygon({
    path: airportPathCoords,
    strokeWeight: 0,
    fillColor: '#add78b',
    fillOpacity: 0.8
});
airportPath.setMap(map);

var restaurantPath = new google.maps.Polygon({
    path: restaurantPathCoords,
    strokeWeight: 0,
    fillColor: '#add78b',
    fillOpacity: 0.8
});
restaurantPath.setMap(map);

You have several options to reduce the code duplication here.

Put the common values into variables, and replace all hardcoded values with those new variables.
Create a prototype object of all the properties, and when you create a new polygon instance, copy the prototype instance and overwrite only the field you want to change (the path in these examples).
I saved my favorite to last. Create a helper function that takes a path and returns a new polygon instance, configured with the common values, and the specified path.

Whichever way you choose, you will be able to change values in one place for all map instances, and thereby avoid much of the code duplication.


functional javascript - how could I generalize this code that correlates parallel async requests with their results? /**
 * takes a list of componentIDs to load, relative to componentRoot
 * returns a promise to the map of (ComponentID -> componentCfg)
 */
function asyncLoadComponents (componentRoot, components) {

    var componentCfgs = {};

    function asyncLoadComponentCfg(component) {
        var url = _.sprintf("%s/%s", componentRoot, component);
        var promise = util.getJSON(url);
        promise.done(function(data) {
            componentCfgs[component] = data;
        });
        return promise;
    }

    var promises = _.map(components, asyncLoadComponentCfg);
    var flattenedPromise = $.when.apply(null, promises);
    var componentCfgPromise = flattenedPromise.pipe(function() {
        // componentCfgs is loaded now
        return $.Deferred().resolve(componentCfgs).promise();
    });

    return componentCfgPromise;
}

var locale = 'en-US';
var componentRoot = '/api/components';
var components = ['facets', 'header', 'DocumentList'];
function buildDocumentListPage(locale, componentCfgs) { /* code goes here */ }

$.when(asyncLoadComponents(componentRoot, components)).done(function(componentCfgs) {
    buildDocumentListPage(locale, componentCfgs)
});

Here's a sample in jsFiddle, with some values and functions mocked-up to use jsFiddle API.

Here's the actual code, with notes in the comments:

//personally, I like comma separated variables preferrably the
//"comma-before style". But it's personal preference.

//JS "hoists" up variable and function declarations higher in the scope.
//To avoid unexpected behaviour, and so that they are easier to find,
//we move them to the top of their scopes
var locale = 'en-US'
  , componentRoot = '/api/components'
  , components = ['facets', 'header', 'DocumentList']
  ;

function buildDocumentListPage(locale, componentCfgs) {}

//load our components
function asyncLoadComponents(componentRoot, components) {

      //our configuration collector
  var componentCfgs = {}

      //we create a promises array by mapping each value to a function
    , promises = _.map(components, function (component) {

        //we use the promise of a getJSON request (Assuming this is jQuery).
        //since you just concatenated the url values, we can just concatenate with +
        return util.getJSON(componentRoot+'/'+component).done(function (data) {

          //when getJSON resolves, we put the data in the collector
          componentCfgs[component] = data
        });
      });

  //as of jQuery 1.8, pipe is deprecated in favor of then. However, then
  //is designed to act like pipe, and instead of resolving with the value
  //we return the value instead
  return $.when.apply(null, promises).then(function () {
    return componentCfgs;
  })
}

//we model the function to return a promise that we'll listen to instead
//of having a $.when here. That way, we'll deal with less code and promises
asyncLoadComponents(componentRoot,components).done(function(componentCfgs) {

  //here, all configs have loaded and stored to componentCfgs
  buildDocumentListPage(locale, componentCfgs);
});

Packed code looks like this, tons shorter:

var locale = 'en-US',
  componentRoot = '/api/components',
  components = ['facets', 'header', 'DocumentList'];

function buildDocumentListPage(locale, componentCfgs) {}

function asyncLoadComponents(componentRoot, components) {
  var componentCfgs = {}, promises = _.map(components, function (component) {
      return util.getJSON(componentRoot + '/' + component).done(function (data) {
        componentCfgs[component] = data
      })
    });
  return $.when.apply(null, promises).then(function () {
    return componentCfgs
  })
}

asyncLoadComponents(componentRoot, components).done(function (componentCfgs) {
  buildDocumentListPage(locale, componentCfgs)
});


Selecting orders submitted by a user, segregated by status I have recently started using Laravel as my chosen framework. It is my first time using a framework. As I have made progress through my project, my controller methods have started to increase in size.

My concern is, I feel like I am doing it wrong. It seems way off of the OO approach.

An example of one of my controller methods:

public function viewUser($name)
    {
        $orders = Orders::where('submitter', $name)
            ->where('closed', false)
            ->where('ceased', false)
            ->where('cancelled', false)
            ->orderBy('updated_at', 'desc')
            ->get();

        $completeOrders = Orders::where('submitter', $name)
            ->where('closed', true)
            ->where('ceased', false)
            ->where('cancelled', false)
            ->orderBy('updated_at', 'desc')
            ->get();

        $cancelledOrders = Orders::where('submitter', $name)
            ->where('closed', false)
            ->where('ceased', false)
            ->where('cancelled', true)
            ->orderBy('updated_at', 'desc')
            ->get();

        $ceasedOrders = Orders::where('submitter', $name)
            ->where('closed', false)
            ->where('ceased', true)
            ->where('cancelled', false)
            ->orderBy('updated_at', 'desc')
            ->get();

        return view('admin.order-overview')->with('orders', $orders)
            ->with('completeOrders', $completeOrders)
            ->with('cancelledOrders', $cancelledOrders)
            ->with('ceasedOrders', $ceasedOrders);
    }

As you can see I run 4 seperate queries to get my desired results then I pass them to my view.

Is there a neater, more professional way to approach the above example?

I see two opportunities to improve your code.

1. Custom orders collection

This would be the fast and easy approach. Make a custom 'Orders' collection that extends the Eloquent collection. On that collection, you can add your custom filters for 'completed', 'cancelled' and 'ceased'. By overwriting the newCollection method on the Order model, you can make it automatically return this custom Orders collection when queried. You can then assign that collection to your view, and there you can ask the collection for the different types of orders and use them as you please. Or you could do that in your controller as well if you prefer.

2. status_id in stead of flags

You may take it a step further, depending on how far you want to refactor your data and the scope of your app. In stead of working with those 3 booleans for determining the 'type' of order, consider working with a single 'status_id' column. You could for instance define in your model:

const STATUS_COMPLETED = 1;
const STATUS_CEASED = 2;
const STATUS_CANCELLED = 3;

Then you can just fetch all your orders (possibly paged, or with some filters added) in a single query, and again filter on your collection to get the order type you need. And if anywhere in your app you only need orders with a certain status, you can just do something like Orders::where('status_id', Orders::STATUS_CANCELLED)->get();

I can see a few aditional advantages for this approach:

It would be very easy to put an index on that status column, which could greatly improve query performance
Query performance will be better anyway, since you only need a single where condition, which is obviously better then 3
If you later decide to add an extra status, like 'shipped' or 'returned' or something, you would only have to add a few constants, your data would remain in tact.
It is just semantically more correct imo. An order can not be confirmed and cancelled at the same time, but what if you make a mistake somewhere. You the risk creating corrupt data.
This approach would make it fairly easy to expand your application with a full order history, by creating 'status_changes' table ('order_id', 'status_id', 'date' , ...), to which you would write the status each time you change it.

As I said, how far you should go depends on the scope of your project (and your budget), as always. But it wouldn't be that big a job I think, and the benefits would be substantial.

Let me know if you want me to elaborate on anything, or if you want me to add some (pseudo) code. Hope it helps!


Short hash generator I am working on some code that will generate a link with a relativly unique 10 character hash.  I am not worried to much about colisions as long as they are rare enough that I could have a couple thousand links out standing since I soft delete after they are used and a colision between an open item and a closed item is not an issue.  I would also like the method to be deterministic, the same input generates the same output so worst case I can recalculate the hash if needed.  Here is the code I have and it works but am wondering if there is a better way.

string input = //Some input text that includes the datetime the hash was created;

using (SHA1Managed sha1 = new SHA1Managed())
{
    var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));

   //make sure the hash is only alpha numeric to prevent charecters that may break the url
   return string.Concat(Convert.ToBase64String(hash).ToCharArray().Where(x => char.IsLetterOrDigit(x)).Take(10));
}

This seems fine.

This should give you a key-space of 64^10.

If you have only a few thousand links then you're more likely to win the lottery jackpot than get a collision.


Finding the output of sequence (a + 2^(i*b)) I just started programming and have taken too much time to code the solution for this problem:

  In this problem you will test your knowledge of Java loops.  Given
  three integers, \$a\$, \$b\$, and \$n\$, output the following series:

  $$a + 2^{0}b, a + 2^{0}b + 2^{1}b, \ldots \ldots, a + 2^{0}b + 2^{1}b + \ldots + 2^{n-1}b$$

  Input Format

  The first line will contain the number of testcases \$t\$.  Each of
  the next \$t\$ lines will have three integers, \$a\$, \$b\$, and
  \$n\$.

  Constraints:

  \$0 \le t \le 500\$
  \$0 \le a, b \le 50\$
  \$1 \le n \le 15\$

  Output

  Print the answer to each test case in separate lines.

I just want to know whether this code can be further optimized in Java.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        int r=0,c=1;
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++){
            int a=sc.nextInt();
            int b=sc.nextInt();
            int n=sc.nextInt();
            r=a;
            for(int j=0;j<n;j++){
                if(j==0)
                    c=1;
                else
                    c=c*2;
                r= r +c*b;
                System.out.print(r +" " );
            }
            System.out.println( );
        }
    }
}

Performance

I tested your code, like so:

int r=0,c=1;
Deque<Integer> list = new ArrayDeque<>(1501);
list.add(500);
for (int x = 0; x < 500; x++)
{
    list.add(50);
    list.add(50);
    list.add(15);
}
long start = System.nanoTime();
int t=list.pop();
for(int i=0;i<t;i++){
    int a=list.pop();
    int b=list.pop();
    int n=list.pop();
    r=a;
    for(int j=0;j<n;j++){
        if(j==0)
            c=1;
        else
            c=c*2;
        r= r +c*b;
        System.out.print(r +" " );
    }
    System.out.println( );
}
long end = System.nanoTime();
System.out.println((end-start)+" nanos");

The resulting code prints "155156556 nanos", so took 155 milliseconds in total to run. I did a few more attempts and got durations in the range 120-145 millseconds.

When you say "have taken too much time to code the solution for this problem", did you mean "I took too long programming this"? Because there's no way to write code faster once it's written - the time has already been spent. 155 milliseconds for the largest inputs, for me, is fast enough.

I do not see any real opportunities for performance improvements. You could, in theory, do this:

        r=a + b;
        c = 1;
        System.out.print(r + " ");
        for(int j=1;j<n;j++){
            c=c*2;
            r= r +c*b;
            System.out.print(r +" " );
        }
        System.out.println( );

This would skip one cycle from the loop and remove a branch. Testing this version gives no large difference, and I see durations in the 120-140 ms range as well. Basically, I think the current version you have is good enough.

If you do want to go FASTER, though, here's what you'd do:

Don't print any output. The resulting code runs within a millisecond. String concatenation and output buffers hate you big time. Using StringBuilder gets the calculations down to 80 ms, but then printing the result takes another 40 ms.

The code you have will run about as fast as things will go.

Readability

What you can improve on is readability. For one, I'd add spaces around operators:

int r = 0, c = 1;
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i < t; i++){
    int a = sc.nextInt();
    int b = sc.nextInt();
    int n = sc.nextInt();
    r = a;
    for(int j = 0; j < n; j++){
        if(j == 0)
            c = 1;
        else
            c = c * 2;
        r = r + c * b;
        System.out.print(r + " ");
    }
    System.out.println();
}

Other things you could do is make use of += and *=:

            c *= 2;
        r += c * b;

In case of c * 2, though, you could shift all the bits left by 1 space, as that results in "multiply by 2"...

c <<= 1;

But maybe that's hard to read for others, so I would stick with *=.


Detecting a certain amount of violet in an image I need to be able to detect if an image has the colour Violet in it. (Follow-up)

The problem that I'm facing is that there are quite a number of shades of violet that it seems almost impossible it add every single one.

 private void ProcessImage(PictureBox picture)
    {
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            List<Color> ColoursToDetect = new List<Color>()
            {
                Color.FromArgb(202,156,254),
                Color.FromArgb(143,125,151),
                Color.FromArgb(100,76,136),
                Color.FromArgb(232,175,254)
            };
            Boolean colour_Found = false;
            Bitmap SelectedImage = new Bitmap(picture.Image);
            Color selected_Pixel;

            for (int x = 0; x != SelectedImage.Width; x++)
            {
                for (int y = 0; y != SelectedImage.Height; y++)
                {
                    selected_Pixel = SelectedImage.GetPixel(x, y);
                    foreach (Color c in ColoursToDetect)
                    {
                        if (c == selected_Pixel)
                        {
                            colour_Found = true;
                            MessageBox.Show("Found");
                            colour_Found = true;
                        }
                    }
                    if (colour_Found)
                    {
                        break;
                    }
                }
            }
        }
    }

The above code is working (So to speak) However I'm worried that one day an image will have a certain violet that i have no added and in hindsight will make the code useless.I did look at the .Net library AForge http://www.aforgenet.com/projects/iplab/, However I couldn't find any information about detecting a range of a certain colour.

Try using HSV/HSL to represent color instead of RGB.

You can then define violet as some hue range, e.g. 250° to 310° and similarly for saturation and lightness/value.

Always use a using when you have tempoary disposable resources like a Bitmap

Variables in C# are camelCase:

Boolean colourFound = false;
Bitmap selectedImage = new Bitmap(picture.Image);
Color selectedPixel;

Try to limit the scope of variables, move the declaration of selectedPixel to where you currently assign it.


Rock, Paper Scissor game (console-based) in Python I'm a beginner at coding with Python, and I've only made small projects, and this is one of them. One part of the code is from an answer on Stack Overflow that I made to solve a problem (is the try part) and all the other code is mine.

import random,os,time
score = {'human':0,'robot':0}
def game(): #Basic Game code.
    time.sleep(1)
    os.system('clear')
    print('IA: ' + str(score['robot']) + ' Human: ' + str(score['human']))
    print('1.Rock 2.Scissors 3.Paper')
    while True:
        try:
            choice = int(input("Input your choice:\n"))
            if choice < 1 or choice > 3: #Valid number but outside range, don't let through
                raise ValueError
            else: #Valid number within range, quit loop and the variable selection contains the input.
                break
        except ValueError: #Invalid input
            print("Enter a number from 1 to 3.")
    rchoice = random.randint(1,3)
    time.sleep(1)
    if rchoice == 1:
        print('IA choice is Rock.')
    elif rchoice == 2:
        print('IA choice is Scissors.')
    elif rchoice == 3:
        print('IA choice is Paper.')

    if (rchoice==1 and choice==2)or(rchoice==2 and choice==3)or(rchoice==3 and choice==1):
        print('IA wins!\n')
        score['robot'] += 1
        time.sleep(0.5)
    elif (rchoice == choice):
        print("Draw, let's repeat")
        time.sleep(0.5)
        game()
    else:
        print('You win!\n')
        time.sleep(0.5)
        score['human'] += 1

def startgame(): #The introduction of the game.
    os.system('clear')
    print('Rock-Paper-Scissors v.1')
    print('Developed by P.R.B.\n')
    ngames = int(input('How many games do you want to play?\n'))
    time.sleep(1)
    i = 0
    while i != ngames:
        game()
        i += 1
    print('Final Score:')
    print('IA: ' + str(score['robot']) + ' Human: ' + str(score['human']))
    if score['human'] > score['robot']:
        print('You win the game!\n')
    else:
        print('Game Over')
        print('IA wins the game!\n')

startgame()

It looks like you are familiar with dictionaries and maybe lists. So, let's look at how you collect and enter input. It looks like you are trying to control erroneous input with your try/except and if statement. There is some trouble though. I can send a float through your code if it has a value like 1.2 or 2.5. Your code will turn it into an int and then try to use the value, but there's another way to handle something like this:

if choice not in ['1','2','3']:
    raise ValueError
else:
    break

So, in this case, I'm using a list of the only acceptable values, checking if the choice is in there, and then moving forward.

Your control flow looks a little messy. There are a couple of ways to handle this.

If we keep the same general approach, you can make it more readable by spreading it out. I would actually make a new function for this:

def compare(x,y):
    if x == y:
        state = "It's a Draw!"
    if x == '1':
        if y == '2':
            state = "You Lose!"
        else:
            state == "You Win!"
    elif x == '2':
        if y == '1':
            state = "You Win!"
        else:
            state == "You Lose!"
    else:
        if y == '1':
            state = "You Lose!"
        elif y == '2':
            state = "You Win!"
    return state

However, depending on how comfortable you are with lists, there is another, simpler way!

You can setup a list of the possible game conditions and then do whatever you want to them:

game_result = ["tie!", "win!", "lose!"]

(Actually, that sequence in the list was coded for 1) Rock, 2)Paper, and 3)Scissors. There should be another arrangement for rock-scissors-paper though that makes things smooth).

Then define a comparison function that just looks at the modulated difference between the user and robot input (you'll need to convert them to the int data type first).

def compare(x,y):
result = game_result[ (x-y)%3 ]
return result

There's a few tricky things with how you're checking which round you should be on. So, first thing, it might be helpful/more readable if you change the variable name to something useful like round_number or matches_left.

Then, you have it set to end the while loop if the round number is not equal to n. There's another potential bug here. What if the user enters a float or something you don't want? -- Actually, you're using int() on the input, which corrects for this. So good call! But, that design pattern doesn't always carry over well and it may not be as clear to other readers ( it wasn't to me anyways).

Suppose the player enters 1.2, then your while loop goes on for ever if you aren't using int(). One way to handle this is to use try/except; another way is to use isinstance; and another way is to do something like this:

while num_of_rounds <= ngames:
        game()
        num_of_rounds += 1

In this way, you cover a broader set of what is acceptable/unacceptable and don't have your code hinging on a small window of operation (and exploitability).

Overall, your code works and was fun to play! The biggest things are style, readability, and different ideas on how to handle incorrect input. I would check out the PEP 8 Python style Guide for some general insights: https://www.python.org/dev/peps/pep-0008/


Python script that alerts me when specific file gets created I wrote a small script that opens a window using PyQt when a specific file gets created.

This is to let me know when another program (that I have no control over) has finished calculating something. I know at the end of the calculation a specific file is created.

Here is the code:

from PyQt5.QtWidgets import QWidget, QLabel
import os.path

file_to_check = "D:/test.txt"

alert_widget = QWidget()
alert_widget.setWindowTitle("Program X finished")
done_label = QLabel("Done",alert_widget)
done_label.move(50,50)

file_does_not_exist = True

while file_does_not_exist:
    if os.path.isfile(file_to_check):
        file_does_not_exist = False

alert_widget.show()

The widget that gets shown luckily just pops up in front of whatever window im currently active in, whether it's browsing the internet or working on an excel sheet. That is intended behaviour, but I did not write it in by specifying it as a "top level" window or somehting.

The script is started in an IPython console in Spyder and just left to run there. It works exactly as expected.

Now my questions

is this constantly running loop good practice?
are there any downsides to having that loop constantly running in the background?
could it block other programs?
is there another, more elegant way to achieve what I'm looking to do?
is the code following python coding conventions?

The variable file_does_not_exist is simply used as loop control, but we don't need it:

while not os.path.isfile(file_to_check):
    pass

However, this loop is very inefficient.  It's what we call a busy loop; that is, it never pauses, but continually polls for its condition.  This is harmful, as it monopolises a processor and wastes energy.  Sensible operating systems will de-prioritise busy tasks like this (to reduce its impact on other processes), which will reduce the UI responsiveness when you exit the loop, until the scheduler catches up with the change in the program's behaviour.

Instead, we should use operating system features (preferably abstracted in a platform-independent Python library) to wait for a change, allowing your process to sleep until it's notified.  I don't know of a platform-independent library, but there are some possibilities for Linux (inotify) and Windows (watchdog) at least.  Using one of these will yield processor time to other processes and make your program into a "good citizen" on a shared system.


Java program that relaunches itself in OS's terminal application I wrote a Java program that when its executable .jar is opened manually, it re-opens itself inside the operating system's shell console. The purpose of this is to have a C#-style console application where the user can enter commands, without the user needing to manually open the shell console and run the java -jar ... command to open the application.

Would you consider this a good implementation?

Would you make a custom console GUI instead of using the OS's console?

public static void main(String[] args){
    if(args.length == 0){ // then re-open in console with argument to indicate that there's no need to re-open next time.
        try {
            String os = System.getProperty("os.name").toLowerCase();
            String path = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();
            if(os.contains("mac")){
                String command = "tell application \"Terminal\"\n" +
                        "do script \"java -jar \'" + path + "\' console\"\n" +
                        "activate\n" +
                        "end tell";
                Runtime.getRuntime().exec( new String[]{"osascript", "-e", command} );
                System.exit(0);
            } else if(os.contains("win")) {
                Runtime.getRuntime().exec("cmd /c start cmd.exe /K java -jar \"" + path + "\" console");
                System.exit(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
    System.out.println("Enter command.  'help' for list of commands.");
    while(true)
        nextCommand();
}

A few empty lines here and there would do wonders to the readability.

This will also relaunch the application if it was started from a terminal without arguments.

String path = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();

String os = System.getProperty("os.name").toLowerCase();
...
if(os.contains("mac")){

Unfortunately that is a quite fragile way to detect the current operating system, but it will do.

On nay other operating system, you simply start reading commands (or not), are you aware of that?

You should have the command reading in an else branch.

System.exit(0);

Please stop sprinkling your code with those. System.exit makes the JVM exit immediately, it is like a SIGKILL on UNIX. That means that not even final branches are being run when invoked.

while(true)
    nextCommand();

I assume that there is a "quit" command which calls System.exit, that might be a bad idea. A better idea would be to have something like this:

while(commandExecutor.isActive()) {
    commandExecutor.readAndExecuteCommand());
}


Splitting a list of numbers into multiple lists I need split the list I get from the select into multiple list so I can use Parallel.For() to generate the next query in different threads.

I create the main list
Create the sub list
Keep filling sub list until reach max capacity.
Add sublist to main list

Create new sub list

When finish the loop save the last sublist

This works but I bet there is an easy / clean way to do this, I can change the db if needed.

List<List<long>> result = new List<List<long>>();
using (var conn = new NpgsqlConnection(strConnection))
{
    conn.Open();
    using (var cmd = new NpgsqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandText = "SELECT route_source_id " +
                          "FROM route_sources " +
                          "WHERE has_route IS NULL " +
                          "LIMIT 1000; ";

        using (var reader = cmd.ExecuteReader())
        {
            const long list_size = 100;

            long row_id = 0;
            List<long> route_list = new List<long>();

            while (reader.Read())
            {
               if (row_id++ > list_size) // Add the sublist to the result
               {
                   result.Add(route_list);
                   row_id = 0;
               }

               if (row_id == 0)  // Create new sublist
               {
                  route_list = new List<long>();
               }

               if (!reader.IsDBNull(0)) // fill the sublist
               {
                    route_list.Add(reader.GetInt64(0));
               }
            }

            if (route_list.Count > 0 ) // add the last sublist
            {
               result.Add(route_list);
            }
        }
   }
 }
 return result;

EDIT: aditional part of the process.

I have ticker to check the db for pending id to be process

// read 1000 rows split into 10 list, using above function
List<List<long>> route_pending = getRouteRange();
long total_rows = 0;

while (route_pending.Count > 0)
{
     foreach (List<long> range in route_pending)
     {
         total_rows += range.Count;
     }
     routeParallelGeneration(route_pending);
     route_pending = getRouteRange(); // keep reading next 1000 rows
}

And the parallel function, here I call my db storeproc with an array parameter. So max 10 connections with array of size 100. Here was where got issues with the excesive number of connections and decide split the data into 10 lists

public void routeParallelGeneration(List<List<long>> route_pending)
{
    Action<List<long>> forEachLoop = route_source_id => //Begin definition of forLoop
    {
        using (var conn = new NpgsqlConnection(strConnection))
        {
            conn.Open();
            using (var cmd = new NpgsqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandText = "SELECT avl_db.process_route(@route_source)";
                cmd.CommandType = CommandType.Text;

                NpgsqlParameter p = new NpgsqlParameter("@route_source", NpgsqlDbType.Array | NpgsqlDbType.Bigint);
                p.Value = route_source_id;
                cmd.Parameters.Add(p);
                cmd.ExecuteNonQuery();
            }
        }
    };
    Parallel.ForEach(route_pending, forEachLoop);
}

Pretty minor but you don't need the  if (row_id == 0)

if (row_id++ > list_size) // Add the sublist to the result
{
    result.Add(route_list);
    row_id = 0;
    route_list = new List<long>();
}

Also it seem like you should also test for

if (route_list.Count > 0 )

Why not just put where route_source_id is not null in the query?

Connection, Command, and Reader behave the same with many DB so this is pretty portable.

I think you can use

conn.CreateCommand()

Long is not required for row_id or list_size

Why bump row_id++ if there is no value?

In summary

    using (var reader = cmd.ExecuteReader())
    {
        const int list_size = 100;
        List<long> route_list = new List<long>(list_size);

        while (reader.Read())
        {
           if (route_list.Count >= list_size) // Add the sublist to the result
           {
               result.Add(route_list);
               route_list = new List<long>(list_size);
           }
           route_list.Add(reader.GetInt64(0));
        }

        if (route_list.Count > 0 ) // add the last sublist
        {
           result.Add(route_list);
        }
    }


Swap nodes in a binary tree I solved this challenge. It passes all the test cases, but I'm not very happy with my solution. I'm convinced this could be done much smoother (i.e less code)

  Swap operation: Given a tree and a integer, K, we have to swap the
  subtrees of all the nodes who are at depth h, where h ∈ [K, 2K,
  3K,...].

  You are given a tree of N nodes where nodes are indexed from [1..N]
  and it is rooted at 1. You have to perform T swap operations on it,
  and after each swap operation print the inorder traversal of the
  current state of the tree.

  Input Format:  First line of input contains N, number of nodes in tree.
  Then N lines follow. Here each of ith line (1 <= i <= N) contains two
  integers, a b, where a is the index of left child, and b is the index
  of right child of ith node. -1 is used to represent null node.  Next
  line contain an integer, T. Then again T lines follows. Each of these
  line contains an integer K.

Here is my code:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        final int N = s.nextInt();
        int[][] leafs = new int[N][2];

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < 2; j++) {
                leafs[i][j] = s.nextInt();
            }
        }

        int[] depths = new int[s.nextInt()];

        for (int i = 0; i < depths.length; i++) {
            depths[i] = s.nextInt();
        }

        TreeNode leftTree = (leafs[0][0] > -1) ? new TreeNode(leafs[0][0]) : null;
        TreeNode rightTree = (leafs[0][1] > -1) ? new TreeNode(leafs[0][1]) : null;

        if (leafs[0][0] > -1) leftTree.mapChildNodes(leftTree, leafs, (leafs[0][0] > -1) ? 1 : 2, 0, N);
        if (leafs[0][1] > -1) rightTree.mapChildNodes(rightTree, leafs, (leafs[0][0] > -1) ? 2 : 1, 0, N);

        TreeNode mainTree = new TreeNode(1, leftTree, rightTree);

        for(int d : depths) {
            mainTree.swap(mainTree, d, 1);
            mainTree.inorder(mainTree);
            System.out.println();
        }
    }
}

class TreeNode {
    private int data;
    private TreeNode left;
    private TreeNode right;

    TreeNode(int data) {
        this.data = data;
    }

    TreeNode(int data, TreeNode left, TreeNode right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }

    private void insertLeft(int data) {
        if (this.left == null) {
            this.left = new TreeNode(data);
        } else {
            this.left.insertLeft(data);
        }
    }
    private void insertRight(int data) {
        if (this.right == null) {
            this.right = new TreeNode(data);
        } else {
            this.right.insertRight(data);
        }
    }

    public void inorder(TreeNode node) {
        if (node == null) return;

        inorder(node.left);
        System.out.print(node.toString());
        inorder(node.right);
    }

    public void mapChildNodes(TreeNode node, int[][] leafs, int i, int j, int arraySize) {
        if (arraySize == 0) return;

        if (leafs[i][j] > -1){
            node.insertLeft(leafs[i][j]);
            mapChildNodes(node.left, leafs, leafs[i][j]-1, 0, arraySize-1);
        }
        if (leafs[i][j+1] > -1){
            node.insertRight(leafs[i][j+1]);
            mapChildNodes(node.right, leafs, leafs[i][j+1]-1, 0, arraySize-1);
        }
    }

    public void swap(TreeNode node, int targetDepth, int depth) {
        if(node == null) return;

        if(depth % targetDepth == 0) {
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        swap(node.left, targetDepth, depth+1);
        swap(node.right, targetDepth, depth+1);

    }

    @Override
    public String toString() {
        return this.data + " ";
    }
}

Current solution
There's nothing really wrong with your current solution.  You build the tree, do the swapping and then do the inorder traversal.  Each step is implemented in a simple way and there isn't much excess code.  However, since you asked about doing it in less code, I will show you two ways to dramatically reduce your code.
You don't need to build a second tree
If you think about it, after you have read in the tree into your array called leafs, you already have a complete tree structure.  You don't need to build a second tree with nodes, left/right children, etc.  You can just use the array as your tree representation.  Therefore, all of your TreeNode code is unnecessary.
You can print the inorder traversal during the swap
Right now, you run the swap() function to swap the requested nodes, and then run the inorder() function to print the nodes in the swapped tree.  Since those are the only two operations you need to do, you can just print the traversal while swapping instead of doing two passes.
Revised solution
Here is what your code would look like after making the above two changes.  Note that I modified the array to be 1-based because the problem wanted the root to be node 1.
import java.util.Scanner;

public class Solution {
    public static final int ROOT_NODE = 1;

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        final int N = s.nextInt();
        int[][] tree = new int[N+ROOT_NODE][2];

        for (int i = ROOT_NODE; i < N+ROOT_NODE; i++) {
            for (int j = 0; j < 2; j++) {
                tree[i][j] = s.nextInt();
            }
        }

        int numDepths = s.nextInt();
        for (int i = 0; i < numDepths; i++) {
            swap(tree, ROOT_NODE, s.nextInt(), 1);
            System.out.println();
        }
    }

    public static void swap(int [][] tree, int node, int targetDepth,
            int depth) {
        if(node == -1) return;

        if(depth % targetDepth == 0) {
            int temp = tree[node][0];
            tree[node][0] = tree[node][1];
            tree[node][1] = temp;
        }
        swap(tree, tree[node][0], targetDepth, depth+1);
        System.out.print(Integer.toString(node) + " ");
        swap(tree, tree[node][1], targetDepth, depth+1);
    }
}


SSO login & authenticate Wordpress users with JWT token I'm in the midst of exploring SSO with JWT & Wordpress, I'm not too sure if it's a good practice or does this setup/flow have any security vulnerabilities.

Currently JWT/SSO method i'm using is based on this answer/method which is getting JWT token using iFrame method instead of redirection method eg: from domain1.com > sso.com (retrieve JWT) > domain1.com

Please refer below for my setup/codebase fmi:

Main SSO domain (using Wordpress and JWT)

https://sso.com/login
https://sso.com/validation

Platform 1 (using plain PHP)

https://domain1.com

Platform 2 (using plain PHP)

https://domain2.com

sso.com/login (Wordpress)

Passport

<input type="text" name="username" value="admin"/>

<input type="text" name="password" value="admin"/>

Submit

Platform 1 & Platform 2 (PHP)

Questions: is it safe if i'm using postMessage to retrieve JWT token from iframe/sso.com? Any security vulnerability i need to concern?

    <meta charset="UTF-8">
    <title>Platform 1</title>

sso.com/validation (Wordpress)

Questions: Since we'll have multiple platform eg: domain1.com, domain2.com, etc, is it a good practice to pass a dynamic parameter in postMessage function using parentUrl?

tldr; is this the right direction to create SSO/JWT authentication with cross domains with PHP? is above method is a secure way to code it?

I don't know why an iframe was suggested to you, but I do see some possibilities for vulnerability.

For your platforms, I would validate server-2-server.

Flow:

If client claims to be logged in ( in JS / has token in local storage), send token to the platform itself.

The receiving endpoint (let's say platform1_showProfile.php) sends a curl-request to the SSO platform in order to validate (and or logout/refresh if expired etc)

For performance reasons, you will want to ask yourself whether

JWT is only your SSO authentication method while maintaining state on each platform or if you want to go stateless and use the sso-endpoint on each call.
WordPress is the right solution for this. Consider setting up an authentication server with slimframework or neoan3


Determining if two strings are anagrams of each other Is this code a good solution for the question, or is there a better way to do it?

package ArraysAndStrings;

import java.util.Arrays;

public class anagram{

    private boolean isAnagram = false;

    public boolean Anagrams(String str1, String str2){

        if(str1.length() != str2.length()){
            return isAnagram;
        }

        boolean [] char_set = new boolean[256];
        boolean [] char_set1 = new boolean [256];

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

            int val1 = str1.charAt(i);
            int val2 = str2.charAt(i);

            char_set[val1] = true;
            char_set1[val2] = true;
        }

        if(Arrays.equals(char_set, char_set1)){
            isAnagram = true;
        }

        return isAnagram;

    }

    public static void main(String [] args){

        anagram ang = new anagram();

        System.out.println(ang.Anagrams("mary","army"));

    }

}

The code is technically broken: it only tells that the strings are composed of the same letters. It is not enough for the strings to be anagrams. Each letter must appear the same number of times in both strings.

Making your char_set array integer instead of boolean you can get the correct result still in linear time:

    int [] counters = new int[256];
    set_counters_to_zero();
    for (int i = 0; i < str1.len(); i++) {
        counters[str1.charAt(i)]++;
    }
    for (int i = 0; i < str2.len(); i++) {
        counters[str2.charAt(i)]--;
    }
    return all_counters_are_zero();


YouTube page scraping using Jsoup I am trying to scrape the YouTube video streaming page to get the metadata of the video. I am considering this YouTube page as an example. You can find the HTML contents of that page over here (I have removed some not-so-useful JavaScript and provided the relevant HTML content).
I am using Jsoup (a Java HTML parser) for this.
I am getting the content what I want but I just wanna know is this the right way to do it?

public VideoData getVideoData(String videoUrl) throws IOException {
    Document doc = Jsoup.connect(videoUrl).header("User-Agent", "Chrome").get();
    Element body = doc.body();
    String videoThumbnail = body.getElementsByAttributeValue("itemprop", "thumbnailUrl").get(0).attr("href");
    String videoEmbedUrl = body.getElementsByAttributeValue("itemprop", "embedURL").get(0).attr("href");
    String videoTitle = body.getElementById("eow-title").attr("title");
    String userLink = body.getElementById("watch7-user-header").getElementsByAttributeValue("class", "yt-user-photo yt-uix-sessionlink      spf-link").attr("href");
    String userPhoto = body.getElementById("watch7-user-header").getElementsByTag("img").attr("data-thumb");
    String channelLink = body.getElementById("watch7-user-header").getElementsByClass("yt-user-info").get(0).child(0).attr("href");
    String channelName = body.getElementById("watch7-user-header").getElementsByClass("yt-user-info").get(0).child(0).wholeText();
    boolean isChannelVerified;
    try {
        isChannelVerified = body.getElementById("watch7-user-header").getElementsByClass("yt-user-info").get(0).child(1).attr("aria-label").equalsIgnoreCase("Verified") ? true : false;
    } catch (Exception e) {
        isChannelVerified = false;
    }
    String noOfSubs = body.getElementsByClass("yt-subscription-button-subscriber-count-branded-horizontal yt-subscriber-count").attr("title");
    String viewCount = body.getElementsByClass("watch-view-count").text();
    String noOfLikes = body.getElementsByAttributeValue("title", "I like this").get(0).text();
    String noOfDislikes = body.getElementsByAttributeValue("title", "I dislike this").get(0).text();
    String publishedOn = body.getElementById("watch-uploader-info").text().replace("Published on ", "");
    String description = body.getElementById("watch-description-text").children().text();
    boolean isFamilyFriendly = body.getElementsByAttributeValue("itemprop", "isFamilyFriendly").attr("content").equalsIgnoreCase("True") ? true : false;
    String genre = body.getElementsByAttributeValue("itemprop", "genre").attr("content");
    VideoData videoData=new VideoData(videoThumbnail,videoEmbedUrl,videoTitle,userLink,userPhoto,channelLink,channelName,isChannelVerified,noOfSubs,viewCount,noOfLikes,noOfDislikes,publishedOn,description,isFamilyFriendly,genre);
    return videoData;
}

There is nothing special to say. This is a big bunch of procedural code. You can maybe improve it by keeping references to items or navigating in them instead of re-reading them from the root :

String userLink = body.getElementById("watch7-user-header").getElementsByAttributeValue("class", "yt-user-photo yt-uix-sessionlink      spf-link").attr("href");
String userPhoto = body.getElementById("watch7-user-header").getElementsByTag("img").attr("data-thumb");

// Can be
Element user = body.getElementById("watch7-user-header");
String userLink = user.getElementsByAttributeValue("class", "yt-user-photo yt-uix-sessionlink      spf-link").attr("href");
String userPhoto = user.getElementsByTag("img").attr("data-thumb");

If you want to change the way you parse that, you can introduce a parsing object. (https://www.javacodegeeks.com/2018/03/dont-parse-use-parsing-objects.html)


Removing spam from a database using NodeJS I've written the following in NodeJS as I am trying to learn a bit more about that toolset. It 'works' but is not very robust. I am not concerned with security at this stage and the code will not be accessible to end users. I would like to incorporate some kind of timer which ensures that the call to the Akismet API does not hit a rate limit. Occasionally I see socket hang up and timeout errors.

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123',
    database : 'mydb',
    //debug: true,
    multipleStatements: true
});

var akismet = require('akismet').client({ blog: 'http://example.com', apiKey: 'xxxxxxx' });

var selectPosts = "SELECT p.topic_id as id, poster_ip, t.subject as message, p.poster FROM topics  t\
                  LEFT JOIN posts p on t.first_post_id = p.id WHERE poster_ip != ''";

akismet.verifyKey(function(err, verified) {
    if(err) throw err;
    if (verified) {

        console.log('API key successfully verified.');
    }

    else {

        console.log('Unable to verify API key.');
    }

});

connection.connect();

connection.query(selectPosts, function(err, rows, fields) {
    if (err) throw err;

    rows.forEach( function(entry) {

    checkSpam(entry)

    });

});

var afterDelete = function (err, result) {

    if (err) throw err;
    console.log('deleted ' + result.affectedRows + ' rows');

}

var afterCheck = function(err, entry) {

    if (err) throw err;

    var deleteQuery = "DELETE t, p FROM topics AS t LEFT JOIN posts AS p ON t.id = p.topic_id WHERE t.id=";
    var deleteUser = "DELETE FROM users WHERE username='"+entry.poster+"';";
        console.log(deleteQuery + entry.id);
        console.log('entry is ' + entry['id']);
        connection.query(deleteQuery + entry.id, function(err,result)
        {
            afterDelete(err,result);
        });

        connection.query(deleteUser, afterDelete);

}

var checkSpam = function(entry) {
    akismet.checkSpam({
        user_ip: entry['poster_ip'],
        comment_author: entry['poster'],
        comment_content: entry['message']

    }, function(err, spam){
        if (err) throw err;
        if (spam) {
            //console.log('spam');
            afterCheck(err, entry);

        } else {

            console.log('Not spam');

        }

    });

}

//connection.end();

Well, your code can use a little formatting. I usually go with 2-character indents (tabs or spaces) since in JS, code tends to be nested. I usually also limit my newlines to 1 or 2, one being a "breather" and 2 for totally different blocks of code. While everyone's preferences vary, always consider consistency and readability.

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '123',
    database : 'mydb',
    //debug: true,
    multipleStatements: true
});

var akismet = require('akismet').client({ blog: 'http://example.com', apiKey: 'xxxxxxx' });

I suggest you read your credentials from environment variables. You wouldn't want anyone seeing your passwords or API keys, especially when you start to use a version control system. This also makes it easy for multiple deployments (multiple machines, virtual hosts etc) as the credentials can be configured from a provisioning tool. I doubt your host will always be localhost on every machine, or your database be named mydb on every instance, or your API key be just one across your system.

const POSTS_QUERY = `
  SELECT
    p.topic_id as id,
    poster_ip,
    t.subject as message,
    p.poster
  FROM
    topics
  LEFT JOIN
    posts p on t.first_post_id = p.id
  WHERE
    poster_ip != ''
`;

If you're using the newer Node.js (I believe the 4.x onwards), it should have ES6 support, which includes multi-line (backticked) strings. This allows you to write SQL queries like the one above. Much cleaner than your single-lined strings. And since it's probably a constant string, I suggest using const as well as a conventional all-caps, snake-cased name.

I notice that your async functions are "node functions" (receive an error object first, data second). You can take advantage of Bluebird's promisify function to turn them into Promise-returning functions. That way, you can take advantage of Promises and write fairly linear-looking code.

Here's an excerpt of what I came up with:

let Promise = require("bluebird");

let connection = require('mysql').createConnection({
  host: 'localhost',
  user: 'root',
  password: '123',
  database: 'mydb',
  //debug: true,
  multipleStatements: true
});

let akismet = require('akismet').client({
  blog: 'http://example.com',
  apiKey: 'xxxxxxx'
});

const SELECT_POSTS = `
  SELECT
    p.topic_id as id,
    poster_ip,
    t.subject as message,
    p.poster
  FROM
    topics
  LEFT JOIN
    posts p on t.first_post_id = p.id
  WHERE
    poster_ip != ''
`;

let verifyKey = Promise.promisify(akismet.verifyKey);
let query = Promise.promisify(connection.query, { multiargs: true });
let checkSpam = Promise.promisify(akismet.checkSpam);

let verifyKeyPromise = verifyKey()
.then(function(verified){
  console.log('API key successfully verified');
  connection.connect()
  return query(SELECT_POSTS);
}, function(err){
  console.log('Unable to verify API key');
})
.then(function(rows, fields){
  console.log('Posts retrieved');
  return Promise.all(rows.map(function(entry){
    return checkSpam({
      user_ip: entry['poster_ip'],
      comment_author: entry['poster'],
      comment_content: entry['message']
    });
  });
}, function(v){
  console.log('Failed to retrieve posts');
})
.then(function(entrySpamStatus){
  console.log('Spam check succeeded');
  // and so on...
}, function(err){
  console.log('Spam check failed');
  // and so on...
})

// and so on...


Multiple permission checks in web app automated tests I am writing automated tests for a web app and at one point I need to make sure that a user can only engage in activities allowed by a set permission. I have written all the standalone methods that perform the required tests and now I need to group all of them together and test. I came up with something that looks like this:

public boolean hasPermissions(String permissions, File file) {

    if ("Read Only".equals(permissions)) {

        return !canCreateNewFolder() && !canAddFiles() && !canAddLink() && canCopyMultipleItems() && !canMoveMultipleItems()
                && !canDeleteMultipleItems() && canDownloadMultipleItems() && canDownload(file) && canViewDetails(file)
                && !canEdit(file) && canCopy(file) && !canMove(file) && !canHide(file) && !canDelete(file);

    } else if ("Read and Add Only".equals(permissions)) {

        return canCreateNewFolder() && canAddFiles() && canAddLink() && canCopyMultipleItems() && !canMoveMultipleItems()
                && !canDeleteMultipleItems() && canDownloadMultipleItems() && canDownload(file) && canViewDetails(file)
                && !canEdit(file) && canCopy(file) && !canMove(file) && !canHide(file) && !canDelete(file);

    } else if ("Full Access".equals(permissions)) {

        return canCreateNewFolder() && canAddFiles() && canAddLink() && canCopyMultipleItems() && canMoveMultipleItems()
                && canDeleteMultipleItems() && canDownloadMultipleItems() && canDownload(file) && canViewDetails(file) && canEdit(file)
                && canCopy(file) && canMove(file) && canHide(file) && canDelete(file);

    } else {
        throw new UnsupportedOperationException("Unsupposrted permission");
    }

}

While this solution works with no issues, it somehow doesn't look right.

So just wanted to ask for another opinion on this design.

So, thing is, it's GREAT that you made the individual tests. Imagine this method with all those tests inlined. That'd be... really bad. So that part is good. But like you say, something is off.

Now, one way you could look at this is that you don't really need to test everything. That depends on what an implementation means, but someone has read rights if they can read a file. Whether or not they can write... it doesn't matter. But, that depends on your business requirements, so such a simplification may not apply.

Another thing you could do is apply semantic grouping. Combine checks that are in the same category.

There seems to be 3 groups:

Read access, which is the ability to read any file (canCopyMultipleItems, canDownloadMultipleItems, canDownload, canViewDetails, canCopy).

Create+Read access, which is read + append to directory. (canCreateNewFolder, canAddLink)

Write access, which is read + create + write. (canMoveMultipleItems, canDeleteMultipleItems, canEdit, canMove, canHide, canDelete).

If you are only interested in verifying that someone has "at least" these rights, this is easy, you can make three groups of checks (each of them including the previous) and return the appropriate value.

If, however, you're only allowed to have the exact matching set of rights, then the check becomes harder, I'd dare say that what you have right now is the fastest code you could have; any faster is going to be faster because of a redesign.

From a readability perspective, all I'd do is this:

Wrap each grouping we just mentioned in two separate functions:

hasAny<group>Right and hasAll<group>Rights.

Then you can use them like so:

public boolean hasPermissions(String permissions, File file) {

    if ("Read Only".equals(permissions)) {
        return hasAllReadRights(file) && !hasAnyCreateRight(file) && !hasAnyWriteRight(file);
    } else if ("Read and Add Only".equals(permissions)) {
        return hasAllReadRights(file) && hasAllCreateRights(file) && !hasAnyWriteRight(file);
    } else if ("Full Access".equals(permissions)) {
        return hasAllReadRights(file) && hasAllCreateRights(file) && hasAllWriteRights(file);
    } else {
        throw new UnsupportedOperationException("Unsupposrted permission");
    }
}

Perhaps even name "create" "add" instead.

That all said, you... clearly have a design issue going on. A string goes in, and based on that you're doing checks? Huh?

First, stringly typed code should be replaced with Enums. Second, having to check every single time if the user has a set of general rights is ... weird. These should be migrated to a different place; then all you're interested in is if the user has generic read rights, + the few things that are file specific. If instead you're relying on class variables in these "generic" checks (like canDownloadMultipleItems), then... well... then I still think it's worth splitting these checks up into "generic" and "file-specific" checks; if you're ever going to be looping over a directory, you'll want to be checking the generic parts only once, and not all the time.

Also, there's a typo in your exception. "Unsupposrted permission" -> "Unsupported permission"


Would this be considered MVC? For many days, I've been re-designing my application, applying some custom pattern and making our code looks like a framework. I have something like this for separate the business logic, from views:

    if(file_exists($route . $urlpara[0] . ".template.php")){
        require_once($route . $urlpara[0] . ".functions.php");
        require_once($route . $urlpara[0] . ".template.php");
    }else{
        // 404 error
    }

$route means the route.

$urlpara[0] means a parsed URL, where $urlpara[0] should be in this case the URL.  In this case, we could say $urlpara[0] = index. So this would like like this without variables:

    if(file_exists("app/index.template.php")){
        require_once("app/index.functions.php");
        require_once("app/index.template.php");
    }else{
        // 404 error
    }

Inside index.template goes the view, and inside index.functions goes the model.

Here's the .htaccess

RewriteEngine On
Options -MultiViews
Options +FollowSymlinks

RewriteBase /script/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#Basic params MVC
RewriteRule ^(.*)$ index.php?page=$1 [L]

Here the index.php (the part where it reads and splits up the model/view):

    $exploded = explode('/', $_GET['page']); // pagename/param1/param2/etc..

    $route = 'script/path/';
    $first_param = $exploded[0];
    $second_param = $exploded[1];
    // Controller
            if(file_exists($route . $first_param . ".template.php")){
                require_once($route . $first_param . ".functions.php");
                require_once($route . $urlpara[0] . ".template.php");
            }else{
                // 404 error
            }

    // now it checks if param1 = pagename exists. For example dashboard.template.php. Same with dashboard.functions.php

function generateTitle(){
echo 'this title generated dynamically';
}

Within dashboard.template.php we find this:

<!-- View -->
<html>
<head>
<title><?php echo generateTitle(); ?></title>
</head>
<?php
foreach($whatever as $some){
echo $some;
}
?>
</html>

And within the dashboard.functions.php we find this:

<?php
// Model
$whatever = array('test', 'test2', 'test3');
?>

I don't really know if I'm doing it well.  Could be this represented as a MVC pattern?

what you have posted is orthogonal to MVC. MVC deals with user interfaces. It has later been reshaped many times to fit various platforms such as the web but the original ideas came out of Xerox some forty years ago and tryed to bridge the gap between the user and the model in the computer (the M) though it's known as MVC it actually MVC-U where the U is for user and the U is there to stress the relationship between the system (MVC) and the User (U).

There's no interface in the code you've posted and hence at best it can be viewed as a mechnism to start some (sub)system that's build on MVC.
The Model is suppossed to represent piece of the users mental model. How they see the world and it has been shown that if there's a 1:1 relation ship between the real life model and the one in the system Users are better at using the system. The view is what the user sees. You can say it's a visual representation of the model and the controller is coordinating user inputs and model updates (which in turn are reflected by an update of the view)

So the short answer would be "no" but the longer is more down the line of "MVC is something unrelated to the problem you are solving with the above code"


Positive cumulative sum of difference I have a water reservoir with input and output rates. I want to determine when the input is exceeding the output by a certain constant. To accomplish this, I need to cumulatively sum all cases where the inflow exceeds the outflow. Thus, I've written this function:

def pos_diff_cum_sum(flow_in: np.ndarray, flow_out: np.ndarray) -> np.ndarray:
    sums = []
    cum_sum = 0
    diff = list(flow_in - flow_out)

    for dd in diff:
        cum_sum += dd
        if cum_sum < 0:
            cum_sum = 0

        sums.append(cum_sum)

    return np.array(sums)

It sums up the periods where the inflow exceeds the outflow while ignoring periods where the opposite is true. Basically, numpy.cumsum with a corner case.

Tests with plots

t_steps = 9

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8))
in_flow = np.linspace(1., 0., t_steps)
out_flow = np.linspace(0., 1., t_steps)

ax1.plot(in_flow, label="in")
ax1.plot(out_flow, label="out")
ax1.legend()

pos_diff = pos_diff_cum_sum(in_flow, out_flow)
ax2.plot(pos_diff)
pos_diff
# => array([1.  , 1.75, 2.25, 2.5 , 2.5 , 2.25, 1.75, 1.  , 0.  ])

t_steps = 9

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8))
in_flow = np.linspace(0., 1., t_steps)
out_flow = np.linspace(1., 0., t_steps)

ax1.plot(in_flow, label="in")
ax1.plot(out_flow, label="out")
ax1.legend()

pos_diff = pos_diff_cum_sum(in_flow, out_flow)
ax2.plot(pos_diff)
pos_diff

# => array([0.  , 0.  , 0.  , 0.  , 0.  , 0.25, 0.75, 1.5 , 2.5 ])

This code isn't vectorized, but it's going to be called very frequently, so is there some way I should speed it up? Is there any way to make this more elegant?

You can use np.cumsum and np.minimum.accumulate (which I found from this post).

Another way to look at what you want is you want the cumsum.

If the value goes below zero then you want to subtract a value to get it to zero, this value is itself. This means that you just need a running minimum. This is as you've subtracted the value from an earlier value so the effect propagates in your version but not in np.cumsum.

You also want to start this minumum from 0.

def pos_diff_cum_sum(flow_in, flow_out):
    delta = np.cumsum(flow_in - flow_out)
    return delta - np.minimum.accumulate(np.append([0], delta))[1:]

For reference below.

def fn(in_, out):
    delta = np.cumsum(np.array(in_) - np.array(out))
    print(delta)
    output = delta - np.minimum.accumulate(np.append([0], delta))[1:]
    print(np.minimum.accumulate(np.append([0], delta))[1:])
    print(output)

If you have an input that only increases then you can just use use np.cumsum:

>>> fn([1, 1, 1, 1, 1], [0, 0, 0, 0, 0])
[1 2 3 4 5]
[0 0 0 0 0]
[1 2 3 4 5]

However if the number goes negative you must subtract all values after it goes negative by that value. This is as the single -= affects the rest of the input in the OP:

>>> fn([1, 0, 0, 0, 0], [0, 1, 1, 0, 0])
[ 1  0 -1 -1 -1]
[ 0  0 -1 -1 -1]
[1 0 0 0 0]

This means you must subtract them even if the value becomes positive again:

>>> fn([1, 0, 0, 1, 1], [0, 1, 1, 0, 0])
[ 1  0 -1  0  1]
[ 0  0 -1 -1 -1]
[1 0 0 1 2]

If more numbers go negative then you have to decrease by these amounts too:

>>> fn([1, 0, 0, 0, 0], [0, 1, 1, 1, 1])
[ 1  0 -1 -2 -3]
[ 0  0 -1 -2 -3]
[1 0 0 0 0]

This allows the value to go positive again if it needs to:

>>> fn([1, 0, 0, 0, 1], [0, 1, 1, 1, 0])
[ 1  0 -1 -2 -1]
[ 0  0 -1 -2 -2]
[1 0 0 0 1]


Link two databases through the java application I have a java application that migrates data from one database to another.
I have to do update data in my database with data from another database. Another database provided by the customer.

Now it is this way:

I make a request from java application to my database(oracle) to get the address and driver of database, user, password from which I want to get the data.

oracleConn = DriverManager.getConnection(...); //connect to my DB

PreparedStatement prStServerP = this.oracleConn.prepareStatement("SELECT adress, driver, user, password from connections where svr_id = ?"); //settings to connect to the remote DB

Then I establish a connection with the remote database.

Connection dbConn = this.getDbConnection(svrId);

From my database I get "selects" for the remote Database.

oraclePrSt = this.oracleConn.prepareStatement("SELECT slq_select FROM SELECTS where svr_id...")

Also from my database I choose the table which will put the data from the remote database.

I Doing "selects" in a remote database and put the data:

Statement dbPrSt = dbConn.createStatement();
ResultSet dbRs = dbPrSt.executeQuery(oracleRs.getString(3)); //here selects that I got from my database
ResultSetMetaData dbRsMd = dbRs.getMetaData();

After all of this I record the results from a remote database into a file and using sqlLoader writes data in my database.

Please, tell me is there any options to make it easier or better?

Your solution is fine if you only have a couple of tables to copy.
If you have a whole database you could export the entire database to a SQL dump and them run that whole script in the new database manually.

If you need to do transformation to the data, then you can look into Oracle ETL tools.


Small class to manage config data I made this small class the allows me to navigate large arrays using something like: key1/key2/key3

I made this because I was creating large arrays to hold my classes configs and needed a simpler way of accessing the data.

Here is the project:
 - https://github.com/AntonioCS/settingsManager

The class is here:

<?php

namespace SettingsManager;

/**
 * To ease access of config data
 *
 */
class settingsManager {

    /**
     * Where that data will be held
     * @var array
     */
    private $_data = array();

    /**
     * To speed up access
     * @var array
     */
    private $_cache = array();

    /**
     * To use or not to use the cache (that is the question!!)
     * @var bool
     */
    private $_useCache = true;

    /**
     * Allow the settings to be changed
     * @var bool
     */
    private $_allowChange = false;

    /**
     * Initialize the class and set the settings data
     *
     * @param array $data
     * @param bool $allowChange - Default false
     * @param bool $useCache - Default true
     */
    public function __construct($data, $allowChange = false, $useCache = true) {
        $this->_data = $data;
        $this->_allowChange = $allowChange;
        $this->_useCache = $useCache;
    }

    /**
    * Access the _config property and return specified section
    *
    * @param string $section - Example: section/config
    * @return mixed
    *
    * @throws OutOfBoundsException
    */
    public function get($section) {
        if ($this->_useCache && isset($this->_cache[$section]))
            return $this->_cache[$section];

        return $this->_engine($section);
    }

    /**
     * If allowed this will set the given section to the given value
     *
     * @param string $section
     * @param mixed $value
     * @return mixed
     *
     * @throws OutOfBoundsException
     * @throws TryToChangeImmutableObjectException
     */
    public function set($section, $value) {
        return $this->_engine($section, $value);
    }

    /**
     * Check and see if section exists
     *
     * @param string $section
     * @return bool
     */
    public function exists($section) {
        try {
            $this->get($section);
        }
        catch (\OutOfBoundsException $e) {
            return false;
        }

        return true;
    }

    /**
     * Clear cache
     */
    public function clearCache() {
        $this->_cache = array();
    }

    /**
     * Get/Set a value from the settings property
     *
     * @param string $section
     * @param mixed $value
     * @return mixed
     *
     * @throws \OutOfBoundsException
     * @throws TryToChangeImmutableObjectException
     */
    private function _engine($section, $value = null) {

        if ($value && !$this->_allowChange)
            throw new TryToChangeImmutableObjectException();

        $sections = explode('/',$section);
        $tempSectionData = &$this->_data;

        foreach ($sections as $currentSection) {
            if (!isset($tempSectionData[$currentSection])) {
                throw new \OutOfBoundsException($section . ' - ' . $currentSection);
            }

            $tempSectionData = &$tempSectionData[$currentSection];
        }

        if ($value) {
            $tempSectionData = $value;
            if ($this->_useCache && isset($this->_cache[$section]))
                unset($this->_cache[$section]);
        }

        return $tempSectionData;
    }
}

class TryToChangeImmutableObjectException extends \Exception {}

So a simple use case would be:

<?php

$_testData = array(
        'data' => 1,
        'data2' => array(
            'date3' => 4
            )
    );

$object = new SettingsManager\settingsManager($_testData);

echo $object->get('data2/date3'); //Should echo 4

Any comments or suggestions?

I swear I've seen this approach somewhere before, I'll have to see if I can't find that link again. Anyways, a couple of drawbacks of this approach is lack of portability and lack of familiarity. Portability meaning no one can move that code without also taking that class with it. Familiarity meaning not well known. Though I do have to admit, I would love to see PHP natively adopt an xpath navigation style for arrays. Would make life so much easier.

I would steer clear of using method names that are similar to PHP's reserved words. In other words get() would be better as fetch() or query() or something similar. Same for set() and exists(). This helps avoid confusion. The only time "get" or "set" is generally used is when defining a specific getter or setter such as getPath() or setPath(). _engine() is also oddly named, would expect _parse() or _evaluate() or something similar. But this is all stylistic.

The only "real" criticism I have for this bit of code is that occasionally you neglect your braces. These are always important. Please remember them.

if ($this->_useCache && isset($this->_cache[$section]))
    return $this->_cache[$section];

The only improvement I can suggest is to abstract your caching to a different class in case you ever decide to change it.

Have you thought about creating relative pathing support? In other words, using your example, you could get the same results by using just "//date3"? The previous project I was thinking about did this and I was quite impressed. If there was more than a single match it would return a set of results. It also knew only to look one level deep relative to the array passed to it.

Overall, very impressive though. Sorry I couldn't add more to it.


jQuery conditional statement to check if a select option has either of 4 values selected I am working on this project that has a reservation form which allow users specify which sort of service they require. I have a select menu with eight (8) options and I have two divs which would either show/hide depending on the value of the option been selected. Seen below is the select element:

<select name="serviceChoice" id="serviceChoice">
  <option value="A">Option A</option>
  <option value="B">Option B</option>
  <option value="C" selected="selected">Option C</option>
  <option value="D">Option D</option>
  <option value="E">Option E</option>
  <option value="F">Option F</option>
</select>

I have several form fields

I have several form fields

I have written my jQuery code to alternate between these divs, however I would like to know if there is a shorter better way to get this done. I would also like to clear the values of any input elements in a div which has been hidden due to the choice of the user. My code is as follows:

(function($){
    $('#field_1').show();
    $('select[name=serviceChoice]').change(function(){
        if( $('select[name=serviceChoice] option:selected').val() == 'A' ) {
            $('.optionBox').hide();
            $('#dropOff').show();
        } else if ( $('select[name=serviceChoice] option:selected').val() == 'B' ) {
            $('.optionBox').hide();
            $('#pickUp').show();
        } else if ( $('select[name=serviceChoice] option:selected').val() == 'C' ) {
            $('.optionBox').hide();
            $('#pickUp').show();
        } else if ( $('select[name=serviceChoice] option:selected').val() == 'D' ) {
            $('.optionBox').hide();
            $('#pickUp').show();
        } else {
            $('.optionBox').show();
        }
    });
})(jQuery);

// You can use the document.ready as both encapsulation as well as
// to make sure the DOM is ready for operation.
$(function ($) {

  // Unless these are dynamic (the set could change), it's better to cache them
  var optionBox = $('.optionBox');
  var dropOff = $('#dropOff');
  var pickUp = $('#pickUp');
  var field1 = $('#field_1');

  field.show();

  // Your select box has an ID. They are faster than attribute selectors
  // in both parsing ase well as fetching from the DOM
  $('#serviceChoice').change(function () {

    // The current context of this function is the DOM element, which is the select
    // You can use it to get the value, rather than using a selector again. Removes
    // the need for jQuery to parse the selector and look for it in the DOM
    switch ($(this).val()) {
    case 'A':
      optionBox.hide();
      dropOff.show();
      break;
    case 'B':
    case 'C':
    case 'D':
      optionBox.hide();
      pickUp.show();
      break;
    default:
      optionBox.show();
    }
  });
});

Minus the comments, here's what you get:

$(function ($) {

  var optionBox = $('.optionBox');
  var dropOff = $('#dropOff');
  var pickUp = $('#pickUp');
  var field1 = $('#field_1');

  field.show();

  $('#serviceChoice').change(function () {

    switch ($(this).val()) {
    case 'A':
      optionBox.hide();
      dropOff.show();
      break;
    case 'B':
    case 'C':
    case 'D':
      optionBox.hide();
      pickUp.show();
      break;
    default:
      optionBox.show()
    }
  })
});


jQuery marquee, without flickering, less memory consumption, and no plugin I have tried using jQuery to create an alternative of marquee, and got no success. It flickers and does not stop on hover. I edited and edited again and it finally came out with a jQuery + JavaScript mess.

JavaScript:

$(document).ready(function(){
        marquee();
        var timeout=1;
        function marquee(){
            var margin= -($('#mydiv > div:eq(0)').outerHeight()+ 20);
            $('#mydiv > div:eq(0)').animate({'margin-top': margin+'px'},4000,function(){
                $('#mydiv > div:eq(2)').html($(this).html());
                $(this).html('').css({'margin-top':'0px'}).appendTo($('#mydiv'));
                loop();
            });
        }
        function loop(){
            if(timeout)
            setTimeout(marquee,0);
        }
        $('#mydiv').hover(function(){
                timeout = 0;
                $('#mydiv > div:eq(0)').stop(true);
        },function(){
                timeout = 1;
                marquee();
        });
    });

Markup:

 Advantages:

blah 1

blah 2

blah 3

Applications:

blah 1

blah 2

blah 3

A few points:

$(this).html('') will throw away the contents of #div1 (on the first iteration) and #div2 (on the second iteration). If you want the marquee to loop, that's not going to work.
This is a perfect use case for a simple jQuery plugin (see the documentation).
You should probably use next() instead of the eq selector, to make your code work with any number of children (or at least any number above 1).
To stop the animations on hover, you'll have to call stop() on any elements that may be half-way into an animation. Pausing and continuing the marquee would be good use cases for plugin methods.
You could consider using the position and top attributes to position the children; this is exactly what position: absolute is for.

Given below is an example of a simple plugin that does roughly what you want. To keep in theme with this site, I've stuck with your approach -- animation is done on margin-top and, as you can see, only the first child is animated.

Because of this, the marquee won't loop until all children are outside the parent div. To make it wrap sooner, I would advise rewriting the plugin to use position: absolute and the top attribute on each child. That way, each child can be idependently animated and the marquee can be looped earlier.

Finally, keep in mind that this example is far from perfect. For example, the total height of the children is re-calculated on each run. The plugin could be made more efficient simply by maintaining state.

Plugin:

(function($) {

    var methods = {
        init: function(options) {
            this.children(':first').stop();
            this.marquee('play');
        },
        play: function() {
            var marquee = this,
                pixelsPerSecond = 100,
                firstChild = this.children(':first'),
                totalHeight = 0,
                difference,
                duration;

            // Find the total height of the children by adding each child's height:
            this.children().each(function(index, element) {
                totalHeight += $(element).innerHeight();
            });

            // The distance the divs have to travel to reach -1 * totalHeight:
            difference = totalHeight + parseInt(firstChild.css('margin-top'), 10);

            // The duration of the animation needed to get the correct speed:
            duration = (difference/pixelsPerSecond) * 1000;

            // Animate the first child's margin-top to -1 * totalHeight:
            firstChild.animate(
                { 'margin-top': -1 * totalHeight },
                duration,
                'linear',
                function() {
                    // Move the first child back down (below the container):
                    firstChild.css('margin-top', marquee.innerHeight());
                    // Restart whole process... :)
                    marquee.marquee('play');
                }
            );
        },
        pause: function() {
            this.children(':first').stop();
        }
    };

    $.fn.marquee = function(method) {

        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.marquee');
        }

    };

})(jQuery);

Usage:

var marquee = $('#mydiv');

marquee.marquee();

marquee.hover(function() {
    marquee.marquee('pause');
}, function() {
    marquee.marquee('play');
});

This example can also be found on jsfiddle: http://jsfiddle.net/PPvG/LgsrU/


Rock Paper Scissors game- JavaScript This is a console version of the famous Rock Paper Scissors game part of The Odin Project curriculum. Please review this code and provide suggestions. Please comment whether the code is DRY and if it is simplified.

function computerPlay() {
    let choices = ['rock', 'paper', 'scissors'];
    return choices[Math.floor(Math.random() * choices.length)];
}

function playRound(playerSelection, computerSelection) {
    const capitalize = word => { return word.charAt(0).toUpperCase() + word.slice(1); }
    const winStatement = (winner, loser) => { return `You Win! ${capitalize(winner)} beats ${capitalize(loser)}`; }
    const loseStatement = (winner, loser) => { return `You Lose! ${capitalize(winner)} beats ${capitalize(loser)}`; }
    const winningChoice = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};

    playerSelection = playerSelection.toLowerCase();

    if(playerSelection === computerSelection) return "Oh! It's a tie";
    else if(playerSelection === winningChoice[computerSelection]) return winStatement(playerSelection, computerSelection);
    else return loseStatement(computerSelection, playerSelection);
}

const playerSelection = 'rock';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));

All in all, a basic review of your question shows that you are creating objects numerous times, when they do not need to be. Other things are pointed out in comments.

const choices = ['rock', 'paper', 'scissors'],
      capitalize = word => word.charAt(0).toUpperCase() + word.slice(1),
      // Should these be made into 1 function, that takes another argument, 'condition', which is 'Win' or 'Lose'?
      winStatement = (winner, loser) => `You Win! ${capitalize(winner)} beats ${capitalize(loser)}`,
      loseStatement = (winner, loser) => `You Lose! ${capitalize(winner)} beats ${capitalize(loser)},
      winningChoice = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};

function computerPlay() {
    return choices[Math.floor(Math.random() * choices.length)];
}

function playRound(playerSelection, computerSelection) {
    playerSelection = playerSelection.toLowerCase();

    // Also, Consecutive if statements that all return need not be else-if.
    if(playerSelection === computerSelection) {
        return "Oh! It's a tie";
    }
    if(playerSelection === winningChoice[computerSelection]) {
        return winStatement(playerSelection, computerSelection);
    }
    return loseStatement(computerSelection, playerSelection);
}

// Should be improved upon? Actually take input?
const playerSelection = 'rock';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));


Words dictionary out of a text file Please tell me what the weak spots of this code are (specially in terms of efficiency) and how I can improve it:

def get_word_frequencies(filename):
  handle = open(filename,'rU')
  text = handle.read()
  handle.close()
  MUST_STRIP_PUNCTUATION = ['\n','&','-','"','\'',':',',','.','?','!'\
    ,';',')','(','[',']','{','}','*','#','@','~','`','\\','|','/','_'\
    ,'+','=','<','>','1','2','3','4','5','6','7','8','9','0']
  text = text.lower()
  for char in MUST_STRIP_PUNCTUATION:
    if char in text:
      text = text.replace(char,' ')
  words_list = text.split(' ')
  words_dict = {}
  for word in words_list:
    words_dict[word] = 0
  for word in words_list:
    words_dict[word] += 1
  del words_dict['']
  return words_dict

Some steps sound repetitive to me and it seems that I'm looping on the text many times but I think I'm obliged to take each of those steps separately(unless I'm wrong), for instance, replacing invalid characters should be on multiple separate iterations, or lower casing the whole text must be a separate step, and so on.

Also for creating the dictionary I'm suspicious a way better than words_dict[word] = 0 must exist?

Some in-place improvements you could make:

PEP-8 recommends four space indentation, not two;
collections.defaultdict would allow you to scan the list of words only once, without having to explicitly initialise to 0 for each word. Even easier, there's a collections.Counter, too;
Rather than iterate over all of the characters you want to replace, you could use re.sub with a regular expression pattern matching those characters (or re.findall for the characters you do want); and
You should generally use the with "context manager" to handle files; see e.g. the tutorial.

More broadly, though, you have one function with three different purposes:

Handling the file;
Cleaning up the text; and
Counting the words.

Splitting these separate concerns up into separate functions would make those functions easier to test, understand and reuse.

With these ideas applied, you could write something like:

from collections import Counter
import re

def get_text(filename):
    """Read and return the content of a specified file."""
    with open(filename, "rU") as handle:
         return handle.read()

def clean_text(text):
    """Lowercase text and extract words."""
    return re.findall("[a-z]+", text.lower())

def get_word_frequencies(filename):
    text = get_text(filename)
    words = clean_text(text)
    return Counter(words)


Pomodoro countdown timer synced to the clock This countdown timer is supposed to:

be synced to the user's clock
at every hour and half hour, will start a 25 minute countdown followed by a 5 minute break

The code works but I question its efficiency.

function startTime() {
    var today = new Date();
    var minutes = today.getMinutes();
    var seconds = today.getSeconds();

    //makes the clock count DOWN instead of up
    if (minutes<25 && seconds<60) {
        document.getElementById("message").innerHTML = "WORK TIME";
        minutes=24-minutes;
        seconds=60-seconds;
    } else if (minutes<30 && seconds<60){
        document.getElementById("message").innerHTML = "BREAK TIME";
        minutes=29-minutes;
        seconds=60-seconds;
    } else if (minutes<55 && seconds<60){
        document.getElementById("message").innerHTML = "WORK TIME";
        minutes=54-minutes;
        seconds=60-seconds;
    } else {
        document.getElementById("message").innerHTML = "BREAK TIME";
        minutes=59-minutes;
        seconds=60-seconds;
    }

    //to make clock show correct format, e.g., 2:59 instead of 03:60
    if (seconds == 60){
      seconds=0;
      minutes=minutes+1;
    }

    document.getElementById('txt').innerHTML=
        minutes+" min and "+seconds+" sec remaining";

}

setInterval(startTime, 1000);
<!DOCTYPE html>

Bug

There is an off chance that the interval event that you start at the bottom of the script with setInterval(startTime, 1000); will fire before the page has fully loaded, causing the first run to throw an error at document.getElementById("message").innerHTML =
However it is a minor bug and will fix itself in the next interval.

Some coding points

Avoid putting code in the HTML. eg you have   which can be done in the script with addEventListener("load",startTime) But its not really needed as you have the interval call the function anyway.
You can access elements directly via their id as long as you ensure that the id is unique on the page. If you use the same name for any other id or name element property then it will not work. Refer to answers to this SO post for more context.
When adding text only (no HTML) to an element it is more efficient to add it via the textContent property. For simple stuff it's not a major issue, it is when you start to add lots of content that it will be noticeable.

Regarding time
The value of a Date object is an integer that counts the milliseconds since 1 January 1970 UTC.
Since you are not interested in the specific time, but rather half hour periods it can be simpler to work in milliseconds rather than the more complex minutes, seconds format.
To get the millisecond value you can use Date.now() and to change that value to half hour chunks you get the remainder of dividing by 30 * 60 * 1000ms using the remainder operator %
The  remainder operator % is great when you need to get cyclic values.
Example snippet
The example below show how it can be done using milliseconds alone.

addEventListener("load", displayPeriod);  // start on page load

const second = 1000;          // length of second in ms
const minute = 60 * second;   // length of minute in ms
const halfHour = 30 * minute; // length of half hour in ms

function displayPeriod() {
     const halfHourTime = Date.now() % halfHour;
     var nextPeriod = 25 * minute;

     if (halfHourTime <= nextPeriod) {
         message.textContent = "WORK TIME";
     } else {
         message.textContent = "BREAK TIME";
         nextPeriod = halfHour;
     }
     const min = Math.floor((nextPeriod - halfHourTime) / minute);
     const sec = Math.floor((nextPeriod - halfHourTime) / second) % 60;

     countDown.textContent = min + ":" + ("" + sec).padStart(2,"0");

     var time2Second = second - halfHourTime % second;
     if (time2Second < 50) { // if too close delay a littl
         time2Second += 50;
     }
     setTimeout(displayPeriod, time2Second);
}
div{
   font-family : arial;
   font-size : 32px;
   width : 100%;
   text-align : center;
}

Or using interval and shortening the naming as I find long names hard on the eyes. Also I use a shortcut for Math.floor the bitwise | 0  which is handy for rounding down positive numbers. I also used the ms times expressed with the exponent as I happen to know them (3e5 is 5 minutes in milliseconds)
I would consider the second snippet of lower quality, but for simple projects less code can be better.

addEventListener("load", () => setInterval(displayPeriod,1000));  // start on page load

function displayPeriod() {
     const time= Date.now() % 18e5;
     var nextP = 15e5;
     var mes = "WORK TIME :(";

     if (time > nextP) {
         mes = "BREAK TIME :)";
         nextP = 18e5;
     }

     const m = (nextP - time) / 6e4 | 0;
     const s = ("" + ((nextP - time) / 1e3 | 0) % 60).padStart(2,"0");

     message.textContent = mes;
     countDown.textContent = m + ":" + s;
}
div{
   font-family : arial;
   font-size : 32px;
   width : 100%;
   text-align : center;
}

setInterval V setTimeout
Personally I prefer using setTimeout rather than the setInterval as it give finer control over when the next event will fire. In the example I use the ms time to workout how long it is till the next second starts, if too close to ensure the timer will fire (browsers may throttle timers) I offset it a little.
This method sets the event for the closest coming second, and will skip any missed seconds.
But setInterval is just as good but if the system is busy the countdown can skip displaying seconds more often than using setTimeout


Parsing strings with escaped characters using Parsec I have been working through the exercises in a Write Yourself a Scheme in 48 Hours/Parsing and hacked together something to get parseString to comprehend escaped characters. Also had some inspiration from Real World Haskell chapter 16 minus the applicative parts.

parseString :: Parser LispVal
parseString = do char '"'
                 x <- many $ chars
                 char '"'
                 return $ String x
    where chars = escaped <|> noneOf "\""
          escaped = choice $ map tryEscaped escapedChars
          tryEscaped c = try $ char '\\' >> char (fst c) >> return (snd c)
          escapedChars = zip "bnfrt\\\"/" "\b\n\f\r\t\\\"/"

This works but I am not fond of my 'tryEscaped' definition. What are the alternatives?

Some suggestions:

Replace fst and snd with a pattern match or explicit function arguments.
Extract the common char '\\' parser. You can then avoid the try.
Strings with lots of escaped characters are hard to read and it's hard to visually
verify that the escape codes are correctly matched with their replacements. Consider
spelling them out and aligning them to make this easy to see.

Here's what I came up with:

escaped = char '\\' >> choice (zipWith escapedChar codes replacements)
escapedChar code replacement = char code >> return replacement
codes        = ['b',  'n',  'f',  'r',  't',  '\\', '\"', '/']
replacements = ['\b', '\n', '\f', '\r', '\t', '\\', '\"', '/']


Project Euler #15: counting paths through a 20 × 20 grid I've recently solved Project Euler's 15th problem stating:

  Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

  How many such routes are there through a 20×20 grid?

This is my dynamic approach in C++

#include <cstdio>

const unsigned short n = 20;

int main() {
    unsigned long long p[n][n];
    for (unsigned short i = 2; i <= n; i++)
        p[n - i][n - 1] = i + 1;
    for (unsigned short i = n - 2; i >= 1; i--) {
        p[i][i] = 2 * p[i][i + 1];
        for (unsigned short k = i; k >= 1; k--)
            p[k - 1][i] = p[k][i] + p[k - 1][i + 1];
    }
    printf("%llu", 2 * p[0][1]);
}

I am aware that this problem could be solved way more efficiently and faster by simply calculating \${(2n)!}/{(n!)^2}\$, however I decided to look at this problem from a programmer's point of view, rather than a mathematician's.

#include <cstdio>

If your goal is to write C++, you're really off to a bad start using the C standard I/O library.

const unsigned short n = 20;

The modern way to do compile time constants is with constexpr.

But I don't understand why you chose to use unsigned short for all your indexing calculations. Any operations you try to do on it will automatically promote it to unsigned int. You're not really gaining anything.

for (unsigned short i = 2; i <= n; i++)

Once again, once you've bought into unsigned short, you keep using it everywhere. But aside from the assignment, every single operation in this statement is promoting all your unsigned shorts to unsigned ints. Even the comparison. You might as well have just used unsigned from the start to save yourself a lot of typing:

constexpr auto n = 20u; // unsigned int

for (auto i = 2u; i <= n; ++i)

And so on.

If you want to be technically correct, indexes should be std::size_t. But unsigned works well enough if you know you're not going any higher than 20. unsigned short is useless except for storage, because any operations you do on it get promoted.

printf("%llu", 2 * p[0][1]);

First, you're missing the std:: here.

But more importantly, you should be using C++ I/O:

std::cout << (2 * p[0][1]);

Other than that, the most important element you're missing here would be comments, I'd say.


Separating items into ordered and unordered lists I'm trying to group all the types which have ordered-list-item & unordered-list-item into new object.

How can I simplify the function and reduce multiple return statements?

const data = {
  data: [{
    areas: [{
        sections: [{
          rjf: [{
              "type": "heading-1",
              "text": "A title",
            },
            {
              "type": "ordered-list-item",
              "text": "Ordered Item A",
            },
            {
              "type": "unordered-list-item",
              "text": "Ordered Item B",
            },
            {
              "type": "heading-1",
              "text": "A title",
            }
          ]
        }]
      },
      {
        sections: [{
          rjf: [{
              "type": "heading-1",
              "text": "Block 2 A title",
            },
            {
              "type": "ordered-list-item",
              "text": "Block 2 Ordered Item A",
            },
            {
              "type": "unordered-list-item",
              "text": "Block 2 Ordered Item B",
            },
            {
              "type": "heading-1",
              "text": "Block 2 A title",
            }
          ]
        }]
      }
    ]
  }]
};

function parseAreas() {
  data[0].areas.forEach(area => {
    this.moveToNewObject(area);
  })
}

function moveToNewObject(data) {
  const areas = data[0].areas;
  //console.log(data[0].areas)
  const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
  return areas.map((area) => {
    var sec = area.sections;
    return sec.map((section) => {
      let lastHeadingIndex = -1;
      return section.rjf.reduce((acc, current, index) => {
        if (!current.type || !listItemTypes.includes(current.type)) {
          lastHeadingIndex = acc.length;
          return [...acc, current]
        } else {
          let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');
          if (!listObject) {
            listObject = {
              type: 'list',
              items: [current]
            }
            return [...acc, listObject];
          }
          listObject.items = [...listObject.items, current];
          return acc;
        }
      }, [])
    });
  });
}
console.log('sections', moveToNewObject(data.data));

How can I simplify the function and reduce multiple return statements?

You could reduce the number of return statements by building up the new object in a more imperative way, without using the map and reduce functions,
but I'm not sure that would be better.
I think it's fine using functions as it is.

This part doesn't look great:

  let listObject = acc.find((el, i) => i > lastHeadingIndex && i < index && el.type === 'list');

The problem with it is that you are using lastHeadingIndex to find the last heading added in acc,
but acc.find will search from the beginning.
With a large data, that would be a waste,
instead of searching from the end.

In fact, I'm wondering if lastHeadingIndex is important at all.
Isn't your real intention more like "consecutive items of list type should be combined into a list object"?
If that's the case, then you don't need to search from the end,
it's enough to look at the last item of acc:
if it's a list type, then append to it, if not, then create a new list type.

If this is indeed your real intention,
then you could get rid of lastHeadingIndex, and write a bit simpler:

function moveToNewObject(data) {
  const listItemTypes = ['unordered-list-item', 'ordered-list-item'];
  return data[0].areas.map(area => {
    var sec = area.sections;
    return sec.map(section => {
      return section.rjf.reduce((acc, current, index) => {
        if (!listItemTypes.includes(current.type)) {
          acc.push(current);
          return acc;
        }

        if (!acc.length || acc[acc.length - 1].type !== 'list') {
          acc.push({type: 'list', items: [current]});
          return acc;
        }

        acc[acc.length - 1].items.push(current);
        return acc;
      }, [])
    });
  });
}

I would also change the name of the function,
because moveToNewObject sounds overly generic,
it doesn't seem to describe its real purpose.
How about combineListItemTypes,
or transformCombiningListItemTypes?