Programs & Examples On #Fileapi

Use this tag for questions related to the W3C File API. The W3C File API specifies how file objects should be represented and how their properties should be accessed.

How do I download a file with Angular2 or greater

If you don't need to add headers in the request, to download a file in Angular2 you can do a simple (KISS PRINCIPLE):

window.location.href='http://example.com/myuri/report?param=x';

in your component.

Getting byte array through input type = file

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
  binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
      console.log(arrayBuffer);_x000D_
        document.querySelector('#result').innerHTML = arrayBuffer + '  '+arrayBuffer.byteLength;_x000D_
        }_x000D_
    reader.readAsArrayBuffer(this.files[0]);_x000D_
  }, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How to get a file or blob from an object URL?

Unfortunately @BrianFreud's answer doesn't fit my needs, I had a little different need, and I know that is not the answer for @BrianFreud's question, but I am leaving it here because a lot of persons got here with my same need. I needed something like 'How to get a file or blob from an URL?', and the current correct answer does not fit my needs because its not cross-domain.

I have a website that consumes images from an Amazon S3/Azure Storage, and there I store objects named with uniqueidentifiers:

sample: http://****.blob.core.windows.net/systemimages/bf142dc9-0185-4aee-a3f4-1e5e95a09bcf

Some of this images should be download from our system interface. To avoid passing this traffic through my HTTP server, since this objects does not require any security to be accessed (except by domain filtering), I decided to make a direct request on user's browser and use local processing to give the file a real name and extension.

To accomplish that I have used this great article from Henry Algus: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/

1. First step: Add binary support to jquery

/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0 
* @author Henry Algus <[email protected]>
*
*/

// use this transport for "binary" data type
$.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
        return {
            // create new XMLHttpRequest
            send: function (headers, callback) {
                // setup all variables
                var xhr = new XMLHttpRequest(),
        url = options.url,
        type = options.type,
        async = options.async || true,
        // blob or arraybuffer. Default is blob
        dataType = options.responseType || "blob",
        data = options.data || null,
        username = options.username || null,
        password = options.password || null;

                xhr.addEventListener('load', function () {
                    var data = {};
                    data[options.dataType] = xhr.response;
                    // make callback and send data
                    callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, async, username, password);

                // setup custom headers
                for (var i in headers) {
                    xhr.setRequestHeader(i, headers[i]);
                }

                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function () {
                jqXHR.abort();
            }
        };
    }
});

2. Second step: Make a request using this transport type.

function downloadArt(url)
{
    $.ajax(url, {
        dataType: "binary",
        processData: false
    }).done(function (data) {
        // just my logic to name/create files
        var filename = url.substr(url.lastIndexOf('/') + 1) + '.png';
        var blob = new Blob([data], { type: 'image/png' });

        saveAs(blob, filename);
    });
}

Now you can use the Blob created as you want to, in my case I want to save it to disk.

3. Optional: Save file on user's computer using FileSaver

I have used FileSaver.js to save to disk the downloaded file, if you need to accomplish that, please use this javascript library:

https://github.com/eligrey/FileSaver.js/

I expect this to help others with more specific needs.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

The canvas element provides a toDataURL method which returns a data: URL that includes the base64-encoded image data in a given format. For example:

var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default

Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.

The toDataURL method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.

For more information see the MDN docs on the canvas API, which includes details on toDataURL, and the Wikipedia article on the data: URI scheme, which includes details on the format of the URI you'll receive from this call.

Convert base64 png data to javascript file objects

You can create a Blob from your base64 data, and then read it asDataURL:

var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];

var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});

var fr = new FileReader();
fr.onload = function ( oFREvent ) {
    var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
    v = atob(v);
    var good_b64 = btoa(decodeURIComponent(escape(v)));
    document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);

Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/


Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;)

fr.onload = function ( oFREvent ) {
    document.getElementById("uploadPreview").src = "data:image/png;base64,"
    + btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here

Full example: http://jsfiddle.net/tTYb8/3/

posting hidden value

I'm not sure what you just did there, but from what I can tell this is what you're asking for:

bookingfacilities.php

<form action="successfulbooking.php" method="post">
    <input type="hidden" name="date" value="<?php echo $date; ?>">  
    <input type="submit" value="Submit Form">
</form>

successfulbooking.php

<?php
    $date = $_POST['date'];
    // add code here
?>

Not sure what you want to do with that third page(booking_now.php) too.

Appending to an existing string

You can use << to append to a string in-place.

s = "foo"
old_id = s.object_id
s << "bar"
s                      #=> "foobar"
s.object_id == old_id  #=> true

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

I would just to like to add that the directory is not necessarily C:\Users\[username]\.ssh. It is the directory in which you created your public key in.

For instance my home directory in Windows was changed to C:\[username]. Your home directory in a .ssh sub-folder is the best and most likely place you may have created your keys. You can check your home directory in Windows with the command:

    echo %HOMEPATH%

Pure CSS collapse/expand div

Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary> and <detail> tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.

I've made an example here:

<details>
<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>
</details>

Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.

C# refresh DataGridView when updating or inserted on another form

DataGridView.Refresh and And DataGridView.Update are methods that are inherited from Control. They have to do with redrawing the control which is why new rows don't appear.

My guess is the data retrieval is on the Form_Load. If you want your Button on Form B to retrieve the latest data from the database then that's what you have to do whatever Form_Load is doing.

A nice way to do that is to separate your data retrieval calls into a separate function and call it from both the From Load and Button Click events.

How to print a single backslash?

A backslash needs to be escaped with another backslash.

print('\\')

How to print values separated by spaces instead of new lines in Python 2.7

First of all print isn't a function in Python 2, it is a statement.

To suppress the automatic newline add a trailing ,(comma). Now a space will be used instead of a newline.

Demo:

print 1,
print 2

output:

1 2

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)

As you can clearly see print() function is much more powerful as we can specify any string to be used as end rather a fixed space.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

How can I add a background thread to flask?

In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:

https://github.com/viniciuschiele/flask-apscheduler

A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:

from flask import Flask
from flask_apscheduler import APScheduler


class Config(object):
    JOBS = [
        {
            'id': 'job1',
            'func': 'jobs:job1',
            'args': (1, 2),
            'trigger': 'interval',
            'seconds': 10
        }
    ]

    SCHEDULER_API_ENABLED = True


def job1(a, b):
    print(str(a) + ' ' + str(b))

if __name__ == '__main__':
    app = Flask(__name__)
    app.config.from_object(Config())

    scheduler = APScheduler()
    # it is also possible to enable the API directly
    # scheduler.api_enabled = True
    scheduler.init_app(app)
    scheduler.start()

    app.run()

Windows batch script to unhide files hidden by virus

echo "Enter Drive letter" 
set /p driveletter=

attrib -s -h -a /s /d  %driveletter%:\*.*

End-line characters from lines read from text file, using Python

The idiomatic way to do this in Python is to use rstrip('\n'):

for line in open('myfile.txt'):  # opened in text-mode; all EOLs are converted to '\n'
    line = line.rstrip('\n')
    process(line)

Each of the other alternatives has a gotcha:

  • file('...').read().splitlines() has to load the whole file in memory at once.
  • line = line[:-1] will fail if the last line has no EOL.

How to leave space in HTML

You can preserve white-space with white-space: pre CSS property which will preserve white-space inside an element. https://www.w3schools.com/cssref/pr_text_white-space.asp

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

Unable to resolve host "<URL here>" No address associated with host name

It is WiFi bug due to wifi disable or not properly connected.

Simply Reconnect the wifi will solve the issue.

Send email from localhost running XAMMP in PHP using GMAIL mail server

Here's the link that gives me the answer:

[Install] the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip

[Modify] the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(ignore the "Unix only" bit, since we actually are using sendmail)

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

To access a Gmail account protected by 2-factor verification, you will need to create an application-specific password. (source)

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

How can you run a command in bash over and over until success?

while [ -n $(passwd) ]; do
        echo "Try again";
done;

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

This error can be resolved by adding MessageBoxOptions.ServiceNotification.

MessageBox.Show(msg, "Print Error", System.Windows.Forms.MessageBoxButtons.YesNo, 
   System.Windows.Forms.MessageBoxIcon.Error,     
   System.Windows.Forms.MessageBoxDefaultButton.Button1, 
   System.Windows.Forms.MessageBoxOptions.ServiceNotification); 

But it is not going to show any dialog box if your web application is installed on IIS or server.Because in IIS or server it is hosted on worker process which dont have any desktop.

Get current date in DD-Mon-YYY format in JavaScript/Jquery

const date = new Date();

date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }))

Daylight saving time and time zone best practices

Never rely only on constructors like

 new DateTime(int year, int month, int day, int hour, int minute, TimeZone timezone)

They can throw exceptions when a certain date time does not exist due to DST. Instead, build your own methods for creating such dates. In them, catch any exceptions that occur due to DST, and adjust the time is needed with the transition offset. DST may occur on different dates and at different hours (even at midnight for Brazil) according to the timezone.

Reset AutoIncrement in SQL Server after Delete

You do not want to do this in general. Reseed can create data integrity problems. It is really only for use on development systems where you are wiping out all test data and starting over. It should not be used on a production system in case all related records have not been deleted (not every table that should be in a foreign key relationship is!). You can create a mess doing this and especially if you mean to do it on a regular basis after every delete. It is a bad idea to worry about gaps in you identity field values.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

For me this problem still exists with SSMS version 2016 (13.0.16100.1).

A decent workaround is to not use the 'Right click' -> 'Add table...' dialog, but simply drag the table you want to add from the Object Explorer, onto the Diagram surface. While dragging the mouse icon changes into an 'add' symbol and the table is added when you release the mouse.

Beats having to close SSMS every time.

What does "-ne" mean in bash?

"not equal" So in this case, $RESULT is tested to not be equal to zero.

However, the test is done numerically, not alphabetically:

n1 -ne n2     True if the integers n1 and n2 are not algebraically equal.

compared to:

s1 != s2      True if the strings s1 and s2 are not identical.

Angular 2 Cannot find control with unspecified name attribute on formArrays

In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:

[formControlName]="'familyName'"

similar to below:

formControlName="familyName"

Can we have multiple "WITH AS" in single sql - Oracle SQL

Yes you can...

WITH SET1 AS (SELECT SYSDATE FROM DUAL), -- SET1 initialised
     SET2 AS (SELECT * FROM SET1)        -- SET1 accessed
SELECT * FROM SET2;                      -- SET2 projected

10/29/2013 10:43:26 AM

Follow the order in which it should be initialized in Common Table Expressions

How to loop through a plain JavaScript object with the objects as members?

Few ways to do that...

1) 2 layers for...in loop...

for (let key in validation_messages) {
   const vmKeys = validation_messages[key];
   for (let vmKey in vmKeys) {
      console.log(vmKey + vmKeys[vmKey]);
   }
}

2) Using Object.key

Object.keys(validation_messages).forEach(key => {
   const vmKeys = validation_messages[key];
   Object.keys(vmKeys).forEach(key => {
    console.log(vmKeys + vmKeys[key]);
   });
});

3) Recursive function

const recursiveObj = obj => {
  for(let key in obj){
    if(!obj.hasOwnProperty(key)) continue;

    if(typeof obj[key] !== 'object'){
      console.log(key + obj[key]);
    } else {
      recursiveObj(obj[key]);
    }
  }
}

And call it like:

recursiveObj(validation_messages);

What happens when a duplicate key is put into a HashMap?

Yes, this means all the 1 keys with value are overwriten with the last added value and here you add "surely not one" so it will display only "surely not one".

Even if you are trying to display with a loop, it will also only display one key and value which have same key.

Blocking device rotation on mobile web pages

In JavaScript-enabled browsers it should be easy to determine if the screen is in landscape or portrait mode and compensate using CSS. It may be helpful to give users the option to disable this or at least warn them that device rotation will not work properly.

Edit

The easiest way to detect the orientation of the browser is to check the width of the browser versus the height of the browser. This also has the advantage that you'll know if the game is being played on a device that is naturally oriented in landscape mode (as some mobile devices like the PSP are). This makes more sense than trying to disable device rotation.

Edit 2

Daz has shown how you can detect device orientation, but detecting orientation is only half of the solution. If want to reverse the automatic orientation change, you'll need to rotate everything either 90° or 270°/-90°, e.g.

$(window).bind('orientationchange resize', function(event){
  if (event.orientation) {
    if (event.orientation == 'landscape') {
      if (window.rotation == 90) {
        rotate(this, -90);
      } else {
        rotate(this, 90);
      }
    }
  }
});

function rotate(el, degs) {
  iedegs = degs/90;
  if (iedegs < 0) iedegs += 4;
  transform = 'rotate('+degs+'deg)';
  iefilter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+iedegs+')';
  styles = {
    transform: transform,
    '-webkit-transform': transform,
    '-moz-transform': transform,
    '-o-transform': transform,
    filter: iefilter,
    '-ms-filter': iefilter
  };
  $(el).css(styles);
}

Note: if you want to rotate in IE by an arbitrary angle (for other purposes), you'll need to use matrix transform, e.g.

rads = degs * Math.PI / 180;
m11 = m22 = Math.cos(rads);
m21 = Math.sin(rads);
m12 = -m21;
iefilter = "progid:DXImageTransform.Microsoft.Matrix("
  + "M11 = " + m11 + ", "
  + "M12 = " + m12 + ", "
  + "M21 = " + m21 + ", "
  + "M22 = " + m22 + ", sizingMethod = 'auto expand')";
styles['filter'] = styles['-ms-filter'] = iefilter;

—or use CSS Sandpaper. Also, this applies the rotation style to the window object, which I've never actually tested and don't know if works or not. You may need to apply the style to a document element instead.

Anyway, I would still recommend simply displaying a message that asks the user to play the game in portrait mode.

Initialise a list to a specific length in Python

If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10, is good enough.

But if you want, say, a list of ten dicts, do not use [{}]*10 -- that would give you a list with the same initially-empty dict ten times, not ten distinct ones. Rather, use [{} for i in range(10)] or similar constructs, to construct ten separate dicts to make up your list.

Last Run Date on a Stored Procedure in SQL Server

The below code should do the trick (>= 2008)

SELECT o.name, 
       ps.last_execution_time 
FROM   sys.dm_exec_procedure_stats ps 
INNER JOIN 
       sys.objects o 
       ON ps.object_id = o.object_id 
WHERE  DB_NAME(ps.database_id) = '' 
ORDER  BY 
       ps.last_execution_time DESC  

Edit 1 : Please take note of Jeff Modens advice below. If you find a procedure here, you can be sure that it is accurate. If you do not then you just don't know - you cannot conclude it is not running.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')

How do I find the parent directory in C#?

Like this:

System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
string parentDirectory = myDirectory.Parent.FullName;

Good luck!

What is sharding and why is it important?

Sharding is horizontal(row wise) database partitioning as opposed to vertical(column wise) partitioning which is Normalization. It separates very large databases into smaller, faster and more easily managed parts called data shards. It is a mechanism to achieve distributed systems.

Why do we need distributed systems?

  • Increased availablity.
  • Easier expansion.
  • Economics: It costs less to create a network of smaller computers with the power of single large computer.

You can read more here: Advantages of Distributed database

How sharding help achieve distributed system?

You can partition a search index into N partitions and load each index on a separate server. If you query one server, you will get 1/Nth of the results. So to get complete result set, a typical distributed search system use an aggregator that will accumulate results from each server and combine them. An aggregator also distribute query onto each server. This aggregator program is called MapReduce in big data terminology. In other words, Distributed Systems = Sharding + MapReduce (Although there are other things too).

A visual representation below. Distributed System

Generating a WSDL from an XSD file

Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.

Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.

Remove duplicated rows using dplyr

Note: dplyr now contains the distinct function for this purpose.

Original answer below:


library(dplyr)
set.seed(123)
df <- data.frame(
  x = sample(0:1, 10, replace = T),
  y = sample(0:1, 10, replace = T),
  z = 1:10
)

One approach would be to group, and then only keep the first row:

df %>% group_by(x, y) %>% filter(row_number(z) == 1)

## Source: local data frame [3 x 3]
## Groups: x, y
## 
##   x y z
## 1 0 1 1
## 2 1 0 2
## 3 1 1 4

(In dplyr 0.2 you won't need the dummy z variable and will just be able to write row_number() == 1)

I've also been thinking about adding a slice() function that would work like:

df %>% group_by(x, y) %>% slice(from = 1, to = 1)

Or maybe a variation of unique() that would let you select which variables to use:

df %>% unique(x, y)

Python float to int conversion

>>> x = 2.51
>>> x*100
250.99999999999997

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),

How to round a number to n decimal places in Java

If you're using a technology that has a minimal JDK. Here's a way without any Java libs:

double scale = 100000;    
double myVal = 0.912385;
double rounded = (int)((myVal * scale) + 0.5d) / scale;

How to advance to the next form input when the current input has a value?

Needed to emulate the tab functionality a while ago, and now I've released it as a library that uses .

EmulateTab: A jQuery plugin to emulate tabbing between elements on a page.

You can see how it works in the demo.

if (myTextHasBeenFilledWithText) {
  // Tab to the next input after #my-text-input
  $("#my-text-input").emulateTab();
}

How to open a WPF Popup when another control is clicked, using XAML markup only?

I did something simple, but it works.

I used a typical ToggleButton, which I restyled as a textblock by changing its control template. Then I just bound the IsChecked property on the ToggleButton to the IsOpen property on the popup. Popup has some properties like StaysOpen that let you modify the closing behavior.

The following works in XamlPad.

 <StackPanel>
  <ToggleButton Name="button"> 
    <ToggleButton.Template>
      <ControlTemplate TargetType="ToggleButton">
        <TextBlock>Click Me Here!!</TextBlock>
      </ControlTemplate>      
    </ToggleButton.Template>
  </ToggleButton>
  <Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False">
    <Border Background="LightYellow">
      <TextBlock>I'm the popup</TextBlock>
    </Border>
  </Popup> 
 </StackPanel>

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

AndroidStudio Menu:

Build/Clean Project

Update old dependencies

Determine function name from within that function (without using traceback)

I do my own approach used for calling super with safety inside multiple inheritance scenario (I put all the code)

def safe_super(_class, _inst):
    """safe super call"""
    try:
        return getattr(super(_class, _inst), _inst.__fname__)
    except:
        return (lambda *x,**kx: None)


def with_name(function):
    def wrap(self, *args, **kwargs):
        self.__fname__ = function.__name__
        return function(self, *args, **kwargs)
return wrap

sample usage:

class A(object):

    def __init__():
        super(A, self).__init__()

    @with_name
    def test(self):
        print 'called from A\n'
        safe_super(A, self)()

class B(object):

    def __init__():
        super(B, self).__init__()

    @with_name
    def test(self):
        print 'called from B\n'
        safe_super(B, self)()

class C(A, B):

    def __init__():
        super(C, self).__init__()

    @with_name
    def test(self):
        print 'called from C\n'
        safe_super(C, self)()

testing it :

a = C()
a.test()

output:

called from C
called from A
called from B

Inside each @with_name decorated method you have access to self.__fname__ as the current function name.

EF LINQ include multiple and nested entities

One may write an extension method like this:

    /// <summary>
    /// Includes an array of navigation properties for the specified query 
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <param name="query">The query to include navigation properties for that</param>
    /// <param name="navProperties">The array of navigation properties to include</param>
    /// <returns></returns>
    public static IQueryable<T> Include<T>(this IQueryable<T> query, params string[] navProperties)
        where T : class
    {
        foreach (var navProperty in navProperties)
            query = query.Include(navProperty);

        return query;
    }

And use it like this even in a generic implementation:

string[] includedNavigationProperties = new string[] { "NavProp1.SubNavProp", "NavProp2" };

var query = context.Set<T>()
.Include(includedNavigationProperties);

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

Percentage Height HTML 5/CSS

You can use 100vw / 100vh. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.

    <div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
        <div style="width:70%; height: 100%; border: 2px dashed red"></div>
        <div style="width:30%; height: 100%; border: 2px dashed red"></div>
    </div>

CMD what does /im (taskkill)?

im is "image process name" example /f /im notepad.exe is specified to kill image process name (program) notepad.exe

How to search for a string in cell array in MATLAB?

>> strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
>> tic; ind=find(ismember(strs,'KU')); toc

Elapsed time is 0.001976 seconds.

>> tic; find(strcmp('KU', strs)); toc

Elapsed time is 0.000014 seconds.

SO, clearly strcmp('KU', strs) takes much lesser time than ismember(strs,'KU')

How set the android:gravity to TextView from Java side in Android

Solved this by doing a few things, first getting the height of my TextView and diving it by the text size to get the total amount of lines possible with the TextView.

int maxLines = (int) TextView.getHeight() / (int) TextView.getTextSize();

After you get this value you need to set your TextView maxLines to this new value.

TextView.setMaxLines(maxLines);

Set the Gravity to Bottom once the maximum amount of lines has been exceeded and it will scroll down automatically.

if (TextView.getLineCount() >= maxLines) {
    TextView.setGravity(Gravity.BOTTOM);
}

In order for this to work correctly, you must use append() to the TextView, If you setText() this will not work.

TextView.append("Your Text");

The benefit of this method is that this can be used dynamically regardless of the height of your TextView and the text size. If you decide to make modifications to your layout this code would still work.

websocket closing connection automatically

Since @Doua Beri is experiencing connection close even when there are 1 Hz SENDs, it may be instead be due to size limits on messages.

This passage from Spring's WebSockets may be useful, with my emphasis ...

Although in theory a WebSocket message can be almost unlimited in size, in practice WebSocket servers impose limits — for example, 8K on Tomcat and 64K on Jetty. For this reason STOMP clients such as stomp.js split larger STOMP messages at 16K boundaries and send them as multiple WebSocket messages thus requiring the server to buffer and re-assemble.

VirtualBox error "Failed to open a session for the virtual machine"

Killing VM process dint work in my case.

Right click on the VM and click on "Discard Saved State".

 Right click on the VM and click on "Discard Saved State".

This worked for me.

Submit Button Image

<INPUT TYPE="image" SRC="images/submit.gif" HEIGHT="30" WIDTH="173" BORDER="0" ALT="Submit Form">
Where the standard submit button has TYPE="submit", we now have TYPE="image". The image type is by default a form submitting button. More simple

jQuery get value of select onChange

Let me share an example which I developed with BS4, thymeleaf and Spring boot.

I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").

First, the thymeleaf snippet:

 <div class="form-group">
     <label th:for="topicId" th:text="#{label.topic}">Topic</label>
     <select class="custom-select"
             th:id="topicId" th:name="topicId"
             th:field="*{topicId}"
             th:errorclass="is-invalid" required>
         <option value="" selected
                 th:text="#{option.select}">Select
         </option>
         <optgroup th:each="topicGroup : ${topicGroups}"
                   th:label="${topicGroup}">
             <option th:each="topicItem : ${topics}"
                     th:if="${topicGroup == topicItem.grp} "
                     th:value="${{topicItem.baseIdentity.id}}"
                     th:text="${topicItem.name}"
                     th:selected="${{topicItem.baseIdentity.id==topicId}}">
             </option>
         </optgroup>
         <option th:each="topicIter : ${topics}"
                 th:if="${topicIter.grp == ''} "
                 th:value="${{topicIter.baseIdentity.id}}"
                 th:text="${topicIter.name}"
                 th:selected="${{topicIter.baseIdentity?.id==topicId}}">
         </option>
     </select>
     <small id="topicHelp" class="form-text text-muted"
            th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->

<div class="form-group">
    <label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
    <select class="custom-select"
            id="subtopicsId" name="subtopicsId"
            th:field="*{subtopicsId}"
            th:errorclass="is-invalid" multiple="multiple">
        <option value="" disabled
                th:text="#{option.multiple.optional}">Select
        </option>
        <option th:each="subtopicsIter : ${subtopicsList}"
                th:value="${{subtopicsIter.baseIdentity.id}}"
                th:text="${subtopicsIter.name}">
        </option>
    </select>
    <small id="subtopicsHelp" class="form-text text-muted"
           th:unless="${#fields.hasErrors('subtopicsId')}"
           th:text="#{label.subtopics.tt}">select</small>
    <small id="subtopicsIdError" class="invalid-feedback"
           th:if="${#fields.hasErrors('subtopicsId')}"
           th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->

I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.

Now, here's the jQuery that handles changes:

$('#topicId').change(function () {
    selectedOption = $(this).val();
    if (selectedOption === "") {
        $('#subtopicsId').prop('disabled', 'disabled').val('');
        $("#subtopicsId option").slice(1).remove(); // keep first
    } else {
        $('#subtopicsId').prop('disabled', false)
        var orig = $(location).attr('origin');
        var url = orig + "/getsubtopics/" + selectedOption;
        $.ajax({
            url: url,
           success: function (response) {
                  var len = response.length;
                    $("#subtopicsId option[value!='']").remove(); // keep first 
                    for (var i = 0; i < len; i++) {
                        var id = response[i]['baseIdentity']['id'];
                        var name = response[i]['name'];
                        $("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
                    }
                },
                error: function (e) {
                    console.log("ERROR : ", e);
                }
        });
    }
}).change(); // and call it once defined

The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.

BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.

How to start Spyder IDE on Windows

The name of the spyder executable was changed to spyder3.exe in python version 3. I install pyqt5 and spyder via pip and was able to launch spyder3. I first tried without installing pyqt5 and nothing happened. Once I installed pyqt5, then spyder 3 opened.

Try the following from a windows cmd.exe prompt:

    C:\Users\..>pip install pyqt5
    C:\Users\..>pip install spyder
    C:\Users\..>spyder3

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

Right here: http://jt400.sourceforge.net/

This is what I use for that exact purpose.

EDIT: Usage Examples (minus exceptions):

// Driver initialization
AS400JDBCDriver driver = new com.ibm.as400.access.AS400JDBCDriver();
DriverManager.registerDriver(driver);

// JDBC Connection URL
String url = "jdbc:as400://10.10.10.10" + ";promt=false" // disable GUI prompting by jt400 library

// Get a Connection object (this is used to create statements, etc)
Connection conn = DriverManager.getConnection(url, UserString, PassString);

Hope that helps!

Zip folder in C#

Following code uses a third-party ZIP component from Rebex:

// add content of the local directory C:\Data\  
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist) 
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");

Or if you want to add more folders without need to open and close archive multiple times:

using Rebex.IO.Compression;
...

// open the ZIP archive from an existing file 
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);

// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");

// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");

// close the archive 
zip.Close(ArchiveSaveAction.Auto);

You can download the ZIP component here.

Using a free, LGPL licensed SharpZipLib is a common alternative.

Disclaimer: I work for Rebex

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    img.remove();
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    img.remove();
    newImg.attr('id', old_id);
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

$("#resetlink").click(function(){
    clearInterval(timerRocket);
    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.
});

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()
};

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    img.css(orig).hide();
    (callback || function() {})();
});

New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

How to sum the values of one column of a dataframe in spark/scala

Using spark sql query..just incase if it helps anyone!

import org.apache.spark.sql.SparkSession 
import org.apache.spark.SparkConf 
import org.apache.spark.sql.functions._ 
import org.apache.spark.SparkContext 
import java.util.stream.Collectors

val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()

df.createOrReplaceTempView("steps")
val sum = spark.sql("select  sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28

endsWith in JavaScript

A way to future proof and/or prevent overwriting of existing prototype would be test check to see if it has already been added to the String prototype. Here's my take on the non-regex highly rated version.

if (typeof String.endsWith !== 'function') {
    String.prototype.endsWith = function (suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };
}

submit form on click event using jquery

Do you need to post the the form to an URL or do you only need to detect the submit-event? Because you can detect the submit-event by adding onsubmit="javascript:alert('I do also submit');"

<form action="javascript:alert('submitted');" method="post" id="testForm" onsubmit="javascript:alert('I do also submit');">...</form>

Not sure that this is what you are looking for though.

How to make a link open multiple pages when clicked

You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:

HTML

<ul class="yourlinks">
    <li><a href="http://www.google.com/"></li>
    <li><a href="http://www.yahoo.com/"></li>
</ul>

jQuery

$(function() { // On DOM content ready...
    var urls = [];

    $('.yourlinks a').each(function() {
        urls.push(this.href); // Store the URLs from the links...
    });

    var multilink = $('<a href="#">Click here</a>'); // Create a new link...
    multilink.click(function() {
        for (var i in urls) {
            window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
        }
    });

    $('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});

This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

Getting JavaScript object key list

If you only want the keys which are specific to that particular object and not any derived prototype properties:

function getKeys(obj) {
    var r = []
    for (var k in obj) {
        if (!obj.hasOwnProperty(k)) 
            continue
        r.push(k)
    }
    return r
}

e.g:

var keys = getKeys({'eggs': null, 'spam': true})
var length = keys.length // access the `length` property as usual for arrays

jQuery or JavaScript auto click

$(document).ready(function(){
   $('.lbOn').click();
});

Suppose this would work too.

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

What is the python keyword "with" used for?

Explanation from the Preshing on Programming blog:

It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

 with open('output.txt', 'w') as f:
     f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.

Is it possible to declare a variable in Gradle usable in Java?

I'm using this code and working very fine.

def baseUrl = '\"http://patelwala.com/myapi/"'
def googleServerKey = '\"87171841097-opu71rk2ps35ibv96ud57g3ktto6ioio.apps.googleusercontent.com"'
android {
  buildTypes {
  release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
    releasedebug {
        initWith debug
        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id' ,googleServerKey
    }
    debug {

        buildConfigField 'String', 'BASE_URL', baseUrl
        buildConfigField 'String', 'web_client_id', googleServerKey
    }
 }
}

}

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:

  • (X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C), where ... means "0 or more different values
  • (B,) dot (B, C) -> (C,)
  • (A, B) dot (B,) -> (A,)
  • (B,) dot (B,) -> ()

Your problem is that you are using np.matrix, which is totally unnecessary in your code - the main purpose of np.matrix is to translate a * b into np.dot(a, b). As a general rule, np.matrix is probably not a good choice.

How to declare 2D array in bash

A way to simulate arrays in bash (it can be adapted for any number of dimensions of an array):

#!/bin/bash

## The following functions implement vectors (arrays) operations in bash:
## Definition of a vector <v>:
##      v_0 - variable that stores the number of elements of the vector
##      v_1..v_n, where n=v_0 - variables that store the values of the vector elements

VectorAddElementNext () {
# Vector Add Element Next
# Adds the string contained in variable $2 in the next element position (vector length + 1) in vector $1

    local elem_value
    local vector_length
    local elem_name

    eval elem_value=\"\$$2\"
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    vector_length=$(( vector_length + 1 ))
    elem_name=$1_$vector_length

    eval $elem_name=\"\$elem_value\"
    eval $1_0=$vector_length
}

VectorAddElementDVNext () {
# Vector Add Element Direct Value Next
# Adds the string $2 in the next element position (vector length + 1) in vector $1

    local elem_value
    local vector_length
    local elem_name

    eval elem_value="$2"
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    vector_length=$(( vector_length + 1 ))
    elem_name=$1_$vector_length

    eval $elem_name=\"\$elem_value\"
    eval $1_0=$vector_length
}

VectorAddElement () {
# Vector Add Element
# Adds the string contained in the variable $3 in the position contained in $2 (variable or direct value) in the vector $1

    local elem_value
    local elem_position
    local vector_length
    local elem_name

    eval elem_value=\"\$$3\"
    elem_position=$(($2))
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    if [ $elem_position -ge $vector_length ]; then
        vector_length=$elem_position
    fi

    elem_name=$1_$elem_position

    eval $elem_name=\"\$elem_value\"
    if [ ! $elem_position -eq 0 ]; then
        eval $1_0=$vector_length
    fi
}

VectorAddElementDV () {
# Vector Add Element
# Adds the string $3 in the position $2 (variable or direct value) in the vector $1

    local elem_value
    local elem_position
    local vector_length
    local elem_name

    eval elem_value="$3"
    elem_position=$(($2))
    eval vector_length=\$$1\_0
    if [ -z "$vector_length" ]; then
        vector_length=$((0))
    fi

    if [ $elem_position -ge $vector_length ]; then
        vector_length=$elem_position
    fi

    elem_name=$1_$elem_position

    eval $elem_name=\"\$elem_value\"
    if [ ! $elem_position -eq 0 ]; then
        eval $1_0=$vector_length
    fi
}

VectorPrint () {
# Vector Print
# Prints all the elements names and values of the vector $1 on sepparate lines

    local vector_length

    vector_length=$(($1_0))
    if [ "$vector_length" = "0" ]; then
        echo "Vector \"$1\" is empty!"
    else
        echo "Vector \"$1\":"
        for ((i=1; i<=$vector_length; i++)); do
            eval echo \"[$i]: \\\"\$$1\_$i\\\"\"
            ###OR: eval printf \'\%s\\\n\' \"[\$i]: \\\"\$$1\_$i\\\"\"
        done
    fi
}

VectorDestroy () {
# Vector Destroy
# Empties all the elements values of the vector $1

    local vector_length

    vector_length=$(($1_0))
    if [ ! "$vector_length" = "0" ]; then
        for ((i=1; i<=$vector_length; i++)); do
            unset $1_$i
        done
        unset $1_0
    fi
}

##################
### MAIN START ###
##################

## Setting vector 'params' with all the parameters received by the script:
for ((i=1; i<=$#; i++)); do
    eval param="\${$i}"
    VectorAddElementNext params param
done

# Printing the vector 'params':
VectorPrint params

read temp

## Setting vector 'params2' with the elements of the vector 'params' in reversed order:
if [ -n "$params_0" ]; then
    for ((i=1; i<=$params_0; i++)); do
        count=$((params_0-i+1))
        VectorAddElement params2 count params_$i
    done
fi

# Printing the vector 'params2':
VectorPrint params2

read temp

## Getting the values of 'params2'`s elements and printing them:
if [ -n "$params2_0" ]; then
    echo "Printing the elements of the vector 'params2':"
    for ((i=1; i<=$params2_0; i++)); do
        eval current_elem_value=\"\$params2\_$i\"
        echo "params2_$i=\"$current_elem_value\""
    done
else
    echo "Vector 'params2' is empty!"
fi

read temp

## Creating a two dimensional array ('a'):
for ((i=1; i<=10; i++)); do
    VectorAddElement a 0 i
    for ((j=1; j<=8; j++)); do
        value=$(( 8 * ( i - 1 ) + j ))
        VectorAddElementDV a_$i $j $value
    done
done

## Manually printing the two dimensional array ('a'):
echo "Printing the two-dimensional array 'a':"
if [ -n "$a_0" ]; then
    for ((i=1; i<=$a_0; i++)); do
        eval current_vector_lenght=\$a\_$i\_0
        if [ -n "$current_vector_lenght" ]; then
            for ((j=1; j<=$current_vector_lenght; j++)); do
                eval value=\"\$a\_$i\_$j\"
                printf "$value "
            done
        fi
        printf "\n"
    done
fi

################
### MAIN END ###
################

Python - round up to the nearest ten

Here is one way to do it:

>>> n = 46
>>> (n + 9) // 10 * 10
50

Uploading an Excel sheet and importing the data into SQL Server database

    public async Task<HttpResponseMessage> PostFormDataAsync()    //async is used for defining an asynchronous method
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        var fileLocation = "";
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);  //Helps in HTML file uploads to write data to File Stream
        try
        {
            // Read the form data.
        await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
                var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
                File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
                fileLocation = file.LocalFileName + filePath; //Complete file location
            }
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
            return response;
}
catch (System.Exception e)
    {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
public void ReadFromExcel()
{
try
        {
            DataTable sheet1 = new DataTable();
            OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
            csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            csbuilder.DataSource = fileLocation;
            csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
            string selectSql = @"SELECT * FROM [Sheet1$]";
            using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
            {
                connection.Open();
                adapter.Fill(sheet1);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }          
}

How to get Locale from its String representation in Java?

Method that returns locale from string exists in commons-lang library: LocaleUtils.toLocale(localeAsString)

Android: how to draw a border to a LinearLayout

Extend LinearLayout/RelativeLayout and use it straight on the XML

package com.pkg_name ;
...imports...
public class LinearLayoutOutlined extends LinearLayout {
    Paint paint;    

    public LinearLayoutOutlined(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    public LinearLayoutOutlined(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        setWillNotDraw(false) ;
        paint = new Paint();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        /*
        Paint fillPaint = paint;
        fillPaint.setARGB(255, 0, 255, 0);
        fillPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(fillPaint) ;
        */

        Paint strokePaint = paint;
        strokePaint.setARGB(255, 255, 0, 0);
        strokePaint.setStyle(Paint.Style.STROKE);
        strokePaint.setStrokeWidth(2);  
        Rect r = canvas.getClipBounds() ;
        Rect outline = new Rect( 1,1,r.right-1, r.bottom-1) ;
        canvas.drawRect(outline, strokePaint) ;
    }

}

<?xml version="1.0" encoding="utf-8"?>

<com.pkg_name.LinearLayoutOutlined
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width=...
    android:layout_height=...
   >
   ... your widgets here ...

</com.pkg_name.LinearLayoutOutlined>

Excel: Can I create a Conditional Formula based on the Color of a Cell?

Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:

=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))

Hit OK then close the "Name Manager" window.

Now, in cell A1 enter the following:

=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))

This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html

Cheers.

::Edit::

The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:

=GET.CELL(63,Sheet1!B2)

Pip install Matplotlib error with virtualenv

None of the above answers worked for me in Mint, so I did:

sudo apt-get install build-essential g++

dd: How to calculate optimal blocksize?

The optimal block size depends on various factors, including the operating system (and its version), and the various hardware buses and disks involved. Several Unix-like systems (including Linux and at least some flavors of BSD) define the st_blksize member in the struct stat that gives what the kernel thinks is the optimal block size:

#include <sys/stat.h>
#include <stdio.h>

int main(void)
{
    struct stat stats;

    if (!stat("/", &stats))
    {
        printf("%u\n", stats.st_blksize);
    }
}

The best way may be to experiment: copy a gigabyte with various block sizes and time that. (Remember to clear kernel buffer caches before each run: echo 3 > /proc/sys/vm/drop_caches).

However, as a rule of thumb, I've found that a large enough block size lets dd do a good job, and the differences between, say, 64 KiB and 1 MiB are minor, compared to 4 KiB versus 64 KiB. (Though, admittedly, it's been a while since I did that. I use a mebibyte by default now, or just let dd pick the size.)

Creating a range of dates in Python

Get range of dates between specified start and end date (Optimized for time & space complexity):

import datetime

start = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")
end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]

for date in date_generated:
    print date.strftime("%d-%m-%Y")

Convert a list of characters into a string

This works in many popular languages like JavaScript and Ruby, why not in Python?

>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'

Strange enough, in Python the join method is on the str class:

# this is the Python way
"".join(['a','b','c','d'])

Why join is not a method in the list object like in JavaScript or other popular script languages? It is one example of how the Python community thinks. Since join is returning a string, it should be placed in the string class, not on the list class, so the str.join(list) method means: join the list into a new string using str as a separator (in this case str is an empty string).

Somehow I got to love this way of thinking after a while. I can complain about a lot of things in Python design, but not about its coherence.

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

Compiling Java 7 code via Maven

Try to change Java compiler settings in Properties in Eclipse-

Goto: Preferences->Java->Compiler->Compiler Compliance Level-> 1.7 Apply Ok

Restart IDE.

Confirm Compiler setting for project- Goto: Project Properties->Java Compiler-> Uncheck(Use Compliance from execution environment 'JavaSE-1.6' on the java Build path.) and select 1.7 from the dropdown. (Ignore if already 1.7)

Restart IDE.

If still the problem persist- Run individual test cases using command in terminal-

mvn -Dtest=<test class name> test

HTML table sort

Here is another library.

Changes required are -

  1. Add sorttable js

  2. Add class name sortable to table.

Click the table headers to sort the table accordingly:

_x000D_
_x000D_
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>

<table class="sortable">
  <tr>
    <th>Name</th>
    <th>Address</th>
    <th>Sales Person</th>
  </tr>

  <tr class="item">
    <td>user:0001</td>
    <td>UK</td>
    <td>Melissa</td>
  </tr>
  <tr class="item">
    <td>user:0002</td>
    <td>France</td>
    <td>Justin</td>
  </tr>
  <tr class="item">
    <td>user:0003</td>
    <td>San Francisco</td>
    <td>Judy</td>
  </tr>
  <tr class="item">
    <td>user:0004</td>
    <td>Canada</td>
    <td>Skipper</td>
  </tr>
  <tr class="item">
    <td>user:0005</td>
    <td>Christchurch</td>
    <td>Alex</td>
  </tr>

</table>
_x000D_
_x000D_
_x000D_

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

None of the answers here worked for me unfortunately.

I ended up using Custom Model Binding and used a third-party Sanitizer.

See my self-answered question here.

Build .NET Core console application to output an EXE

The following will produce, in the output directory,

  • all the package references
  • the output assembly
  • the bootstrapping exe

But it does not contain all .NET Core runtime assemblies.

<PropertyGroup>
  <Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>

<ItemGroup>
  <BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>

<Target Name="GenerateNetcoreExe"
        AfterTargets="Build"
        Condition="'$(IsNestedBuild)' != 'true'">
  <RemoveDir Directories="$(Temp)" />
  <Exec
    ConsoleToMSBuild="true"
    Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
    <Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
  </Exec>
  <Copy
    SourceFiles="@(BootStrapFiles)"
    DestinationFolder="$(OutputPath)"
  />

</Target>

I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole

How to animate the change of image in an UIImageView?

As of iOS 5 this one is far more easy:

[newView setAlpha:0.0];
[UIView animateWithDuration:0.4 animations:^{
    [newView setAlpha:0.5];
}];

React onClick and preventDefault() link refresh/redirect?

In a context like this

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

As you can see, you have to call preventDefault() explicitly. I think that this docs, could be helpful.

Laravel - display a PDF file in storage without forcing download?

Update for 2017

As of Laravel 5.2 documented under Other response types you can now use the file helper to display a file in the user's browser.

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

Source/thanks to below answer

Outdated answer from 2014

You just need to send the contents of the file to the browser and tell it the content type rather than tell the browser to download it.

$filename = 'test.pdf';
$path = storage_path($filename);

return Response::make(file_get_contents($path), 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'inline; filename="'.$filename.'"'
]);

If you use Response::download it automatically sets the Content-Disposition to attachment which causes the browser to download it. See this question for the differences between Content-Disposition inline and attachment.

Edit: As per the request in the comments, I should point out that you'd need to use Response at the beginning of your file in order to use the Facade.

use Response;

Or the fully qualified namespace if Response isn't aliased to Illuminate's Response Facade.

object==null or null==object?

This trick supposed to prevent v = null kind of typos.

But Java allows only boolean expressions as if() conditions so that trick does not make much sense, compiler will find those typos anyway.

It is still valuable trick for C/C++ code though.

Python/BeautifulSoup - how to remove all tags from an element?

Here is the source code: you can get the text which is exactly in the URL

URL = ''
page = requests.get(URL)
soup = bs4.BeautifulSoup(page.content,'html.parser').get_text()
print(soup)

How to sign an android apk file

APK Signing Process

To manually sign an Android APK file run these three commands:

  1. Generate Keystore file

    keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000
    
  2. Sign Your APK file using jarsigner

    jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME
    
  3. Align Signed APK using zipalign tool

    zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH
    

STEP 1


Generate Keystore file

keytool -genkey -v -keystore YOUR_KEYSTORE_NAME.keystore -alias ALIAS_NAME -keyalg RSA -keysize 2048 -validity 10000

Example:

keytool -genkey -v -keystore id.keystore -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000

keystore password : yourApp@123 key password : yourApp@123

CMD O/P

D:\ru\SignedBuilds\MySignedApp>keytool -genkey -v -keystore id.keystore
 -alias MySignedApp -keyalg RSA -keysize 2048 -validity 10000
Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  MySignedApp Sample
What is the name of your organizational unit?
  [Unknown]:  Information Technology
What is the name of your organization?
  [Unknown]:  MySignedApp Demo
What is the name of your City or Locality?
  [Unknown]:  Mumbai
What is the name of your State or Province?
  [Unknown]:  Maharashtra
What is the two-letter country code for this unit?
  [Unknown]:  IN
Is CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra, C=IN corr
ect?
  [no]:  y

Generating 2,048 bit RSA key pair and self-signed certificate (SHA256withRSA) with a validity of 10,
000 days
        for: CN=MySignedApp Demo, OU=Information Technology, O=MySignedApp Demo, L=Mumbai, ST=Maharashtra,
 C=IN
Enter key password for <MySignedApp>
        (RETURN if same as keystore password):
Re-enter new password:
[Storing id.keystore]

D:\ru\SignedBuilds\MySignedApp>

STEP 2


Sign your app with your private keystore using jarsigner

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore KEYSTORE_FILE_PATH UNSIGNED_APK_PATH ALIAS_NAME

Example

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id

CMD O/P

D:\ru\SignedBuilds\MySignedApp>jarsigner -verbose -sigalg SHA1withRSA -
digestalg SHA1 -keystore D:\ru\SignedBuilds\MySignedApp\id.keystore D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk id ---
ect
Enter Passphrase for keystore:
   adding: META-INF/MANIFEST.MF
   adding: META-INF/---.SF
   adding: META-INF/---.RSA
  signing: AndroidManifest.xml
  ..... 
    signing: classes.dex
  signing: lib/commons-codec-1.6.jar
  signing: lib/armeabi/libkonyjsvm.so
jar signed.

Warning:
No -tsa or -tsacert is provided and this jar is not timestamped. Without a timestamp, users may not
be able to validate this jar after the signer certificate's expiration date (2044-02-07) or after an
y future revocation date.

D:\ru\SignedBuilds\MySignedApp>

Verify that your APK is signed

jarsigner -verify -verbose -certs JARSIGNED_APK_FILE_PATH

Example

jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk

CMD O/P

D:\ru\SignedBuilds\MySignedApp>jarsigner -verify -verbose -certs MySignedAppS1-release-unsigned.apk
 s = signature was verified
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope

jar verified.

Warning:
This jar contains entries whose certificate chain is not validated.
This jar contains signatures that does not include a timestamp. Without a timestamp, users may not b
e able to validate this jar after the signer certificate's expiration date (2044-02-09) or after any
 future revocation date.

D:\ru\SignedBuilds\MySignedApp>

STEP 3


Align the final APK package using zipalign

zipalign -v 4 JARSIGNED_APK_FILE_PATH ZIPALIGNED_SIGNED_APK_FILE_PATH_WITH_NAME_ofSignedAPK

Example

zipalign -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedAppS1-release-unsigned.apk D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk

CMD O/P

D:\Android\android-sdk\build-tools\19.1.0>zipalign -v 4 D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16
_prod_playstore\MySignedAppS1-release-unsigned.apk D:\ru\ru_doc\Signed_apk\MySignedApp\28.09.16_prod
_playstore\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...

  4528613 classes.dex (OK - compressed)
 5656594 lib/commons-codec-1.6.jar (OK - compressed)
 5841869 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful

D:\Android\android-sdk\build-tools\19.1.0>

Verify that your APK is Aligned successfully

zipalign -c -v 4 YOUR_APK_PATH

Example

zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk

CMD O/P

D:\Android\android-sdk\build-tools\19.1.0>zipalign -c -v 4 D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk
Verifying alignment of D:\ru\SignedBuilds\MySignedApp\MySignedApp.apk (
4)...

 4453984 res/drawable/zoomout.png (OK)
 4454772 res/layout/tabview.xml (OK - compressed)
 4455243 res/layout/wheel_item.xml (OK - compressed)
 4455608 resources.arsc (OK)
 4470161 classes.dex (OK - compressed)
 5597923 lib/commons-codec-1.6.jar (OK - compressed)
 5783198 lib/armeabi/libkonyjsvm.so (OK - compressed)
Verification succesful

D:\Android\android-sdk\build-tools\19.1.0>

Note:

The verify command is just to check whether APK is built and signed correctly!

References

I hope this will help one and all :)

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

Just to make sure that in studio version 2.3 you won't see a dropdown near constraint-layout in sdk tools, it will by default install the latest version

To get the desired version check the box saying show package details and boom you can now choose the desired version you want to install

Implement Validation for WPF TextBoxes

When it comes to DiSaSteR's answer, I noticed a different behavior. textBox.Text shows the text in the TextBox as it was before the user entered a new character, while e.Text shows the single character the user just entered. One challenge is that this character might not get appended to the end, but it will be inserted at the carret position:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e){
  Regex regex = new Regex ( "[^0-9]+" );

  string text;
  if (textBox.CaretIndex==textBox.Text.Length) {
    text = textBox.Text + e.Text;
  } else {
    text = textBox.Text.Substring(0, textBox.CaretIndex)  + e.Text + textBox.Text.Substring(textBox.CaretIndex);
  }

  if(regex.IsMatch(text)){
      MessageBox.Show("Error");
  }
}

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

My Solution in laravel 5.2

{{ Form::open(['route' => ['votes.submit', $video->id],  'method' => 'POST']) }}
    <button type="submit" class="btn btn-primary">
        <span class="glyphicon glyphicon-thumbs-up"></span> Votar
    </button>
{{ Form::close() }}

My Routes File (under middleware)

Route::post('votar/{id}', [
    'as' => 'votes.submit',
    'uses' => 'VotesController@submit'
]);

Route::delete('votar/{id}', [
    'as' => 'votes.destroy',
    'uses' => 'VotesController@destroy'
]);

How to set the timeout for a TcpClient?

As Simon Mourier mentioned, it's possible to use ConnectAsync TcpClient's method with Task in addition and stop operation as soon as possible.
For example:

// ...
client = new TcpClient(); // Initialization of TcpClient
CancellationToken ct = new CancellationToken(); // Required for "*.Task()" method
if (client.ConnectAsync(this.ip, this.port).Wait(1000, ct)) // Connect with timeout of 1 second
{

    // ... transfer

    if (client != null) {
        client.Close(); // Close the connection and dispose a TcpClient object
        Console.WriteLine("Success");
        ct.ThrowIfCancellationRequested(); // Stop asynchronous operation after successull connection(...and transfer(in needed))
    }
}
else
{
    Console.WriteLine("Connetion timed out");
}
// ...

Also, I would recommended checking the AsyncTcpClient C# library with some examples provided like Server <> Client.

How to explicitly obtain post data in Spring MVC?

Another answer to the OP's exact question is to set the consumes content type to "text/plain" and then declare a @RequestBody String input parameter. This will pass the text of the POST data in as the declared String variable (postPayload in the following example).

Of course, this presumes your POST payload is text data (as the OP stated was the case).

Example:

    @RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
    public ModelAndView someMethod(@RequestBody String postPayload) {    
        // ...    
    }

How to write a:hover in inline CSS?

You could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't .

find first sequence item that matches a criterion

a=[100,200,300,400,500]
def search(b):
 try:
  k=a.index(b)
  return a[k] 
 except ValueError:
    return 'not found'
print(search(500))

it'll return the object if found else it'll return "not found"

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

One more example of 'Variable is out of scope'

As I've seen that kind of questions a few times already, maybe one more example to what's illegal even if it might feel okay.

Consider this code:

if(somethingIsTrue()) {
  String message = "Everything is fine";
} else {
  String message = "We have an error";
}
System.out.println(message);

That's invalid code. Because neither of the variables named message is visible outside of their respective scope - which would be the surrounding brackets {} in this case.

You might say: "But a variable named message is defined either way - so message is defined after the if".

But you'd be wrong.

Java has no free() or delete operators, so it has to rely on tracking variable scope to find out when variables are no longer used (together with references to these variables of cause).

It's especially bad if you thought you did something good. I've seen this kind of error after "optimizing" code like this:

if(somethingIsTrue()) {
  String message = "Everything is fine";
  System.out.println(message);
} else {
  String message = "We have an error";
  System.out.println(message);
}

"Oh, there's duplicated code, let's pull that common line out" -> and there it it.

The most common way to deal with this kind of scope-trouble would be to pre-assign the else-values to the variable names in the outside scope and then reassign in if:

String message = "We have an error";
if(somethingIsTrue()) {
  message = "Everything is fine";
} 
System.out.println(message);

PHP Date Time Current Time Add Minutes

I think one of the best solutions and easiest is:

strtotime("+30 minutes")

Maybe it's not the most efficient but is one of the more understandable.

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

This happened to me when I tried to install a higher MySQL version than the one coming with the distribution.

I erased the old version then installed the new one (rpm -e ... then rpm -i MySQL-server* ) But did not realize that the files in /var/lib/mysql were still from the older version (with differences as explained by Marc Alff - thanks!)

I could have done an mysql_upgrade, but as I wanted to start from scratch I did:

# su - mysql
$ rm -rf /var/lib/mysql/*
$ mysql_install_db
# /etc/init.d/mysql start

Then set root password (/usr/bin/mysqladmin -u root password), and all worked as expected with the GRANT commands...

SyntaxError: expected expression, got '<'

I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess. The solution was to add the correct path slashes in . Each situation is unique, but hope this helps someone.

Fatal error: unexpectedly found nil while unwrapping an Optional values

Replace this line cell.labelTitle.text = "This is a title"
with cell.labelTitle?.text = "This is a title"

Download file of any type in Asp.Net MVC using FileResult?

If you're using .NET Framework 4.5 then you use use the MimeMapping.GetMimeMapping(string FileName) to get the MIME-Type for your file. This is how I've used it in my action.

return File(Path.Combine(@"c:\path", fileFromDB.FileNameOnDisk), MimeMapping.GetMimeMapping(fileFromDB.FileName), fileFromDB.FileName);

CSS blur on background image but not on content

Add another div or img to your main div and blur that instead. jsfiddle

.blur {
    background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
    background-size:cover;
    -webkit-filter: blur(13px);
    -moz-filter: blur(13px);
    -o-filter: blur(13px);
    -ms-filter: blur(13px);
    filter: blur(13px);
    position:absolute;
    width:100%;
    height:100%;
}

Type.GetType("namespace.a.b.ClassName") returns null

If the assembly is referenced and the Class visible :

typeof(namespace.a.b.ClassName)

GetType returns null because the type is not found, with typeof, the compiler may help you to find out the error.

addEventListener, "change" and option selection

The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){
      document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
      }

function addActivityItem(){
      //option is selected
      alert("yeah");
}

window.addEventListener("load", start, false);

In PowerShell, how do I test whether or not a specific variable exists in global scope?

Test-Path can be used with a special syntax:

Test-Path variable:global:foo

This also works for environment variables ($env:foo):

Test-Path env:foo

And for non-global variables (just $foo inline):

Test-Path variable:foo

Setting width of spreadsheet cell using PHPExcel

setAutoSize method must come before setWidth:

$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimensionByColumn('C')->setWidth('10');

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Using mysql concat() in WHERE clause?

you can do that (work in mysql) probably other SQL too.. just try this:

select * from table where concat(' ',first_name,last_name) 
    like '%$search_term%';

Show hidden div on ng-click within ng-repeat

Remove the display:none, and use ng-show instead:

<ul class="procedures">
    <li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
        <h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="showDetails">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Here's the fiddle: http://jsfiddle.net/asmKj/


You can also use ng-class to toggle a class:

<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">

I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/

Why use String.Format?

One reason it is not preferable to write the string like 'string +"Value"+ string' is because of Localization. In cases where localization is occurring we want the localized string to be correctly formatted, which could be very different from the language being coded in.

For example we need to show the following error in different languages:

MessageBox.Show(String.Format(ErrorManager.GetError("PIDV001").Description, proposalvalue.ProposalSource)

where

'ErrorCollector.GetError("ERR001").ErrorDescription' returns a string like "Your ID {0} is not valid". This message must be localized in many languages. In that case we can't use + in C#. We need to follow string.format.

Check if a value is in an array or not with Excel VBA

This Question was asked here: VBA Arrays - Check strict (not approximative) match

Sub test()
    vars1 = Array("Examples")
    vars2 = Array("Example")
    If IsInArray(Range("A1").value, vars1) Then
        x = 1
    End If

    If IsInArray(Range("A1").value, vars2) Then
        x = 1
    End If
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

Javascript select onchange='this.form.submit()'

If you're using jQuery, it's as simple as this:

 $('#mySelect').change(function()
 {
     $('#myForm').submit();
 });

Table-level backup

You can run the below query to take a backup of the existing table which would create a new table with existing structure of the old table along with the data.

select * into newtablename from oldtablename

To copy just the table structure, use the below query.

select * into newtablename from oldtablename where 1 = 2

Common xlabel/ylabel for matplotlib subplots

Since the command:

fig,ax = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size)

you used returns a tuple consisting of the figure and a list of the axes instances, it is already sufficient to do something like (mind that I've changed fig,axto fig,axes):

fig,axes = plt.subplots(5,2,sharex=True,sharey=True,figsize=fig_size)

for ax in axes:
    ax.set_xlabel('Common x-label')
    ax.set_ylabel('Common y-label')

If you happen to want to change some details on a specific subplot, you can access it via axes[i] where i iterates over your subplots.

It might also be very helpful to include a

fig.tight_layout()

at the end of the file, before the plt.show(), in order to avoid overlapping labels.

how to call a variable in code behind to aspx page

For

<%=clients%>

to work you need to have a public or protected variable clients in the code-behind.

Here is an article that explains it: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

What are WSDL, SOAP and REST?

Example: In a simple terms if you have a web service of calculator.

WSDL: WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract and so on.

SOAP: Where as using SOAP you actually perform actions like doDelete(), doSubtract(), doAdd(). So SOAP and WSDL are apples and oranges. We should not compare them. They both have their own different functionality.

Why we use SOAP and WSDL: For platform independent data exchange.

EDIT: In a normal day to day life example:

WSDL: When we go to a restaurant we see the Menu Items, those are the WSDL's.

Proxy Classes: Now after seeing the Menu Items we make up our Mind (Process our mind on what to order): So, basically we make Proxy classes based on WSDL Document.

SOAP: Then when we actually order the food based on the Menu's: Meaning we use proxy classes to call upon the service methods which is done using SOAP. :)

Error after upgrading pip: cannot import name 'main'

I used the following code to load a module that might need install, thus avoiding this error (which I also got) - using the latest Python and latest pip with no problem

try
  from colorama import Fore, Back, Style
except:
  !pip install colorama
  from colorama import Fore, Back, Style

Calculating distance between two geographic locations

distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).

distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]

hope that this helps

i've used distanceTo to get the distance from point A to B i think that is the way to go.

Refresh image with a new one at the same url

I solved this problem by sending the data back through a servlet.

response.setContentType("image/png");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
response.setDateHeader("Expires", 0);

BufferedImage img = ImageIO.read(new File(imageFileName));

ImageIO.write(img, "png", response.getOutputStream());

Then from the page you just give it the servlet with some params to grab the correct image file.

<img src="YourServlet?imageFileName=imageNum1">

Difference between filter and filter_by in SQLAlchemy

filter_by uses keyword arguments, whereas filter allows pythonic filtering arguments like filter(User.name=="john")

Styling Password Fields in CSS

I found I could improve the situation a little with CSS dedicated to Webkit (Safari, Chrome). However, I had to set a fixed width and height on the field because the font change will resize the field.

@media screen and (-webkit-min-device-pixel-ratio:0){ /* START WEBKIT */
  INPUT[type="password"]{
  font-family:Verdana,sans-serif;
  height:28px;
  font-size:19px;
  width:223px;
  padding:5px;
  }
} /* END WEBKIT */

How to modify existing, unpushed commit messages?

I realised that I had pushed a commit with a typo in it. In order to undo, I did the following:

git commit --amend -m "T-1000, advanced prototype"
git push --force

Warning: force pushing your changes will overwrite the remote branch with your local one. Make sure that you aren't going to be overwriting anything that you want to keep. Also be cautious about force pushing an amended (rewritten) commit if anyone else shares the branch with you, because they'll need to rewrite their own history if they have the old copy of the commit that you've just rewritten.

Converting JavaScript object with numeric keys into array

var obj = {"0":"1","1":"2","2":"3","3":"4"};

var vals = Object.values(obj);

console.log(vals); //["1", "2", "3", "4"]

Another alternative to the question

var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed

How can I check the size of a collection within a Django template?

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count

jQuery get an element by its data-id

$('[data-item-id="stand-out"]')

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

If above all options are not working and you have used nuget packages like Microsoft.Net.Compilers and CodeDom and still not working then there is issue with your project file open project file. Project file is using one of the compiler option which not support your selected language. Open project file with notepad++ and remove the following line.

Orignal Project File

<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />
  <!--Don't delete below one-->
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

Remove The following lines

  <Import Project="..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.Toolset.3.7.0\build\Microsoft.Net.Compilers.Toolset.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.3.7.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />

How do you detect where two line segments intersect?

Based on @Gareth Rees answer, version for Python:

import numpy as np

def np_perp( a ) :
    b = np.empty_like(a)
    b[0] = a[1]
    b[1] = -a[0]
    return b

def np_cross_product(a, b):
    return np.dot(a, np_perp(b))

def np_seg_intersect(a, b, considerCollinearOverlapAsIntersect = False):
    # https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/565282#565282
    # http://www.codeproject.com/Tips/862988/Find-the-intersection-point-of-two-line-segments
    r = a[1] - a[0]
    s = b[1] - b[0]
    v = b[0] - a[0]
    num = np_cross_product(v, r)
    denom = np_cross_product(r, s)
    # If r x s = 0 and (q - p) x r = 0, then the two lines are collinear.
    if np.isclose(denom, 0) and np.isclose(num, 0):
        # 1. If either  0 <= (q - p) * r <= r * r or 0 <= (p - q) * s <= * s
        # then the two lines are overlapping,
        if(considerCollinearOverlapAsIntersect):
            vDotR = np.dot(v, r)
            aDotS = np.dot(-v, s)
            if (0 <= vDotR  and vDotR <= np.dot(r,r)) or (0 <= aDotS  and aDotS <= np.dot(s,s)):
                return True
        # 2. If neither 0 <= (q - p) * r = r * r nor 0 <= (p - q) * s <= s * s
        # then the two lines are collinear but disjoint.
        # No need to implement this expression, as it follows from the expression above.
        return None
    if np.isclose(denom, 0) and not np.isclose(num, 0):
        # Parallel and non intersecting
        return None
    u = num / denom
    t = np_cross_product(v, s) / denom
    if u >= 0 and u <= 1 and t >= 0 and t <= 1:
        res = b[0] + (s*u)
        return res
    # Otherwise, the two line segments are not parallel but do not intersect.
    return None

How do I concatenate a boolean to a string in Python?

answer = True
myvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer

Checking host availability by using ping in bash scripts

up=`fping -r 1 $1 `
if [ -z "${up}" ]; then
    printf "Host $1 not responding to ping   \n"
    else
    printf "Host $1 responding to ping  \n"
fi

Directory index forbidden by Options directive

Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/

Output (echo/print) everything from a PHP Array

You can use print_r to get human-readable output. But to display it as text we add "echo '';"

echo ''; print_r($row);

Troubleshooting "Illegal mix of collations" error in mysql

I used ALTER DATABASE mydb DEFAULT COLLATE utf8_unicode_ci;, but didn't work.

In this query:

Select * from table1, table2 where table1.field = date_format(table2.field,'%H');

This work for me:

Select * from table1, table2 where concat(table1.field) = date_format(table2.field,'%H');

Yes, only a concat.

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

curl posting with header application/x-www-form-urlencoded

Try something like:

$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch);

echo $result;

Paste multiple columns together

Here's a fairly unconventional (but fast) approach: use fwrite from data.table to "paste" the columns together, and fread to read it back in. For convenience, I've written the steps as a function called fpaste:

fpaste <- function(dt, sep = ",") {
  x <- tempfile()
  fwrite(dt, file = x, sep = sep, col.names = FALSE)
  fread(x, sep = "\n", header = FALSE)
}

Here's an example:

d <- data.frame(a = 1:3, b = c('a','b','c'), c = c('d','e','f'), d = c('g','h','i')) 
cols = c("b", "c", "d")

fpaste(d[cols], "-")
#       V1
# 1: a-d-g
# 2: b-e-h
# 3: c-f-i

How does it perform?

d2 <- d[sample(1:3,1e6,TRUE),]
  
library(microbenchmark)
microbenchmark(
  docp = do.call(paste, c(d2[cols], sep="-")),
  tidr = tidyr::unite_(d2, "x", cols, sep="-")$x,
  docs = do.call(sprintf, c(d2[cols], '%s-%s-%s')),
  appl = apply( d2[, cols ] , 1 , paste , collapse = "-" ),
  fpaste = fpaste(d2[cols], "-")$V1,
  dt2 = as.data.table(d2)[, x := Reduce(function(...) paste(..., sep = "-"), .SD), .SDcols = cols][],
  times=10)
# Unit: milliseconds
#    expr        min         lq      mean     median         uq       max neval
#    docp  215.34536  217.22102  220.3603  221.44104  223.27224  225.0906    10
#    tidr  215.19907  215.81210  220.7131  220.09636  225.32717  229.6822    10
#    docs  281.16679  285.49786  289.4514  286.68738  290.17249  312.5484    10
#    appl 2816.61899 3106.19944 3259.3924 3266.45186 3401.80291 3804.7263    10
#  fpaste   88.57108   89.67795  101.1524   90.59217   91.76415  197.1555    10
#     dt2  301.95508  310.79082  384.8247  316.29807  383.94993  874.4472    10

In LINQ, select all values of property X where X != null

get one column in the distinct select and ignore null values:

 var items = db.table.Where(p => p.id!=null).GroupBy(p => p.id)
                                .Select(grp => grp.First().id)
                                .ToList();

How can I make a div stick to the top of the screen once it's been scrolled to?

As of January 2017 and the release of Chrome 56, most browsers in common use support the position: sticky property in CSS.

#thing_to_stick {
  position: sticky;
  top: 0px;
}

does the trick for me in Firefox and Chrome.

In Safari you still need to use position: -webkit-sticky.

Polyfills are available for Internet Explorer and Edge; https://github.com/wilddeer/stickyfill seems to be a good one.

Pythonic way to create a long multi-line string

Generally, I use list and join for multi-line comments/string.

lines = list()
lines.append('SELECT action.enter code here descr as "action", ')
lines.append('role.id as role_id,')
lines.append('role.descr as role')
lines.append('FROM ')
lines.append('public.role_action_def,')
lines.append('public.role,')
lines.append('public.record_def, ')
lines.append('public.action')
query = " ".join(lines)

You can use any string to join all these list elements, like '\n'(newline) or ','(comma) or ' '(space).

How to find substring inside a string (or how to grep a variable)?

expr match "$LIST" '$SOURCE'

don't work because of this function search $SOURCE from begin of the string and return the position just after pattern $SOURCE if found else 0. So you must write another code:

expr match "$LIST" '.*'"$SOURCE" or expr "$LIST" : '.*'"$SOURCE"

The expression $SOURCE must be double quoted so as a parser may set substitution. Single quoted not substitute and the code above will search textual string $SOURCE from the beginning of the $LIST. If you need the beginning of the string subtract the length $SOURCE e.g ${#SOURCE}. You may write also

expr "$LIST" : ".*\($SOURCE\)"

This function just extract $SOURCE from $LIST and return it. You'll get empty string else. But they problem with double double quote. I don't know how it resolve without using additional variable. It's light solution. So you may write in C. There is ready function strstr. Don't use expr index, So is very attractive. But index search not substring and only first char.

How do I determine the dependencies of a .NET application?

Dependency walker works on normal win32 binaries. All .NET dll's and exe's have a small stub header part which makes them look like normal binaries, but all it basically says is "load the CLR" - so that's all that dependency walker will tell you.

To see which things your .NET app actually relies on, you can use the tremendously excellent .NET reflector from Red Gate. (EDIT: Note that .NET Reflector is now a paid product. ILSpy is free and open source and very similar.)

Load your DLL into it, right click, and chose 'Analyze' - you'll then see a "Depends On" item which will show you all the other dll's (and methods inside those dll's) that it needs.

It can sometimes get trickier though, in that your app depends on X dll, and X dll is present, but for whatever reason can't be loaded or located at runtime.

To troubleshoot those kinds of issues, Microsoft have an Assembly Binding Log Viewer which can show you what's going on at runtime

When is the finalize() method called in Java?

Class where we override finalize method

public class TestClass {    
    public TestClass() {
        System.out.println("constructor");
    }

    public void display() {
        System.out.println("display");
    }
    @Override
    public void finalize() {
        System.out.println("destructor");
    }
}

The chances of finalize method being called

public class TestGarbageCollection {
    public static void main(String[] args) {
        while (true) {
            TestClass s = new TestClass();
            s.display();
            System.gc();
        }
    }
}

when the memory is overloaded with dump objects the gc will call finalize method

run and see the console, where you dont find the finalize method being called frequently, when the memory is getting overloaded then the finalize method will be called.

Vue.js get selected option on @change

@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function

<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

function onChange(value) {
  console.log(value);
}

If you want to call Vue methods, do it like this-

<select name="LeaveType" @change="onChange($event)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
  ...
  ...
  methods:{
    onChange:function(event){
       console.log(event.target.value);
    }
  }
})

You can use v-model data attribute on the select element to bind the value.

<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
    data:{
        selectedValue : 1, // First option will be selected by default
    },
    ...
    ...
    methods:{
        onChange:function(event){
            console.log(this.selectedValue);
        }
    }
})

Hope this Helps :-)

Add class to <html> with Javascript?

document.documentElement.classList.add('myCssClass');

classList is supported since ie10: https://caniuse.com/#search=classlist

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18

Saving an Object (Data persistence)

You can use anycache to do the job for you. It considers all the details:

  • It uses dill as backend, which extends the python pickle module to handle lambda and all the nice python features.
  • It stores different objects to different files and reloads them properly.
  • Limits cache size
  • Allows cache clearing
  • Allows sharing of objects between multiple runs
  • Allows respect of input files which influence the result

Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

@anycache(cachedir='/path/to/your/cache')    
def myfunc(name, value)
    return Company(name, value)

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the function name and its arguments) as filename. On any consecutive run, the pickled object is loaded. If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

For any further details see the documentation

How to change the Text color of Menu item in Android?

Thanks to max.musterman, this is the solution I got to work in level 22:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    MenuItem searchMenuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);
    setMenuTextColor(menu, R.id.displaySummary, R.string.show_summary);
    setMenuTextColor(menu, R.id.about, R.string.text_about);
    setMenuTextColor(menu, R.id.importExport, R.string.import_export);
    setMenuTextColor(menu, R.id.preferences, R.string.settings);
    return true;
}

private void setMenuTextColor(Menu menu, int menuResource, int menuTextResource) {
    MenuItem item = menu.findItem(menuResource);
    SpannableString s = new SpannableString(getString(menuTextResource));
    s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0);
    item.setTitle(s);
}

The hardcoded Color.BLACK could become an additional parameter to the setMenuTextColor method. Also, I only used this for menu items which were android:showAsAction="never".

Plotting 4 curves in a single plot, with 3 y-axes

One possibility you can try is to create 3 axes stacked one on top of the other with the 'Color' properties of the top two set to 'none' so that all the plots are visible. You would have to adjust the axes width, position, and x-axis limits so that the 3 y axes are side-by-side instead of on top of one another. You would also want to remove the x-axis tick marks and labels from 2 of the axes since they will lie on top of one another.

Here's a general implementation that computes the proper positions for the axes and offsets for the x-axis limits to keep the plots lined up properly:

%# Some sample data:
x = 0:20;
N = numel(x);
y1 = rand(1,N);
y2 = 5.*rand(1,N)+5;
y3 = 50.*rand(1,N)-50;

%# Some initial computations:
axesPosition = [110 40 200 200];  %# Axes position, in pixels
yWidth = 30;                      %# y axes spacing, in pixels
xLimit = [min(x) max(x)];         %# Range of x values
xOffset = -yWidth*diff(xLimit)/axesPosition(3);

%# Create the figure and axes:
figure('Units','pixels','Position',[200 200 330 260]);
h1 = axes('Units','pixels','Position',axesPosition,...
          'Color','w','XColor','k','YColor','r',...
          'XLim',xLimit,'YLim',[0 1],'NextPlot','add');
h2 = axes('Units','pixels','Position',axesPosition+yWidth.*[-1 0 1 0],...
          'Color','none','XColor','k','YColor','m',...
          'XLim',xLimit+[xOffset 0],'YLim',[0 10],...
          'XTick',[],'XTickLabel',[],'NextPlot','add');
h3 = axes('Units','pixels','Position',axesPosition+yWidth.*[-2 0 2 0],...
          'Color','none','XColor','k','YColor','b',...
          'XLim',xLimit+[2*xOffset 0],'YLim',[-50 50],...
          'XTick',[],'XTickLabel',[],'NextPlot','add');
xlabel(h1,'time');
ylabel(h3,'values');

%# Plot the data:
plot(h1,x,y1,'r');
plot(h2,x,y2,'m');
plot(h3,x,y3,'b');

and here's the resulting figure:

enter image description here

Number format in excel: Showing % value without multiplying with 100

_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_ 

"Javac" doesn't work correctly on Windows 10

java is part of the JRE, not the JDK.

You need to add the JDK bin to the system PATH, in

"Control Panel" | System | Advanced | "Environment Variables"

Java : Sort integer array without using Arrays.sort()

int x[] = { 10, 30, 15, 69, 52, 89, 5 };
    int max, temp = 0, index = 0;
    for (int i = 0; i < x.length; i++) {
        int counter = 0;
        max = x[i];
        for (int j = i + 1; j < x.length; j++) {

            if (x[j] > max) {
                max = x[j];
                index = j;
                counter++;
            }

        }
        if (counter > 0) {
            temp = x[index];
            x[index] = x[i];
            x[i] = temp;
        }
    }
    for (int i = 0; i < x.length; i++) {
        System.out.println(x[i]);
    }

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

Create list of object from another using Java 8 Streams

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    // Getter & Setter
}

Change SQLite database mode to read-write

In the project path Terminal django_project#

sudo chown django:django *

What's HTML character code 8203?

ZERO WIDTH SPACE.

I've used it as content for "empty" table cells. No idea what it's doing in a <script> tag, though.

Can I escape html special chars in javascript?

Using lodash

_.escape('fred, barney, & pebbles');
// => 'fred, barney, &amp; pebbles'

source code

Creating a config file in PHP

One simple but elegant way is to create a config.php file (or whatever you call it) that just returns an array:

<?php

return array(
    'host' => 'localhost',
    'username' => 'root',
);

And then:

$configs = include('config.php');

Remove category & tag base from WordPress url - without a plugin

instead put this in your functions.php works fine, no redirect problems.

function fix_slash( $string, $type )
{
global $wp_rewrite;
if ( $wp_rewrite->use_trailing_slashes == false )
{
    if ( $type != 'single' && $type != 'category' )
        return trailingslashit( $string );

    if ( $type == 'single' && ( strpos( $string, '.html/' ) !== false ) )
        return trailingslashit( $string );

    if ( $type == 'category' && ( strpos( $string, 'category' ) !== false ) )
    {
        $aa_g = str_replace( "/category/", "/", $string );
        return trailingslashit( $aa_g );
    }
    if ( $type == 'category' )
        return trailingslashit( $string );
}
return $string;
}

add_filter( 'user_trailingslashit', 'fix_slash', 55, 2 );

Difference between Groovy Binary and Source release?

A source release will be compiled on your own machine while a binary release must match your operating system.

source releases are more common on linux systems because linux systems can dramatically vary in cpu, installed library versions, kernelversions and nearly every linux system has a compiler installed.

binary releases are common on ms-windows systems. most windows machines do not have a compiler installed.

Purpose of ESI & EDI registers?

In addition to the registers being used for mass operations, they are useful for their property of being preserved through a function call (call-preserved) in 32-bit calling convention. The ESI, EDI, EBX, EBP, ESP are call-preserved whereas EAX, ECX and EDX are not call-preserved. Call-preserved registers are respected by C library function and their values persist through the C library function calls.

Jeff Duntemann in his assembly language book has an example assembly code for printing the command line arguments. The code uses esi and edi to store counters as they will be unchanged by the C library function printf. For other registers like eax, ecx, edx, there is no guarantee of them not being used by the C library functions.

https://www.amazon.com/Assembly-Language-Step-Step-Programming/dp/0470497025

See section 12.8 How C sees Command-Line Arguments.

Note that 64-bit calling conventions are different from 32-bit calling conventions, and I am not sure if these registers are call-preserved or not.

Stylesheet not loaded because of MIME-type

I know it might be out of context but linking a non existed file might cause this issue as it happened to me before.

<!-- bootstrap grid -->
<link rel="stylesheet" href="./css/bootstrap-grid.css" />

If this file does not exist you will face that issue.

How to change legend title in ggplot

I didn't dig in much into this but because you used fill=cond in ggplot(),

 + labs(color='NEW LEGEND TITLE') 

might not have worked. However it you replace color by fill, it works!

+ labs(fill='NEW LEGEND TITLE') 

This worked for me in ggplot2_2.1.0

How to check empty DataTable

You can also simply write

 if (dt.Rows.Count == 0)
     {
         //DataTable does not contain records
     }        

Find max and second max salary for a employee table MySQL

For unique salaries (i.e. first can't be same as second):

SELECT
  MAX( s.salary ) AS max_salary,
  (SELECT
     MAX( salary ) 
   FROM salaries
   WHERE salary <> MAX( s.salary ) 
   ORDER BY salary DESC 
   LIMIT 1
  ) AS 2nd_max_salary
FROM salaries s

And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)

How to show only next line after the matched one?

grep /Pattern/ | tail -n 2 | head -n 1

Tail first 2 and then head last one to get exactly first line after match.

Call An Asynchronous Javascript Function Synchronously

Take a look at JQuery Promises:

http://api.jquery.com/promise/

http://api.jquery.com/jQuery.when/

http://api.jquery.com/deferred.promise/

Refactor the code:


    var dfd = new jQuery.Deferred();


    function callBack(data) {
       dfd.notify(data);
    }

    // do the async call.
    myAsynchronousCall(param1, callBack);

    function doSomething(data) {
     // do stuff with data...
    }

    $.when(dfd).then(doSomething);


What is the iBeacon Bluetooth Profile

Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:

02 01 1a 1a ff 4C 00

Is part of the advertising data format specification [1]

  02 # length of following AD structure
  01 # <<Flags>> AD Structure [2]
  1a # read as b00011010. 
     # In this case, LE General Discoverable,
     # and simultaneous BR/EDR but this may vary by device!

  1a # length of following AD structure
  FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header

Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.

References:

  1. Core Bluetooth Spec v4, Vol 3, Part C, 11
  2. Vol 3, Part C, 18.1
  3. Vol 3, Part C, 18.11
  4. https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
  5. Vol 3, Part C, 18.2

Retrieving an element from array list in Android?

What I understand your question is that you want to fetch an element in an ArrayList at a specific location.

Suppose your list contains Integers 1,2,3,4,5 and you want to fetch the value 3. Then the following lines of code will work.

ArrayList<Integer> list = new ArrayList<Integer>();
        if(list.contains(3)){//check if the list contains the element
            list.get(list.indexOf(3));//get the element by passing the index of the element
        }

Either ways you could use list.get(list.lastIndexOf(3))

What is the "-->" operator in C/C++?

(x --> 0) means (x-- > 0).

  1. You can use (x -->)
    Output: 9 8 7 6 5 4 3 2 1 0
  1. You can use (-- x > 0) It's mean (--x > 0)
    Output: 9 8 7 6 5 4 3 2 1
  1. You can use
(--\
    \
     x > 0)

Output: 9 8 7 6 5 4 3 2 1

  1. You can use
(\
  \
   x --> 0)

Output: 9 8 7 6 5 4 3 2 1 0

  1. You can use
(\
  \
   x --> 0
          \
           \
            )

Output: 9 8 7 6 5 4 3 2 1 0

  1. You can use also
(
 x 
  --> 
      0
       )

Output: 9 8 7 6 5 4 3 2 1 0

Likewise, you can try lot of methods to execute this command successfully.

Python: How to increase/reduce the fontsize of x and y tick labels?

It is simpler than I thought it would be.

To set the font size of the x-axis ticks:

x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)

To do it for the y-axis ticks:

y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)

The arguments rotation and fontsize can easily control what I was after.

Reference: http://matplotlib.org/api/axes_api.html

Android Gradle Apache HttpClient does not exist?

if you are using target sdk as 23 add below code in your build.gradle

android{
    compileSdkVersion 23
    buildToolsVersion '23.0.1'
    useLibrary  'org.apache.http.legacy'
}

and change your buildscript to

classpath 'com.android.tools.build:gradle:1.3.0' 

for more info follow this link

Capturing image from webcam in java?

There's a pretty nice interface for this in processing, which is kind of a pidgin java designed for graphics. It gets used in some image recognition work, such as that link.

Depending on what you need out of it, you might be able to load the video library that's used there in java, or if you're just playing around with it you might be able to get by using processing itself.

Android : Check whether the phone is dual SIM

I was taking a look at the call logs and I noticed that apart from the usual fields in the contents of managedCursor, we have a column "simid" in Dual SIM phones (I checked on Xolo A500s Lite), so as to tag each call in the call log with a SIM. This value is either 1 or 2, most probably denoting SIM1/SIM2.

managedCursor = context.getContentResolver().query(contacts, null, null, null, null);
managedCursor.moveToNext();        
for(int i=0;i<managedCursor.getColumnCount();i++)
{//for dual sim phones
    if(managedCursor.getColumnName(i).toLowerCase().equals("simid"))
        indexSIMID=i;
}

I did not find this column in a single SIM phone (I checked on Xperia L).

So although I don't think this is a foolproof way to check for dual SIM nature, I am posting it here because it could be useful to someone.

Generic type conversion FROM string

With inspiration from the Bob's answer, these extensions also support null value conversion and all primitive conversion back and fourth.

public static class ConversionExtensions
{
        public static object Convert(this object value, Type t)
        {
            Type underlyingType = Nullable.GetUnderlyingType(t);

            if (underlyingType != null && value == null)
            {
                return null;
            }
            Type basetype = underlyingType == null ? t : underlyingType;
            return System.Convert.ChangeType(value, basetype);
        }

        public static T Convert<T>(this object value)
        {
            return (T)value.Convert(typeof(T));
        }
}

Examples

            string stringValue = null;
            int? intResult = stringValue.Convert<int?>();

            int? intValue = null;
            var strResult = intValue.Convert<string>();

What is tail recursion?

There are two basic kinds of recursions: head recursion and tail recursion.

In head recursion, a function makes its recursive call and then performs some more calculations, maybe using the result of the recursive call, for example.

In a tail recursive function, all calculations happen first and the recursive call is the last thing that happens.

Taken from this super awesome post. Please consider reading it.

C++ preprocessor __VA_ARGS__ number of arguments

For convenience, here's an implementation that works for 0 to 70 arguments, and works in Visual Studio, GCC, and Clang. I believe it will work in Visual Studio 2010 and later, but have only tested it in VS2013.

#ifdef _MSC_VER // Microsoft compilers

#   define GET_ARG_COUNT(...)  INTERNAL_EXPAND_ARGS_PRIVATE(INTERNAL_ARGS_AUGMENTER(__VA_ARGS__))

#   define INTERNAL_ARGS_AUGMENTER(...) unused, __VA_ARGS__
#   define INTERNAL_EXPAND(x) x
#   define INTERNAL_EXPAND_ARGS_PRIVATE(...) INTERNAL_EXPAND(INTERNAL_GET_ARG_COUNT_PRIVATE(__VA_ARGS__, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
#   define INTERNAL_GET_ARG_COUNT_PRIVATE(_1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, _33_, _34_, _35_, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count

#else // Non-Microsoft compilers

#   define GET_ARG_COUNT(...) INTERNAL_GET_ARG_COUNT_PRIVATE(0, ## __VA_ARGS__, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#   define INTERNAL_GET_ARG_COUNT_PRIVATE(_0, _1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, _33_, _34_, _35_, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, _65, _66, _67, _68, _69, _70, count, ...) count

#endif

static_assert(GET_ARG_COUNT() == 0, "GET_ARG_COUNT() failed for 0 arguments");
static_assert(GET_ARG_COUNT(1) == 1, "GET_ARG_COUNT() failed for 1 argument");
static_assert(GET_ARG_COUNT(1,2) == 2, "GET_ARG_COUNT() failed for 2 arguments");
static_assert(GET_ARG_COUNT(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70) == 70, "GET_ARG_COUNT() failed for 70 arguments");

What is the most efficient/quickest way to loop through rows in VBA (excel)?

EDIT Summary and reccomendations

Using a for each cell in range construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).

What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.

So, some general advice:

  1. keep it simple at first. If the result is too slow for your needs, then optimise
  2. focus on optimisation of the content of the loop
  3. don't just assume a loop is needed. There are sometime alternatives
  4. if you need to use cell values (a lot) inside the loop, load them into a variant array outside the loop.
  5. a good way to avoid complexity with inserts is to loop the range from the bottom up
    (for index = max to min step -1)
  6. if you can't do that and your 'insert a row here and there' is not too many, consider reloading the array after each insert
  7. If you need to access cell properties other than value, you are stuck with cell references
  8. To delete a number of rows consider building a range reference to a multi area range in the loop, then delete that range in one go after the loop

eg (not tested!)

Dim rngToDelete as range
for each rw in rng.rows
    if need to delete rw then

        if rngToDelete is nothing then
            set rngToDelete = rw
        else
            set rngToDelete = Union(rngToDelete, rw)
        end if

    endif
next
rngToDelete.EntireRow.Delete

Original post

Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:

test data set: a simple list in cells A1 .. A1000000 (thats 1,000,000 rows)

Test case 1: loop an array

Dim v As Variant
Dim n As Long

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    'i = i + 1
    'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")

Result:

Array Time = 0.249 sec
Array Count = 1,000,001

Test Case 2: loop the range

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 0.296 sec
Range Count = 1,000,000

So,looping an array is faster but only by 19% - much less than I expected.

Test 3: loop an array with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")

Result:

Array Time = 5.897 sec
Array Count = 1,000,000

Test case 4: loop range with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
    i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 2.356 sec
Range Count = 1,000,000

So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!

So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options

FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with

  • ScreenUpdating off,
  • Calulation manual,
  • Events disabled.

How to get current time with jQuery

You need to fetch all "numbers" manually

like this:

_x000D_
_x000D_
var currentdate = new Date(); _x000D_
    var datetime = "Now: " + currentdate.getDate() + "/"_x000D_
                + (currentdate.getMonth()+1)  + "/" _x000D_
                + currentdate.getFullYear() + " @ "  _x000D_
                + currentdate.getHours() + ":"  _x000D_
                + currentdate.getMinutes() + ":" _x000D_
                + currentdate.getSeconds();_x000D_
_x000D_
document.write(datetime);
_x000D_
_x000D_
_x000D_

Laravel 5.2 redirect back with success message

In Controller

return redirect()->route('company')->with('update', 'Content has been updated successfully!');

In view

@if (session('update'))
  <div class="alert alert-success alert-dismissable custom-success-box" style="margin: 15px;">
     <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
     <strong> {{ session('update') }} </strong>
  </div>
@endif

What does ${} (dollar sign and curly braces) mean in a string in Javascript?

You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

Android Notification Sound

On Oreo (Android 8) and above it should be done for custom sound in this way (notification channels):

Uri soundUri = Uri.parse(
                         "android.resource://" + 
                         getApplicationContext().getPackageName() +
                         "/" + 
                         R.raw.push_sound_file);

AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_ALARM)
            .build();

// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
                                                      "YOUR_CHANNEL_NAME",
                                                      NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                           .createNotificationChannel(notificationChannel);

AttributeError: 'numpy.ndarray' object has no attribute 'append'

Use numpy.concatenate(list1 , list2) or numpy.append() Look into the thread at Append a NumPy array to a NumPy array.

How to do case insensitive search in Vim

Some important information, if u want to find out more about the commands of vim, as mentioned below u can give a try the following steps :

  • invoke the command "help" follow by a space and then complete the word with TAB key, once u find the right command press return key.
:help ignorecase
  • information like the following will be displayed :

enter image description here

  • you will be able to move forward and backward and also watch the short command, such as the case of "ignorecase" ( 'ic' ). In addition, another short example could be the case of 'smartcase' ('scs' and some more) :

enter image description here

  • In order to leave of the documentation just type ":q" as usual and you will return to "command mode" .
:q

I really hope the information provided would be helpful for someone.

Best regards,

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

What is the difference between procedural programming and functional programming?

Funtional Programming

num = 1 
def function_to_add_one(num):
    num += 1
    return num


function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)

#Final Output: 2

Procedural Programming

num = 1 
def procedure_to_add_one():
    global num
    num += 1
    return num


procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()

#Final Output: 6

function_to_add_one is a function

procedure_to_add_one is a procedure

Even if you run the function five times, every time it will return 2

If you run the procedure five times, at the end of fifth run it will give you 6.

DISCLAIMER: Obviously this is a hyper-simplified view of reality. This answer just gives a taste of "functions" as opposed to "procedures". Nothing more. Once you have tasted this superficial yet deeply penetrative intuition, start exploring the two paradigms, and you will start to see the difference quite clearly.

Helps my students, hope it helps you too.

Understanding the map function

map creates a new list by applying a function to every element of the source:

xs = [1, 2, 3]

# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
    ys.append(x * 2)

n-ary map is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. It's not a Cartesian product:

xs = [1, 2, 3]
ys = [2, 4, 6]

def f(x, y):
    return (x * 2, y // 2)

# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
    zs.append(f(x, y))

I've used zip here, but map behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None.

make div's height expand with its content

Typically I think this can be resolved by forcing a clear:both rule on the last child-element of the #items_list.

You can either use:

#items_list:last-child {clear: both;}

Or, if you're using a dynamic language, add an additional class to the last element generated in whatever loop creates the list itself, so you end up with something in your html like:

<div id="list_item_20" class="last_list_item">

and css

.last_list_item {clear: both; }

Immutable array in Java

Another one answer

static class ImmutableArray<T> {
    private final T[] array;

    private ImmutableArray(T[] a){
        array = Arrays.copyOf(a, a.length);
    }

    public static <T> ImmutableArray<T> from(T[] a){
        return new ImmutableArray<T>(a);
    }

    public T get(int index){
        return array[index];
    }
}

{
    final ImmutableArray<String> sample = ImmutableArray.from(new String[]{"a", "b", "c"});
}

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

The configuration here is working for me:

configurations {
    customProvidedRuntime
}

dependencies {
    compile(
        // Spring Boot dependencies
    )

    customProvidedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

war {
    classpath = files(configurations.runtime.minus(configurations.customProvidedRuntime))
}

springBoot {
    providedConfiguration = "customProvidedRuntime"
}

How to get second-highest salary employees in a table

Try this one for MSSQL:

SELECT
    TOP 1 salary
FROM
    (
        SELECT
            TOP 2 salary
        FROM
            Employees 
    ) sal
ORDER BY
    salary DESC;

But you should try this generic SQL query which is working for all kinds of database.

SELECT
    MAX(salary)
FROM
    Employee
WHERE
    Salary NOT IN (
        SELECT
            Max(Salary)
        FROM
            Employee
    );

OR

SELECT
    MAX(Salary)
FROM
    Employee
WHERE
    Salary < (
        SELECT
            Max(Salary)
        FROM
            Employee
    );

How do I install the ext-curl extension with PHP 7?

If "sudo apt-get install php-curl" command doesnt work and display error We should run this code before install curl.

  • step1 - sudo add-apt-repository ppa:ondrej/php
  • step2 - sudo apt-get update
  • step3 - sudo apt-get install php-curl
  • step4 - sudo service apache2 restart