Rectangle 27 2

Here's one way to do it using a helper function that will account for days that do not have 24 observations.

library(xts)
xtime <- timeBasedSeq('2015-01-01/2015-01-30 23')
set.seed(21)
df <- xts(rnorm(length(xtime),30,4), xtime)

tHourly <- function(x) {
  # initialize result matrix for all 24 hours
  dnames <- list(format(index(x[1]), "%Y-%m-%d"),
                 paste0("H", 0:23))
  res <- matrix(NA, 1, 24, dimnames = dnames)
  # transpose day's rows and set colnames
  tx <- t(x)
  colnames(tx) <- paste0("H", .indexhour(x))
  # update result object and return
  res[,colnames(tx)] <- tx
  res
}
# split on days, apply tHourly to each day, rbind results
p_mat <- split(df, f="days", drop=FALSE, k=1)
p_list <- lapply(p_mat, tHourly)
p_hmat <- do.call(rbind, p_list)

Convert continuous time-series data into daily-hourly representation u...

r time-series xts zoo
Rectangle 27 6

This recursive function returns all dimensions of a given array or false if one or more dimensions are not straight (i.e. different sizes between array items). It uses a helper function to determine whether two simple arrays are the same (read the function comments before using it).

// pre: a !== b, each item is a scalar
function array_equals(a, b)
{
  return a.length === b.length && a.every(function(value, index) {
    return value === b[index];
  });
};

function getdim(arr)
{
  if (/*!(arr instanceof Array) || */!arr.length) {
    return []; // current array has no dimension
  }
  var dim = arr.reduce(function(result, current) {
    // check each element of arr against the first element
    // to make sure it has the same dimensions
    return array_equals(result, getdim(current)) ? result : false;
  }, getdim(arr[0]));

  // dim is either false or an array
  return dim && [arr.length].concat(dim);
}

console.log(getdim(123)); // []
console.log(getdim([1])); // [1]
console.log(getdim([1, 2])); // [2]
console.log(getdim([1, [2]])); // false
console.log(getdim([[1, 2], [3]])); // false
console.log(getdim([[1, 2],[1, 2]])); // [2, 2]
console.log(getdim([[1, 2],[1, 2],[1, 2]])); // [3, 2]

console.log(getdim([[[1, 2, 3],[1, 2, 4]],[[2, 1, 3],[4, 4, 6]]])); // [2, 2, 3]

console.log(getdim([[[1, 2, 3], [1, 2, 4]], [[2, 1], [4, 4]]])); // false

Also I've explicitly checked the parameter is an array, because the length property could be anything, not necessary an array (e.g. [{length:100},{length:200}] and this code screws up)

@AlvinWong Thanks for the feedback. I suppose the conditions should be strengthened if objects may occur; I've added it as a code comment though.

You finally decided that you cannot omit the part of comparing two arrays :P

How can I get the dimensions of a multidimensional Javascript array? -...

javascript arrays
Rectangle 27 3

preorder(node)
  if node == null then return
  print node.value
  preorder(node.left) 
  preorder(node.right)

Using a stack to store the leaf nodes I added the values onto them and was able to transverse the stack and change into lea nodes.

the parse tree leafs using preorder would give me a stack of [+ 10 4]

Using a helper function I could convert this into a

parsing - Converting Parse Tree Into AST (Abstract Syntax Tree) C++ - ...

c++ parsing abstract-syntax-tree parse-tree
Rectangle 27 3

I have used the helper function below in the past. I just gave the user a checkbox that they could select to include grid lines or not. Obviously you could change this to always include the grid lines.

namespace Helpers
{
    public class GridViewExportUtil
    {
        public static void Export(string fileName, GridView gv, bool includeGridLines)
        {
           HttpContext.Current.Response.Clear();
           HttpContext.Current.Response.AddHeader(
               "content-disposition", string.Format("attachment; filename={0}", fileName));
           HttpContext.Current.Response.ContentType = "application/ms-excel";

           using (StringWriter sw = new StringWriter())
           {
               using (HtmlTextWriter htw = new HtmlTextWriter(sw))
               {
               //  Create a form to contain the grid
               Table table = new Table();

            if (includeGridLines)
            {
               table.GridLines = gv.GridLines;
            }

               //  add the header row to the table
               if (gv.HeaderRow != null)
               {
                   GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                   table.Rows.Add(gv.HeaderRow);
               }

               //  add each of the data rows to the table
               foreach (GridViewRow row in gv.Rows)
               {
                GridViewExportUtil.PrepareControlForExport(row);
                   table.Rows.Add(row);
               }

               //  add the footer row to the table
               if (gv.FooterRow != null)
               {
                   GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                   table.Rows.Add(gv.FooterRow);
               }

                  //  render the table into the htmlwriter
                  table.RenderControl(htw);

                  //  render the htmlwriter into the response
                  HttpContext.Current.Response.Write(sw.ToString());
                  HttpContext.Current.Response.End();
              }
           }
       }

        /// <summary>
        /// Replace any of the contained controls with literals
        /// </summary>
        /// <param name="control"></param>
       private static void PrepareControlForExport(Control control)
        {
           for (int i = 0; i < control.Controls.Count; i++)
           {
               Control current = control.Controls[i];
               if (current is LinkButton)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
               }
               else if (current is ImageButton)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
               }
               else if (current is HyperLink)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
               }
               else if (current is DropDownList)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
               }
               else if (current is CheckBox)
               {
                  control.Controls.Remove(current);
                  control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
               }

               if (current.HasControls())
               {
                GridViewExportUtil.PrepareControlForExport(current);
               }
           }
        }
    }
}

This is an example of how you would call it:

GridViewExportUtil.Export("QueryResults.xls", GridView1, includeGridLines);

I put this code in to place but it's not working. Now nothing exports, the page just reloads like the button click event had no code in it.

Also, that code handles showing or not showing the gridlines in the grid of values being output to excel. It does nothing to the rest of the cells in the workbook.

David Glass...nice snippet. It's a keeper!

.net - Export GridView to Excel without losing grid lines in Excel - S...

.net asp.net excel gridview export
Rectangle 27 46

JSON.stringify and JSON.parse are almost oposites, and "usually" this kind of thing will work:

var obj = ...;
var json = JSON.stringify(obj);  
var obj2 = JSON.parse(json);

However there are some limitations to be aware of. Often these issues dont matter as you're dealing with simple objects. But I'll illustrate some of them here, using this helper function:

function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
  • You'll only get ownProperties of the object and lose prototypes: var MyClass = function() { this.foo="foo"; } MyClass.prototype = { bar:"bar" } var o = new MyClass(); var oo = jsonrepack(o); console.log(oo.bar); // undefined console.log( oo instanceof MyClass ); // false
var o = {};
var oo = jsonrepack(o);
console.log( o === oo ); // false
jsonrepack( { f:function(){} } ); // Returns {}
jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
  • Undefined values dont survive: var v = { x:undefined } console.log("x" in v); // true console.log("x" in jsonrepack(v)); // false

Objects that provide a toJSON function may not behave correctly.

x = { f:"foo", toJSON:function(){ return "EGAD"; } }
jsonrepack(x) // Returns 'EGAD'

I'm sure there are issues with other built-in-types too. (All this was tested using node.js so you may get slightly different behaviour depending on your environment too).

When it does matter it can sometimes be overcome using the additional parameters of JSON.parse and JSON.stringify. For example:

function MyClass (v) {
   this.date = new Date(v.year,1,1);
   this.name = "an object";
};

MyClass.prototype.dance = function() {console.log("I'm dancing"); }

var o = new MyClass({year:2010});
var s = JSON.stringify(o);

// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
  if(k==="") { 
     var rv = new MyClass(1990,0,0);
     rv.date = v.date;
     rv.name = v.name;
     return rv
  } else if(k==="date") {
    return new Date( Date.parse(v) );
  } else { return v; } } );

console.log(o);             // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance();                  // I'm dancing

console.log(o2);            // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]        
o2.dance();                 // I'm dancing
JSON SPEC

One example of this is that { bar:"bar" } (from your prototype) is not considered valid json since foo is a variable rather than a string. Valid json needs the key to be a string.

I read the OP as saying "I converted a javascript object to a JSON string, and now I want to convert it back - how do I do it?" All the other answers say just use JSON.parse. I'm just warning that theres a lot of cases that will not handle correctly. If you're using pure primitive data (no classes, prototypes) and only the datatypes supported by JSON (no dates, XML, HTML etc. ) then you're OK.

Also in Javascript X = { foo:"bar" } is the same as X = { "foo":"bar" } which is the same as X = {}; X.foo = "bar" which is the same as X={}; X["foo"] = "bar" The resulting object is identical in all 4 cases. That makes no difference to the validity of the generated JSON.

This is an outstandingly comprehensive answer, and far more worthy of being the accepted answer. Thank you for your excellent work.

javascript - Reverse of JSON.stringify? - Stack Overflow

javascript json object
Rectangle 27 46

JSON.stringify and JSON.parse are almost oposites, and "usually" this kind of thing will work:

var obj = ...;
var json = JSON.stringify(obj);  
var obj2 = JSON.parse(json);

However there are some limitations to be aware of. Often these issues dont matter as you're dealing with simple objects. But I'll illustrate some of them here, using this helper function:

function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
  • You'll only get ownProperties of the object and lose prototypes: var MyClass = function() { this.foo="foo"; } MyClass.prototype = { bar:"bar" } var o = new MyClass(); var oo = jsonrepack(o); console.log(oo.bar); // undefined console.log( oo instanceof MyClass ); // false
var o = {};
var oo = jsonrepack(o);
console.log( o === oo ); // false
jsonrepack( { f:function(){} } ); // Returns {}
jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
  • Undefined values dont survive: var v = { x:undefined } console.log("x" in v); // true console.log("x" in jsonrepack(v)); // false

Objects that provide a toJSON function may not behave correctly.

x = { f:"foo", toJSON:function(){ return "EGAD"; } }
jsonrepack(x) // Returns 'EGAD'

I'm sure there are issues with other built-in-types too. (All this was tested using node.js so you may get slightly different behaviour depending on your environment too).

When it does matter it can sometimes be overcome using the additional parameters of JSON.parse and JSON.stringify. For example:

function MyClass (v) {
   this.date = new Date(v.year,1,1);
   this.name = "an object";
};

MyClass.prototype.dance = function() {console.log("I'm dancing"); }

var o = new MyClass({year:2010});
var s = JSON.stringify(o);

// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
  if(k==="") { 
     var rv = new MyClass(1990,0,0);
     rv.date = v.date;
     rv.name = v.name;
     return rv
  } else if(k==="date") {
    return new Date( Date.parse(v) );
  } else { return v; } } );

console.log(o);             // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance();                  // I'm dancing

console.log(o2);            // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]        
o2.dance();                 // I'm dancing
JSON SPEC

One example of this is that { bar:"bar" } (from your prototype) is not considered valid json since foo is a variable rather than a string. Valid json needs the key to be a string.

I read the OP as saying "I converted a javascript object to a JSON string, and now I want to convert it back - how do I do it?" All the other answers say just use JSON.parse. I'm just warning that theres a lot of cases that will not handle correctly. If you're using pure primitive data (no classes, prototypes) and only the datatypes supported by JSON (no dates, XML, HTML etc. ) then you're OK.

Also in Javascript X = { foo:"bar" } is the same as X = { "foo":"bar" } which is the same as X = {}; X.foo = "bar" which is the same as X={}; X["foo"] = "bar" The resulting object is identical in all 4 cases. That makes no difference to the validity of the generated JSON.

This is an outstandingly comprehensive answer, and far more worthy of being the accepted answer. Thank you for your excellent work.

javascript - Reverse of JSON.stringify? - Stack Overflow

javascript json object
Rectangle 27 43

JSON.stringify and JSON.parse are almost oposites, and "usually" this kind of thing will work:

var obj = ...;
var json = JSON.stringify(obj);  
var obj2 = JSON.parse(json);

However there are some limitations to be aware of. Often these issues dont matter as you're dealing with simple objects. But I'll illustrate some of them here, using this helper function:

function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
  • You'll only get ownProperties of the object and lose prototypes: var MyClass = function() { this.foo="foo"; } MyClass.prototype = { bar:"bar" } var o = new MyClass(); var oo = jsonrepack(o); console.log(oo.bar); // undefined console.log( oo instanceof MyClass ); // false
var o = {};
var oo = jsonrepack(o);
console.log( o === oo ); // false
jsonrepack( { f:function(){} } ); // Returns {}
jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
  • Undefined values dont survive: var v = { x:undefined } console.log("x" in v); // true console.log("x" in jsonrepack(v)); // false

Objects that provide a toJSON function may not behave correctly.

x = { f:"foo", toJSON:function(){ return "EGAD"; } }
jsonrepack(x) // Returns 'EGAD'

I'm sure there are issues with other built-in-types too. (All this was tested using node.js so you may get slightly different behaviour depending on your environment too).

When it does matter it can sometimes be overcome using the additional parameters of JSON.parse and JSON.stringify. For example:

function MyClass (v) {
   this.date = new Date(v.year,1,1);
   this.name = "an object";
};

MyClass.prototype.dance = function() {console.log("I'm dancing"); }

var o = new MyClass({year:2010});
var s = JSON.stringify(o);

// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
  if(k==="") { 
     var rv = new MyClass(1990,0,0);
     rv.date = v.date;
     rv.name = v.name;
     return rv
  } else if(k==="date") {
    return new Date( Date.parse(v) );
  } else { return v; } } );

console.log(o);             // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance();                  // I'm dancing

console.log(o2);            // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]        
o2.dance();                 // I'm dancing
JSON SPEC

One example of this is that { bar:"bar" } (from your prototype) is not considered valid json since foo is a variable rather than a string. Valid json needs the key to be a string.

I read the OP as saying "I converted a javascript object to a JSON string, and now I want to convert it back - how do I do it?" All the other answers say just use JSON.parse. I'm just warning that theres a lot of cases that will not handle correctly. If you're using pure primitive data (no classes, prototypes) and only the datatypes supported by JSON (no dates, XML, HTML etc. ) then you're OK.

Also in Javascript X = { foo:"bar" } is the same as X = { "foo":"bar" } which is the same as X = {}; X.foo = "bar" which is the same as X={}; X["foo"] = "bar" The resulting object is identical in all 4 cases. That makes no difference to the validity of the generated JSON.

This is an outstandingly comprehensive answer, and far more worthy of being the accepted answer. Thank you for your excellent work.

javascript - Reverse of JSON.stringify? - Stack Overflow

javascript object
Rectangle 27 2

In my case I was using a helper function to save some data in Firebase. That function was returning a dictionary with about 20 elements and it would take about 40 mins to compile. My solution was to initialize an empty dictionary and then add the items one by one to someDict . Now it compiles in less than 30 seconds. I hope it helps.

func toAnyObject() -> AnyObject {
  return
      ["BookingAmount":BookingAmount,
     "BookingNumber":BookingNumber,
     "PostCode":PostCode,
     "SelectedBathRow":SelectedBathRow,
     "SelectedBedRow":SelectedBedRow,
     "DateAndTime":DateAndTime,
     "TimeStampDateAndTime":TimeStampDateAndTime,
     "TimeStampBookingSavedInDB": TimeStampBookingSavedInDB,
     "FrequencyName":FrequencyName,
     "FrequecyAmount":FrequecyAmount,
     "insideCabinets": insideCabinets,
     "insideFridge": insideFridge,
     "insideOven": insideOven,
     "laundryWash": laundryWash,
     "interiorWindows": interiorWindows,
     "FullName":FullName,
     "SuppliesName":SuppliesName,
     "SuppliesAmount":SuppliesAmount,
     "FlatNumber":FlatNumber,
     "StreetAddress":StreetAddress,
     "PhoneNumber":PhoneNumber,
     "EmailAddress":EmailAddress] as AnyObject

}
func toAnyObject() -> AnyObject {

    var someDict = [String : AnyObject]()
    someDict["BookingAmount"] = self.BookingAmount as AnyObject?
    someDict["BookingNumber"] = self.BookingNumber as AnyObject?
    someDict["PostCode"] = self.PostCode as AnyObject?
    someDict["SelectedBathRow"] = self.SelectedBathRow as AnyObject?
    someDict["SelectedBedRow"] = self.SelectedBedRow as AnyObject?
    someDict["DateAndTime"] = self.DateAndTime as AnyObject?
    someDict["TimeStampDateAndTime"] = self.TimeStampDateAndTime as AnyObject?
    someDict["TimeStampBookingSavedInDB"] = self.TimeStampBookingSavedInDB as AnyObject?
    someDict["FrequencyName"] = self.FrequencyName as AnyObject?
    someDict["FrequecyAmount"] = self.FrequecyAmount as AnyObject?
    someDict["insideCabinets"] = self.insideCabinets as AnyObject?
    someDict["insideFridge"] = self.insideFridge as AnyObject?
    someDict["insideOven"] = self.insideOven  as AnyObject?
    someDict["laundryWash"] = self.laundryWash as AnyObject?
    someDict["interiorWindows"] = self.interiorWindows as AnyObject?
    someDict["FullName"] = self.FullName as AnyObject?
    someDict["SuppliesName"] = self.SuppliesName as AnyObject?
    someDict["SuppliesAmount"] = self.SuppliesAmount as AnyObject?
    someDict["FlatNumber"] = self.FlatNumber as AnyObject?
    someDict["StreetAddress"] = self.StreetAddress as AnyObject?
    someDict["PhoneNumber"] = self.PhoneNumber as AnyObject?
    someDict["EmailAddress"] = self.EmailAddress as AnyObject?

    return someDict as AnyObject
}

ios - XCode 8 very slow swift compiling - Stack Overflow

ios swift xcode swift3 xcode8
Rectangle 27 68

I'd do it like this so changing its type in foo() won't require also changing it in bar().

def foo():
    try:
        raise IOError('Stuff')
    except:
        raise

def bar(arg1):
    try:
        foo()
    except Exception as e:
        raise type(e)(e.message + ' happens at %s' % arg1)

bar('arg1')

Here's a slight modification that preserves the original traceback:

...
def bar(arg1):
    try:
        foo()
    except Exception as e:
        import sys
        raise type(e), type(e)(e.message +
                               ' happens at %s' % arg1), sys.exc_info()[2]

bar('arg1')
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    bar('arg1')
  File "test.py", line 11, in bar
    foo()
  File "test.py", line 5, in foo
    raise IOError('Stuff')
IOError: Stuff happens at arg1

For Python 3.x, the code in my first update is syntactically incorrect plus the idea of having a message attribute on BaseException was retracted in a change to PEP 352 on 2012-05-16 (my first update was posted on 2012-03-12). So currently, in Python 3.5.2 anyway, you'd need to do something along these lines to preserve the traceback and not hardcode the type of exception in function bar(). Also note that there will be the line:

During handling of the above exception, another exception occurred:

in the traceback messages displayed.

# for Python 3.x
...
def bar(arg1):
    try:
        foo()
    except Exception as e:
        import sys
        raise type(e)(str(e) +
                      ' happens at %s' % arg1).with_traceback(sys.exc_info()[2])

bar('arg1')

A commenter asked if there was a way that would work in both Python 2 and 3. Although the answer might seem to be "No" due to the syntax differences, there is a way around that by using a helper function like reraise() in the six add-on module. So, if you'd rather not use the library for some reason, below is a simplified standalone version.

Note too, that since the exception is reraised within the reraise() function, that will appear in whatever traceback is raised, but the final result is what you want.

import sys

if sys.version_info.major < 3:  # Python 2?
    # Using exec avoids a SyntaxError in Python 3.
    exec("""def reraise(exc_type, exc_value, exc_traceback=None):
                raise exc_type, exc_value, exc_traceback""")
else:
    def reraise(exc_type, exc_value, exc_traceback=None):
        if exc_value is None:
            exc_value = exc_type()
        if exc_value.__traceback__ is not exc_traceback:
            raise exc_value.with_traceback(exc_traceback)
        raise exc_value

def foo():
    try:
        raise IOError('Stuff')
    except:
        raise

def bar(arg1):
    try:
       foo()
    except Exception as e:
        reraise(type(e), type(e)(str(e) +
                                 ' happens at %s' % arg1), sys.exc_info()[2])

bar('arg1')

That loses the backtrace, kind of defeating the point of adding information to an existing exception. Also, it doesn't work exceptions with ctor that takes >1 arguments (the type is something you cannot control from the place where you catch the exception).

@Vclav: It's fairly easy to prevent losing the backtrace -- as shown in the update I added. While this still doesn't handle every conceivable exception, it does work for cases similar to what was shown in the OP's question.

This isn't quite right. If type(e) overrides __str__, you may get undesirable results. Also note that the second argument is passed to the constructor given by the first argument, which yields a somewhat nonsensical type(e)(type(e)(e.message). Thirdly, e.message is deprecated in favor of e.args[0].

@martineau: I just wanted to update your link to Exceptions chapter of the free book "Building Skills in Python - A Programmer's Introduction to Python" by Steven F. Lott

@joshsvoss: Just to make it lazily imported (delayed until actually needed) -- ideally exceptions are cases not conforming to the general rule -- however moving it to the top of the function or module would be fine, too.

python - Adding information to an exception? - Stack Overflow

python exception-handling
Rectangle 27 1

Here's my solution for inline comments in between multiple piped commands.

#!/bin/sh
    at input.txt \
    | grep something \
    | sort -r

Solution for a pipe comment (using a helper function):

#!/bin/sh
    pipe_comment() {
        cat - 
    }
    cat input.txt \
    | pipe_comment "filter down to lines that contain the word: something" \
    | grep something \
    | pipe_comment "reverse sort what is left" \
    | sort -r

Or if you prefer, here's the same solution without the helper function, but it's a little messier:

#!/bin/sh
    cat input.txt \
    | cat - `: filter down to lines that contain the word: something` \
    | grep something \
    | cat - `: reverse sort what is left` \
    | sort -r

As an aside, if you move the pipe character to the end of the previous line, you can get rid of the yucky backslash-newlines.

Inline comments for Bash? - Stack Overflow

bash
Rectangle 27 1

Here's my solution for inline comments in between multiple piped commands.

#!/bin/sh
    at input.txt \
    | grep something \
    | sort -r

Solution for a pipe comment (using a helper function):

#!/bin/sh
    pipe_comment() {
        cat - 
    }
    cat input.txt \
    | pipe_comment "filter down to lines that contain the word: something" \
    | grep something \
    | pipe_comment "reverse sort what is left" \
    | sort -r

Or if you prefer, here's the same solution without the helper function, but it's a little messier:

#!/bin/sh
    cat input.txt \
    | cat - `: filter down to lines that contain the word: something` \
    | grep something \
    | cat - `: reverse sort what is left` \
    | sort -r

As an aside, if you move the pipe character to the end of the previous line, you can get rid of the yucky backslash-newlines.

Inline comments for bash? - Stack Overflow

bash
Rectangle 27 1

(-1 * b - sqrt(delta)) / 2 * a
(-1 * b - sqrt(delta)) / (2 * a)

Suggest using a helper function as that equation is used repetitively in code.

#include <assert.h>
#include <math.h>

int quadratic(double a, double b, double c, double x[2]) {
  if (a == 0.0) return 0;
  double d = b*b - 4*a*c;
  if (d < 0.0) return -1;
  d = sqrt(d);
  x[0] = (-b + d) / (2 * a);
  x[1] = (-b - d) / (2 * a);
  return 2;
}

Yes, thanks a lot. I mis-coded the quadratic. The lights are now fine !! But when I rotate by 45 degrees, the reflections are still wrong ... nearly the same as in my image... 90 degrees is ok, but another one is wrong. Do I calculate the normal the right way ?

@Seybol Too many unknowns, unposted code. Perhaps init_rotation_matrix( uses radians, not degrees, je ne sais pas.

math - Raytracing in C - Cylinder, normal vector and rotation - Stack ...

c math geometry
Rectangle 27 1

  • Using of namespacing in JS is considered to be best practice, keep doing this.
  • As it's been said, using of helper function instead of 'manual' namespacing, if better. The namespace function I use, if here.
  • App = App || {}; - does the following. If App is undefined (not initialized, used first time) || operator returns false so, second statement applied and App variable is initialized with empty object.

javascript - Namespacing in Backbone.js - Stack Overflow

javascript jquery backbone.js namespaces underscore.js
Rectangle 27 1

$path = $request->file('logo')->store('/clients/logos','public');
$path

You need to provide a fully qualified path to the public storage directory.

This can be achieved by using the helper function storage_path() so you use storage_path($path) instead of just $path

$path = $request->file('logo')->store('/clients/logos','public');

$canvas = Image::canvas($width, $height);
$image = Image::make(storage_path('app/'.$path))->resize($width, $height, function ($constraint)
{
    $constraint->aspectRatio();
});

$canvas->insert($image, 'center');
$canvas->save(storage_path('app/'.$path));

$this->logo_path = 'app/'.$path;

It is worth mentioning that this has not been tested but I would assume this is your issue.

Edit: Also, when using Storage::disk('public')->url($path), it is going to return a storage/ path relative to your public directory. Therefore, as the docs mention:

The storage/app/public directory may be used to store user-generated files, such as profile avatars, that should be publicly accessible. You should create a symbolic link at public/storage which points to this directory. You may create the link using the php artisan storage:link command.

home/vagrant/php-resq/storage/clients/logos/ObaIpvgexGPcOStz0jaU73BJ8AUDp2ME85lUpMoY.jpeg

Then you just need to prepend app/ to your path and that should work. The reason you are getting Image not readable is because you are not providing the correct path.

Adding app, seems like a hacky solution, so not really gonna do that. Got it working without using canvas() gonna ad that to my first post, so maybe someone will find a solution based on that

php - Use laravel storage with Image intervention canvas() - Stack Ove...

php laravel intervention laravel-5.4
Rectangle 27 2

Late to the party, but why use third party for such a simple problem?

You could either do it as @Huw Davies mentioned - the best way

1. <i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
2. <i className={[styles['foo-bar-baz'], 'fa fa-user', 'fa-2x'].join(' ')}

Both are good. But writing can become complex for a large app. To make it optimal, I do the same above things but put it in a helper class

Using my below helper function, allows me to keep the logic separate for future editing, and also gives me multiple ways to add the classes

classNames(styles['foo-bar-baz], 'fa fa-user', 'fa-2x')
classNames([styles['foo-bar-baz], 'fa fa-user', 'fa-2x'])

This is my helper function below. I've put it in a helper.js where I keep all my common methods. Being such a simple function, I avoided using 3rd party to keep control

export function classNames (classes) {
    if(classes && classes.constructor === Array) {
        return classes.join(' ')
    } else if(arguments[0] !== undefined) {
        return [...arguments].join(' ')
    }
    return ''
}

javascript - How to add multiple classes to a ReactJS Component - Stac...

javascript css reactjs ecmascript-6 react-jsx
Rectangle 27 12

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

solution that also works when the script is invoked through a symlink or even a chain of symlinks

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")
readlink
--canonicalize
-e
--canonicalize-existing
-m
--canonicalize-missing
man readlink
-f

If your script must run on any platform that:

has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

  • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.

does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

rreadlink()

in effect a POSIX-compliant implementation of GNU readlink's -e option

similar to the -f option, except that the ultimate target must exist

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")
scriptDir=$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")

@iElectric: (I originally misread your comment as relating to the rreadlink function). Yes, shellcheck.net issues a warning when referencing a variable that is technically an array without also specifying an index, in which case the 1st element is returned (here, $BASH_SOURCE is equivalent to ${BASH_SOURCE[0]}). While doing so can be a pitfall, it is also a convenient shortcut, especially with variables such as BASH_SOURCE, where it is almost always the 1st element that is of interest.

bash - Shell: Relative paths based on file location instead of current...

bash shell
Rectangle 27 12

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

solution that also works when the script is invoked through a symlink or even a chain of symlinks

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")
readlink
--canonicalize
-e
--canonicalize-existing
-m
--canonicalize-missing
man readlink
-f

If your script must run on any platform that:

has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

  • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.

does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

rreadlink()

in effect a POSIX-compliant implementation of GNU readlink's -e option

similar to the -f option, except that the ultimate target must exist

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")
scriptDir=$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")

@iElectric: (I originally misread your comment as relating to the rreadlink function). Yes, shellcheck.net issues a warning when referencing a variable that is technically an array without also specifying an index, in which case the 1st element is returned (here, $BASH_SOURCE is equivalent to ${BASH_SOURCE[0]}). While doing so can be a pitfall, it is also a convenient shortcut, especially with variables such as BASH_SOURCE, where it is almost always the 1st element that is of interest.

bash - Shell: Relative paths based on file location instead of current...

bash shell
Rectangle 27 175

Without a helper function, just using regex's .test method:

/^He/.test('Hello world')

To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):

new RegExp('^' + needle).test(haystack)

You should check out Is there a RegExp.escape function in Javascript? if the possibility exists that regexp control characters appear in the string.

javascript - How to check if a string "StartsWith" another string? - S...

javascript string startswith
Rectangle 27 173

Without a helper function, just using regex's .test method:

/^He/.test('Hello world')

To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):

new RegExp('^' + needle).test(haystack)

You should check out Is there a RegExp.escape function in Javascript? if the possibility exists that regexp control characters appear in the string.

javascript - How to check if a string "StartsWith" another string? - S...

javascript string startswith
Rectangle 27 173

Without a helper function, just using regex's .test method:

/^He/.test('Hello world')

To do this with a dynamic string rather than a hardcoded one (assuming that the string will not contain any regexp control characters):

new RegExp('^' + needle).test(haystack)

You should check out Is there a RegExp.escape function in Javascript? if the possibility exists that regexp control characters appear in the string.

javascript - How to check if a string "StartsWith" another string? - S...

javascript string startswith