Laravel controller method to update user I'm using Laravel and this PHP method is in a controller. It's the back-end for a edit profile page. The user can change the profile picture, reset the password, the username, and so on. I'm new in PHP and would like to know if there is a better or simple way to code this.
public function update(Request $request){

        $user = Auth::user();

        $username = $request->username;
        // PENDING $email = $request->email;
        $wallet_address = $request->wallet_address;
        $about = $request->about;
        $password = $request->password;
        $website = $request->website;
        $location = $request->location;

        if($username){
            $user->username = $username;
            $user->save();
        }

        /** upload avatar section */

        $image = $request->file('avatar');

        if($image){

            // note: if avatar_name variable is null it means the user has never uploaded an image..
            // if the user has uploaded an avatar before, delete it before uploading the new one..
            if($user->avatar_name){
                Storage::delete('/public/profile-pics/'.$user->avatar_name);
            }

            $image_new_name = date('dmy_H_s_i').'_'.$user->id.'_'.$image->getClientOriginalName();
            $image->storeAs('profile-pics',$image_new_name,'public');
            $user->avatar_url = 'storage/profile-pics/'.$image_new_name;
            $user->avatar_name = $image_new_name;
            $user->save();
        }

        if($wallet_address){
             $user->wallet_address = $wallet_address;
             $user->save();
        }

        if($about){
             $user->about = $about;
             $user->save();
        }

        if($password){
             $user->password = $password;
             $user->save();
        }

        if($website){
            $user->website = $website;
            $user->save();
        }

        if($location){
             $user->location = $location;
             $user->save();
        }

        return redirect()->route('edit_profile')->with('success','Your account has been updated successfully.');
    }

So the above answer from Sᴀᴍ Onᴇᴌᴀ already covers quite a few points.
I've worked with Laravel for the past 4 years, so I'll go a bit further in depth on how I'd approach this, including a few suggestions.
First you'll want to use RequestValidation as Sᴀᴍ Onᴇᴌᴀ indicated, this will help guard against invalid input. And make use of Laravel's own input validation logic (sends the user back to the form with error messages in your message bag)
Secondly you have a lot of logic on the User model related to an avatar. I'd suggest creating an Image / Avatar Model that handles the image part of it all, in the end you'd end up with an image_id/avatar_id on the User model as a relation. That way you can have all the logic that handles a file on your filesystem and the associated data. It also enables you (if you go for image) to reuse the logic in a different context.
And declutters your user model
Thirdly, as Sᴀᴍ Onᴇᴌᴀ indicated you do a lot of ->save() calls.
Each call is a database round trip. And a costly action.
You can set each property seperately if you want and at the end of your logic you can call ->isDirty() on your user model, if it returns true, data has changed from the database returned data, indicating an update should be done. At this point you could save.
I however would suggest building an update array of the data to update, and calling the ->update() method with an array containing the key => value pairs that you wish to update. You can check this data array for emptyness to avoid unneccessary updates.
I would always suggest having some form of validation when changing passwords, to make sure an unauthorized user can't simply change the password. (a simple enter current password would do here)
I'll refactor the code you had and try to leave it inside the existing method.
public function update(Request $request)
{
    $user = Auth::user();
    // Read up on the Laravel Request Validation for available rules and usages
    $request->validate([
        'username'         => 'sometimes',
        'email'            => 'email|sometimes',
        'wallet_address'   => 'sometimes',
        'about'            => 'sometimes',
        'password'         => 'sometimes',
        'current_password' => 'required_with:password',
        'website'          => 'sometimes',
        'location'         => 'sometimes',
    ]);
    // $request->input() will return null if the given key is not found
    // I use an array_filter here to filter out empty results, if you expect falsey values (like null to unset something, or 0/false/'') you should use a different approach
    $update_data = array_filter([
        'username'       => $request->input('username'),
        'email'          => $request->input('email'),
        'wallet_address' => $request->input('wallet_address'),
        'about'          => $request->input('about'),
        'password'       => $request->input('password'),
        'website'        => $request->input('website'),
        'location'       => $request->input('location'),
    ]);
    if ($request->input('password')) {
        // enter logic here to validate existing password
        // if this logic fails, you should just return instead of saving anything
    }
    if (!empty($update_data)) {
        // You can store the result to see if you successfully updated
        $update_status = $user->update($update_data);
    }
    // Check if an file has been given
    if ($request->hasFile('avatar')) {
        // I'd suggest moving the image handling to a seperate method at least.
        $this->handleImage($user, $request->file('avatar'));
    }
    if (!$update_status) {
        return redirect()->route('edit_profile')->with('failure','Your account could not be updated.')
    }
    return redirect()->route('edit_profile')->with('success','Your account has been updated successfully.')
}

private function handleImage(User $user, UploadedFile $image)
{
    // if the image is a seperate relation, you could delete the existing relation
    // on the delete for the relation you could hook in a cleanup for the file.
    if ($user->avatar_name) {
        // You can add a "disk" to your filesystem configuration where you can set the default path.
        Storage::delete('/public/profile-pics/' . $user->avatar_name);
    }
    $image_new_name = date('dmy_H_s_i') . '_' . $user->id . '_' . $image->getClientOriginalName();
    $image->storeAs('profile-pics', $image_new_name, 'public');
    // if you use a properly configured Storage::disk you can only store the name, and the disk will resolve where to look for the file
    // Storing paths in the database binds your database to your filesystem structure making future changes more difficult to handle (think moving images to a seperate location, or a different server)
    // Another point, if you expect many users, consider using a subdivision in your path (something like the first few digits of the user id or anything that'll let you break up the files into subdirectories), most systems do weird things once you deal with 200k+ files in a single directory.
    $user->avatar_url = 'storage/profile-pics/' . $image_new_name;
    $user->avatar_name = $image_new_name;
    $user->save();
}


Convert Json response to object array I'm looking for the best solution.

Here is a response from server and i need to get Organizations list:

Content-Type:application/json;charset=UTF-8
 {
   "code": 0,
   "message": "success",
   "organizations": [
     {
       "organization_id": "10234695",
       "name": "Zillum",
       "contact_name": "John Smith",
       "email": "johnsmith@zillum.com",
       "is_default_org": false,
       "language_code": "en",
       "fiscal_year_start_month": 0,
       "account_created_date": "2016-02-18",
       "time_zone": "PST",
       "is_org_active": true,
       "currency_id": "460000000000097",
       "currency_code": "USD",
       "currency_symbol": "$",
       "currency_format": "###,##0.00",
       "price_precision": 2
     },
     {...},
     {...}
   ]

Here is my convert method:

var contentJson = await SendRequest(request);
            var contentJo = (JObject)JsonConvert.DeserializeObject(contentJson);
            var organizationsJArray = contentJo["organizations"]
                .Value<JArray>();

            var organizations = organizationsJArray.ToObject<List<Organization>>();

Code works, but I'm looking for a better Convert Method. Can I do without converting to JArray?

Given that you are already using the ToObject, consider simplifying the code for readability and the advantage of not having to convert anything.

var contentJson = await SendRequest(request);
dynamic response = JsonConvert.DeserializeObject(contentJson);
List<Organization> organizations = response.organizations.ToObject<List<Organization>>();

The actual response appears to be of no concern so using a dynamic simplifies things. Converting back to strongly typed objects by calling ToObject<T> was a good choice and should work out fine.


Use SRP to refactor this Ruby Class I have a class, and it does one thing, It adds numerals to the numerals array.

In doing so it uses a number of private methods and has ended up looking a little bit sickening...

brace yourself...

require './lib/number_interpreter'
require './lib/numeral_adders/m_adder'
require './lib/numeral_adders/cm_adder'
require './lib/numeral_adders/cd_adder'
require './lib/numeral_adders/d_adder'
require './lib/numeral_adders/c_adder'
require './lib/numeral_adders/xc_adder'
require './lib/numeral_adders/xl_adder'
require './lib/numeral_adders/l_adder'
require './lib/numeral_adders/x_adder'
require './lib/numeral_adders/ix_adder'
require './lib/numeral_adders/iv_adder'
require './lib/numeral_adders/v_adder'
require './lib/numeral_adders/i_adder'

# A class for adding individual numerals
class NumeralAdder
  attr_reader :num_to_convert,
              :num_interpreter,
              :numeral

  def initialize(num_to_convert)
    @num_to_convert = num_to_convert
    @num_interpreter = NumberInterpreter.new(num_to_convert)
    @numeral = []
  end

  def add_numerals
    @numeral << m_adder.add_numerals.split('')
    @numeral << cm_adder.add_numerals.split('')
    @numeral << cd_adder.add_numerals.split('')
    @numeral << d_adder.add_numerals.split('')
    @numeral << c_adder.add_numerals.split('')
    @numeral << xc_adder.add_numerals.split('')
    @numeral << xl_adder.add_numerals.split('')
    @numeral << l_adder.add_numerals.split('')
    @numeral << x_adder.add_numerals.split('')
    @numeral << ix_adder.add_numerals.split('')
    @numeral << iv_adder.add_numerals.split('')
    @numeral << v_adder.add_numerals.split('')
    @numeral << i_adder.add_numerals.split('')
    flatten_numeral
  end

  private

  def flatten_numeral
    @numeral = @numeral.flatten
  end

  def m_adder
    MAdder.new(@num_interpreter.thousands)
  end

  def cm_adder
    CMAdder.new(@num_interpreter.hundreds)
  end

  def cd_adder
    CDAdder.new(@num_interpreter.hundreds)
  end

  def d_adder
    DAdder.new(@num_interpreter.hundreds)
  end

  def c_adder
    CAdder.new(@num_interpreter.hundreds)
  end

  def xc_adder
    XCAdder.new(@num_interpreter.tens)
  end

  def xl_adder
    XLAdder.new(@num_interpreter.tens)
  end

  def l_adder
    LAdder.new(@num_interpreter.tens)
  end

  def x_adder
    XAdder.new(@num_interpreter.tens)
  end

  def ix_adder
    IXAdder.new(@num_interpreter.units)
  end

  def iv_adder
    IVAdder.new(@num_interpreter.units)
  end

  def v_adder
    VAdder.new(@num_interpreter.units)
  end

  def i_adder
    IAdder.new(@num_interpreter.units)
  end
end

I'm thinking I need to separate the private class creations into their own class, but i'm not sure how.

Any tips?

To start out with all of the

require './lib/numeral_adders/<lib>

should be moved to a separate file like/lib/number_interpreter

Moving on, looking at repetitive parts of your code. The add_numerals method has a lot of lines like this:

@numeral << <type>_adder.add_numerals.split('')

and you have methods like this:

def <type>_adder
  <type>Adder.new(@num_interpreter.<unit>)
end

You can make this DRY by enumerating over a list defined elsewhere. For example:

# in the lib/number_interpreter.rb file
class NumberInterpreter
  Adders = {
    MAdder => :thousands,
    CMAdder => :hundreds
    # ...
  }
end

# in the main file (numeral_adder.rb)

def add_numerals
  NumberInterpreter::Adders.each do |klass, unit|
    @numeral << adder(klass, unit).add_numerals.split('')
  end
  flatten_numeral
end

def adder(klass, unit)
  klass.new(@num_interpreter.send(unit))
end

Important concepts here include setting a class as a hash key then initializing it using new later on. It also uses send for programmatic method invocation. You're writing a generic adder class to make all that repetition unnecessary - its arguments are a class to initialize and a unit to convert the results with.

By the way your flatten_numeral is so simple that it'd be better to not make it a separate method. The flatten would probably be unnecessary if you use concat instead of << (shovel):

@numeral.concat adder(klass, unit).add_numerals.split('')


Floaty bars module, need improvement? Here is my attempt at a floaty Bar module, used in a mobile application. There are several "bars", which stick to the top of the browser window once they are passed. When the next bar is reached, it takes over that sticky position...
Based on: http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-css.html

CMBi.floatyBar = (function(){
    var dayGroups = [];

    function getPositions() {
        var that = this;
        $.each( $('.day-group'), function(i, day) {
            if ($(this).length >= 1) {
                // Add the initial starting Y position to the object
                this.initialYPosition = $(this).offset().top;
                that.dayGroups[i] = this;
            }
        });
    }

    function setPositionsOnScroll() {
        var _daygroups = dayGroups, that = this;

        if ( window.scrollY < _daygroups[0].initialYPosition) {
            this.restoreInitialPosition(_daygroups[0]);
        }

        for ( var i = 0; i < _daygroups.length; i++ ) {
            // Get the next floaty bar position
            var _nextYposition = _daygroups[i+1] ? _daygroups[i+1].initialYPosition : config.vars.docHeight;
            // Between two bars, or betweem the last bar and the end of the doc
            if ( window.scrollY > _daygroups[i].initialYPosition && window.scrollY < _nextYposition) {
                // Stick the bar to the top
                that.setTop(_daygroups[i]);
                // Restore initial positions of the other bars
                $.each(_daygroups, function(index, day) {
                    if (index !== i) {
                        that.restoreInitialPosition(day);
                    }
                });
            }
        }
    }

    function setTop(element) { // Called when it's time for the floaty bar to move
        var _yPos = window.scrollY - element.initialYPosition;
        element.style['-webkit-transform'] = 'translateY(' + _yPos + 'px)';
    }

    function restoreInitialPosition(element) { // Called when the floaty bar is dismissed
        var _yPos = 0;
        element.style['-webkit-transform'] = 'translateY(' + _yPos + 'px)';
    }

    return {
        init : getPositions,
        setPositions : setPositionsOnScroll
    };

}());

What I tend to do in these situations is have two states for the floaty thing:

When it's not in "stay on the page" mode, it has position:relative.
When the page is scrolled down enough, it gets position:fixed and stays on the page.

It is not animation intensive at all,  it's more like the way gmail used to be before the recent changes. You only change the element's style when the page scrolls up or down past a certain point, but most scroll events you just ignore.


C - A function that calculates the integral of a polynomial I have written a simple function which takes an array of coefficients of a polynomial and then integrates it. My polynomial is represented like this:
$$polynomial[0] + polynomial[1]x + polynomial[2]x^2 + \dots + polynomial[n]x^n$$
And its integral will become:
$$polynomial[0]x + \frac 1 2 polynomial[1]x^2 + \frac 1 3 polynomial[2] x^3 + \dots + \frac{1}{n+1}x^{n+1}$$

#include <stdio.h>

void integrate(double *polynomial, double *buff, int number_of_terms) {
    for(int i = 0; i < number_of_terms; i++) {
        buff[i+1] = polynomial[i] / (i+1);
    }
    buff[0] = 0;
}

int main(void) {
    double polynomial[4] = {1, 2, 3, 4}; // 1 + 2x + 3x^2 + 4x^3
    double buff[5];
    integrate(polynomial, buff, 4);
    for(int i = 0; i < 5; i++) {
        printf("%f, ",  buff[i]);
    }
    //Output: 0.000000, 1.000000, 1.000000, 1.000000, 1.000000
    //0 + x + x^2 + x^3 + x^4
}

The problem with my solution is that I need  to set the value at index zero manually - I don't think this is a good practice and therefore would like to somehow wrap the 0th index into the formula in the loop. Is there an easy way to do this?

buff is not a meaningful name. Call it integral perhaps?
I'd use a more mathematical degree rather than number_of_terms.
In your approach (going from lowest to highest degree) polynomial and buff may never overlap. restrict them:

void integrate(double * restrict polynomial, double * restrict buff, int number_of_terms)

I see no other way to deal with the integration constant but passing it as a separate parameter.


Optimize DriveSpace Checker I recently wrote my first C# app that's goal it to take a drive letter and output a CSV list of some basic information. TOTALSPACE,FREESPACE,STATUS.

I've been wondering If it would be possible to make this application even faster. Got any good suggestions?

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

namespace drivespace
{
class Program
{
    static void Main(string[] args)
    {
       //"PATHTOEXE\drivespace.exe" drive-C:
        foreach (String arg in args)
        {
            String[] parts = arg.Split('-');
            if (parts[0].Equals("drive"))
            {
                long toalspace = 0;
                long freespace = 0;
                string status = "NOTFOUND";

                foreach (DriveInfo drive in DriveInfo.GetDrives())
                {
                    if (drive.Name == parts[1] + ":\\")
                    {
                        if (drive.IsReady)
                        {
                            toalspace = drive.TotalSize;
                            freespace = drive.TotalFreeSpace;
                            status = "READY";
                        }
                        else
                        {
                            status = "NOTREADY";
                        }
                        break;
                    }
                }
                //TOTALSPACE,FREESPACE,STATUS
                Console.WriteLine(toalspace.ToString() + "," + freespace.ToString() + ',' + status);
            }
        }
    }
}
}

https://github.com/keverw/drivespace is the Github page, it might have some more useful info.

It is possible to make the application faster (but I am not sure that you will notice the difference unless you call the application with many arguments and have many drives). The main problem with the code is that you iterate through all the arguments, and for each argument you iterate through all the drives until you find the matching drive-letter.

So if the the application is called with an unknown drive-letter 10 times (as in "PATHTOEXE\drivespace.exe" drive-X drive-X drive-X drive-X ... and if you have 15 drives mounted, then DriveInfo.GetDrives() will be called 10 times and the line if (drive.Name == parts[1] + ":\\") will be executed 150 times. To avoid this you could store the drive information in a dictionary and then just lookup the matching drive in near constant time.

Notice below that I have changed the format of the arguments to the application to DriveSpace.exe C D X to avoid the parsing of the individual argument.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Drivespace
{
    class Program
    {
        static void Main(string[] args)
        {
            var allDrives = DriveInfo.GetDrives().ToDictionary(drive => drive.Name);

            foreach (String arg in args)
            {
                DriveInfo driveInfo;
                if (allDrives.TryGetValue(arg + @":\", out driveInfo))
                {
                    if (driveInfo.IsReady)
                    {
                        WriteOutput(driveInfo.TotalSize, driveInfo.TotalFreeSpace, "READY");
                    }
                    else
                    {
                        WriteOutput(0, 0, "NOTREADY");
                    }
                }
                else
                {
                    WriteOutput(0, 0, "NOTFOUND");
                }
            }
        }

        private static void WriteOutput(long totalSize, long freeSpace, string status)
        {
            Console.WriteLine(String.Format("{0},{1},{2}", totalSize, freeSpace, status));
        }
    }
}


Quadratic Calculator I am about a month into learning Java and I'm just looking for some comments on my code.  Specifically, I would like to know if I'm being as efficient as I can be.  This is the most complex thing I've come up with so far (that works) and I wanted some feedback on my developing coding style.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    double numOne, numTwo, numThree, negativeB,
            discriminant, divisor, sqRtDisc, dividendPlus,
            dividendMinus;

    System.out.println("Enter the value for A: ");
    numOne = sc.nextFloat();

    System.out.println("Enter the value for B: ");
    numTwo = sc.nextFloat();

    System.out.println("Enter the value for C: ");
    numThree = sc.nextFloat();

    negativeB = -numTwo;
    discriminant = (numTwo * numTwo) - 4 * numOne * numThree;
    divisor = 2 * numOne;
    sqRtDisc = Math.sqrt(discriminant);

    System.out.println(" ");

    if (sqRtDisc > 0) {
        dividendPlus = ((negativeB + sqRtDisc) / divisor);
        dividendMinus = ((negativeB - sqRtDisc) / divisor);

        System.out.println("x = " + dividendPlus);
        System.out.println("x = " + dividendMinus);
    } else {
        System.out.println("x = " + (negativeB / divisor) + " + "
                + (Math.sqrt(-discriminant) / divisor) + "i");
        System.out.println("x = " + (negativeB / divisor) + " - "
                + (Math.sqrt(-discriminant) / divisor) + "i");
        System.out.println(" ");
    }

}

Bugs

You are losing precision by calling sc.nextFloat() instead of sc.nextDouble().

If the equation has complex roots, Math.sqrt(discriminant) will crash.

Style

You are using too many variables to easily keep track of them mentally.  Also, it's better to avoid a giant block of declarations like your

double numOne, numTwo, numThree, negativeB,
        discriminant, divisor, sqRtDisc, dividendPlus,
        dividendMinus;

We know that we need to store at least a, b, and c, so let's start there.  Why not use the conventional terminology instead of numOne, numTwo, numThree?

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Enter the value for A: ");
    double a = sc.nextDouble();

    System.out.println("Enter the value for B: ");
    double b = sc.nextDouble();

    System.out.println("Enter the value for C: ");
    double c = sc.nextDouble();

from there, the next important calculation is the discriminant, and optionally, its square root and the divisor.

    double discriminant = (b * b) - 4 * a * c;
    double divisor = 2 * a;

From there, you could go straight to formatting.  I suggest System.out.printf() for readability.

    if (discriminant < 0) {         // Complex roots
        System.out.printf("x = %d + %d i\n",
                          -b / divisor, Math.sqrt(-discriminant) / divisor));
        System.out.printf("x = %d - %d i\n",
                          -b / divisor, Math.sqrt(-discriminant) / divisor));
    } else {
        System.out.println("x = " + (-b + Math.sqrt(discriminant)) / divisor);
        System.out.println("x = " + (-b - Math.sqrt(discriminant)) / divisor);
    }
}


Modularized JavaScript event handler to increment counters In the following code we use the function Incrementer (capitalized for clarity, despite that it's to be used without new), to instantiate a number.

Incrementer provides a method increment to augment a counter in a span. We have two such counters, and so we define Incrementer to avoid code duplication (although it would be nice to program always like this, even in the absence of the worry of duplication).

function Incrementer(name, value) {
    let that = {};

    // Constructor
    that.name = name;
    let mydiv = document.getElementById('mydiv');
    mydiv.appendChild(document.createElement('br'));
    that.span = document.createElement('span');
    that.span.id = '#num' + name;
    that.span.innerHTML = value;
    mydiv.appendChild(that.span);

    that.increment = function() {
        var i = parseInt(that.span.textContent) + 1;
        that.span.innerHTML = i;
    }
    return that;
}
var incrementer1 = Incrementer('one', 10);
var incrementer2 = Incrementer('two', 20);

function double_increment() {
    incrementer1.increment();
    incrementer2.increment();
}

    <button id="inc" onclick="double_increment()">Increment</button>

The function double_increment() is then used to increment both numbers.

I'm seeking critique of this code, in particular:

The block marked "Constructor" is directly inside the function Incrementer rather than in a function called Constructor. What is the right basis for cleaner code?
The function double_increment() seems awkward. It exists at the global scope merely to respond to events (from user input in general, whether a button or otherwise). Is this an adequate basis for a (larger) code base?

disclaimer: "bad" is simply a way of saying it's not the best way.

If we were in the early 2000s this would probably be relatively clean code, however javascript has advanced a lot since then (current version: es6)

Take some time to check what's new.

Best practices today is to completely separate HTML / JS / CSS (unless you're using vue, react, angular)

Cleaner code
Logic separation
Reusability
Easier to maintain

So the following should not appear in your HTML.

/// bad
onclick="double_increment()"

/// good
const button = document.getElementById("some_id");
button.addEventListener("click", double_increment);

There is always a better alternative than
 and it's not semantic

Don't use it.

const before let and let before var

Always declare your variables with const by default. If you're ok with the variable mutating then use let. Don't use var unless you know what you're doing and you actually need it.

note: pushing an element to an array (declared with const) does not mutate the variable, just the array. Thus no error.

Do not hardcode your html element id in your function.

function Incrementer(name, value) {
   /// bad
   let mydiv = document.getElementById('mydiv');
}

It either needs to be sent via the parameter or accessed statically using class

class Incrementer {
   /// still bad though
   static target = "mydiv"
}

Object methods should do what their name infers.

Here, the increment function is supposed to increment the variable, but it does more than that.

Gets the text value of the span
Parses the text value
Increases by one
Updates the UI

(1) is hacky
(2) completely unneeded
(3) the actual thing your function is supposed to do
(4) updates UI ? not what your function says it does

/// bad
that.increment = function() {
        var i = parseInt(that.span.textContent) + 1;
        that.span.innerHTML = i;
}

/// better
that.i = value;

//increments value
that.increment = function() {
        that.i++;
}

//updates UI
that.update = function(){
        that.span.innerHTML = that.i;
}

// Method that should be called on button click
that.handleOnClick = function(){
   that.increment();
   that.update();
}

A double_increment function doesn't need to exist. Each Incrementer should add an event listener to the button click.

/// bad
function double_increment() {
    incrementer1.increment();
    incrementer2.increment();
}

See next section add event listener for solution

Using class and working example

es6 has introduced class

  JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

Thus your Incremental function should be a class instead.

class Incrementer {

  constructor(incrementId, options) {

    const {
      name  = "N/A",
      value = 0,
      target
    } = options;

    this.name     = name;
    this.counter  = value;
    this.view     = document.createElement("span");

    this.view.id = `#num_${name}`

    const button = document.getElementById(incrementId);
    button.addEventListener("click", ()=>this.handleOnClick())

    this.update();

    const container = document.getElementById(target);
    container.appendChild(this.view);
  }

  handleOnClick(){
    this.increment();
    this.update();
  }

  increment() {
    this.counter++;
  }

  update() {
    this.view.innerText = this.counter;
  }
}

const incrementer1 = new Incrementer(
  "increment",
  {name: "Hello World", value: 3, target: "container"}
);

const incrementer2 = new Incrementer(
  "increment",
  {name: "Hello World", value: 0, target: "container"}
)
#container {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  align-items: center;
  background-color: darkblue;
}

#container > span {
  padding: 10px;
  background-color: lightblue;
}
<button id="increment">Increment</button>


Caesar cipher implementation I am not very familiar with JavaScript and I'am a little confused with the object oriented peculiarities of it. I am trying to create a Caesar shift using the concepts of objects, methods and properties in JavaScript. I am using an HTML form to take input from user and OnClick return the encoded cipher text to user. This is what I have. I'm pretty much sure about my logic but I guess my object creation and method calls fall through. Am I doing it right?

<form>
Enter Plaintext : <input type = "text" name = "plaintext" id = "plaintext">
Enter Shift:      <input type = "text" name = "shift" id = "shift">
 --How do I get the input from here and create my caesar object and pass the constructor the shift from this text box?
<input type="button" value="Encode" onclick ="encode()"> --How do I call the encode() method with input from the plaintext text box?
</form>

Your code is reviewable, even if it does not work, from a once over:

Indent your code (!!), this is bad:

function Caesar(order){
this.order = order;
this.encode = encode;
function encode(input){
this.output = '';
for (var i = 0; i < input.length; i++) {
var this.c = input.charCodeAt(i);
if      (this.c >= 65 && this.c <=  90) this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65);  // Uppercase
else if (this.c >= 97 && this.c <= 122) this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97);  // Lowercase
else   this.output += input.charAt(i);
}
return answer.innerHTML= output;
 }

This is better:

function Caesar(order){
    this.order = order;
    this.encode = encode;
    function encode(input){
        this.output = '';
        for (var i = 0; i < input.length; i++) {
            var this.c = input.charCodeAt(i);
            if (this.c >= 65 && this.c <=  90)
                // Uppercase
                this.output += String.fromCharCode((this.c - 65 + this.order) % 26 + 65);
            else if (this.c >= 97 && this.c <= 122)
                // Lowercase
                this.output += String.fromCharCode((this.c - 97 + this.key) % 26 + 97);
            else
                this.output += input.charAt(i);
        }
    return answer.innerHTML= output;
}

Caesar is an unfortunate name

It does not really say what it does ( one can guess )
it should not start with a capital C, it is not a constructor

The Caesar is completely wrong

it puts encode in this.encode and then never uses this.encode
if encode were called, it set this.output but then in the end you put output in answer.innerHTML
you try to access answer, but you never declared it with var, much less pointed it to the answer element with getElementById

You hardcode magical numbers

Some developers know 65 is A, you should put a comment about that
Same for 97 , 26 and 122

order -> what does order do ? Should be commented, it is not obvious
onclick ="encode()" <- This is very old skool ( bad ), the correct way is using an addEventListener for load and in there use an addEventListener for click


Executing a file through a swing button I am making a Swing application for light local database management and I have the button Run XAMPP.

When that button is pressed this code is executed:

private void jRunXAMPPButtonActionPerformed(java.awt.event.ActionEvent evt)
    {
        String[] paths = {"C:\\xampp\\xampp-control.exe",
            "C:\\Program Files\\xampp\\xampp-control.exe",
            "C:\\Program Files (x86)\\xampp\\xampp-control.exe"};

        for (String path : paths) {
            final File file = new File(path);

            if (file.exists()) {
                try {
                    Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
                } catch (IOException e) {
                    continue;
                }
                return;
            }
        }
        Helper.printErrln("xampp-control.exe was not found or is corrupt!"); // Prints error in red
    }

I basically have the three possible paths that xampp could be at and I go through them and check if the file exists and can be executed. If not then it prints the error that the file could not be found or is corrupt.

Do you have any tips for my code? Any better way of doing this and I'm especially concerned that my error handling is not that great.

Give your method a proper name. These auto-generated names are pure terror!
You can import ActionEvent directly, no need to reference it with the entire package name.
Your formatting is unusual at best, I'd call it bad. I know this is, for some reason, the preferred way to set braces in the Linux kernel code, but this is Java, not C.
You are using hard-coded file paths. Absolute no-go. What if the user named his main partition D or installed xampp somewhere else – or is using Mac or Linux?
Why are you storing the result in Process p if you never use that variable?
" // Prints error in red" is a comment that is both completely useless (why do I need to know this right then and there?) and will rot faster than you can imagine.


Recursive directory copy program A little while ago, I had to write a little C# application to recover my HDD data (full context on this question)

To answer my problem I developed a console application which job was to recursively copy the entire folder tree of my HDD.

The code can be seen below :

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

namespace CopyCat
{
    class Program
    {
        private static long _fileCount = 0;
        private static long _byteCount = 0;
        private static long _byteProgress = 0;
        private static ProgressBar _progressCount = new ProgressBar();

        static void Main(string[] args)
        {
            Directory.Exists(args[0]);
            Directory.Exists(args[1]);

            FileDiscovery(args[0]);
            FileCopy(args[0], args[1]);

            Console.ReadLine();
        }

        static void FileCopy(String source, String dest)
        {
            try
            {
                foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.TopDirectoryOnly))
                {
                    try
                    {
                        if (file == null) continue;

                        var oFile = File.OpenRead(file);
                        var dFile = File.Open(Path.Combine(dest, Path.GetFileName(file)), FileMode.Create,
                            FileAccess.ReadWrite);
                        oFile.CopyTo(dFile, 104857600);

                        oFile.Close();

                        dFile.Flush();
                        dFile.Close();

                        _byteProgress += new FileInfo(file).Length;

                        _progressCount.Report((double)_byteProgress / (double)_byteCount);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("[COPY][ERROR] : Couldn't copy file  : {0} => {1}", file, e.Message);
                    }
                }
                foreach (var directory in Directory.EnumerateDirectories(source, "*", SearchOption.TopDirectoryOnly))
                {
                    if (directory == @"G:\$RECYCLE.BIN") continue;
                    var dir = Path.GetFileName(directory);
                    if (!Directory.Exists(Path.Combine(dest, dir)))
                    {
                        Directory.CreateDirectory(Path.Combine(dest, dir));
                    }

                    FileCopy(directory, Path.Combine(dest, dir));
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("[COPY][WARNING] : Couldn't open directory  : {0}", source);
            }
        }

        static void FileDiscovery(String dir)
        {
            try
            {
                foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.TopDirectoryOnly))
                {
                    _fileCount++;
                    _byteCount += new FileInfo(file).Length;
                }
                foreach (var directory in Directory.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly))
                {
                    FileDiscovery(directory);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("[DISCOVERY][WARNING] : Couldn't open directory : {0}", dir);
            }
        }

        static String HumanReadableByteCount(long bytes, Boolean si = false, int precision = 2)
        {
            int unit = si ? 1000 : 1024;
            if (bytes < unit) return bytes + " B";
            int exp = (int)(Math.Log(bytes) / Math.Log(unit));
            String pre = (si ? "kMGTPE" : "KMGTPE")[(exp - 1)] + (si ? "" : "i");
            return String.Format("{0} {1}{2}", Math.Round(bytes / Math.Pow(unit, exp), precision), pre, si ? "b" : "B");
        }
    }
}

(Using a custom ProgressBar)

I wanted to know specifically how I could improve the copying speed.

This

Directory.Exists(args[0]);
Directory.Exists(args[1]);

doesn't serve any purpose because you aren't evaluating the returned boolean value. In fact its more dangerous to use it with the args not checked for null at all. Your application will just crash if the application is called using only one or no argument at all.

The static void FileDiscovery() method would benefit from a better name like CalculateDirectorySize() and by returning a long instead of void.

Another point to mention is that the DirectoryInfo class contains the method GetFileSystemInfos() which would lead to the following change

    private static long CalculateDirectorySize(String dir)
    {
        long directorySize = 0;
        var dirInfo = new DirectoryInfo(dir);
        try
        {
            foreach (var fileInfo in dirInfo.GetFileSystemInfos("*", SearchOption.TopDirectoryOnly))
            {
                directorySize += fileInfo.Length;
            }

            foreach (var directory in Directory.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly))
            {
               directorySize += CalculateDirectorySize(directory);
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine("[DISCOVERY][WARNING] : Couldn't open directory : {0}", dir);
        }
        return directorySize;
    }

I have added private access modifier to the method, because it is a good habit to add one.

Because _fileCount is no where used I have removed it.

The FileCopy() method is using a strange way to copy the files by reading and writing them using FileStream's.

A more idiomatic way would be to use one of the overloaded File.Copy() methods. This methods are doing under the hood the same like your code but the streams are properly closed if any exception occurs.
Directory.CreateDirectory() can be called regardless if the directory exists or not. You can just skip the check for Exists().
Having three times Path.Combine(dest, dir) won't be necessary if the result is stored in a variable.
Instead of calling GetFileName() for a directory you should call GetDirectoryName()

this would result in the following change

    private static void FileCopy(String source, String dest)
    {
        try
        {
            foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.TopDirectoryOnly))
            {
                try
                {
                    File.Copy(file, Path.Combine(dest, Path.GetFileName(file)));

                    _byteProgress += new FileInfo(file).Length;

                    _progressCount.Report((double)_byteProgress / (double)_byteCount);
                }
                catch (Exception e)
                {
                    Console.WriteLine("[COPY][ERROR] : Couldn't copy file  : {0} => {1}", file, e.Message);
                }
            }
            foreach (var directory in Directory.EnumerateDirectories(source, "*", SearchOption.TopDirectoryOnly))
            {
                if (directory == @"G:\$RECYCLE.BIN") continue;

                var dir = Path.GetDirectoryName(directory);
                var destination = Path.Combine(dest, dir)

                Directory.CreateDirectory(destination);

                FileCopy(directory, destination);
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine("[COPY][WARNING] : Couldn't open directory  : {0}", source);
        }
    }

Based on the comment

  I was aware of the File.Copy() method at the time of writing the application BUT (and that's why I included the context) this method was throwing the same error as my explorer when used : that the file was not accessible and/or corrupted.

I would like to suggest to only use this kind of copy operation if the File.Copy() method throws an IOException having its own method like so

private static readonly int blockSize = 104857600;
private static bool SafeFileCopy(string source, string destination) {

    try
    {
        using(var sourceStream = File.OpenRead(source))
        using(var destinationStream = File.Open(destination, FileMode.Create,
                            FileAccess.ReadWrite))
        {
            sourceStream.CopyTo(destinationStream, blockSize);
            return true
        }

    }
    catch (Exception ex)
    {
        // do some logging
    }
    return false;

}

Resulting in the former foreach like so

           foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.TopDirectoryOnly))
            {
                string destinationFile = Path.Combine(dest, Path.GetFileName(file));
                try
                {
                    File.Copy(file, destinationFile);

                    _byteProgress += new FileInfo(file).Length;

                    _progressCount.Report((double)_byteProgress / (double)_byteCount);
                }
                catch (IOException ioex)
                {
                    if (!SafeFileCopy(file, destinationFile))
                    {
                         // do some logging here
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[COPY][ERROR] : Couldn't copy file  : {0} => {1}", file, e.Message);
                }
            }

Basically you should only catch exceptions which you can handle or which you only need to log/swallow. But you should always catch specific exceptions only. Catching Exception itself is a bad habit so for the SafeFileCopy() this would be for you to change.


Webcrawler for a car forum I've been experimenting more with webcrawling and hence have started to get a better understanding compared to my previous questions. Right now, my code scraps from a car forum on each page and iterates through every pages. What would you recommend to improve on?

import requests
from bs4 import BeautifulSoup, SoupStrainer
import pandas as pd

list_topic = []
list_time = []

SESSION = requests.Session()

def get_response(url):  # Gets the <html> structure from the website #
    response = SESSION.get(url)
    soup = BeautifulSoup(response.text, 'lxml',
                         parse_only=SoupStrainer('ul', {'class': 'posts posts-archive'}))
    return soup

def iteration(url, max_page=52):
    starting_page = 1
    while starting_page <= max_page:
        ## formats the new URL etc (https://paultan.org/topics/test-drive-reviews/page/1) ##
        new_url = url + f"page/{starting_page}"
        data = get_response(new_url)
        get_reviews(data)
        ## iteration starts ##
        starting_page += 1

def get_reviews(response):
    for container in response('article'):
        title = container.h2.a.text
        time = container.time.text
        list_topic.append(title)
        list_time.append(time)
    else:
        None

def create_pdReview():
    return pd.DataFrame({'Title': list_topic, 'Time': list_time})

if __name__ == '__main__':
    URL = 'https://paultan.org/topics/test-drive-reviews/'
    print(iteration(URL))
    print(create_pdReview())

I've been wondering; would using yield improve the efficiency and simplicity of the code? How would it be done? Because I've been trying to learn from my previous inquiries that has been answered on earlier. Here is a similar question and I'm trying to put to practice what has been recommended so far.

When we are discussing performance of a particular piece of code, it's important to recognize bottlenecks and major contributors to the runtime of the program.

In your particular case, even though you've applied some optimizations like SoupStrainer speed-up for HTML parsing, the synchronous nature of the script is the biggest problem by far. The script is processing pages one by one, not getting to the next page until the processing for the current page is finished.

Switching to an asynchronous approach would be the natural next step in your optimizations. Look into using third-party frameworks like Scrapy or, if you are adventurous, things like asyncio or grequests.

You could apply one more optimization to your current script which should help you optimize the "crawling/scraping" part - instead of using requests.get(), initialize session = requests.Session() and use session.get() to make requests (documentation). This would allow the underlying TCP connection to be re-used for subsequent requests resulting in a performance increase.


Sorting a 2-dimensional array with counting sort The task I'm solving is:

Sort a list by its keys
Print out the corresponding values on one line separated by whitespace
Replace the values of the first half of the input to "-"
Use Counting Sort

The following code works, but times out when given 1 million entries:

public class Solution {

static String[] countingSort(String[][] arr) {
    String[] result = new String[arr.length];
    int[] count = new int[100];
    for(int i=0;i<arr.length;i++) {
        count[Integer.parseInt(arr[i][0])]++;
    }
    for(int i=1;i<count.length;i++) {
      count[i] += count[i-1];
    }
    for(int i=arr.length-1;i>=0;i--) {
        result[count[Integer.parseInt(arr[i][0])]-1] = arr[i][1];
        count[Integer.parseInt(arr[i][0])]--;
    }
    return result;
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    String[][] arr = new String[n][2];
    for(int a0 = 0; a0 < n; a0++){
        int a = in.nextInt();
        arr[a0][0] = Integer.toString(a);
        if(a0<n/2) {
            String s =in.next();
            arr[a0][1] = "-";
        } else {
            String s = in.next();
            arr[a0][1] = s;
        }
    }
    in.close();
    String[] result = countingSort(arr);
    for(int i=0;i<result.length;i++) {
        System.out.print(result[i]+" ");
    }
}

input is being put into 2 dimensional array. values are being replaced with "-" for first half of the values. [array: arr]
Array is passed to method [array: arr, method: countingSort]
New array of size 100 is being created as the keys are 0 < key < 100 [array: count]
occurrences of each key are added in the newly created array [array: count]
values of the array are being accumulated [array: count]
the values of the corresponding key are being sorted into the result array according to the count array.
result is being returned.

Particular concerns:

How can the code be improved in order to increase performance and avoid timeout using counting sort?
Are there any other possibilities (sorting algorithms) which have higher performance (can solve the problem faster)?

Algorithm is ok, and there is nothing faster than counting sort. You just need to use single System.out.print:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++) {
    sb.append(result[i]).append(" ");
}
System.out.print(sb.toString());

It is faster than many separate calls;


Refactoring APEX to keep all database calls outside of for loops I have the following APEX code. I have been trying for hours to try and refactor it so that the SOQL query is outside of the for loop without any luck. Any ideas?

public static void ErrorIfWorklogsOverlap(List<Worklog__c> worklogs) {
        for (Worklog__c worklog : worklogs) {
            List<Worklog__c> timesheetWorklogs = [
                    SELECT
                            Id
                    FROM Worklog__c
                    WHERE Timesheet__c IN (
                            SELECT
                                    Id
                            FROM Timesheet__c
                    )
            ];
            DateTime worklogStartTime = worklog.Start_Time__c;
            DateTime worklogEndTime = worklog.End_Time__c;
            for (Worklog__c checkLog : timesheetWorklogs) {
                DateTime checkLogStart = checkLog.Start_Time__c;
                DateTime checkLogEnd = checkLog.End_Time__c;
                if (worklogStartTime > checkLogStart && worklogStartTime < checkLogEnd) {
                    worklog.Start_Time__c.addError('Worklog\'s start time is within the bounds of another worklog');
                } else if (worklogEndTime < checkLogEnd && worklogEndTime > checkLogStart) {
                    worklog.End_Time__c.addError('Worklog\'s end time is within the bounds of another worklog');
                } else if (worklogStartTime < checkLogStart && worklogEndTime > checkLogEnd) {
                    worklog.addError('Worklog overlaps another worklog');
                }
            }
        }
    }

A Worklog belongs to a Timesheet. This code is supposed to be checking if any of the Worklogs in the list worklogs overlaps another Worklog in the same Timesheet.

The first step would be to create a set of Timelogs that you are interested in and then query for the related Worklogs. Querying Timelogs and getting child Worklogs is probably the simplest solution.

Sample code:

Set<Id> timelogIds = new Set<Id>();
for (Worklog__c worklog : worklogs) {
  timelogIds.add(worklog.Timelog__c);
}

// Get timelogs and related child worklogs
Map<Id, Timelog__c> timeLogs = new Map<Id, Timelog__c>(
                             [SELECT Id,
                             (SELECT ... FROM Worklogs__r) //query child relationship
                             FROM Timelog__c
                             WHERE Id IN :timelogIds]);

for (Worklog__c worklog : worklogs) {
  List<Worklog__c> tempList = timeLogs.get(worklog.Timelog__c).Worklogs__r;
  // iterate through tempList to check for overlapping records
}


Handling an unknown number of arguments I'm writing a function that takes between one and three arguments (function callback [, number limit] [, regexp pattern]). Since the second two are both optional, I need to determine which argument is being passed when the function is supplied with only two. Below is my solution, but it seems overly verbose. Is there a cleaner way to do this?

  var get_queued_pages = function() {
    if(arguments>0){
        var callback = arguments[0];
        if(arguments.length == 3){ //all arguments are being passed
        var limit    = arguments[1];
        var pattern  = arguments[2];
        }
        else if(arguments.length == 2){ //only 2 arguments passed
        if(typeof(arguments[1]) == "number"){ //check if the second one is limit or pattern
            var limit = arguments[1];//no pattern defined; second argument is limit
        }
        }
        else{
        var limit = 1;
        }
    }
    //do stuff

}

function(cb,limit,pattern) {
    limit = typeof(limit) === "undefined" ? 1 : limit;
    //do stuff
}

Calling a function with less arguments than declared will just fill them with undefined. You can then check if that is the value, if so fill in your default ones.
The I have above will have the same affect as yours, there are always three variables (even in your code, Javascript variables are function scope, all of the var declarations are pulled to the top.).
The variables:
cb - unchanged
limit - set to 1 if not supplied
pattern - unchanged (undefined if not supplied)

EDIT:
I just saw your comment on reordering
you can do the following

  function foo(cb,limit,pattern) {
        if(limit instanceof RegExp) {
            pattern = limit;
            limit = 1;
        }
        else {
            limit = typeof(limit) === "undefined" ? 1 : limit;
        }
        //do stuff
    }


Fill ArrayList of String with empty String to maintain order of elements I'm writing a logic for converting data fetched from data base into CSV format.
The total number of header fields in CSV file are 14. Now it is possible that not all the field values are available. To give an example the data could be :

__________________________________________
|C1 | C2 | C3 | C4 | C5 |....|C12|C13|C14|
------------------------------------------
| V | V  | V  | V  | V  | V  | V |   |   |
| V | V  | V  | V  | V  |    |   |   |   |
| V | V  | V  | V  | V  |    |   |   |   |

Now I use an ArrayList to store the data in order of CSV fields. Also the values for first five columns (C1-C5) and the column C12 of CSV file are always available . The values for C6-C11 may or may not be available and they are stored in another list.And this will always be the case.Now to maintain the order, I have to insert empty string in ArrayList. So the code would be like -

ArrayList<String> csvRow = new ArrayList<String>();
// adding mandatory values (C1-C5)
csvRow.add(value); // there will be 5 such statement.
if(!optionalValList.isEmpty()) {
   // add the values to csvRow List for the C6-C11 fields
}else {
     csvRow.add(""); csvRow.add("");
     // do this for C6-C11 fields. So there
     // will be 6 such statements to add the empty string to List to
     // maintain the order of fields in CSV.
     csvRow.add(value); //adding the mandatory C12 field

 }

Note : Values C1-C5 and C12 are always available. And this will always be the case.

Now I don't like this approach. So I have come up with a logic using the lambda expression which will replace the logic in else block. It is as below :

 public List<String> createList(List<String> inputList){
   return IntStream.range(0,14)
            .mapToObj(i -> (i < inputList.size())? inputList.get(i):"")
            .collect(Collectors.toList());
 }

So the else block will be like :

else {
  csvRow = createList(csvRow);
  csvRow.set(11,value); // setting the column C12
}

Now I want get feedback on this approach. Is this abuse of the lambda features?
If yes how can I do this better.

Have you considered that ArrayList could be a little overkill?  If your list will always be a defined length, you could use a String[] to hold your data.  That way, the default value is always null and you don't have to worry about IndexOutOfBoundsExceptions.

You can still use constructs like for(String value : csvRow) to access your data, and if you need the finesse of the Collections API, you can always use Arrays.asList(csvRow).

If you're looking for NullPointerException protection, you can run Arrays.fill(csvRow, "") first to ensure that all indexes return an empty string unless otherwise populated.

String tmp = "placeholder";

String[] csvRow = new String[14];
Arrays.fill(csvRow, "");
// Add values for C1-C5 (dummy data)
for(int i=0;i<5;i++) csvRow[i] = tmp;

// Add in optional values
List<String> optionalValues = Collections.emptyList();
if(!optionalValues.isEmpty()) {
    int i = 6;
    for(Iterator<String> ovI = optionalValues.iterator();
            ovI.hasNext() && i < csvRow.length;i++){
        csvRow[i] = ovI.next();
    }
}
// Add C12 if not already present
if("".equals(csvRow[11])) csvRow[11] = tmp;


Nested while loop for getting db data. Timing out at random times because of the PHP. Any way to make this more efficient? So today I jumbled together a script that would get data from a database, from different tables and such.  I had wanted to just use simple ifs without the whiles, but I couldn't make it possible. The code I posted is useable but randomly times out when testing, and i'm afraid of how it would perform under stress.  Is there any way to improve this code to stop the timing out?

<?php
    $getConference = sprintf("SELECT DISTINCT confName, tableName FROM conferences WHERE enabled='1' ORDER BY id DESC");
    $catConference = mysql_query($getConference);
    while($conference = mysql_fetch_array($catConference)) {
        echo "
".$conference['confName']."

";
        $getExistingEvent = sprintf("SELECT DISTINCT event FROM " . $conference['tableName']);
        $catExistingEvent = mysql_query($getExistingEvent);
        while($existingevent = mysql_fetch_array($catExistingEvent)) {
            $getCat = sprintf("SELECT * FROM event WHERE id='".$existingevent['event']."'");
            $catResult = mysql_query($getCat);
            while($row = mysql_fetch_array($catResult)) {
                $getWinner = sprintf("SELECT place, name, event FROM 2012rlc WHERE event='".$row['id']."' ORDER BY place");
                $catWinner = mysql_query($getWinner);
                echo "

".$row['eventName']."

                    ";

                while($winner = mysql_fetch_array($catWinner)) {
                    echo "
".$winner['place']. " ".$winner['name']."
";
                }
                echo "

";
            }
        }
        echo "
";
    }
    mysql_free_result($catResult);
    mysql_free_result($catWinner);
    mysql_free_result($catExistingEvent);
    mysql_free_result($catConference);
?>

Some have asked for the database schema, which I have included below:

CREATE TABLE `2012rlc` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `place` varchar(4) default '',
    `name` varchar(255) default NULL,
    `event` int(5) default NULL,
    PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=52 DEFAULT CHARSET=latin1;

CREATE TABLE `conferences` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `confName` varchar(255) default NULL,
    `tableName` varchar(50) default NULL,
    `enabled` tinyint(1) default '0',
    PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

CREATE TABLE `event` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `eventName` varchar(255) default NULL,
    `teamEvent` tinyint(1) default '0',
    PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;

Output to EXPLAIN MySQL command:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  conferences ALL NULL    NULL    NULL    NULL    4   Using where; Using temporary; Using filesort

First of all, does you tables have indexes? If you run the queries with EXPLAIN on MySql console (for example EXPLAIN SELECT DISTINCT confName, tableName FROM conferences WHERE enabled='1' ORDER BY id DESC), does it show that it uses indexes?

I'm not sure that it's a real performance issue or not but the current mysql_free_result calls doesn't free all resources, just the last one because the code runs lots of queries in loops. You should put these calls immediately after the last use of the resource, for example:

while (...) {
    ...
    while($winner = mysql_fetch_array($catWinner)) {
        echo "<li>".$winner['place']. " ".$winner['name']."</li>";
    }
    // free $catWinner at the end of every iteration
    mysql_free_result($catWinner);
}

I don't think that (generally) a good design to create separate tables for (probably) the same type of records. Instead of creating separate tables for every conference, consider creating only one table. It should have a conferenceId attribute as well as the conferences table should have a conferenceId too (instead of the tableName attribute). (Don't forget the foregin keys.)

If I'm right, this conferenceId could be in the event table and you don't need separate conference tables at all. (Feel free to post your database schema too. It could be worth a new question.)

Using sprintf does not make any sense here and in the similar calls:

$getExistingEvent = sprintf("SELECT DISTINCT event FROM " . $conference['tableName']);

It's the same as

$getExistingEvent = "SELECT DISTINCT event FROM " . $conference['tableName'];

Or it could be

$getExistingEvent = sprintf("SELECT DISTINCT event FROM %s", $conference['tableName']);

where sprintf does the including/formatting.

Edit:

I'd create the following indexes:

ALTER TABLE `conferences` ADD INDEX `enabled`(`enabled`);
ALTER TABLE `2012rlc` ADD INDEX `event_id`(`event`);

I hope it helps.


Add one to a number represented as an array of digits I submitted this problem for an interview, and I was wondering if I could have done better. My solution works, and I solved in about 12-15 minutes. I feel like I did a bad job with the code.  Please be honest.

Here is the question:

  Given a non-negative number represented as an array of digits, plus
  one to the number. Also, the numbers are stored such that the most
  significant digit is at the head of the list.

In particular, what stumped me was the fact that I'd get the right answer, but have the initial index (at 0) in sometimes empty with the answer on the other half, and couldn't figure out a quick half to shift all the elements to the left without using extra storage.

public int[] plusOne(int[] digits) {
    int[] toRet=new int[digits.length+1];
    int[] temp=null;

    for(int i=toRet.length-1; i>=0; i--){
        if(i-1>=0){
            toRet[i]=digits[i-1];
        }
    }
    for(int i=toRet.length-1; i>=0; i--){
        if(toRet[i]+1 == 10){
            toRet[i]=0;
        }
        else{
            toRet[i] = toRet[i]+1;
            break;
        }
    }
    if(toRet[0]==0){
        temp = new int[toRet.length-1];
        for(int i=1; i<toRet.length;i++){
            temp[i-1] = toRet[i];
        }
       return temp;
    }
    else{
        return toRet;
    }

}

What you did well
I like that you have:

decently named varaibles
you use good backward looping through the data
the formatting and style is good.

Issues

you are doing a lot of manual copying... Arrays.copyOf() is your friend.
you should be declaring variables where you need them, not at the beginning of the method (temp).
the algorithm is not a natural fit for the problem.... too complicated, and that is why there is the odd offset in your results.

Alternative...
Consider this code alternative, which uses a standard adder-with-carry:
public static final int[] addOne(int[] digits) {
    int carry = 1;
    int[] result = new int[digits.length];
    for (int i = digits.length - 1; i >= 0; i--) {
        int val = digits[i] + carry;
        result[i] = val % 10;
        carry = val / 10;
    }
    if (carry == 1) {
        result = new int[digits.length + 1];
        result[0] = 1;
    }
    return result;
}

The carry is initialized with the value-to-add 1, and it is added to the least significant value.
If the overall addition results in a carry still, then we add a new digit to the result, and, because the sub being added is a 1, we can make assumptions about the result.
Edit:
My test code:
public static void main(String[] args) {
    System.out.println(Arrays.toString(addOne(new int[]{})));
    System.out.println(Arrays.toString(addOne(new int[]{1})));
    System.out.println(Arrays.toString(addOne(new int[]{9})));
    System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9})));
    System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9, 9})));
    System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 9})));
    System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 8})));
}

and my results:

[1]
[2]
[1, 0]
[4, 0, 0]
[4, 0, 0, 0]
[1, 0, 0, 0, 0]
[9, 9, 9, 9]


Custom implementation of the linq Zip operator for different length lists Based on my answer I have my implementation of linq Zip operator which operates on different length lists, and loops shortest list.

My implementation:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SO
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            List<String> listA = new List<string> {"a", "b", "c", "d", "e", "f", "g"};
            List<String> listB = new List<string> {"1", "2", "3"};

            var mix = listA.ZipNew(listB, (l1, l2) => new[] {l1, l2}).SelectMany(x => x);

            foreach (var m in mix)
            {
                Console.WriteLine(m);
            }
        }
    }

    public static class Impl
    {
        public static IEnumerable<TResult> ZipNew<TFirst, TSecond, TResult>(
            this IEnumerable<TFirst> first,
            IEnumerable<TSecond> second,
            Func<TFirst, TSecond, TResult> resultSelector)
        {
            using (IEnumerator<TFirst> iterator1 = first.GetEnumerator())
            using (IEnumerator<TSecond> iterator2 = second.GetEnumerator())
            {
                var i1 = true;
                var i2 = true;
                var i1Shorter = false;
                var i2Shorter = false;
                var firstRun = true;

                while(true)
                {
                    i1 = iterator1.MoveNext();
                    i2 = iterator2.MoveNext();

                    if (!i1 && (i1Shorter || firstRun))
                    {
                        iterator1.Reset();
                        i1 = iterator1.MoveNext();
                        i1Shorter = true;
                        firstRun = false;
                    }

                    if (!i2 && (i2Shorter || firstRun))
                    {
                        iterator2.Reset();
                        i2 = iterator2.MoveNext();
                        i2Shorter = true;
                        firstRun = false;
                    }

                    if (!(i1 && i2))
                    {
                        break;
                    }

                    yield return resultSelector(iterator1.Current, iterator2.Current);
                }
            }
        }
    }
}

And I wonder if this implementation could be improved somehow, what could be improved, for better readability or speed.

public static class Impl
    {
        public static IEnumerable<TResult> ZipNew<TFirst, TSecond, TResult>(

Names? The class would be more descriptive as something like LinqExtensions; the method something like ZipLooped.

            using (IEnumerator<TFirst> iterator1 = first.GetEnumerator())
            using (IEnumerator<TSecond> iterator2 = second.GetEnumerator())
            {
                var i1 = true;
                var i2 = true;
                var i1Shorter = false;
                var i2Shorter = false;
                var firstRun = true;

The iterators have useful names, but what does i1 mean? And why five variables to track the state of two iterators? IMO it would be simpler as

                var firstEnded = false;
                var secondEnded = false;

                while (true)
                {
                    if (!iterator1.MoveNext())
                    {
                        if (secondEnded) yield break;
                        firstEnded = true;
                        iterator1.Reset();
                        if (!iterator1.MoveNext()) yield break;
                    }
                    if (!iterator2.MoveNext())
                    {
                        if (firstEnded) yield break;
                        secondEnded = true;
                        iterator2.Reset();
                        if (!iterator2.MoveNext()) yield break;
                    }

                    yield return resultSelector(iterator1.Current, iterator2.Current);
                }

and the almost repeated code might be worth pulling out as an inner method:

                var firstEnded = false;
                var secondEnded = false;

                bool advance<T>(IEnumerator<T> it, ref bool thisEnded, bool otherEnded)
                {
                    if (it.MoveNext()) return true;
                    // `it` has done a full cycle; if the other one has too, we've finished
                    if (otherEnded) return false;
                    thisEnded = true;
                    // Start again, although if `it` is empty we need to abort
                    it.Reset();
                    return it.MoveNext();
                }

                while (true)
                {
                    if (!advance(iterator1, ref firstEnded, secondEnded)) yield break;
                    if (!advance(iterator2, ref secondEnded, firstEnded)) yield break;
                    yield return resultSelector(iterator1.Current, iterator2.Current);
                }

I notice that you've decided to yield break if either of the enumerables is empty. Would an exception be a better choice?


Splitting URL query string to key-value pairs I have a URL query string "key={value}&key2={value2}&key3={value3}" and have to produce a key-value pair of the string by splitting & and =. Also, I have to watch out for corner cases such that if a key isn't present do not add it to the hash map but if a value is missing the key can be added with an empty value. One way is to first split the string by & and finally by =. So this can be accomplished but having two passes. But I am attempting to accomplish this in one pass.

First idea: I came up with one pass using the split function, but it didn't account for corner cases.

public Map<String, String> splitString(String s) {
    // String s represents ParamAndMacro
    String[] split = s.split("=|\\&");
    int length = split.length;
    Map<String, String> maps = new HashMap<>();
    for (int i=0; i<length; i+=2){
          maps.put(split[i], split[i+1]);
     }
    return maps;
}

Second idea: One pass with certain conditions and using StringBuilder:

public Map<String, String> splitString(String s){
 Map<String, String> maps = new HashMap<>();
 int length = s.length();
 StringBuilder sb = new StringBuilder();
 String key = "";
 String value = "";

char prev = ' ';
for (int i=0; i<length; i++) {
    char a = s.charAt(i);
    if ( a != '=' && a != '&' && prev != a) {
           sb.append(a);
      }
    //finds a key
    else if( a == '=' && prev != a && prev != '&') {
          key = sb.toString();
          sb = new StringBuilder();
      }
    // finds a value and also ensuring a key is not empty
    else if (a=='&' && prev != a && prev != '=') {
          value = sb.toString();
          sb = new StringBuilder();
          maps.put(key, value);
            }
    // checks corner case to see if a value is empty
    else if (prev=='=' && a == '&') {
          value = "";
          maps.put(key, value);
          sb = new StringBuilder();
    }
   //how to check if a key is missing and skip to other pair

            prev = a;
    }
    return maps;
}

My concern is whether my code is efficient in terms of splitting and using StringBuilder. Please feel free to improve or give suggestions.

To decode the query string correctly, you must take care of percent-encoding, like %25 for a literal percent, or %C3%A4 for an ä (encoded as UTF-8). The canonical code for doing this is:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;

public class QueryStringDecoder {

    public static Map<String, String> decodeQueryString(String query) {
        try {
            Map<String, String> params = new LinkedHashMap<>();
            for (String param : query.split("&")) {
                String[] keyValue = param.split("=", 2);
                String key = URLDecoder.decode(keyValue[0], "UTF-8");
                String value = keyValue.length > 1 ? URLDecoder.decode(keyValue[1], "UTF-8") : "";
                if (!key.isEmpty()) {
                    params.put(key, value);
                }
            }
            return params;
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e); // Cannot happen with UTF-8 encoding.
        }
    }

    public static void main(String[] args) {
        System.out.println(decodeQueryString("&&&"));
        System.out.println(decodeQueryString("&&&a=b"));
        System.out.println(decodeQueryString("a=b&c=%26%25==&utf8=%E2%9C%93"));
        System.out.println(decodeQueryString("latin1=%FC"));
    }
}

I don't know why you prefer to do the parsing in a single pass. That would be possible, but the single-pass code must then behave exactly like the above code.
Furthermore, since this part of the code is probably not the bottleneck, there is no point in optimizing it for execution speed instead of readability.


Assigning atomic number based on atomic symbol I currently have the following code:

unsigned int symToZ(const std::string & sym){
    unsigned int atomicNum;
    if(sym == "H"){atomicNum = 1;}
    else if(sym == "He"){atomicNum = 2;}
    else if(sym == "Li"){atomicNum = 3;}
    else if(sym == "Be"){atomicNum = 4;}
    else if(sym == "B"){atomicNum = 5;}
    else if(sym == "C"){atomicNum = 6;}
    else if(sym == "N"){atomicNum = 7;}
    else if(sym == "O"){atomicNum = 8;}
    else if(sym == "F"){atomicNum = 9;}
    ...

    return atomicNum;
}

The code simply takes in a string sym (which is the atomic symbol, such as He, F, Au, and so on), and converts it to the respective atomic number. As you can see, it involves a lot of repeated code. For such simple code, I feel it is needlessly complex.

How can this be done more effectively?

The most efficient way is to use unordered_map since C++11:

int main(int argc, const char * argv[]) {
    std::unordered_map<std::string, unsigned int> symbol_to_number = {
        {"H",  1},
        {"He", 2},
        {"Li", 3},
        // And so on..
    };

    // Usage:
    std::cout << symbol_to_number["H"] << std::endl;
    return 0;
}

Above, you get the number out of a symbol in constant time which improves on going through a lot of if statements.


Interactive Linux upgrade script One year ago, I asked for a review of Simple Linux upgrade script in Bash.

Conditions are slightly changed, and/or more accurate:

Code readability for the code user, making it simple to adjust the script's behavior
Output readability for the script user, supposing it will run always in interactive form (this is sort of contradicting the original post)
Colored headings describing what exactly is the script doing
Attempt to correct things; well this one is hard to make, but let's suppose the two initial commands will do the trick
Clean-up old packages after successful update

I hereby add:

It must be a portable POSIX shell script
It must have a clear typed-in header for users to distinguish between different computers, if running this script on several machines. It could be a hostname, but I decided otherwise for personal purposes (I myself run it on 3 machines in sequence with SSH public key authentication)
It must, in the end, check if the Linux it is running on, is Mint. If so, it needs to offer a kernel upgrade (I chose the safest way through MintUpdate) - ask if the user wants to run it
I want it to pass ShellCheck.net without any warning

#!/bin/sh

red="\\033[1;31m"
green="\\033[1;32m"
yellow="\\033[1;33m"
blue="\\033[1;34m"
nocolor="\\033[0m"

print_newline()
{
    printf "\\n"
}

show_success()
{
    echo "${green}Success.${nocolor}"
    print_newline
}

show_error_and_exit()
{
    echo "${red}An error occured.${nocolor}"
    print_newline
    exit "$1"
}

error_handler()
{
    if [ "$1" -ne 0 ]
    then
        show_error_and_exit "$2"
    else
        show_success
    fi
}

ask_for_sudo_password()
{
    sudo sh -c ":"
}

is_it_linux_mint()
{
    return $(grep -i mint /etc/lsb-release > /dev/null 2>&1)
}

print_newline

echo "${blue}--------------------${nocolor}"
echo "${blue}Vlasta - Laptop Mint${nocolor}"
echo "${blue}--------------------${nocolor}"

print_newline

echo "${green}Step 0: enter password${nocolor}"

# in order to print information AFTER sudo password has been provided
ask_for_sudo_password

error_handler "$?" 1

echo "${green}Step 1: configure packages${nocolor}"
echo "${yellow}dpkg --configure -a${nocolor}"

sudo dpkg --configure -a

error_handler "$?" 2

echo "${green}Step 2: fix broken dependencies${nocolor}"
echo "${yellow}apt-get install --fix-broken${nocolor}"

sudo apt-get install --fix-broken

error_handler "$?" 3

echo "${green}Step 3: update cache${nocolor}"
echo "${yellow}apt-get update${nocolor}"

sudo apt-get update

error_handler "$?" 4

echo "${green}Step 4: upgrade packages${nocolor}"
echo "${yellow}apt-get upgrade${nocolor}"

sudo apt-get upgrade

error_handler "$?" 5

echo "${green}Step 5: upgrade packages with possible removals${nocolor}"
echo "${yellow}apt-get dist-upgrade${nocolor}"

sudo apt-get dist-upgrade

error_handler "$?" 6

echo "${green}Step 6: remove unused packages${nocolor}"
echo "${yellow}apt-get --purge autoremove${nocolor}"

sudo apt-get --purge autoremove

error_handler "$?" 7

echo "${green}Step 7: clean up${nocolor}"
echo "${yellow}apt-get autoclean${nocolor}"

sudo apt-get autoclean

error_handler "$?" 8

if is_it_linux_mint
then

    while true
    do
        echo "Do you want to check for kernel upgrade via MintUpdate?"
        read -r answer
        case "$answer" in
            [Yy]) :   ; break;;
            [Nn]) exit; break;;
               *) echo "Please answer Y or N.";;
        esac
    done

    echo "${green}Step 8: Linux Mint kernel upgrade${nocolor}"
    echo "${yellow}mintupdate${nocolor}"

    sudo /usr/bin/python3 /usr/lib/linuxmint/mintUpdate/mintUpdate.py show

fi

2018/04/24 edit

I missed an obvious bug: is_linux_mint is not implemented correctly. The results of a return on an empty output of a command substitution, with or without quotes, is implementation-defined:

  The value of the special parameter '?' shall be set to n, an unsigned decimal integer, or to the exit status of the last command executed if n is not specified. If n is not an unsigned decimal integer, or is greater than 255, the results are unspecified.

The fix is to remove the return and dollar-parentheses:

is_linux_mint()
{
    grep -i mint /etc/lsb-release >/dev/null 2>&1
}

#!/bin/sh

printc()
{
    fd=1
    color=0 # Black
    case "$1" in
        -info)
            color=4 # Blue
            ;;
        -ok)
            color=2 # Green
            ;;
        -warning)
            fd=2
            color=3 # Yellow
            ;;
        -error)
            fd=2
            color=1 # Red
            ;;
        *)
            ;;
    esac
    [ "$color" -ne 0 ] && shift
    printf '%s\n' "$(tput bold)$(tput setaf "$color")$@$(tput sgr0)" >&"$fd"
}

show_error_and_exit()
{
    if [ "$?" -ne 0 ]
    then
        printc -error 'An error has occurred.'
        echo
        exit "$step"
    fi
}

ask_for_sudo_password()
{
    sudo sh -c ':'
}

is_linux_mint()
{
    return "$(grep -i mint /etc/lsb-release >/dev/null 2>&1)"
}

mintupdate()
{
    if is_linux_mint
    then
        while true
        do
            echo 'Do you want to check for kernel upgrade via MintUpdate?'
            read -r answer </dev/tty
            case "$answer" in
                [Yy])
                    break
                    ;;
                [Nn])
                    exit
                    ;;
                *)
                    echo 'Please answer Y or N.'
                    ;;
            esac
        done
        sudo /usr/bin/python3 /usr/lib/linuxmint/mintUpdate/mintUpdate.py show
    fi
}

echo
printc -info '--------------------'
printc -info 'Vlasta - Laptop Mint'
printc -info '--------------------'
echo
step=0
trap show_error_and_exit EXIT
while IFS='#' read -r command description
do
    printc -ok "Step $step:$description"
    printc -warning "$command"
    step=$(( step + 1 ))
    set -e
    eval "$command"
    set +e
    printc -ok 'Success.'
    echo
done <<'EOF'
ask_for_sudo_password # enter password
sudo dpkg --configure -a # configure packages
sudo apt-get install --fix-broken # fix broken dependencies
sudo apt-get update # update cache
sudo apt-get upgrade # upgrade packages
sudo apt-get dist-upgrade # upgrade packages with possible removals
sudo apt-get --purge autoremove # remove unused packages
sudo apt-get autoclean # clean up
mintupdate # Linux Mint kernel upgrade
EOF

ShellCheck output:

$ shellcheck myscript

Line 26:
    printf '%s\n' "$(tput bold)$(tput setaf "$color")$@$(tput sgr0)" >&"$fd"
                                                     ^-- SC2145: Argument mixes string and array. Use * or separate argument.
                                                                     ^-- SC2039: In POSIX sh, >& is undefined.

Line 31:
    if [ "$?" -ne 0 ]
         ^-- SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.

SC2181 is a minor, irrelevant warning: the exit code can't be checked directly in this case.
SC2039 is a false positive for it couldn't detect the value of fd; just make sure that fd is always assigned a valid number here, which I have.
SC2145 is what I disagree with. See What is the difference between $* and $@?, from which I quote:

  "$*" expands to a single word "$1c$2c...". Usually c is a space, but it's actually the first character of IFS, so it can be anything you choose.

  "$@" expands to separate words: "$1" "$2" ...

Of course this depends on how you want to use printc: if you're only giving it strings to print, it's OK to use "$*"; if you're also passing it the format string, or don't want IFS to affect the output presentation, use "$@". Feel free to replace $@ with $* if you feel so inclined to clear this warning.

You forgot to enable interpretation of backslash escapes in echo with the -e option, so I didn't get colorful outputs on my openSUSE where the default for echo is to disable interpretation of backslash escapes. But it doesn't matter since options for echo aren't specified by POSIX. Also, the ANSI escape code is probably less portable, and definitely less readable, than the tput alternative, as a SO user noted.

I grabbed the printc function from my personal arsenal (with minor modifications) and put it here. Originally it didn't have the format string hard-coded in, but you always use it like echo in your code and I'm not about to define another function or add another option to get this behavior, so I sacrificed generality for convenience.

echo without any argument prints a newline, so you don't have to define a function to do just that.

The time frame between each prompt for a password by sudo is dependent on the sudoers policy, specifically the timestamp_timeout option, which can be set to 0 to always prompt for a password. Therefore, I'm not sure of the utility of your ask_for_sudo_password function when one can already type in the password on-demand, unless it is to test if sudo is available as a command, in which case it's better to write it in the same way as your is_it_linux_mint function and rename it to has_sudo or test_sudo.

Compare if is_linux_mint with if is_it_linux_mint, I think is_linux_mint is a better name.

There's no easy way to identify which Linux distribution is running on a user's system. /etc/os-release is a new standard, but for those without it, the most reliable way to find out, in general, is probably by parsing lsb_release -i, provided it is installed on the system.

I see some superfluous code in your case statement:

            [Yy]) :   ; break;;
            [Nn]) exit; break;;

It's probably done for stylistic reasons, but still I want to point out that : and the break after exit are not needed. On a side note, I prefer the shell equivalent of the Allman coding style, so I don't cramp up my case constructs into one line per pattern. But however you write your code, consistency is key.

Last but not least, you're repeating the same patterns throughout each step of the maintenance tasks, so I wrapped them in a while read loop reading from a here document. So now your while read loop, which I grouped inside a new function mintupdate, has to have its input redirected back to the controlling terminal, and rest assured that /dev/tty is required to exist by the POSIX specifications.

After the rewrite, it has become quite easy to adjust the script's behavior: you just add the commands you want to run, potentially wrapped inside functions, in sequential order in the here document. The descriptions are optional, and you can omit them by not adding #-style comments after the commands that they annotate. The # delimiter is chosen so one can easily copy the lines and run them on their terminal.


Readability & Maintainability

Right now your code is a bit hard to read.  A way to greatly help this would be to use better variable names.

Put the variable declarations to separate lines and initialize them to some value at the same time. From Code Complete, 2d Edition, p. 759:

  With statements on their own lines, the code reads from top to bottom,
  instead of top to bottom and left to right. When you’re looking for a
  specific line of code, your eye should be able to follow the left
  margin of the code. It shouldn’t have to dip into each and every line
  just because a single line might contain two statements.

You should declare your for loops as such:

for(int i = 0; i < size; ++i)

Note that this was introduced in the C99 standard.  There is no reason you should not be using this standard in your code.

Design

Group your variables in structs to make them more maintainable, a
good hint that you should be doing this is when you are passing in
9 parameters to your function.
Return the output vector; it makes your function easier to use.
You'll have to allocate the space in your method and free it
elsewhere.  This also eliminates the potential bug discussed below.
Don't cast malloc().
Right now you are using this loop to zero out temp (or at least part of it)

for (r = 0; r <= c - 1; r++){
    temp[r] = 0.0;
}

The original algorithm doesn't implement this in a separate loop, and I don't recommend you do either.  It's a loop in the code you don't need.
These lines:

temp[r] = temp[r] + Nu[k]*P[idx+r];
S[r] = S[r] + Nv[l]*temp[r];

Can be shortened to:

temp[r] += Nu[k]*P[idx+r];
S[r] += Nv[l]*temp[r];

Set those pointers you free()ed to NULL right after.  This prevents us from trying to access the data afterwards, which will result in undefined and usually catastrophic behavior.

Bug

Right now you are relying on the passed in values already stored in S[r] when you add Nv[l]*temp[r] to them.  In the original NURBS A3.5 algorithm, they are 0'ed out right before their use.  You could overwrite all these values to 0 with a memset() in our function and continue as is. However, overwriting something the user passes when we could've started from scratch is usually not expected behavior.

Create the array at the top of the function like you do with the other arrays, using calloc().


Client side authorization when retrieving from server I have an endpoint to retrieve the user's authorization based on Joseph Silber's Bouncer.
I have a global can() function. It creates a unique key based on the authorization request and sets an object's property based on that key.
can (ability, model = null, id = null) {
  const key = `${ability}_${model}_${id}`
  const params = {
    ability, model, id
  }

  axios.get(this.route('authorize', params))
    .then(res => {
      Vue.set(this.userAuthorizations, key, res.data.allowed)
    })
    .catch(err => this.showError(err.message))

  return key
}

data () {
  return {
    userAuthorizations: {}
  }
}

So in a template, I do something like...
<button v-if="userAuthorizations[can('create', 'users')]">
  Create User
</button>

There will be a delay while it's retrieving the result, but since the key doesn't exist it won't show a restricted thing.
It looks ugly to me, but it's the most sustainable and reusable way I could think to do it on the front-end. Thoughts? What's a better way?

Bearing in mind that it is a ecmascript-8 feature, instead of waiting for the promise to be fulfilled with a callback:

axios.get(this.route('authorize', params))
   .then(res => {
     Vue.set(this.userAuthorizations, key, res.data.allowed)
   })
   .catch(err => this.showError(err.message))

the code could wait until the response is retrieved using await:
async can (ability, model = null, id = null) {
  const key = `${ability}_${model}_${id}`
  const params = {
    ability, model, id
  }

  const response = await axios.get(this.route('authorize', params))
    .catch(err => this.showError(err.message))

  Vue.set(this.userAuthorizations, key, res.data.allowed)
  return res.data.allowed
}

Note that can() needs to be declared as async in order for await to be permitted inside of it.


Automatically run doctest every time program is run I would like this to happen every time I run a program from the command line. Is my approach Pythonic? I'm interested to know whether there is any problem with readability or correctness. Any general advice on better ways of doing things or potential problems are also welcome.

Although the main function is just an example, I'm looking for a review of the rest of the code, which I intend to append to all my existing programs and is therefore not just example code. I have included the example main function here as I used this to observe the different behaviour when including a passing or failing doctest. If any doctest fails, this will be printed to stdout and the program will not run. If all doctests pass, there is no output from the testing and the program runs as normal.

"""Auto doctest.

Code to run the doctests before the main code every time the code is run
from the command line. Uses assert so that running the code in optimised
mode will skip the testing.
"""

def main(arguments):
    """Perform the functions of the program.

    Example doctest:

        >>> 1 + 1
        2

    """
    print('The main function received the following arguments:')
    print(arguments)

def _doctests_pass():
    """Return True if all doctests pass, otherwise False."""
    import doctest
    failure_count, test_count = doctest.testmod()
    return failure_count == 0

if __name__ == '__main__':
    assert _doctests_pass()
    import sys
    main(sys.argv)

Make it a habit to run pyflakes and the pep8 tools on Python projects. pep8 finds some style violations in this code:

There should be two blank lines before global method declarations (main and _doctests_pass in your case)
There shouldn't be trailing whitespace at the end of line 3 and 4.

You can install pyflakes and pep8 using pip. See also the PEP8 documentation for more details on Python style.

By the way, I think running unit tests is a job for a Continuous Integration system, not something to do every time you run the code. The point of testing is to run after every code change. You're going way further, but it's completely pointless. If the code hasn't changed, then the repeated tests are just wasting CPU cycles. I think it would be better to abandon this approach and leave this up to a Continuous Integration tool, where you could include other goodies easily like pep8, pyflakes, and others.

If this is not a team project, then setting up a Continuous Integration system could be overkill. A good middle ground can be setting up a pre-commit hook with your version control system. That should be relatively easy to do, and ensure that all your committed code pass your tests.


PHP Cache weather in a file I'm using the darksky api to get weather data for a display board website.

The free version is limited to 1000 api calls per month.
I have a lot of devices (iPads) displaying this information in the building and refreshing every minute or so to update weather and the message of the hour.

I think that caching the weather into a file and reading it when the refresh time is over is a solution to my problem.
Is it the best solution?
And is this the best implementation of this solution

function getWeather(){
    //compares the time of the saved weather at each call of the method
    $last_modif = filemtime("weather.json");

    //if the weather is 10 minutes old, renew it by calling the api
    if(time() - $last_modif > WEATHER_REFRESH_TIME){
        //echo "call api";
        $file = fopen("weather.json", "w");
        $request = 'https://api.darksky.net/forecast/MY_KEY/LAT,LNG?lang=fr&units=si&exclude=minutely,flags';
        $data = file_get_contents($request);
        fwrite($file,$data);
        fclose($file);
    }

    $file = fopen("weather.json", "r");
    $weather = fread($file,filesize("weather.json"));
    fclose($file);

    return json_decode($weather);
}

Should i write the data in a database instead or is there any other way to store the weather?
What are the best practices in this case ?

Whether you stick with a flat file or a database depends on how you're using the data. It looks you you're only caching the latest API response for one specific query and not any historical data or data for other queries. If you have no desire to use those other data, caching to a file as you're doing is the easiest solution.

If you want to use other data at some point (maybe for multiple offices or historical graphs), a database would be far more scalable and manageable.

Spinning up a basic MySQL DB on your server would be fairly painless.

Install MySQL, if needed: https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-14-04
(Optional) Install PHPMyAdmin, if you're not comfortable running MySQL commands over the terminal: https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-phpmyadmin-on-ubuntu-16-04
Create the weather database and user.
Create whatever tables you need for caching the data. This should include either a column next to the data saying when it was cached or a table that records the time of the api queries.
Use some basic PDO to connect to the database and query it: http://coursesweb.net/php-mysql/pdo-introduction-connection-database

With either scheme, if users are hitting your service frequently enough, you can continue with your current scheme of requerying the API as you serve the page, after the data invalidation interval.

If you want to prevent any slow-downs for users or if they're not hitting it regularly enough, you could create a cron job to run your update script, regardless of where you're dumping the data.

As for your current script, I wrestled a bear once is correct. You should try to avoid opening and closing the same file repeatedly. You might try refactoring to this:

function getWeather()
{
    $last_modif = filemtime('weather.json');

    $response = '';

    if(time() - $last_modif > WEATHER_REFRESH_TIME)
    {
        $response = file_get_contents('https://api.darksky.net/forecast/MY_KEY/LAT,LNG?lang=fr&units=si&exclude=minutely,flags');
        file_put_contents('weather.json', $response);
    }
    else
    {
        $response = file_get_contents('weather.json');
    }

    return json_decode($response);
}