texts: Remove sections of content from Quora.com

texts:
I wrote a Chrome browser extension to hide Top Content posts from Quora, which bother users following too few topics.

A user's feed in Quora.com starts as a list of posts relevant to the user, including a set of "Top Content" posts. As the user scrolls down the page, it loads more posts for them to view.

My extension triggers its initial removal when the DOM loads, and removes all Top Content posts currently visible to the user. This in itself triggers Quora to load in more posts.

My extension responds to the new load by running again and removing the Top Content posts again.

This seems to work well, but I'm concerned about Performance. In some cases, Quora goes through and loads the entire user's feed over a much shorter time, even without action from the user.

Github is available here.

main.js

var QuoraExtension =
{
/* Initialize Quora Extension */
main: function()
{
    QuoraExtension.hideContent();
},

/* Hide Selected Content From Quora */
hideContent: function()
{
    $(document).ready(
        function()
        {
            //Run the clean out as soon as possible
            QuoraExtension.hideTopContent();

            /*
                Now, we add a listener for when the DOM tree is updated,
                when it is, we check for more content to hide.

                Timeouts are used to prevent infinite loops of removals
                Removal of content can sometimes trigger another check,
                so timeouts prevent us from using too much processing
             */
            var hideTopContentTimeout = null;

            document.addEventListener("DOMSubtreeModified", function() {
                if(hideTopContentTimeout) {
                    clearTimeout(hideTopContentTimeout);
                }
                hideTopContentTimeout = setTimeout(QuoraExtension.hideTopContent, 500);
            }, false);
        }
    );
},

/* Hide Top Content sections */
hideTopContent: function()
{
    var $topContent = jQuery("span:contains('Top content on Quora')").closest('.pagedlist_item');
    $topContent.hide();
}
};

// Initialize QuoraExtension if JQuery is available
if(!!jQuery)
{
    QuoraExtension.main();
}

manifest.json

{
"manifest_version": 2,

"name": "Quora Extension by 2NickPick",
"description": "Utilities for using Quora.com",
"version": "0.1",

"permissions": [
    "activeTab"
],
"content_scripts": [
    {
        "matches": ["https://*.quora.com/*"],
        "js": ["lib/jquery/1.7.2/jquery.min.js", "main.js"],
        "runat": "document_start"
    }
]
}


texts: Counting contiguous subarrays with a negative sum

texts:
I'm doing a coding challenge that asks to count the number of contiguous subarrays that have a negative sum:

A subarray of an n-element array is an array composed from a contiguous block of the original array'selements. For example, if array = [1,2,3], then the subarrays are [1], [2], [3], [1,2], [2,3], and [1,2,3]. Something like [1,3] would not be a subarray as it's not a contiguous subsection of the original array.
The sum of an array is the total sum of its elements.
An array's sum is negative if the total sum of its elements is negative.
An array's sum is positive if the total sum of its elements is positive.
Given an array of integers, find and print its number of negative subarrays on a new line.

I wrote this method and I'm trying to figure out the runtime for it but I'm not sure how to handle the loop and the recursion. Assume the length of array a is > 0.
int numNegatives(int[] a){

    if(a.length == 1){
        if(a[0] < 0){ return 1; } else { return 0; }
    }

    int count = 0;
    int sum = 0;

    for(int i = 0; i < a.length; i++){ //N
        sum += a[i];
        if(sum < 0){ count++; }
    }
    count += numNegatives(Arrays.copyOfRange(a, 1, a.length));//N-1

    return count;
}

The for loop will be O(N), since it loops over the array, and I believe the recursion call will then be O(N-1). Since the recursion call is outside the for loop, does that make the total O(N)? Most solutions to this challenge are two nested for loops with O(N²) runtime, and so I'm not sure if I actually made any improvement. Is it worse than O(N²)?


texts: Enhancing parser for 8 byte command string (expect problems with type conversions) for Arduino/Radio communication

texts:
Because the throughput of my radio and device is limited, I wanted to compress my control string. I decided to compress the command into an 8 bytes (quasi) string (throttle high, throttle low, pitch, roll, yaw plus/minus, yaw value, checksum, stop byte) and after parsing in four variables:

Pitch (between -45° and 45°)
Roll (between -45° and 45°)
Yaw (between -180° and 180°)
Throttle (between 1000 and ~1900)

Because Some number ranges don't fit into a single byte (0 to 255 number range), I used two instead (throttle: one byte for hundreds (1-9) and one byte for tenners (1-99); Yaw: One byte for plus or minus and one byte for 0° - 180°). I send and read these bytes as characters. Then I convert them into numbers (0-255).

I noticed that sometimes a few reads are totally out of range (e.g. value: -31001) but checksum test is OK. I don't know exactly why (maybe radio, maybe I caused unexpected behavior because of type conversions here). This is why I made an additional range test. Now the remote control seems to be reliable.

However I don't feel very nice about it, because I do signed/unsigned and! number range conversions, the checksum function is also not very reliable. Maybe someone has suggestions how to make the code better.

Code (The command stored in buffer is already red correctly until the stop byte and valid in length):

bool Receiver::parse_radio(char *buffer) {
  int16_t throttle_high  = (uint8_t)buffer[0];       // 1. 1 - 9
  int16_t throttle_low   = (uint8_t)buffer[1];       // 2. 0 - 99
  int16_t pit            = (uint8_t)buffer[2] - 127; // 3. -45° - 45°
  int16_t rol            = (uint8_t)buffer[3] - 127; // 4. -45° - 45°
  int16_t yaw_pm         = (uint8_t)buffer[4] - 127; // 5. -1 || +1
  int16_t yaw_val        = (uint8_t)buffer[5];       // 6. yaw angle in degrees 180°

  int16_t chk            = (uint8_t)buffer[6];       // 7. checksum

  int16_t thr            = 1000 + (throttle_high * 100) + throttle_low;
  int16_t yaw            = yaw_val * yaw_pm;

  // Calculate checksum
  uint8_t checksum = 0;
  for(int i = 0; i < 6; i++) {
    checksum = (checksum + buffer[i]) << 1; // % 256 can be saved because of the uint8_t
  }

  // Validity check:
  // First checksum
  if(checksum != chk)
    return false;
  // Later other values
  if(yaw_pm < -1 || yaw_pm > 1)
    return false;
  if(rol > 45 || rol < -45)
    return false;
  if(pit > 45 || pit < -45)
    return false;
  if(yaw > 180 || yaw < -180)
    return false;
  if(thr > RC_THR_80P || thr < RC_THR_MIN)
    return false;

  // Do rest here
  return true;
}


texts:
This was brought about by this codegolf question.

Problem

A program is said to be pristine if it is:

A working program (No errors).
The program will produce errors by removing any contiguous substring of N characters, where 1 <= N < program length.

My goal is to check if a given C# program's source is pristine or not with the assumption that the given program is already working.

What I Did

I generated all possible removal combinations and compiled the resulting string with CompileAssemblyFromSource. Compile errors are then checked with CompilerResults.Errors.

static bool isPristine(string sourceCode)
{
    using (var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }))
    {
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" });
        parameters.GenerateExecutable = true;

        int length = sourceCode.Length;

        for (int i = 0; i < length; i++)
        {
            for (int j = 1; j < length - i; j++)
            {
                string sourceWithRemoval = sourceCode.Remove(i, j);
                CompilerResults results = csc.CompileAssemblyFromSource(parameters, sourceWithRemoval);

                if (results.Errors.Count == 0)
                {
                    Debug.WriteLine("Still works by removing:");
                    Debug.WriteLine("@{0}@ ", sourceCode.Substring(i, j));
                    Debug.WriteLine("At index {0}.", i);

                    return false;
                }
            }
        }
    }

    return true;
}

Usage

static void Main(string[] args)
{
    string sourceCode = "class e{static void Main(){System.Console.Write(new char[1\n#if l\n#else\n*5]{'w','o','r','l','d'\n#if o\n#else\n});\n#endif\n}\n#endif\n}";

    Console.WriteLine(isPristine(sourceCode) ? "Pristine" : "Not pristine");
    Console.ReadLine();
}

Main Concerns

What can I improve (performance, readability)?
Are there better, faster C# techs that I should have used?


texts: When an object has different representations... what's the OO pattern?

texts:
I've an AbstractMessage object (a hierarchy, actually). It represents a small text message and can be sent using different transport methods: HTTP, REST and a "mailer" transport. Each transport relies on an external library for executing the transport itself, injected using a DI container.

Message itself may have different representations (query string, resource string or an instance of\Swift_Message), based on the transport used. A transport should use the more appropriate representation, again injected using constructor injection.

interface TransportInterface
{
    public function executeTransport(AbstractMessage $message, array &$fails = array());
}

class HttpTransport implements TransportInterface
{
    /**
     * @var \Guzzle\Service\Client
     */
    private $client;

    /**
     * @var Converter\MessageConverterInterface
     */
    private $converter;

    public function __construct(Client $client, MessageConverterInterface $converter)
    {
        $this->client    = $client;
        $this->converter = $converter;
    }

    public function executeTransport(AbstractMessage $message, array &$fails = array())
    {
        $representation = $this->converter->convert($message);

        /* ... */
    }
}

class RestTransport implements TransportInterface
{
    /**
     * @var \Guzzle\Service\Client
     */
    private $client;

    /**
     * @var Converter\MessageConverterInterface
     */
    private $converter;

    public function __construct(Client $client, MessageConverterInterface $converter)
    {
        $this->client    = $client;
        $this->converter = $converter;
    }

    public function executeTransport(AbstractMessage $message, array &$fails = array())
    {
        $representation = $this->converter->convert($message);

        /* ... */
    }
}

class MailerTransport implements TransportInterface
{
    /**
     * @var \Swift_Mailer
     */
    private $mailer;

    /**
     * @var Converter\MessageConverterInterface
     */
    private $converter;

    public function __construct(Swift_Mailer $mailer,
        MessageConverterInterface $converter)
    {
        $this->mailer    = $mailer;
        $this->converter = $converter;
    }

    public function executeTransport(AbstractMessage $message, array &$fails = array())
    {
        $representation = $this->converter->convert($message);

        /* ... */
    }
}

The MessageConverterInterface and the actual helper may be fairly simple:

interface MessageConverterInterface
{
    /**
     * @param AbstractMessage $message
     * @return mixed
     */
    public function convert(AbstractMessage $message);
}

class MessageHelper
{
    /**
     * @var Transport\TransportInterface
     */
    private $mailer;

    public function send(AbstractMessage $message, array &$fails = array())
    {
        $this->transport->executeTransport($message, $fails);
    }

}

Question: is this a good OO pattern for the library design? Does the pattern have a name?


texts: Displaying information about people from a JSON file

texts:
I'm working with Python 2.7.5 and I have written the following code:

def func(x):
  if x == 1:
    list = data.parseJSON(fileName)
    person = [l for l in list if l['worker'] == sys.argv[1]]
    displayPeople(flatten(person))
  elif x == 2:
    list = data.parseJSON(fileName)
    person = [l for l in list if sys.argv[1] in set(l['children'])]
    displayPeople(person)
  elif x == 3:
    list = data.parseJSON(fileName)
    person = [l for l in list if l['age'] == sys.argv[1]]
    displayPeople(flatten(person))

def flatten(lData):
  if len(lData) == 0
    return lData
  return reduce(lambda x,y:x+y,lData)

I realize that I am repeating myself a lot in the if else section. I would make a function that would do this but, as you can see, the way to get the person list is a little different each time. Also, you'll notice that the person list sometimes needs to be flattened before being passed in the displayPeople() method.

I was thinking that I could use a lambda to get the person, but I don't think that will work. I may need to add more cases, so I think it would be best to have a function where I could just change how the person is calculated and flatten it if necessary, and then pass it to displayPeople().

Any suggestions on how to make this code more modular?


texts:
I made a header generator that creates a linear gradient of two random colors from its top left to its bottom right.

Please tell me about everything I could do better, but especially how to calculate and not hardcode the randomly shifted second array secondColor, that has the minColorValue, maxColorValue and the random value on other positions.

const settings = {
  width: 500,
  height: 180,
  minColorValue: 70, // min rgb value
  maxColorValue: 185, // max rgb value
};
let container = document.getElementsByClassName("container")[0];
let firstColor = [0, 0, 0];
let secondColor = [0, 0, 0];

let create = function(width, height) {
  let canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  container.appendChild(canvas);
};

let colorPicker = function() {
  // possible configurations of which of the rgb values is min, which is max, and which is inbetween
  let configurations = [
    [0, 1, 2],
    [0, 2, 1],
    [1, 0, 2],
    [1, 2, 0],
    [2, 0, 1],
    [2, 1, 0],
  ];
  let randomConfig = configurations[random(0, 5)];
  firstColor[randomConfig[0]] = settings.minColorValue;
  firstColor[randomConfig[1]] = settings.maxColorValue;
  firstColor[randomConfig[2]] = random(settings.minColorValue, settings.maxColorValue);

  // shift configuration by one or two to never get a different second color
  let shiftAmount = random(1, 2);
  let secondConfig = [0, 0, 0];
  for (let i = 0; i < 3; i++) {

    if (i + shiftAmount < 3) {
      secondConfig[i] = randomConfig[i + shiftAmount];
    } else {
      secondConfig[i] = randomConfig[i - 3 + shiftAmount];
    }
  }
  secondColor[secondConfig[0]] = settings.minColorValue;
  secondColor[secondConfig[1]] = settings.maxColorValue;
  secondColor[secondConfig[2]] = random(settings.minColorValue, settings.maxColorValue);

};

let fill = function() {
  let canvas = document.getElementsByTagName("canvas")[0];
  let context = canvas.getContext("2d");
  let gradient = context.createLinearGradient(0, 0, settings.width, settings.height);
  gradient.addColorStop(0, `rgb(${firstColor[0]},${firstColor[1]},${firstColor[2]})`);
  gradient.addColorStop(1, `rgb(${secondColor[0]},${secondColor[1]},${secondColor[2]})`);
  context.fillStyle = gradient;
  context.fillRect(0, 0, settings.width, settings.height);
};
let start = function() {
  create(settings.width, settings.height);
  colorPicker();
  fill();
};

// help function
function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
html {
  background-color: #1d1f21;
}

canvas {
  display: inline-block;
}

.container {
  text-align: center;
}

.textbox {
  text-align: center;
  color: white;
  font-family: monospace;
}

  <title>random gradient header</title>
  <meta charset="UTF-8">
  <link href="style.css" rel="stylesheet">

Reload to get a different header gradient.


texts: Transforming data from an array of objects to a nested array of objects

texts:
I have an array of objects where each object has a datetime key/value pair:

var original = [
  {
    datetime: '2015-07-22 09:00:00'
  },
  {
    datetime: '2015-07-22 11:00:00'
  },
  {
    datetime: '2015-07-23 10:00:00'
  }
]

I need to transform them into a new array with objects where the first key/value pair of each object is the date associated with an array of datetimes from the original array of objects. The second key/value pair is an array of the original objects which have a datetime date that matches the new date.

var new = [
  {
    date: '2015-07-22',
    events: [
      {
        datetime: '2015-07-22 09:00:00'
      },
      {
        datetime: '2015-07-22 11:00:00'
      }
    ]
  },
  {
    date: '2015-07-23',
    events: [
      {
        datetime: '2015-07-23 10:00:00'
      }
    ]
  }
];

Below is my current method of making this transformation happen and it is this method that I am seeking to improve upon. It is clunky. It is convoluted. It is hacky.

I am currently selecting the substring from the first object's datetime as currentDate which only contains the date. Then I'm creating an empty array, new. as well as an object as datum which contains a date key with currentDate as it's value  and an events key with an empty array as its value.

var currentDate = original[0].datetime.substring(0,10); // => '2015-07-22';
var new = [];
var datum = {
  date: currentDate,
  events: []
};

Then I'm using a forEach function on the original array in the following manner:

original.forEach(function(item){

  //if item's date matches currentDate add it to datum object
  if (item.datetime.substr(0,10) === currentDate){
    datum.events.push(item);
  }

  //if item's date does not match then it is the next date
  else {

    //add the previous day's datum object to the new array
    new.push(datum);

    //set new currentDate and set new datum object
    currentDate = item.datetime.substr(0,10);
    datum = {
      date: currentDate,
      events: []
    };

    //push the current item into the new datum array
    datum.events.push(item);
  }
});

//push final day's datum to new array
new.push(datum);

What is a more efficient way to transform this data?


texts:
Okay I have the following use case:

Module A broadcasts an event.
Module B listens to that event.
Maybe also Module C listens to that event.

Now Module B has to perform an asynchronous operation before Module A may proceed with its code.

I solved this by creating an custom module $deferredEvents which allows to queue up asynchronous tasks before proceeding.

Example: http://jsfiddle.net/68845rw4/

Module:

angular.module('deferredEvents', []).provider('$deferredEvent', function () {
  this.$get = function ($q) {
    /**
     *  @param type String - 'broadcast' | 'emit'
     *  @param $scope Scope
     *  @param eventName String - name of the event
     */
    return function $deferredEvent(type, $scope, eventName) {
      var queueHelper = {
        queue: [],
        promise: $q.when(),
        /**
         * Promise will be executed after all previous promisses passed
         */
        appendThen: function appendThen () {
          return this.queuePromise(this.promise.then.apply(this.promise, arguments));
        },
        /**
         * Promise will be executed immediately
         */
        queuePromise: function queuePromise (promise) {
          if (promise === this.promise) {
            throw new Error('Can\'t wait for own promise');
          }
          // Execute promise
          promise = $q.when(promise);
          // Add the promise result to the queue
          this.promise = this.promise.then(function () {
            return promise;
          });
          return this.promise;
        }
      };
      var args = Array.prototype.slice.call(arguments, 3);
      var emitArgs = [eventName, queueHelper].concat(args);
      var event = $scope['$' + type].apply($scope, emitArgs);
      return queueHelper.promise.then(function() {
          return $q.all(queueHelper.queue);
        }).then(function (results) {
          var failed = results.some(function (val) {
            return val === false;
          });
          return failed ? $q.reject(event) : event;
        }, function () {
          return $q.reject(event);
        });
    };
  };
}).provider('$deferredEmit', function () {
  this.$get = function ($deferredEvent) {
    return function $deferredEmit($scope, eventName) {
      return $deferredEvent.apply(this, ['emit', $scope, eventName].concat(Array.prototype.slice.call(arguments, 2)));
    };
  };
}).provider('$deferredBroadcast', function () {
  this.$get = function ($deferredEvent) {
    return function $deferredBroadcast($scope, eventName) {
      return $deferredEvent.apply(this, ['broadcast', $scope, eventName].concat(Array.prototype.slice.call(arguments, 2)));
    };
  };
});


texts:
I want to make a general alert dialog to use across the whole app. I created a class called AlertDialogManager and just one method to show AlertDialog.

Is there a way to refine my code or this code?

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AlertDialogManager {
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *               - pass null if you don't want icon
     * */
    public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        if(status != null)
            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}


texts: Node.js parallel file download, the ES6 way

texts:
I wrote a script that downloads all PDFs found on the web page of a particular government agency. I would have chosen bash for such a task, but I want the script to run in Node.js. The downloaded files are a few hundred kilobytes big, if that matters.

It is the first time I use ES6, but I want to learn how to take advantage of all ES6 features, and I want to make my script very much in the spirit of ES6. In bash I would have downloaded the list of PDF files first, then proceeded to download them with indentation back to zero, but I got the impression that putting everything within the first request.get block is more in the ES6 spirit, correct me if I am wrong.

The script works, and validates with ESLint after disabling the following rules:

no-console because it is intended to be run on the console
no-undef because it tells me require is not defined
one-var because it would force me to mix require and other declaration thus triggering no-mixed-requires
sort-vars because I want to order constants in a more sensible way
strict because it would not accept "use strict"; as the first line

My code:

"use strict";

// Imports
const async = require("async"),
    fs = require("fs"),
    http = require("http"),
    request = require("request");

// Settings
const INDEX_URL = "http://www.kokuminhogo.go.jp/hinan/index.html",
    MAX_PARALLEL_DOWNLOADS = 3,
    PREFECTURES_REGEX = /area.*hinan_(.*)\.pdf/g,
    REMOTE_PREFIX = "http://www.kokuminhogo.go.jp/pdf/hinan_",
    LOCAL_PREFIX = "data/file",
    FORMAT_EXTENSION = ".pdf",
    REGEX_MATCH_INDEX = 1,
    HTTP_STATUS_OK = 200;

// ///////////////////////////////////////////////////////////
// Utility to download a file, with callback
// ///////////////////////////////////////////////////////////
const download = (url, dest, next) => {

    console.log(`Downloading ${url} to ${dest}`);
    const file = fs.createWriteStream(dest);

    http.get(url, (response) => {

        response.pipe(file);
        file.on("finish", () => {

            file.close();
            next();

        });

    });

};

// ///////////////////////////////////////////////////////////
// Get list of available prefectures
// ///////////////////////////////////////////////////////////
request.get(INDEX_URL, (error, response, body) => {

    const prefectures = [];

    if (!error && response.statusCode === HTTP_STATUS_OK) {

        let match = PREFECTURES_REGEX.exec(body);

        while (match !== null) {

            prefectures.push(match[REGEX_MATCH_INDEX]);
            match = PREFECTURES_REGEX.exec(body);

        }

    }

    console.log(`Number of prefectures available: ${prefectures.length}`);

// ///////////////////////////////////////////////////////////
// Download the PDF files for all prefectures
// ///////////////////////////////////////////////////////////
    // Files will be numbered 1, 2, etc
    let fileNumber = 1;

    // Process in parallel
    async.eachLimit(
        prefectures,
        MAX_PARALLEL_DOWNLOADS,
        (prefecture, next) => {

            download(
                REMOTE_PREFIX + prefecture + FORMAT_EXTENSION,
                LOCAL_PREFIX + fileNumber + FORMAT_EXTENSION,
                next
            );
            fileNumber += 1;

        }

        ,
        () => {

            console.log("Finished downloading");

        }
    );

});


texts: Plotting the integer values in text format in matplotlib piechart

texts:
I have done a clustering algorithm and represented the results in a pie chart as shown below.

fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents  = []

for k,v  in clusters.items():
    indi= str(len(clusters[k])) + " users " +  "Cluster_"+ str(k)
    contents.append(indi)

#contents = ['23 users Cluster_0', '21 users Cluster_1']

data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]

def func(pct, allvals):
    absolute = int(pct/100.*np.sum(allvals))
    return "{:.0f}%\n({:d} users)".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, Cluster,
          title="CLuster",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight="bold")

ax.set_title("Distribution of users: A pie chart")

Even though the users are 23 and 21 in each cluster, the piechart shows 22 and 20.
This is due to the conversion to int and some float values are cut off in the function def func().

But, to fix this I wrote the below code and it works:

def func(percentage, allvals):
    absolute = int(np.sum(allvals))
    newV = (percentage/100)*absolute
    roundnewV = round(newV)
    intnewV = int(roundnewV)
    return "{:.0f}%\n({:d} users)".format(percentage, intnewV)

Is this a good way to save the original form of integer and not lose out any value?


texts:
I'm working on a page where a user can create new records, but not all values are required. When creating the SqlCommand with potentially null values, I'm wondering what's the best way, from a code readability standpoint, to check if there's any valid/useful information in a given field. If there is, add that information to the command, if there's isn't, add a DBNull.

Let's say we have a textbox, Address, which is non-compulsory (comm is the SqlCommand):

if(String.IsNullOrEmpty(Address.Text))
{
    comm.Parameters.AddWithValue("@Address", (Object) DBNull.Value)
}
else
{
    comm.Parameters.AddWithValue("@Address", (Object) Address.Text);
}

That seems like a lot of unnecessary typing. But trying to get clever and condense it into a single statement:

comm.Parameters.AddWithValue("@Address",
     String.IsNullOrWhiteSpace(Address.Text) ?
     (Object) DBNull.Value :
     (Object) Address.Text
     );

That seems a little too condensed, harder to parse and understand. Not too difficult to figure out, but (at least to me), also not immediately apparent what's going on. So a trade-off:

Object addressParam =
    String.IsNullOrEmpty(Address.Text) ?
    (Object) DBNull.Value :
    (Object) Address.Text;

 comm.Parameters.AddWithValue("@Address", addressParam);

(Or the above in a if/else block).
Another option that just occurred as I wrote this question:

Object addressParam = (Object) DBNull.Value;
if(!String.IsNullOrWhiteSpace(Address.Text))
{
     addressParam = (Object) Address.Text;
}

Are any of these methods prefered? I am going about this completely the wrong way? Am I just way over-thinking this? It's the latter, isn't it?


texts: Serve folder content using PHP route (SSI) (dynamic includes)

texts:
I have just written a PHP router, but I have some security concerns about this function. I am trying to serve all the content of a folder using this function. I am trying to prevent harmful URLs.

public static function set_up($reletive_path = true)
{
    self::$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    if ($reletive_path && self::$url !== "/") {
        $cut_of = strlen(dirname($_SERVER['PHP_SELF']));
        self::$url = substr(self::$url, $cut_of);
    }
    if (substr(self::$url, -1) == "/") {
        self::$url = substr(self::$url, 0, -1);
    }
    if (self::$url == "") {
        self::$url = "/";
    }
}

/**
 * Serves ONLY php and html files from a folder, the full path with extension must be provided
 * @param $url_path string Route to access the folder
 * @param $foldername string Path to the folder to serve
 * @param string|array $methods String or array of methods there will execute this route, all methods MUST be in UPPERCASE
 * @return bool True if route is executed
 */
public static function serve_folder($url_path, $foldername, $methods = "ALL")
{
    /** unrelated code */
    $foldername = rtrim($foldername, "/");

    $query_patten = $url_path;
    if (substr(self::$url, 0, strlen($query_patten)) === $query_patten) {
        $sub_path = substr(self::$url, strlen($query_patten));
        if ($sub_path === false) {
            if (file_exists($foldername . "/index.php") && is_file($foldername . "/index.php")) {
                require $foldername . "/index.php";
                self::$route_found = true;
                return true;
            } else if (file_exists($foldername . "/index.html") && is_file($foldername . "/index.html")) {
                require $foldername . "/index.html";
                self::$route_found = true;
                return true;
            }
        } else if (preg_match('/^(\/[a-zA-Z0-9-_]+)*\/[a-zA-Z0-9-_]+\.(html|php)$/', $sub_path)) {  // matches urls like /folder/subfolder/file.php /subfolder/file.html file.php
            $full_file_path = $foldername . $sub_path;
            if (file_exists($full_file_path) && is_file($full_file_path)) {
                require $full_file_path;
                self::$route_found = true;
                return true;
            }
        } else if (preg_match('/^(\/[a-zA-Z0-9-_]+)*\/[a-zA-Z0-9-_]+(\/)?$/', $sub_path)) { // matches urls like /folder/subfolder/ /folder/subfolder /folder
            $full_file_path = $foldername . rtrim($sub_path, "/");
            if (file_exists($full_file_path . "/index.php") && is_file($full_file_path . "/index.php")) {
                require $full_file_path . "/index.php";
                self::$route_found = true;
                return true;
            } else if (file_exists($full_file_path . "/index.html") && is_file($full_file_path . "/index.html")) {
                require $full_file_path . "/index.html";
                self::$route_found = true;
                return true;
            }
        }
    }
    return false;
}

EDIT

A usage example would be following:

You are having following folder structure:

/router.php (all traffic is routed to this file)

/homepage.php

/functions/signup.php

/functions/login.php

/functions/admin/add_article.php

// router.php
// the libery is called Highway
Highway::get("/", function () {
    include "homepage.php";
});
Highway::serve_folder("/actions", "functions/");

Following request will include following file:

website.com -> /homepage.php

website.com/actions/signup.php -> /functions/signup.php

website.com/actions/login.php -> /functions/login.php

website.com/actions/admin/add_article.php -> /functions/admin/add_article.php


texts: Better writing JS - from general variables to object

texts:
This might be a dumb question for you advanced developers.

Below is a script on my own website that I want to modify, in order to avoid declaring same variables in each function. I want to avoid declaring variables in the main script structure.

Below code works, still wanted to know if there is a more elegant way to do this.

As Answered below, it's best to enclose everything in an object.

var var1 = document.getElementById("div1");
var var2 = document.getElementById("div2");

function foo1(){
div1.style.display = "none";
}

function foo2(){
div2.style.display = "block";
}


texts:
I have written this code which precisely calculates the nth power of x by a recursive method.

I compared my program with Java's pow(double, double) function, and most of the time I get comparable results, although sometimes pow is slow and the other times this program is slow.

Can anyone suggest any improvements or the way Java implements this function?

public double power(long x, int n) {

    double pow = 1L;
    if(n==0)
        return 1;
    if (n == 1)
        return x;
    if(n%2==0){
        pow = power(x, n / 2);
        return pow * pow;
    }
    else{
        pow = power(x,n/2);
        return pow * pow * x;
    }
}


texts: Detecting if two given strings are isomorphic using Java data structures

texts:
So I have written the following code and it works for various same length isomorphic strings I have tried. However I am not sure what are some time complexity improvements and coding tweaks that could be applied to the code:

/**
 * Created by mona on 5/26/16.
 */
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Collections;

public class IsomorphicStrings {
    //the words "abca" and "zbxz" are isomorphic
    //aabc a(2) b(1) c(1)
    //zzbx z(2) b(1) x(1)
    //my algorithm
    //create a sorted hashmap  on value
    //check to see if two hashmap are equal based on their value set
    //assuming two isomorphic strings are of the same length

    public static boolean areIsomorphic(String s1, String s2) {
        Map<Character, Integer> freqMap1 = new HashMap<>();
        Map<Character, Integer> freqMap2 = new HashMap<>();

        for (int i=0; i<s1.length(); i++) {
            if (freqMap1.containsKey(s1.charAt(i))) {
                int freq1 = freqMap1.get(s1.charAt(i));
                freqMap1.put(s1.charAt(i), freq1 + 1);
            } else {
                freqMap1.put(s1.charAt(i), 1);
            }

        }

        for (int i=0; i<s2.length(); i++) {
            if (freqMap2.containsKey(s2.charAt(i))) {
                int freq2 = freqMap2.get(s2.charAt(i));
                freqMap2.put(s2.charAt(i), freq2 + 1);
            }
            else {
                freqMap2.put(s2.charAt(i), 1);
            }

        }

        List<Integer> freqList1 = new ArrayList<>();
        List<Integer> freqList2 = new ArrayList<>();

        for (Map.Entry entry: freqMap1.entrySet()) {
            freqList1.add((Integer) entry.getValue());
        }

        for (Map.Entry entry: freqMap2.entrySet()) {
            freqList2.add((Integer) entry.getValue());
        }

        Collections.sort(freqList1);
        Collections.sort(freqList2);

        return freqList1.equals(freqList2);

    }

    public static void main(String[] args) {
        String s1="abca";
        String s2="zbxz";
        System.out.println(areIsomorphic(s1, s2));
    }
}

/* side note: can isomorphic strings be of different lengths? Then what algorithm do you suggest? */


texts:
I've become a bit rusty in Java. This is an attempt at brushing up my skills.

  Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list.

Code

import java.util.Comparator;
import java.util.Objects;

public class Sorting {
    /**
     * Day 07 - Bubble Sort
     * In place sort given array with bubble sort algorithm
     *
     * @param data       array
     * @param comparator implementation of comparator for given data type
     * @param ascending  sort order
     * @param <T>        data type of array elements
     * @return sorted data array
     */
    public static <T> T[] bubbleSort(T[] data, Comparator<T> comparator, boolean ascending) {
        Objects.requireNonNull(data);
        int len = data.length;
        if (len <= 0) return data;
        T temp;
        boolean swapped;
        for (int i = 0; i < len - 1; i++) {
            swapped  = false;
            for (int j = 0; j < len - 1 - i; j++) {
                if ((comparator.compare(data[j], data[j + 1]) * (ascending ? 1 : -1)) > 0) {
                    temp = data[j];
                    data[j] = data[j + 1];
                    data[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break;
        }
        return data;
    }
}

Test cases

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestSorting {
    @Test
    public void testBubbleSort() {
        Assert.assertEquals(asc(1, 2, 3), ar(1, 2, 3));
        Assert.assertEquals(asc(3, 2, 1), ar(1, 2, 3));
        Assert.assertEquals(asc(2, 0, -1, 2, 1), ar(-1, 0, 1, 2, 2));

        Assert.assertEquals(dsc(1, 2, 3), ar(3, 2, 1));
        Assert.assertEquals(dsc(3, 2, 1), ar(3, 2, 1));
        Assert.assertEquals(dsc(2, 0, -1, 2, 1), ar(2, 2, 1, 0, -1));

        Assert.assertEquals(asc(2, 1), ar(1, 2));
        Assert.assertEquals(asc(1), ar(1));
        Assert.assertEquals(asc(), ar());
        Assert.assertEquals(dsc(1), ar(1));
        Assert.assertEquals(dsc(), ar());
    }

    @Test(expectedExceptions = {NullPointerException.class})
    public void testNullExcept() {
        Sorting.bubbleSort(null, Integer::compare, true);
    }

    private static Integer[] ar(Integer... objects) {
        return objects;
    }

    private static Integer[] asc(Integer... objects) {
        return Sorting.bubbleSort(objects, Integer::compare, true);
    }

    private static Integer[] dsc(Integer... objects) {
        return Sorting.bubbleSort(objects, Integer::compare, false);
    }
}


texts:
I have this function I've written to encode strings of binary data as base64 strings. I'd like to see if there are areas where it could be improved, specifically:

Is the function correct? Are there edge cases I haven't accounted for? (Handling arbitrary UTF-8 correctly is a "nice-to-have" but not a "need-to-have" if it significantly increases complexity, but it should be able to handle arbitrary ASCII, treating control and whitespace characters as normal characters)
Can the performance of the algorithm I used be improved? Am I mistaken that its time and space complexities are both O(n), and can either be improved further? Can this problem be parallelized nicely?
Can it safely accept arbitrary/malicious input?
Am I using the right language features for the best performance? (The strings in this case would be generated at runtime, but it would be interesting if anyone wanted to show how to do it with template magic at compile-time, which is a few steps above my level).
Is it idiomatic, modern code that follows best practices? Am I relying on any nonstandard behavior? (Not necessarily a problem, but good to know).

#include "ToBase64.h" // string, experimental/string_view
#include <cinttypes>
#include <stdexcept>

using std::length_error; // stdexcept
using std::string; // string
using std::experimental::string_view; // experimental/string_view
using std::uint8_t; // cinttypes

string to_base64(const string_view input)
{
        static constexpr auto BASE64{
                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
        };

        const auto len{ input.length() };
        string output;
        if (len > output.max_size() / 4 * 3 - 4) {
                throw length_error{ "Output too large to fit in std::string" };
        }
        output.reserve(len / 3 * 4 + 4);

        auto remainder{ 0 };
        uint8_t leftover{ 0 };

        for (uint8_t c : input) {
                switch ((remainder %= 3)++) {
                case 0:
                        output += BASE64[c >> 2];
                        leftover = c << 6;
                        break;
                case 1:
                        output += BASE64[(leftover >> 2) + (c >> 4)];
                        leftover = c << 4;
                        break;
                case 2:
                        output += BASE64[(leftover >> 2) + (c >> 6)];
                        output += BASE64[c & 0x3F];
                        break;
                }
        }

        switch (remainder) {
        case 1:
                output += BASE64[leftover >> 2];
                output += "==";
                break;
        case 2:
                output += BASE64[leftover >> 2];
                output += '=';
                break;
        }

        return output;
}


texts: Architecture for manager that gets shared among different components

texts:
It started with a simple log manager. Then I wanted to implement more features, for example printing the name of the component that send a message. Later on, I can think of giving each component that prints log messages it's own text color in the terminal and options to mute or solo single modules.

Therefore, the manager needs the identity of the component that called its methods. So I decided to wrap the manager with an instance for every component. It tunnels function calls to the manager together with the name of the component.

#include <iostream>
#include <string>
#include <memory>
#include <unordered_map>
using namespace std;

////////////////////////////////////////////////////////////////
// Manager declaration
////////////////////////////////////////////////////////////////

class manager {
public:
    class instance;

    instance &get_instance(string name);
    void print(string sender, string message);

private:
    unordered_map<string, unique_ptr<instance>> m_instances;
};

////////////////////////////////////////////////////////////////
// Instance declaration
////////////////////////////////////////////////////////////////

class manager::instance {
public:
    instance(string name, manager &manager);
    void print(string message);

private:
    string m_name;
    manager &m_manager;
};

////////////////////////////////////////////////////////////////
// Manager implementation
////////////////////////////////////////////////////////////////

manager::instance &manager::get_instance(string name) {
    if (m_instances.find(name) == m_instances.end())
        m_instances[name] = unique_ptr<instance>(new instance(name, *this));
    return *m_instances[name].get();
}

void manager::print(string sender, string message) {
    cout << sender << ": " << message << "." << endl;
}

////////////////////////////////////////////////////////////////
// Instance implementation
////////////////////////////////////////////////////////////////

manager::instance::instance(string name, manager &manager) : m_name(name),
    m_manager(manager) {}

void manager::instance::print(string message) {
    m_manager.print(m_name, message);
}

////////////////////////////////////////////////////////////////
// Main function
////////////////////////////////////////////////////////////////

int main() {
    manager m;
    m.get_instance("Window").print("Open up");
    m.get_instance("Asset").print("Load textures");
    return 0;
}

Here is a working example of my code. What do you think about the class structure and architecture? Is there an easier or more expressive way? I'd like to get feedback and improve the code structure before implementing other managers the same way.


texts: List of binary numbers: How many positions have a one and zero

texts:
I have a list of integers, e.g. i=[1,7,3,1,5] which I first transform to a list of the respective binary representations of length L, e.g. b=["001","111","011","001","101"] with L=3.
Now I want to compute at how many of the L positions in the binary representation there is a 1 as well as a zero 0. In my example the result would be return=2 since there is always a 1 in the third (last) position for these entries. I want to compute this inside a function with a numba decorator.
Currently my code is:
@nb.njit
def count_mixed_bits_v2(lst):
    andnumber = lst[0] & lst[1]
    ornumber = lst[0] | lst[1]
    for i in range(1, len(lst)-1):
        andnumber = andnumber & lst[i+1]
        ornumber = ornumber | lst[i+1]
    xornumber = andnumber ^ ornumber
    result = 0
    while xornumber > 0:
       result += xornumber & 1
       xornumber = xornumber >> 1
    return result

First I take the AND of all numbers, ans also the OR of all numbers, then the XOR of those two results will have a 1 where the condition is fulfilled. In the end I count the number of 1's in the binary representation. My code seems a bit lengthy and I'm wondering if it could be more efficient as well. Thanks for any comment!
Edit: Without the numba decorator the following function works:
def count_mixed_bits(lst):
    xor = reduce(and_, lst) ^ reduce(or_, lst)
    return bin(xor).count("1")

(Credit to trincot)


texts: Linux performance using multi-threads (vs one thread) and ssh message

texts:
My server receives requests in one thread and responds in another. I am using thread pools of pthread-s for both receiving and sending. The performance is not that bad, however...

When I am doing the same algorithm in one thread only(MULTITHREAD not defined) so that both recvs and sends are in the same worker thread, my app runs about 10% better.

Strangely, when I am using separate threads(worker and operation) but include printf in any operation, the performance raises (yes, raises - not declines) some 20%. My printfs goes over SSH.(*)

(Packet analyses shows some 100 micros of delay of ACKing responses (not separate ACKs). This delay does not happen with the printfs, neither it happens in a single-thread mode. It seems like SSH triggers something in the TCP stack. )

I tried to use the TCP_QUICKACK option after every recv() but the performance goes down!(**)
I am using Centos7. The application is very concurrent - it is SMB server.

The algorithm is as follow:

  One thread that get the message with epoll_wait() and then execute the first worker thread, this thread parse the message and launch the operation thread(create/read/write etc.).

main thread:

static void mainThreadBodySocketTransport(CSTransport * transport)
{
    struct epoll_event e;
    int res;

    while (true)
    {
        void * context = NULL;              /* to pass to thread */
        res = epoll_wait(transport->epoll, &e, 1, (int)*60 * 12 * 1000));
        if (res == 1)
        {
            *context = e.data.ptr;
        }
    /* wrapper to execute the worker thread */
        cmThreadPoolExecute(transport->threadPool, context);
    }
}

worker thread

static void threadBodySocketTransport(void * context)
{
   msgBuffer * message;

   message = parseMSG(context);
   switch (message->cmd)
   {
   case WRITE:
      doWriteOp(message);
   break;
   case READ:
      doReadOp(message);
   break;
   case CREATE:
      doCreateOp(message);
   break;
   }
}

void doWriteOp(msgBuffer * message)
{
#ifdef MULTITHREAD
    /* wrapper to execute the worker thread */
    cmThreadPoolExecute(threadPoolWrite, (void *)message);
#else
    /* write to file */
    threadBodyWrite(message);
#endif
}

operation thread

static void threadBodyWrite(void * context)
{
   msgBuffer * message = (msgBuffer *)context;
   int fd;

   .
   .(get the fd)
   .
   /* printf("w\n");*/
   write(fd, message->write.data , message->write.len);
   sendResponse(message->cmd, true);
}

pthread create

void threadStart(SYThread *taskIdPtr, void (*startpoint)(void), NQ_BOOL background)
{
    pthread_attr_t attr;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(taskIdPtr, &attr, (void * (*)(void *))startpoint, NULL)
    pthread_attr_destroy(&attr);
}

Maybe I need to use different thread attribute??

Packet sequence:
(*)ack time - request time = ~50 micros
request
response(builtin ack)
request
request
ack
respons

(**)ack time - request time = ~50 micros
request
ack
response
request
request
ack
respons


texts: Two squares or not two squares - constant time optimization

texts:
I have been trying to solve this problem, and after a bit of googling, I realised a \$O(\sqrt{n})\$ time complexity works fine (though the algorithm suggested is different from that I have used). My algorithm is as follows (pseudo code):

for i in range(sqrt(n/2+1)):
    if n-i*i is a perfect square:
        return True
return False

The exact code is as follows:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAX 100000000
typedef unsigned long long int llu;
int isSquare(llu n){
    if(n%16!=0 && n%16!=1 && n%16!=9 && n%16!=4)
        return 0;//as a square can only be of the form 16n+r ,where r belongsto {0,1,4,9}
    //The above step prevents use of expensive function sqrtl() in 75% cases
    llu root = sqrtl(n);
    return root*root == n;
}
int isSqSum(llu n){
    if(n%4==3)//as sum of two squares cannot be of the form 4n+3
        return 0;
    llu i;
    for(i=0;i*i<n/2+1;++i)
        if(isSquare(n-i*i))
            return 1;
    return 0;
}
int main()
{
    int c ;
    scanf("%d",&c);
    llu n;
    while(c--){
        scanf("%llu",&n);
        if(isSqSum(n))
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}

As you can see, I have already applied most of the optimizations I could think of, but I still keep getting TLE. Is there something wrong with my code or is it that the algorithm that I am using has a large constant of proportionality in time complexity?


texts:
In the below GameOutcome class I'm checking for wins/ties in Tic Tac Toe. I'm pretty set on breaking the checks into 5 different functions because I'm specifically practicing making functions short and single-purposed. But I'm not at all set on my 5 if statements in the find_winner_or_tie method. Does somebody know a more elegant solution for the find_winner_or_tie method so it doesn't have 5 if statements in it? I sort of which I could just call each of the "check functions" in a loop but I don't know how to do this without hardcoding the names of all 5 of the "check functions".

class GameOutcome:

    def __init__(self):
        self.letter_dict = {'X': -1, 'O': 1, ' ': 0}
        self.state_of_game = None
        self.row_index_of_move = None
        self.column_index_of_move = None
        self.game_outcome = None

    def find_winner_or_tie(self, state_of_game, row_index_of_move, column_index_of_move):

        self.set_board_and_move(state_of_game, row_index_of_move, column_index_of_move)

        if self.check_row_containing_move_for_win():
            return self.game_outcome
        if self.check_column_containing_move_for_win():
            return self.game_outcome
        if self.check_main_diagonal_for_win_iff_it_contains_move():
            return self.game_outcome
        if self.check_off_diagonal_for_win_iff_it_contains_move():
            return self.game_outcome
        if self.check_for_tie():
            return self.game_outcome

        return ''

    def set_board_and_move(self, state_of_game, row_index_of_move, column_index_of_move):
        self.state_of_game = state_of_game
        self.row_index_of_move = row_index_of_move
        self.column_index_of_move = column_index_of_move

    def check_row_containing_move_for_win(self):
        total = 0
        for column in range(3):
            total = total + int(self.letter_dict[self.state_of_game.board[self.row_index_of_move][column]])
            if abs(total) == 3:
                winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]
                self.game_outcome = winning_letter
                return True
        return False

    def check_column_containing_move_for_win(self):
        total = 0
        for row in range(3):
            total = total + int(self.letter_dict[self.state_of_game.board[row][self.column_index_of_move]])
            if abs(total) == 3:
                winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]
                self.game_outcome = winning_letter
                return True
        return False

    def check_main_diagonal_for_win_iff_it_contains_move(self):
        if self.row_index_of_move == self.column_index_of_move:
            total = 0
            for diagonal_indexing in range(3):
                total = total + int(self.letter_dict[self.state_of_game.board[diagonal_indexing][diagonal_indexing]])
                if abs(total) == 3:
                    winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]
                    self.game_outcome = winning_letter
                    return True
        return False

    def check_off_diagonal_for_win_iff_it_contains_move(self):
        if self.row_index_of_move + self.column_index_of_move == 2:
            total = 0
            for off_diagonal_indexing in range(3):
                total = total + int(self.letter_dict[self.state_of_game.board[off_diagonal_indexing][2 - off_diagonal_indexing]])
                if abs(total) == 3:
                    winning_letter = self.state_of_game.board[self.row_index_of_move][self.column_index_of_move]
                    self.game_outcome = winning_letter
                    return True
        return False

    def check_for_tie(self):
        if len(self.state_of_game.available_squares) == 0:
            self.game_outcome = 'Tie'
            return True
        return False


texts: JavaScript-based quiz application called Quizz

texts:
I've been spending lot of time reading through this site and found plenty of resources that shaped up my code.

I am working on an open source project known as Quizz. It is in a primitive stage as I work only during my spare time I cannot concentrate much. For this JavaScript to work, I have a huge objects and array's of topics and questions in a variable called qbank (read question bank).

var qbank   = {};

qbank['js'] = [];
qbank['html']   = [];

qbank['js'].push({
    level:  'basic',
    questions:  [
        {
            title:  'One JS BASIC A question statement?',
            type:   'single',
            anss:   [
                'Answer 1',
                'Answer 2',
                'Answer 3'
            ],
            ans:    [1],
            comments:   'If there is a wrong answer, a justification is needed'

        },

    ]
});

I guess from the above code it is understandable that the topics may be JavaScript/HTML/PHP or Java, and each JavaScript array holds set of questions based on levels (basic, intermediate,... advanced).

The idea is to iterate over array and hold each levels and topics in a separate array variable.

Do you think this approach is good? I really feel there is something wrong with this.

var digest  = function() {
        for( var q in qbank ) {
            //  q   is js/html/php/..... topic names
            var
                topic,
                t,
                qns     = 0,
                i   = 0,
                questions,
                question,
                level
            ;

            topic   = qbank[q];

            //  Initializing instance topics
            _instance.topics[q]= [];

            for(
                var
                    l = levels.length
                ; i < l; i++ ) {

                if( typeof _instance.topics[q][i] === 'undefined' ) {
                    _instance.topics[q][i]  = {
                        'level': levels[i],
                        'questions': []
                    };
                }
            }

            for( t in topic ) {
                questions   = topic[t].questions;
                level       = topic[t].level;

                for( qns in questions ) {
                    for( var
                            inst = 0,
                            l = _instance.topics[q].length; inst < l; inst++ ) {

                        if( _instance.topics[q][inst].level === level ) {
                            _instance.topics[q][inst].questions.push( questions[qns] );
                        }
                    }
                }
            }
        }
    };

Secondly, I have this digest function where it will pull out and merge all the questions based on levels and topics. I really hate to see my code with plenty of for loops. Please help in suggesting a good practice or approach I need to take.


texts:
The following code is from the DataAccess layer that calls the SQL stored procedure and returns the result set back to the calling code.

public class CoffeeDataAccess : ICoffeeDataAccess
    {
        private readonly Database coffeeDatabase;

        public CoffeeDataAccess(ICoffeeShopDatabaseFactory factory)
        {
            this.coffeeDatabase = factory.GetCoffeeDatabase();
        }

        public async Task<IEnumerable<Coffee>> GetAllAvailableCoffees()
        {
            IEnumerable<Coffee> coffees = await this.ExecuteCommandAsync("spGetAllCoffees");
            return coffees;
        }

        public async Task<IEnumerable<Coffee>> GetCofeesOfTheWeek()
        {
            IEnumerable<Coffee> coffees = await this.ExecuteCommandAsync("spGetCoffeesOfTheWeek");
            return coffees;
        }

        private async Task<IEnumerable<Coffee>> ExecuteCommandAsync(string spName)
        {
            IList<Coffee> coffees;

            using (DbCommand command = this.coffeeDatabase.GetStoredProcCommand("dbo" + spName))
            {

                Task<IDataReader> dataReaderTask =
                    Task<IDataReader>.Factory.FromAsync(this.coffeeDatabase.BeginExecuteReader, this.coffeeDatabase.EndExecuteReader, command, null);

                using (IDataReader reader = await dataReaderTask)
                {
                    coffees = new List<Coffee>();
                    while (reader.Read())
                    {
                        Coffee c = new Coffee();
                        c.Id = int.Parse(reader["ID"].ToString());
                        c.Name = reader["Name"].ToString();
                        c.ShortDesc = reader["ShortDesc"].ToString();
                        c.LongDesc = reader["LongDesc"].ToString();
                        c.Price = decimal.Parse(reader["Price"].ToString());
                        c.ImageUrl = reader["ImageUrl"].ToString();
                        c.ImageThumbnailUrl = reader["ImageThumbnailUrl"].ToString();
                        c.CategoryId = int.Parse(reader["CategoryId"].ToString());
                        coffees.Add(c);
                    }
                }
            }

            return coffees;
        }

    }

The CoffeeDataAccess object is newly instantiated every time when a client code asks for it from the IoC container (registered as Trasient in ASP.NET Core - startup class). Is the method name ExecuteCommandAsync thread safe or not?

I think it is because each time a new instance of the CoffeeDataAccessclass is created but I'm not sure.


texts:
It's been a year or two since I last dabbled in jQuery and have attempted to write a simple "on key press move to the next element" script.  However my first attempt has a lot a repetition. I just know there is a more elegant way to write this, probably using a dictionary of elements or such.

$("#DialFirst").keypress(function () {
        $("#DialSecond").focus();
    });

    $("#DialSecond").keypress(function () {
        $("#DialThird").focus();
    });

    $("#DialThird").keypress(function () {
        $("#DialFourth").focus();
    });

    $("#DialFourth").keypress(function () {
        $("#DialFifth").focus();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="DialFirst" name="DialFirst" type="text" value="" />
<input id="DialSecond" name="DialSecond" type="text" value="" />
<input id="DialThird" name="DialThird" type="text" value="" />
<input id="DialFourth" name="DialFourth" type="text" value="" />
<input id="DialFifth" name="DialFifth" type="text" value="" />

Usage: Type in each box, focus should move to the next.


texts:
I am trying to implement the solution for the problem "Max Min" in HackerRank. The solution runs for some test cases but for few test cases it pops out showing "Terminated due to Time Out"

  Problem:

  Given a list of \$N\$ integers, your task is to select \$K\$ integers
  from the list such that its unfairness is minimized.

  Unfairness = Max{K integer Set} - Min{K integer Set}

  where max denotes the largest integer among the elements of \$K\$, and
  min denotes the smallest integer among the elements of \$K\$.

  Input Format

  The first line contains an integer \$N\$.
  The second line contains an integer \$K\$.
  \$N\$ lines follow. Each line contains an integer that belongs to the list \$N\$.

  Note: Integers in the list \$N\$ may not be unique.

  Output Format

  An integer that denotes the minimum possible value of unfairness.

  Constraints

  \$2 \le N \le 10^5\$
  \$2 \le K \le N\$
  \$0 \le \text{integer in} N \le 10^9\$

  Sample Input #00

7
3
10
100
300
200
1000
20
30

  Sample Output #00

20

Can anyone please point to me which part of my code is taking longer to implement and what a better solution can be?

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>

#define MAX 100000
#define MAX_VAL 1000000001

int list[MAX];

int main() {

    int N, K;
    int i;
    int unfairness=0;
    scanf_s("%d %d", &N, &K);
    int set = K - 1;
    for (i = 0; i < N; i++)
        scanf_s("%d", &list[i]);
    for (int l = 0; l < N - 1; l++){
        for (int j = 0; j < N - l - 1; j++)
        {
            if (list[j] > list[j + 1])
            {
                int temp;
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
    }
    for (int x = 0; x < N - set; x++)
    {
        int differ = list[x + set] - list[x];
        //printf("Dif - %d\n", differ);
        //printf("Unfair - %d\n", unfairness);
        if (unfairness == 0){
            unfairness = differ;
        }
        else if (differ<unfairness)
            unfairness = differ;
    }
    printf("%d", unfairness);
    return 0;
}


texts: Illumination as a way of instantiating new objects

texts:
Basically, what I mean by illumination is having a method create an object where the caller supplies all the dependencies.  This allows us to hide our new keyword behind a dependency on an Illuminator, allowing us to much more easily test our code.

Yes, a little bit of reflection is involved, but not too much (IMO).

Please tell me what you think of this type (is the intent behind it clear? et alia):

namespace xofz.Illumination
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    public class Illuminator
    {
        public virtual T Illumine<T>(params object[] dependencies) where T : class
        {
            var constructors = new LinkedList<ConstructorInfo>(
                typeof(T).GetConstructors().OrderByDescending(ci => ci.GetParameters().Length));
            var list = new List<object>(dependencies);
            foreach (var ctor in constructors)
            {
                var parameters = ctor.GetParameters();
                var valuesNeeded = new List<object>(list.Count);
                foreach (var parameter in parameters)
                {
                    for (var i = 0; i < list.Count; ++i)
                    {
                        if (!parameter.ParameterType.IsInstanceOfType(list[i]))
                        {
                            continue;
                        }

                        valuesNeeded.Add(list[i]);
                        list.Remove(list[i]);
                        break;
                    }
                }

                if (valuesNeeded.Count == parameters.Length)
                {
                    list = valuesNeeded;
                    break;
                }

                // if the objects don't line up with this constructor, start over with the next one
                list = new List<object>(dependencies);
                valuesNeeded.Clear();
            }

            return (T)Activator.CreateInstance(typeof(T), list.ToArray());
        }
    }
}

Edit 2: added some ordering to GetConstructors().  So far, it only orders by the number of parameters.

Edit: here is an example of what you can do with an Illuminator.  Say you have a class that has a lot of dependencies.  We can new up all the dependencies of the dependencies, and then actually assign the fields of the class through illuminator.Illumine() calls:

public class MegaBigClass
{
    public MegaBigClass(Illuminator illuminator)
    {
        var a = new A(); // new in a constructor?! Blasphemy!
        var b = new B();
        var c = new C();
        var x = new X();
        var y = new Y();
        var z = new Z();

        // then actually set the fields with the illuminator
        this.abc = illuminator.Illumine<AbcComposite>(a, b, c);
        this.xyz = illuminator.Illumine<XyzComposite>(x, y, z);
    }

    private readonly AbcComposite abc;
    private readonly XyzComposite xyz;
}

Contemplate how testable this code is.  Because Illumine is virtual, it is easy to create a fake or alternate Illuminator for test code to enable us to exactly specify what gets put into the fields.  Look at how we can use new all we want in our constructors, but we need to make sure to assign fields only through illuminator.Illumine() calls.

Could I wrap the entire implementation into a single Activator.CreateInstance() call?  Perhaps, but I feel like doing it this way instead allows for imperfect calls to illuminator.Illumine<T> that still supplies all the necessary dependencies.


texts:
I recently started cleaning up my projects and decided that I want to create a personal repository of useful bits of code. I found this bitmap code between them and heavily edited it and I'd appreciate if someone could review it, because I'm not that used to bitwise operations and such. Is the code portable enough, or there should be changes?

bitmap.h

#ifndef BITMAP__
#define BITMAP__

#define BIT (8*sizeof(byte))
#define BITMAP_NOTFOUND -1

typedef enum{false=0, true} bool;
typedef unsigned char byte;

bool bitmapGet   (byte *, int);
void bitmapSet   (byte *, int);
void bitmapReset (byte *, int);
int  bitmapSearch(byte *, bool, int, int);

#endif

bitmap.c

#include "bitmap.h"

static bool get  (byte,   byte);
static void set  (byte *, byte);
static void reset(byte *, byte);

/* CAREFUL WITH pos AND BITMAP SIZE! */

bool bitmapGet(byte *bitmap, int pos) {
/* gets the value of the bit at pos */
    return get(bitmap[pos/BIT], pos%BIT);
}

void bitmapSet(byte *bitmap, int pos) {
/* sets bit at pos to 1 */
    set(&bitmap[pos/BIT], pos%BIT);
}

void bitmapReset(byte *bitmap, int pos) {
/* sets bit at pos to 0 */
    reset(&bitmap[pos/BIT], pos%BIT);
}

int bitmapSearch(byte *bitmap, bool n, int size, int start) {
/* Finds the first n value in bitmap after start */
/* size is the Bitmap size in bytes */
    int i;
    /* size is now the Bitmap size in bits */
    for(i = start+1, size *= BIT; i < size; i++)
        if(bitmapGet(bitmap,i) == n)
            return i;
    return BITMAP_NOTFOUND;
}

static bool get(byte a, byte pos) {
/* pos is something from 0 to 7*/
    return (a >> pos) & 1;
}

static void set(byte *a, byte pos) {
/* pos is something from 0 to 7*/
/* sets bit to 1 */
    *a |= 1 << pos;
}

static void reset(byte *a, byte pos) {
/* pos is something from 0 to 7*/
/* sets bit to 0 */
    *a &= ~(1 << pos);
}


texts: Permutation of phone numbers starting at button x, ending at button y, and z numbers long

texts:
I am trying find the total number of permutations possible with a given x, y, and z.
x is the initial number, y is the final number, and z is the total number of buttons pressed.
I am supposed to only move from number to number like the knight in chess, in an 'L' shape.
For example, if you just dialed a 1, the next number you dial has to be either a 6 or an 8. If you just dialed a 6, the next number must be a 1 or 7.
Currently, my implementation outputs the correct answer for all the numbers I have given it. However, it is god awful slow because compute time is exponential. What I want to know is how I can compute this in linear time, more or less. z will always be between 1 and 100, inclusive.

##Computes the number of phone numbers one
##can dial that start with the digit x, end
##in the digit y, and consist of z digits in
##total. Output this number as a
##string representing the number in base-10.
##Must follow "knights rule" moves, like chess
##########_________##########
##########|1||2||3|##########
##########|_||_||_|##########
##########|4||5||6|##########
##########|_||_||_|##########
##########|7||8||9|##########
##########|_||_||_|##########
##########|_||0||_|##########
##########^^^^^^^^^##########
dict = {0: [4, 6], 1: [6, 8], 2: [7, 9], 3: [4, 8],
    4: [0, 3, 9], 5: [], 6: [0, 1, 7], 7: [2, 6], 8: [1, 3],
    9: [2, 4]}

def recAnswer(current, y, z, count, total):
    if count == z and current == y:
            total += 1
            return total
    count+=1
    if count > z:
            return total
    for i in dict.get(current):
            total = recAnswer(i, y, z, count, total)
    return total

def answer(x, y, z):
    if x == y:
            if z%2 == 0:
                    return '0'
    elif x == 5 or y == 5:
            if z == 1 and x == y:
                    return '1'
            else:
                    return '0'
    elif x%2 != 0 and y%2 == 0:
            if z%2 != 0:
                    return '0'
    elif x%2 == 0 and y%2 != 0:
            if z%2 != 0:
                    return '0'
    elif x%2 == 0 and y%2 ==0:
            if z%2 == 0:
                    return '0'
    elif x%2 != 0 and y%2 != 0:
            if z%2 == 0:
                    return '0'

    total = recAnswer(x,y,z,1,0)
    return str(total)

def test():
    for i in xrange(1,15,1):
            print i,":",answer(1,3,i)

    print answer(6, 2, 5)
    print answer(1, 6, 3)
    print answer(1, 1, 99)

test()


texts:
I'm new To C++ and decided to have a go at the Spotify challenges on their website.

I have now finished but I get the feeling my code is just terrible. I'm guessing it would be very hard for someone else to read and I feel like there are much better ways to code this.

Their "Best Before" puzzle asks: Given a possibly ambiguous date written in "A/B/C" format, where A,B,C are integers between 0 and 2999, interpret them as M/D/Y or D/M/Y or whatever common date format. Pick the interpretation that yields the earliest possible legal date between Jan 1, 2000 and Dec 31, 2999 (inclusive) in "YYYY-MM-DD" format.  If the string cannot be interpreted as a valid date, state so.

Here is my code for the best before puzzle:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;

int Year;
int Month;
int Day;

stringstream ss;
string input;
string in;
bool loop=true;
int date[4];
bool DateFound=false;

void Check_date();
void Check_date()
{

    if(DateFound==false)
    {
    //Check if valid Year
    if (date[1]<2999 && date[1]>0 && date[2]>0 && date[3]>0)
    {   //check months & days are valid
        if(date[2]==1 || date[2]==3 || date[2]==5 || date[2]==7 || date[2]==8 || date[2]==10 || date[2]==12){if(date[3]<=31){DateFound=true;}}
        if(date[2]==4 || date[2]==6 || date[2]==9 || date[2]==11){if(date[3]<=30){DateFound=true;}}
        //Check For Leap Year
        if (date[2]==2)
        {   if(date[3]<28)DateFound=true;
            if(date[1]%4==0 && date[3]<=29)DateFound=true;
            if(date[1]%100==0 && date[1]%400!=0 && date[3]>28)DateFound=false;
        }

    }
    if(DateFound==true){Year=date[1]; Month=date[2]; Day=date[3];if(Year<1000){Year=Year+2000;} if(Month<10){}}

    }

}

void SwitchDate(){int temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();};
void ShiftDate(int places)
{   if(places==1)
    {
    int temp; temp=date[3]; date[3]=date[2]; date[2]=temp; temp=date[1]; date[1]=date[2]; date[2]=temp;  Check_date();
    }
    if(places==2)
    {
    int temp; temp=date[1]; date[1]=date[2]; date[2]=temp; temp=date[2]; date[2]=date[3]; date[3]=temp; Check_date();
    }
};

int main ()
{
    //Main Loop
    while(loop==true)
    {

    cout <<"Please Enter a date \n";
    cin>>input;
    cout<<endl;

    for (int x=0, y=1; y<=3; y++, x++)
        {
            while (input[x] !='/' && x !=input.length()) ss<<input[x++];
            ss>> date[y];
            ss.clear();
        }

    //order small medium large
    for (int x=3, temp; x!=0; x--)
    {
        if (date[x] < date[x-1])
            {   temp=date[x-1];
                date[x-1]=date[x];
                date[x]=temp;
            }
        if (x==1 && (date[2] > date[3] ))
                {
                    temp=date[3];
                    date[3]=date[2];
                    date[2]=temp;
                }

    }

    Check_date();
    SwitchDate();
    ShiftDate(1);
    SwitchDate();
    ShiftDate(2);
    SwitchDate();

    //PRINT
    if(DateFound==true)
    {
    cout <<"The smallest valid date is: ";
    cout <<setw(2)<<setfill('0')<<Year; cout<<"-";
    cout <<setw(2)<<setfill('0')<<Month; cout<<"-" ;
    cout <<setw(2)<<setfill('0')<<Day;
    cout<<endl;
    }
    else cout<<date[1]<<"/"<<date[2]<<"/"<<date[3]<<" Is illegal \n";

    DateFound=false;
    cout <<"Again? 'Y' or 'N' \n";
    cin >>in;
    cout << endl;
    if(in=="y" || in=="Y"){loop=true;}
    if(in=="n" || in=="N"){loop=false;}
    }//End of Loop
}


texts: It is a hashmap, using linear probing on an array

texts:
I have been studying hashtable for two days and was musterring up the courage to write a code. Finally I have written code in which I have taken many shortcuts:

The first being I have used compression function as key % hash_size;
I have not used any hashing function.
I have implemented it using array. A better option could be a vector.
For linear probing I have choose to store in the next empty index.
My code is not commented but is pretty straightforward.

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
class data{
  private:
    int key;
    int value;
    bool deleteme;
  friend class hashtable;
};
class hashtable{
  public:
    hashtable(int m);
    hashtable(const hashtable& that);
    hashtable & operator= (hashtable src);
    ~hashtable();
    void add(int key, int value);
    bool exists(int key);
    int get(int key);
    void remove(int key);
    void display();
  private:
    int size;
    data* array;
};
hashtable::hashtable(int m):size(m){
    array = new data[m]();
    // data array[] = {NULL};
}
hashtable::hashtable(const hashtable& that){
  size = that.size;
  array = new data[that.size];
  for(int i = 0; i < that.size ; ++i){
    array[i] = that.array[i];
  }
}
hashtable & hashtable::operator=(hashtable src){
    std::swap(array, src.array);
    std::swap(size, src.size);
    return *this;
}
hashtable::~hashtable(){
    delete [] array;
}
void hashtable::add(int k, int val){
  int index = k % size;
  while(array[index].key != 0 || array[index].deleteme == 1){
    if(array[index].key == k)
      break;
    index += 1;
  }
  array[index].key = k;
  array[index].value = val;
}
bool hashtable::exists(int key){
  int index = key % size;
  while((array[index].key != key && index < size ) || (array[index].deleteme == 1 && index < size)){
    index += 1;
  }
  return index < size;
}
int hashtable::get(int key){
  int index = key % size;
  while((array[index].key != key && index < size) || (array[index].deleteme == 1 && index < size)){
    index += 1;
  }
  if(index < size)
    return array[index].value;
}
void hashtable::remove(int key){
  int index = key % size;
  while((array[index].key != key && index < size)|| (array[index].deleteme == 1 && index < size)){
    index += 1;
  }
  array[index].key = 0;
  array[index].value = 0;
  array[index].deleteme = 1;
}
void hashtable::display(){
    for (int i = 0; i < size; ++i)
    {
        cout << array[i].key << " " << array[i].value  << " " << array[i].deleteme << endl;
    }
}

int main(){
  hashtable h1(11);
  h1.add(3,134);
  h1.add(14,139);
  h1.add(742,963);
  h1.add(11,456);
  h1.add(22,635);
  h1.add(33,852);
  h1.add(44,968);
  h1.add(9,589);
  h1.add(9,7890);
  h1.remove(14);
  h1.remove(33);
  h1.add(55,786);
  h1.add(10,56);
  cout << h1.get(44) << endl;
  // cout << h1.(43) << endl;
  h1.display();
}


texts:
See the next iteration: Bare bones painter app in Java - follow-up.

I have this tiny program for drawing:

PaintCanvas.java:

package net.coderodde.javapaint;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;

/**
 * This class implements a GUI component for drawing.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Jun 8, 2016)
 */
public class PaintCanvas extends Canvas {

    /**
     * The actual image being drawn to.
     */
    private final BufferedImage image;

    /**
     * The graphics context of the above.
     */
    private final Graphics2D imageGraphics;

    public PaintCanvas(final int width, final int height) {
        super();
        super.setBounds(0, 0, width, height);

        this.image  = new BufferedImage(width,
                                        height,
                                        BufferedImage.TYPE_INT_RGB);
        this.imageGraphics = this.image.createGraphics();
        this.imageGraphics.setColor(Color.WHITE);
        this.imageGraphics.fillRect(0, 0, width, height);
        this.imageGraphics.setColor(Color.BLACK);

        final PaintCanvasMouseListener listener =
                new PaintCanvasMouseListener();

        this.addMouseListener(listener);
        this.addMouseMotionListener(listener);
    }

    @Override
    public void paint(final Graphics g) {
        update(g);
    }

    @Override
    public void update(final Graphics g) {
        g.drawImage(this.image, 0, 0, null);
    }

    private class PaintCanvasMouseListener
    extends MouseAdapter implements MouseMotionListener  {

        @Override
        public void mouseClicked(final MouseEvent event) {
            processEvent(event);
        }

        @Override
        public void mouseDragged(final MouseEvent event) {
            processEvent(event);
        }

        private void processEvent(final MouseEvent event) {
            PaintCanvas.this.imageGraphics.fillOval(event.getX(), event.getY(), 5, 5);
            PaintCanvas.this.repaint();
        }
    }
}

App.java:

package net.coderodde.javapaint;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

/**
 * This class implements an application for simple drawing.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Jun 8, 2016)
 */
public class App {

    private final JFrame frame = new JFrame("JavaPaint");

    public App() {
        frame.getContentPane().add(new PaintCanvas(640, 480));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        setFrameLocationToCenter();
        frame.setVisible(true);
    }

    private void setFrameLocationToCenter() {
        final Dimension screenDimension = Toolkit.getDefaultToolkit()
                                                 .getScreenSize();
        final int screenWidth  = screenDimension.width;
        final int screenHeight = screenDimension.height;

        frame.setLocation((screenWidth - frame.getWidth()) / 2,
                          (screenHeight - frame.getHeight()) / 2);
    }

    public static void main(final String... args) {
        final App app = new App();
    }
}

It allowed me to draw the following masterpiece:

I am most interested to hear about the internals, yet feel free to tell me anything that comes to mind.


texts:
So, here is the code:
#pragma once
#include <vector>
#include <iostream>
#include <queue>
#include <functional>

using node = int;
using cost = int;
using arc = std::pair<node, cost>;

using AdjList = std::vector<std::vector<arc>>; // first is node, second is cost

class Graph {
private:
    AdjList adjList;
    std::vector<node> nodes;

public:
    Graph(int n) : nodes{ n },  adjList{ n } {}
    void addEdge(const node v, const node u, const cost c) {
        adjList[v].push_back({ u, c });
        adjList[u].push_back({ v, c });
    }

    std::vector<int> dijkstra(const node n) const {
        std::vector<cost> dist(adjList.size(), INT_MAX);
        std::vector<bool> visited(adjList.size(), false);
        dist[n] = 0;
        std::priority_queue<node, std::vector<node>, std::greater<int>> to_visit;
        to_visit.push(n);
        while (!to_visit.empty()) {
            node v = to_visit.top();
            to_visit.pop();
            visited[v] = true;
            for (const arc& a : adjList[v]) {
                node u = a.first;
                cost c = a.second;
                if (!visited[u] and (dist[u] == INT_MAX or dist[u] > dist[v] + c)) {
                    dist[u] = dist[v] + c;
                    to_visit.push(v);
                }
            }
        }
        return dist;
    }

    friend std::ostream& operator<<(std::ostream& stream, const Graph& g) {
        for (size_t i = 0; i < g.adjList.size(); i++) {
            stream << "node " << i << "\n";
            for (const arc& p : g.adjList[i]) {
                stream << "connected with " << p.first << " cost: " << p.second << " ";
            }
            stream << "\n";
        }
        return stream;
    }

};

I think I did a decent job, but I want to make sure I'm not missing anything. I'm using just a adjacent list for storing the arcs. I was unsure if I should reserve some memory for the vectors there, because maybe it's going to get a little bit slow with the push_back operation, but I also wanted to be able to get rid of the O(n^2) for storing.


texts: Adding ID to body tag from variable defined in URL

texts:
I have written a small PHP script to get a variable from the URL and echo it in the body ID.

An example of the url:

http://www.example.com/?var=123

I have added this to the head of my HTML page:

<?php if (isset($_GET['var'])) {
    $var = $_GET['var'];
} else {
    $var = NULL;
} ?>

The body tag of the HTML page looks like this:

<body class="whatever" <?php if(isset($var)) {echo "id=\"$var\""; } ?>>

The result is a body tag like this when the ?var=123 is added to the URL:

<body class="whatever" id="123">

This is working but I am sure there is a better way to go about it.


texts: Function to discard repeats, applied to numbers

texts:
Solving a 4Clojure problem, I got this answer to compress a sequence (problem 30):

#(map first (partition-by identity %))

What would be the best approach to have this work with plain numbers too?

My solution was this:

(defmulti comp class)
(defmethod comp java.lang.Long [x] x)
(defmethod comp :default [x] (map first (partition-by identity %)))

The code is more than tripled.
Are there better solutions? Shorter? More idiomatic?
I tried extending java.lang.Long with ISeqable, but failed miserably.


texts: Train reservation system in Rust as my practice

texts:
Abstract

I am a beginner of Rust language. As my practice I want to create simple train reservation system.

I know little about the "best practice" in Rust, so I want some advises in my code. In terms of the function there are much luck to improve, but I want advises about how to write codes "in Rust".

Code structure

reservation
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── lib.rs
│   ├── main.rs
│   └── reserve_request
│       └── mod.rs
└── target

My codes

lib.rs

pub mod reserve_request;

reserve_request/mod.rs

use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash)]
pub struct Stations<'a> {
    pub start: &'a str,
    pub destination: &'a str,
}

pub struct Request<'a> {
    pub start: &'a str,
    pub destination: &'a str,
    pub time: &'a str,
    pub time_kind: &'a str,
}

impl<'a> Request<'a> {
    pub fn reserve(&self, timetable: HashMap<Stations, &[&str]>) -> bool {
        let st = Stations {
            start: self.start,
            destination: self.destination,
        };

        let times = timetable.get(&st);
        let default: &[&str] = &[];
        let result = match times {
            Some(r) => r,
            None => default,
        };

        for t in result {
            if *t == self.time {
                return true;
            }
        }

        false
    }

    pub fn is_valid(&self) -> bool {
        if self.start == "" {
            println!("You need to determine start point");
            return false;
        } else if self.destination == "" {
            println!("You need to determine destination");
            return false;
        } else if self.start == self.destination {
            println!("Invalid. The start point and destication is same");
        } else if self.time == "" && self.time_kind != "" {
            println!("Invalid time specification");
            return false;
        }

        true
    }
}

main.rs

use reserve::reserve_request;
use std::collections::HashMap;

fn main() {
    //TODO: save time table in the json file
    let time: &[&str] = &["12:00", "14:00", "18:00", "19:00"];
    let mut stations = HashMap::new();
    stations.insert(
        reserve_request::Stations {
            start: "Tokyo",
            destination: "Kyoto",
        },
        time,
    );

    let request = reserve_request::Request {
        start: "Tokyo",
        destination: "Kyoto",
        time: "18:00",
        time_kind: "start",
    };

    if request.is_valid() && request.reserve(stations) {
        println!("Succeed in reserving that train");
    } else {
        println!("Failed to reserved that train");
    }
}

What I want to know especially

In main.rs, to make a value of the HashMap (type &[&str]), I define time variable and insert into HashMap. I feel it is redundant but I do not know how to deal with.
Similar to above, in mod.rs, I make default variable for using in match clause only.


texts:
This is practically my first time using async in my code. I read about dos-and-donts but I wanted to get some feedback on what I've written.

I'm using a repository pattern and I'm inserting asynchronously into the database.

An explanation of the models involved: I have one DomainModel and three tblModels (tblModel1, tblModel2, tblModel3). tblModel2 and tblModel3 hold an ID from tblModel1. The DomainModel is made up of all three of the tblModels. I'm simplifying the domain to database mapping here because I'm focusing on feedback about the asynchronous calls.

Repository

public async Task<int> InsertAsync(tblModel1 tm1)
{
    tm1 = db.tblModel1.Add(tm1);
    await db.SaveChangesAsync();
    return tm1.ID;
}

public async Task<int> InsertAsync(tblModel2 tm2)
{
    tm2 = db.tblModel2.Add(tm2);
    await db.SaveChangesAsync();
    return tm2.ID;
}

public async Task<int> InsertAsync(tblModel3 tm3)
{
    tm3 = db.tblModel3.Add(tm3);
    await db.SaveChangesAsync();
    return tm3.ID;
}

Manager

public async Task<bool> InsertAsync(DomainModel M)
{
    try
    {
        await Task.Run(async () => {
            var tm1ID = await repo.InsertAsync(M.tm1);
            var tm2ID = await repo.InsertAsync(AddID(M.tm2,tm1ID));
            var tm3ID = await repo.InsertAsync(AddID(M.tm3,tm1ID));
        });
    }
    catch (Exception ex)
    {
        return false;
    }

    return true;
}

The method AddID(tblModel, int) is to get the point across that I'm adding the ID from tblModel1 after it's inserted into tblModel2 and tblModel3. In actuality, I do this but I map the DomainModel to completely new tblModels and during that process I add the IDs to tblModel2 and tblModel3. I believe the code above is representative of what I'm doing.

Please let me know if there is a better way for me to optimize these asynchronous inserts into the database. Thank you!


texts: Vowels in a String are in Alphabetical Order

texts:
Task

Write an implementation that returns whether a String has vowels (English language) in alphabetical (A-Z) order or not.

Feedback

Is my vowels variable appropriate? Is there a better way to implement a vowel lookup?
If a candidate String has no vowels, the validator will return true - is that reasonable? From a logical perspective, the program isn't lying, but you could make the same argument if it returned false. Would it be better to return an exception - something like NoVowelsInCandidateException?

Implementation

public class VowelOrderValidator {
    private static final List<Character> vowels = new ArrayList<>(
            Arrays.asList('A', 'E', 'I', 'O', 'U', 'Y')
    );

    public static boolean areVowelsOrdered(final String candidate) {
        final char[] chars = candidate.toUpperCase().toCharArray();
        int lastVowelIndex = 0;
        for (final char c : chars) {
            final int lookupIndex = vowels.indexOf(c);
            if (-1 != lookupIndex) {
                if (lookupIndex < lastVowelIndex) {
                    return false;
                } else {
                    lastVowelIndex = lookupIndex;
                }
            }

        }

        return true;
    }
}


texts: VBA code that pulls information from 1000+ files in directory performance

texts:
Below is the code I am using to run through files in a folder, pull information from the files, and record that information on a sheet. I am not the original author of the main portion of the code. The files the code is opening are fairly large and there are 1000+ of them.  I also hard coded the cells the code is pulling information from.

Is there any way to make this code run more efficiently?

Sub LoopAllExcelFilesInFolder()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim PartInfoArr() As Long
Dim ArrCount As Integer
Dim PartNum As Integer
Dim i As Integer
Dim DocDate As String
Dim j, r As Integer
Dim SeenPart, SeenCount As Integer

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual
ArrCount = 0

'folder path for where to pull files from
  myPath = "C:\Users\.........."

'Target File Extension (must include wildcard "*")
  myExtension = "*.xlsm*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
      Set wb = Workbooks.Open(Filename:=myPath & myFile)

    'Ensure Workbook has opened before moving on to next line of code
      DoEvents

'Coppy all file information
Sheets("Tool GT Block").Select
Range("B11:C11").Select

'While there are part numbers record all info for each into arry
While ActiveCell.Offset(i, 0) <> ""
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 0) = ActiveCell.Offset(i, 0)
    DocDate = Range("D8")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 1) = DocDate
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 2) = Range("D11")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 3) = Range("I9")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 4) = Range("I10")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 5) = Range("I12")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 6) = Range("I13")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 8) = Range("I15")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 9) = Range("I16")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 10) = Range("I17")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 11) = Range("I18")
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 12) = Range("I21")
    'min packing processing overall
    Workbooks("MTM File.xlsm").Worksheets("MTM Pack Process Data").Range("A2").Offset(k, 13) = Range("R10")

i = i + 1
k = k + 1
Wend

' reset  var for next file
i = 0

    'Save and Close Workbook
      wb.Close SaveChanges:=False

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

'Message Box when tasks are completed
  MsgBox "Task Complete!"

End Sub


texts: Trimming unicode whitespace, control characters, and line breaks with regex

texts:
I'm getting user submitted text from a <textarea></textarea>, and I want to edit it a bit before storing it in a database. Here are my 3 regexes, with explanations below them:

/(?:^((\pZ)+|((?!\R)\pC)+)(?1)*)|((?1)$)|(?:((?2)+|(?3)+)(?=(?2)|(?3)))/um

For every line...

Match all leading whitespace and unicode control characters ("WS/CC") (EXCEPT LINE BREAKS).
Match all trailing WS/CC (EXCEPT LINE BREAKS).
Match all but one WS/CC between non-whitespace characters.

regex101

/(\pZ+)|((?!\R)\pC)/u

Match remaining WS/CC (EXCEPT LINE BREAKS).
regex101

/(^\R+)|(\R+$)|(\R(?=\R{2}))/u

Match all leading line breaks.
Match all trailing line breaks.
Match all but 2 consecutive line breaks.
regex101

This is pretty much how I'm planning on using these regexes in my PHP script

// ...
// [Get user input from $_POST
// check its length, etc.,
// if everything looks O.K., store it in $str]
// ...

// Trim unnecessary whitespace (leave line breaks)
$str = preg_replace("/(?:^((\pZ)+|((?!\R)\pC)+)(?1)*)|((?1)$)|(?:((?2)+|(?3)+)(?=(?2)|(?3)))/um", '', $str);
// Convert remaining whitespace to regular spaces (leave line breaks)
$str = preg_replace("/(\pZ+)|((?!\R)\pC)/u", ' ', $str);
// Trim line breaks
$str = preg_replace("/(^\R+)|(\R+$)|(\R(?=\R{2}))/u", '', $str);

// Sanitize for safe printing between html tags
$str = htmlspecialchars($str, ENT_HTML5, 'UTF-8');

// ...
// [Store $str in DB with prepared statements]
// ...

And here's a test case which I've executed on regex101:

Input
(with some WS/CC in it):

a b  c
 d    e
fghi  j

k l m n
op

Output after 1st regex
(still has some WS/CC, but none consecutive, except for line breaks):

a b c
d e
fghi j

k l m n
op

Output after 2nd regex
(all previous WS/CC - except for line breaks - are now regular spaces):

a b c
d e
f g h i j

k l m n
o p

Output after 3rd regex
(max 2 consecutive line breaks, and no whitespace other than non-consecutive regular spaces):
a b c
d e
f g h i j

k l m n
o p

Based on my testing, this process seems to work as intended. I would however be very interested if you can think of any cases in which it would fail to behave as expected.

Also - in addition to possible fail-cases - I'd like to know if there are ways I could make these regexes perform better (faster), while still keeping the functionality as is. This is pretty much the first time I've ever done anything in regex, so I'm assuming there's some room for optimizations.

And if you see something else that is done incorrectly/could be done better, do let me know.

EDIT: Added regex101 links
EDIT2: Also, I've heard there's something called ReDoS, or Regex DoS. If you can tell that these regexes are susceptible to those, and which ones specifically, I'd like to know how to avoid them.


texts: SPOJ is giving TLE for this solution of ROCK

texts:
I am solving ROCK problem on SPOJ. I have used bottom up dynamic programming approach for this problem. Time complexity for this is \$O(n^3)\$.

#include<stdio.h>
#include<string.h>
#include<math.h>
#define MAX 210
#define NEG_INFINITY -1000

int sellable(int a[MAX], int i, int j)
{
    int index,sweet=0,sour=0;
    for(index=i;index<=j;index++)
    {
        if(a[index])
            sweet++;
        else
            sour++;
    }
    if(sweet>sour)
        return 1;
    return 0;
}
int main()
{
    int test_cases,i,j,k,length,l;
    int number,cost;
    int a[MAX];
    int m[MAX][MAX];
    char buffer[MAX];

    for(scanf("%d",&test_cases);test_cases>0;test_cases--)
    {

        scanf("%d",&number);
        for(i=0;i<number;i++)
            for(j=0;j<number;j++)
                m[i][j]=NEG_INFINITY;
        scanf("%s",&buffer);
        for(i=0;i<number;i++)
        {
            a[i]=buffer[i]-'0';
            m[i][i]=a[i];
        }
        for(l=2;l<=number;l++)
        {
            for(i=0;i<number-l+1;i++)
            {
                j=i+l-1;
                for(k=i;k<j;k++)
                {
                    if(sellable(a,i,j))
                        cost=j-i+1;
                    else
                        cost=m[i][k]+m[k+1][j];
                    if(cost>m[i][j])
                    {
                        m[i][j]=cost;
                    }
                }
            }
        }
        printf("%d\n",m[0][number-1]);
    }
    return 0;
}

Can you please suggest an alternative approach for this problem, or if any changes can be made in my code?