Programs & Examples On #Django authentication

django-authentication refers to the built-in auth module for authentication & authorization that can be extended.

How to get the currently logged in user's user id in Django?

Assuming you are referring to Django's Auth User, in your view:

def game(request):
  user = request.user

  gta = Game.objects.create(name="gta", owner=user)

In Django, how do I check if a user is in a certain group?

Just in case if you wanna check user's group belongs to a predefined group list:

def is_allowed(user):
    allowed_group = set(['admin', 'lead', 'manager'])
    usr = User.objects.get(username=user)
    groups = [ x.name for x in usr.groups.all()]
    if allowed_group.intersection(set(groups)):
       return True
    return False

Having Django serve downloadable files

def qrcodesave(request): 
    import urllib2;   
    url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0"; 
    opener = urllib2.urlopen(url);  
    content_type = "application/octet-stream"
    response = HttpResponse(opener.read(), content_type=content_type)
    response["Content-Disposition"]= "attachment; filename=aktel.png"
    return response 

Extending the User model with custom fields in Django

Try this:

Create a model called Profile and reference the user with a OneToOneField and provide an option of related_name.

models.py

from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    try:
        if created:
            Profile.objects.create(user=instance).save()
    except Exception as err:
        print('Error creating user profile!')

Now to directly access the profile using a User object you can use the related_name.

views.py

from django.http import HttpResponse

def home(request):
    profile = f'profile of {request.user.user_profile}'
    return HttpResponse(profile)

How can I tell if a DOM element is visible in the current viewport?

I had the same question and figured it out by using getBoundingClientRect().

This code is completely 'generic' and only has to be written once for it to work (you don't have to write it out for each element that you want to know is in the viewport).

This code only checks to see if it is vertically in the viewport, not horizontally. In this case, the variable (array) 'elements' holds all the elements that you are checking to be vertically in the viewport, so grab any elements you want anywhere and store them there.

The 'for loop', loops through each element and checks to see if it is vertically in the viewport. This code executes every time the user scrolls! If the getBoudingClientRect().top is less than 3/4 the viewport (the element is one quarter in the viewport), it registers as 'in the viewport'.

Since the code is generic, you will want to know 'which' element is in the viewport. To find that out, you can determine it by custom attribute, node name, id, class name, and more.

Here is my code (tell me if it doesn't work; it has been tested in Internet Explorer 11, Firefox 40.0.3, Chrome Version 45.0.2454.85 m, Opera 31.0.1889.174, and Edge with Windows 10, [not Safari yet])...

// Scrolling handlers...
window.onscroll = function(){
  var elements = document.getElementById('whatever').getElementsByClassName('whatever');
  for(var i = 0; i != elements.length; i++)
  {
   if(elements[i].getBoundingClientRect().top <= window.innerHeight*0.75 &&
      elements[i].getBoundingClientRect().top > 0)
   {
      console.log(elements[i].nodeName + ' ' +
                  elements[i].className + ' ' +
                  elements[i].id +
                  ' is in the viewport; proceed with whatever code you want to do here.');
   }
};

How do I know the script file name in a Bash script?

$BASH_SOURCE gives the correct answer when sourcing the script.

This however includes the path so to get the scripts filename only, use:

$(basename $BASH_SOURCE) 

How to return a value from pthread threads in C?

You've returned a pointer to a local variable. That's bad even if threads aren't involved.

The usual way to do this, when the thread that starts is the same thread that joins, would be to pass a pointer to an int, in a location managed by the caller, as the 4th parameter of pthread_create. This then becomes the (only) parameter to the thread's entry-point. You can (if you like) use the thread exit value to indicate success:

#include <pthread.h>
#include <stdio.h>

int something_worked(void) {
    /* thread operation might fail, so here's a silly example */
    void *p = malloc(10);
    free(p);
    return p ? 1 : 0;
}

void *myThread(void *result)
{
   if (something_worked()) {
       *((int*)result) = 42;
       pthread_exit(result);
   } else {
       pthread_exit(0);
   }
}

int main()
{
   pthread_t tid;
   void *status = 0;
   int result;

   pthread_create(&tid, NULL, myThread, &result);
   pthread_join(tid, &status);

   if (status != 0) {
       printf("%d\n",result);
   } else {
       printf("thread failed\n");
   }

   return 0;
}

If you absolutely have to use the thread exit value for a structure, then you'll have to dynamically allocate it (and make sure that whoever joins the thread frees it). That's not ideal, though.

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

Use a LIKE statement on SQL Server XML Datatype

You should be able to do this quite easily:

SELECT * 
FROM WebPageContent 
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'

The .value method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.

Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:

  • create a stored function which gets the XML and returns the value you're looking for as a VARCHAR()
  • define a new computed field on your table which calls this function, and make it a PERSISTED column

With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).

Marc

Register 32 bit COM DLL to 64 bit Windows 7

put the dll in system32 or syswow32 directory, and use appropriate regsvr32 to register it. wiered that even though it gave failed to register error, I rebooted my WIN 7 64 AND my vb app loaded the dll just fine!!

How can I create 2 separate log files with one log4j config file?

Try the following configuration:

log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

Then configure the loggers in the Java code accordingly:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Do you want output to go to stdout? If not, change the first line of log4j.properties to:

log4j.rootLogger=OFF

and get rid of the stdout lines.

Detect element content changes with jQuery

You can add a callback option to html (,or any) function:

$.fn.oldHtml = $.fn.html;
$.fn.html = function(html,fn){
  fn = fn || function(){};
  var result =  this.oldHtml(html);
  fn();
  return result;
};
$('body').html(11,function(){alert("haha");});

Demo here.

You do the change on some element, not the element is forced to change by something that you have to catch.

How to stop a function

In this example, the line do_something_else() will not be executed if do_not_continue is True. Control will return, instead, to whichever function called some_function.

def some_function():
    if do_not_continue:
        return  # implicitly, this is the same as saying `return None` 
    do_something_else()

pip3: command not found

Try this if other methods do not work:

  1. brew install python3
  2. brew link --overwrite python
  3. brew postinstall python3

What is the difference between `let` and `var` in swift?

The main difference is that var variable value can change, and let can't. If you want to have a user input data, you would use var so the value can be changed and use let datatype variable so the value can not be changed.

var str      = "dog"  // str value is "dog"
str          = "cat"  // str value is now "cat"

let strAnimal = "dog" // strAnimal value is "dog"
strAnimal     = "cat" // Error !

Oracle: how to UPSERT (update or insert into a table?)

I've been using the first code sample for years. Notice notfound rather than count.

UPDATE tablename SET val1 = in_val1, val2 = in_val2
    WHERE val3 = in_val3;
IF ( sql%notfound ) THEN
    INSERT INTO tablename
        VALUES (in_val1, in_val2, in_val3);
END IF;

The code below is the possibly new and improved code

MERGE INTO tablename USING dual ON ( val3 = in_val3 )
WHEN MATCHED THEN UPDATE SET val1 = in_val1, val2 = in_val2
WHEN NOT MATCHED THEN INSERT 
    VALUES (in_val1, in_val2, in_val3)

In the first example the update does an index lookup. It has to, in order to update the right row. Oracle opens an implicit cursor, and we use it to wrap a corresponding insert so we know that the insert will only happen when the key does not exist. But the insert is an independent command and it has to do a second lookup. I don't know the inner workings of the merge command but since the command is a single unit, Oracle could have execute the correct insert or update with a single index lookup.

I think merge is better when you do have some processing to be done that means taking data from some tables and updating a table, possibly inserting or deleting rows. But for the single row case, you may consider the first case since the syntax is more common.

How to delete all data from solr and hbase

You can use the following commands to delete. Use the "match all docs" query in a delete by query command:

'<delete><query>*:*</query></delete>

You must also commit after running the delete so, to empty the index, run the following two commands:

curl http://localhost:8983/solr/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'
curl http://localhost:8983/solr/update --data '<commit/>' -H 'Content-type:text/xml; charset=utf-8'

Another strategy would be to add two bookmarks in your browser:

http://localhost:8983/solr/update?stream.body=<delete><query>*:*</query></delete>
http://localhost:8983/solr/update?stream.body=<commit/>


Source docs from SOLR:
https://wiki.apache.org/solr/FAQ#How_can_I_delete_all_documents_from_my_index.3F

How to configure PostgreSQL to accept all incoming connections

Configuration all files with postgres 12 on centos:

step 1: search and edit file

sudo vi /var/lib/pgsql/12/data/pg_hba.conf

press "i" and at line IPv4 change

host    all             all             0.0.0.0/0            md5

step 2: search and edit file postgresql.conf

sudo vi /var/lib/pgsql/12/data/postgresql.conf

add last line: listen_addresses = '*' :wq! (save file) - step 3: restart

systemctl restart postgresql-12.service

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Does the basic HTML5 datalist work? It's clean and you don't have to play around with the messy third party code. W3SCHOOL tutorial

The MDN Documentation is very eloquent and features examples.

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

How do I install Java on Mac OSX allowing version switching?

This is how I did it.

Step 1: Install Java 11

You can download Java 11 dmg for mac from here: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html

Step 2: After installation of Java 11. Confirm installation of all versions. Type the following command in your terminal.

/usr/libexec/java_home -V

Step 3: Edit .bash_profile

sudo nano ~/.bash_profile

Step 4: Add 11.0.1 as default. (Add below line to bash_profile file).

export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.1)

to switch to any version

export JAVA_HOME=$(/usr/libexec/java_home -v X.X.X)

Now Press CTRL+X to exit the bash. Press 'Y' to save changes.

Step 5: Reload bash_profile

source ~/.bash_profile

Step 6: Confirm current version of Java

java -version

How to draw polygons on an HTML5 canvas?

In addition to @canvastag, use a while loop with shift I think is more concise:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var poly = [5, 5, 100, 50, 50, 100, 10, 90];

// copy array
var shape = poly.slice(0);

ctx.fillStyle = '#f00'
ctx.beginPath();
ctx.moveTo(shape.shift(), shape.shift());
while(shape.length) {
  ctx.lineTo(shape.shift(), shape.shift());
}
ctx.closePath();
ctx.fill();

How to find the operating system version using JavaScript?

You can use this javascript function to check users' OS simply

  function getOS() {
  var userAgent = window.navigator.userAgent,
      platform = window.navigator.platform,
      macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
      windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
      iosPlatforms = ['iPhone', 'iPad', 'iPod'],
      os = null;

  if (macosPlatforms.indexOf(platform) !== -1) {
    os = 'Mac OS';
  } else if (iosPlatforms.indexOf(platform) !== -1) {
    os = 'iOS';
  } else if (windowsPlatforms.indexOf(platform) !== -1) {
    os = 'Windows';
  } else if (/Android/.test(userAgent)) {
    os = 'Android';
  } else if (!os && /Linux/.test(platform)) {
    os = 'Linux';
  }

  return os;
}

alert(getOS());

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

Remove menubar from Electron app

As of 7.0.0, most of the above solutions no longer work. BrowserWindow.setMenu() has been replaced by Menu.setApplicationMenu(), which now changes the menu on all windows. setMenu(), removeMenu() no longer do anything, Which by the way are still mentioned in the docs.

setAutoHideMenuBar() still works, but could be a nuisance if you planned to use Alt as a hotkey modifier. Once menu is visible you have to click away from window (loose focus) to hide menu again.

If your application has more than one window, you can't set/remove menus separately on each window. The only way to remove a menu is to use the frameless window approach. That happens to be what I want in my current application, but not a good solution in all cases.

how to add lines to existing file using python

Use 'a', 'a' means append. Anything written to a file opened with 'a' attribute is written at the end of the file.

with open('file.txt', 'a') as file:
    file.write('input')

Find an element in DOM based on an attribute value

Modern browsers support native querySelectorAll so you can do:

document.querySelectorAll('[data-foo="value"]');

https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Details about browser compatibility:

You can use jQuery to support obsolete browsers (IE9 and older):

$('[data-foo="value"]');

How to find the Windows version from the PowerShell command line

$OSVersion = [Version](Get-ItemProperty -Path "$($Env:Windir)\System32\hal.dll" -ErrorAction SilentlyContinue).VersionInfo.FileVersion.Split()[0]

On Windows 10 returns: 10.0.10586.420

You can then use the variable to access properties for granular comparison

$OSVersion.Major equals 10
$OSVersion.Minor equals 0
$OSVersion.Build equals 10586
$OSVersion.Revision equals 420

Additionally, you can compare operating system versions using the following

If ([Version]$OSVersion -ge [Version]"6.1")
   {
       #Do Something
   }

Submitting a form by pressing enter without a submit button

HTML5 solution

<input type="submit" hidden />

Better way to get type of a Javascript variable?

Angus Croll recently wrote an interesting blog post about this -

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

He goes through the pros and cons of the various methods then defines a new method 'toType' -

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

How to clear the logs properly for a Docker container?

Use:

truncate -s 0 /var/lib/docker/containers/*/*-json.log

You may need sudo

sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"

ref. Jeff S. How to clear the logs properly for a Docker container?

Reference: Truncating a file while it's being used (Linux)

ffprobe or avprobe not found. Please install one

This is so simple if on windows...

In the folder where you have youtube-dl.exe

goto https://www.gyan.dev/ffmpeg/builds/

download the ffmpeg-git-full.7z file the download link is https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z

Open that zip file and move the ffmpeg.exe file to the same folder where youtube-dl.exe is

Example "blahblah.7z / whatevertherootfolderis / bin / ffmpeg.exe"

youtube-dl.exe -x --audio-format mp3 -o %(title)s.%(ext)s https://www.youtube.com/watch?v=wyPKRcBTsFQ

Nested JSON: How to add (push) new items to an object?

push is an Array method, for json object you may need to define it

this should do it:

library[title] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

You can also use CopyOnWriteArrayList instead of an ArrayList. This is the latest recommended approach by from JDK 1.5 onwards.

Nginx not running with no error message

I had the exact same problem with my instance. My problem was that I forgot to allow port 80 access to the server. Maybe that's your issue as well?

Check with your WHM and make sure that port is open for the IP address of your site,

How to center the text in PHPExcel merged cell

if you want to align only this cells, you can do something like this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getStyle("A1:B1")->applyFromArray($style);

But, if you want to apply this style to all cells, try this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getDefaultStyle()->applyFromArray($style);

Detecting iOS orientation change instantly

That delay you're talking about is actually a filter to prevent false (unwanted) orientation change notifications.

For instant recognition of device orientation change you're just gonna have to monitor the accelerometer yourself.

Accelerometer measures acceleration (gravity included) in all 3 axes so you shouldn't have any problems in figuring out the actual orientation.

Some code to start working with accelerometer can be found here:

How to make an iPhone App – Part 5: The Accelerometer

And this nice blog covers the math part:

Using the Accelerometer

Function to convert timestamp to human date in javascript

Moment.js can convert unix timestamps into any custom format

In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");

will print 18-10-2013 11:53:14;

Here's a plunker that demonstrates this.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

CPython has reference counting and garbage collection, PyPy has garbage collection only.

So objects tend to be deleted earlier and __del__ is called in a more predictable way in CPython. Some software relies on this behavior, thus they are not ready for migrating to PyPy.

Some other software works with both, but uses less memory with CPython, because unused objects are freed earlier. (I don't have any measurements to indicate how significant this is and what other implementation details affect the memory use.)

Excel VBA: Copying multiple sheets into new workbook

Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.

Angular - Can't make ng-repeat orderBy work

You're going to have to reformat your releases object to be an array of objects. Then you'll be able to sort them the way you're attempting.

VBA equivalent to Excel's mod function

Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.

In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0

They are certainly not equivalent!

Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123

Could not find server 'server name' in sys.servers. SQL Server 2014

I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers still had the old server name.

I had to drop the old server name and add the new server name to sys.servers on the new server

sp_dropserver 'Server_A'
GO
sp_addserver  'Server',local
GO

SQL User Defined Function Within Select

If it's a table-value function (returns a table set) you simply join it as a Table

this function generates one column table with all the values from passed comma-separated list

SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')

How to join two tables by multiple columns in SQL?

You should only need to do a single join:

SELECT e.Grade, v.Score, e.CaseNum, e.FileNum, e.ActivityNum
FROM Evaluation e
INNER JOIN Value v ON e.CaseNum = v.CaseNum AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

How does numpy.histogram() work?

import numpy as np    
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))

Below, hist indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4.

print(hist)
# array([0, 2, 4, 1])   

bin_edges indicates that bin #0 is the interval [0,1), bin #1 is [1,2), ..., bin #3 is [3,4).

print (bin_edges)
# array([0, 1, 2, 3, 4]))  

Play with the above code, change the input to np.histogram and see how it works.


But a picture is worth a thousand words:

import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()   

enter image description here

Async always WaitingForActivation

I had the same problem. The answers got me on the right track. So the problem is that functions marked with async don't return a task of the function itself as expected (but another continuation task of the function).

So its the "await"and "async" keywords that screws thing up. The simplest solution then is simply to remove them. Then it works as expected. As in:

static void Main(string[] args)
{
    Console.WriteLine("Foo called");
    var result = Foo(5);

    while (result.Status != TaskStatus.RanToCompletion)
    {
        Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId, result.Status);
        Task.Delay(100).Wait();
    }

    Console.WriteLine("Result: {0}", result.Result);
    Console.WriteLine("Finished.");
    Console.ReadKey(true);
}

private static Task<string> Foo(int seconds)
{
    return Task.Run(() =>
    {
        for (int i = 0; i < seconds; i++)
        {
            Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
            Task.Delay(TimeSpan.FromSeconds(1)).Wait();
        }

        return "Foo Completed.";
    });
}

Which outputs:

Foo called
Thread ID: 1, Status: WaitingToRun
Thread ID: 3, second 0.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 1.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 2.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 3.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 3, second 4.
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Thread ID: 1, Status: Running
Result: Foo Completed.
Finished.

What are some examples of commonly used practices for naming git branches?

Note, as illustrated in the commit e703d7 or commit b6c2a0d (March 2014), now part of Git 2.0, you will find another naming convention (that you can apply to branches).

"When you need to use space, use dash" is a strange way to say that you must not use a space.
Because it is more common for the command line descriptions to use dashed-multi-words, you do not even want to use spaces in these places.

A branch name cannot have space (see "Which characters are illegal within a branch name?" and git check-ref-format man page).

So for every branch name that would be represented by a multi-word expression, using a '-' (dash) as a separator is a good idea.

How to drop all stored procedures at once in SQL Server database?

By mixing the cursor and system procedure, we would have a optimized solution, as follow:

DECLARE DelAllProcedures CURSOR
FOR
    SELECT name AS procedure_name 
    FROM sys.procedures;
OPEN DelAllProcedures
DECLARE @ProcName VARCHAR(100)
FETCH NEXT 
FROM DelAllProcedures
INTO @ProcName
WHILE @@FETCH_STATUS!=-1
BEGIN 
    DECLARE @command VARCHAR(100)
    SET @command=''
    SET @command=@command+'DROP PROCEDURE '+@ProcName
    --DROP PROCEDURE  @ProcName
    EXECUTE (@command)
    FETCH NEXT 
    FROM DelAllProcedures
    INTO @ProcName
END
CLOSE DelAllProcedures
DEALLOCATE DelAllProcedures

Simple pagination in javascript

You can use the code from this minimal plugin. https://www.npmjs.com/package/paginator-js

Array.prototype.paginate = function(pageNumber, itemsPerPage){
  pageNumber   = Number(pageNumber)
  itemsPerPage = Number(itemsPerPage)
  pageNumber   = (pageNumber   < 1 || isNaN(pageNumber))   ? 1 : pageNumber
  itemsPerPage = (itemsPerPage < 1 || isNaN(itemsPerPage)) ? 1 : itemsPerPage

  var start     = ((pageNumber - 1) * itemsPerPage)
  var end       = start + itemsPerPage
  var loopCount = 0
  var result    = {
    data: [],
    end: false
  }

  for(loopCount = start; loopCount < end; loopCount++){
    this[loopCount] && result.data.push(this[loopCount]);
  }

  if(loopCount == this.length){
    result.end = true
  }

  return result
}

Add and remove attribute with jquery

First you to add a class then remove id

<script type="text/javascript">
$(document).ready(function(){   
 $("#page_navigation1").addClass("page_navigation");        

 $("#add").click(function(){
        $(".page_navigation").attr("id","page_navigation1");
    });     
    $("#remove").click(function(){
        $(".page_navigation").removeAttr("id");
    });     
  });
</script>

How to do Base64 encoding in node.js?

Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:

> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World

Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toString and Buffer constructor encodings are as follows:

'ascii' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.

'utf8' - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.

'ucs2' - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).

'base64' - Base64 string encoding.

'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

How to find an available port?

This works for me on Java 6

    ServerSocket serverSocket = new ServerSocket(0);
    System.out.println("listening on port " + serverSocket.getLocalPort());

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

How to install the JDK on Ubuntu Linux

The following used to work before the Oracle Java license changes in early 2019.

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

The PPA is discontinued, until the author finds a workaround for the license issues.

Kill detached screen session

Alternatively, while in your screen session all you have to do is type exit

This will kill the shell session initiated by the screen, which effectively terminates the screen session you are on.

No need to bother with screen session id, etc.

How to insert an object in an ArrayList at a specific position

This method Appends the specified element to the end of this list.

add(E e) //append element to the end of the arraylist.

This method Inserts the specified element at the specified position in this list.

void add(int index, E element) //inserts element at the given position in the array list.

This method Replaces the element at the specified position in this list with the specified element.

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:

div:nth-child(4n)

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.


By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n+4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

LOL, I was doing all the steps here - I ended up doing the unpairing/repairing steps from the "given by Surjeet" answer. It didn't work, and then I noticed that when I clicked the "connect via network" button, the same yellow box would pop up that pops up when you repair, saying "busy" - I got frustrated and just started hammering the "connect via network" button, clicking it quickly for probably like 15 - 20 clicks - it started spazzing out, but eventually landed on being able to connect to the network. Before that worked, I also shut my wifi off and turned it on again, as suggested by one of these answers, but clicking the "connect via network" button really fast did the trick...LOL

Also, before I hammered the button, I linked the device support folders, although I'm not sure if it did anything:

open the terminal

cd /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

ln -s 13.3 13.4

ls -l 13.4

restart Xcode and retry run on device

Said to do it here - https://forums.developer.apple.com/thread/126940 - I edited the folder version in my comment to adjust to the latest version of iOS 13.4.

EDIT I believe I figured out what my problem was, I had to stop my Little Snitch network filter. Also, after I was able to connect by hammering the button, the "connect via IP address" option appeared in the dropdown when you right click on the device in the devices manager in xcode, it wasn't there before I was able to connect ultra-hacky style the first time. If I connect, and then turn my network filter on, it disconnects my phone.

Table scroll with HTML and CSS

This work for me

Demo: jsfiddle

$(function() 
{
    Fixed_Header();
});

function Fixed_Header()
{
    $('.User_Table thead').css({'position': 'absolute'});
    $('.User_Table tbody tr:eq("2") td').each(function(index,e){
        $('.User_Table thead tr th:eq("'+index+'")').css({'width' : $(this).outerWidth() +"px" });
    });
    var Header_Height = $('.User_Table thead').outerHeight();
    $('.User_Table thead').css({'margin-top' : "-"+Header_Height+"px"});
    $('.User_Table').css({'margin-top' : Header_Height+"px"});
}

HTTP Error 500.30 - ANCM In-Process Start Failure

After spending an entire day fighting with myself on deciding to host my asp.net core application on IIS with InProcess hosting, i am finally proud and relieved to have this solved. Hours of repeatedly going through the same forums, blogs and SO questions which tried their best to solve the problem, i was still stuck after following all the above mentioned approaches. Now here i will describe my experience of solving it.

Step 1: Create a website in IIS

Step 2: Make sure the AppPool for the website has .Net CLR version set to "No Managed Code" and "Enable 32-bit Applications" property in AppPool -> Advanced Settings is set to false

Step 3: Make sure your project is referencing .Net core 2.2

Step 4: Add the following line in your startup.cs file inside ConfigureServices method

services.Configure<IISServerOptions>(options =>
{
     options.AutomaticAuthentication = false;
});

Step 6: Add the following Nuget packages

Microsoft.AspNetCore.App v2.2.5 or greater

Microsoft.AspNetCore.Server.IIS v2.2.2 or greater

Step 7: Add following line to your .csproj file

<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

Step 8: Build and publish your code (preferably x64 bitness)

Step 9: Make sure you added your website hostname in etc/hosts file

Step 10: Restart World Wide Web Publishing Service

Now test your asp.net core application and it should be hosted using InProcess hosting In order to verify whether your app is hosted using InProcess mode, check the response headers and it should contain the following line

Server: Microsoft-IIS/10.0 (IIS version could be any depeding on your system)

Update: Download and Install ASP.Net Core Hosting Bundle which is required for it to work

What is the use of style="clear:both"?

clear:both makes the element drop below any floated elements that precede it in the document.

You can also use clear:left or clear:right to make it drop below only those elements that have been floated left or right.

+------------+ +--------------------+
|            | |                    |
| float:left | |   without clear    |
|            | |                    |
|            | +--------------------+
|            | +--------------------+
|            | |                    |
|            | |  with clear:right  |
|            | |  (no effect here,  |
|            | |   as there is no   |
|            | |   float:right      |
|            | |   element)         |
|            | |                    |
|            | +--------------------+
|            |
+------------+
+---------------------+
|                     |
|   with clear:left   |
|    or clear:both    |
|                     |
+---------------------+

How do I make the method return type generic?

I know this is a completely different thing that the one asked. Another way of resolving this would be reflection. I mean, this does not take the benefit from Generics, but it lets you emulate, in some way, the behavior you want to perform (make a dog bark, make a duck quack, etc.) without taking care of type casting:

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

abstract class AnimalExample {
    private Map<String,Class<?>> friends = new HashMap<String,Class<?>>();
    private Map<String,Object> theFriends = new HashMap<String,Object>();

    public void addFriend(String name, Object friend){
        friends.put(name,friend.getClass());
        theFriends.put(name, friend);
    }

    public void makeMyFriendSpeak(String name){
        try {
            friends.get(name).getMethod("speak").invoke(theFriends.get(name));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    } 

    public abstract void speak ();
};

class Dog extends Animal {
    public void speak () {
        System.out.println("woof!");
    }
}

class Duck extends Animal {
    public void speak () {
        System.out.println("quack!");
    }
}

class Cat extends Animal {
    public void speak () {
        System.out.println("miauu!");
    }
}

public class AnimalExample {

    public static void main (String [] args) {

        Cat felix = new Cat ();
        felix.addFriend("Spike", new Dog());
        felix.addFriend("Donald", new Duck());
        felix.makeMyFriendSpeak("Spike");
        felix.makeMyFriendSpeak("Donald");

    }

}

Download file from an ASP.NET Web API method using AngularJS

Send your file as a base64 string.

 var element = angular.element('<a/>');
                         element.attr({
                             href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
                             target: '_blank',
                             download: fname
                         })[0].click();

If attr method not working in Firefox You can also use javaScript setAttribute method

Determining the size of an Android view at runtime

Based on @mbaird's advice, I found a workable solution by subclassing the ImageView class and overriding onLayout(). I then created an observer interface which my activity implemented and passed a reference to itself to the class, which allowed it to tell the activity when it was actually finished sizing.

I'm not 100% convinced that this is the best solution (hence my not marking this answer as correct just yet), but it does work and according to the documentation is the first time when one can find the actual size of a view.

What is the shortcut in IntelliJ IDEA to find method / functions?

Intellij v 13.1.4, OSX

The Open Symbol keyboard shortcut is command+shift+s

convert base64 to image in javascript/jquery

One quick and easy way:

function paintSvgToCanvas(uSvg, uCanvas) {

    var pbx = document.createElement('img');

    pbx.style.width  = uSvg.style.width;
    pbx.style.height = uSvg.style.height;

    pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
    uCanvas.getContext('2d').drawImage(pbx, 0, 0);

}

What's the difference between %s and %d in Python string formatting?

%d and %s are placeholders, they work as a replaceable variable. For example, if you create 2 variables

variable_one = "Stackoverflow"
variable_two = 45

you can assign those variables to a sentence in a string using a tuple of the variables.

variable_3 = "I was searching for an answer in %s and found more than %d answers to my question"

Note that %s works for String and %d work for numerical or decimal variables.

if you print variable_3 it would look like this

print(variable_3 % (variable_one, variable_two))

I was searching for an answer in StackOverflow and found more than 45 answers to my question.

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

Check Whether a User Exists

Depending on your shell implementation (e.g. Busybox vs. grown-up) the [ operator might start a process, changing $?.

Try

getent passwd $1 > /dev/null 2&>1
RES=$?

if [ $RES -eq 0 ]; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

File.Move Does Not Work - File Already Exists

1) With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:

see https://docs.microsoft.com/en-us/dotnet/api/system.io.file.move?view=netcore-3.1

In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.

2) For all other versions of .Net, https://stackoverflow.com/a/42224803/887092 is the best answer. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)

Laravel - Return json along with http status code

laravel 7.* You don't have to speicify JSON RESPONSE cause it's automatically converted it to JSON

return response(['Message'=>'Wrong Credintals'], 400);

Detect application heap size in Android

Asus Nexus 7 (2013) 32Gig: getMemoryClass()=192 maxMemory()=201326592

I made the mistake of prototyping my game on the Nexus 7, and then discovering it ran out of memory almost immediately on my wife's generic 4.04 tablet (memoryclass 48, maxmemory 50331648)

I'll need to restructure my project to load fewer resources when I determine memoryclass is low.
Is there a way in Java to see the current heap size? (I can see it clearly in the logCat when debugging, but I'd like a way to see it in code to adapt, like if currentheap>(maxmemory/2) unload high quality bitmaps load low quality

Sending emails in Node.js?

Nodemailer Module is the simplest way to send emails in node.js.

Try this sample example form: http://www.tutorialindustry.com/nodejs-mail-tutorial-using-nodemailer-module

Additional Info: http://www.nodemailer.com/

SQL multiple columns in IN clause

Ensure you have an index on your firstname and lastname columns and go with 1. This really won't have much of a performance impact at all.

EDIT: After @Dems comment regarding spamming the plan cache ,a better solution might be to create a computed column on the existing table (or a separate view) which contained a concatenated Firstname + Lastname value, thus allowing you to execute a query such as

SELECT City 
FROM User 
WHERE Fullname in (@fullnames)

where @fullnames looks a bit like "'JonDoe', 'JaneDoe'" etc

How to check if Receiver is registered in Android?

There is no API function to check if a receiver is registered. The workaround is to put your code in a try catch block as done below.

try {

 //Register or UnRegister your broadcast receiver here

} catch(IllegalArgumentException e) {

    e.printStackTrace();
}

Common HTTPclient and proxy

Here is how to do that with the last version of HTTPClient (4.3.4)

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpHost target = new HttpHost("localhost", 443, "https");
        HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");

        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy)
                .build();
        HttpGet request = new HttpGet("/");
        request.setConfig(config);

        System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);

        CloseableHttpResponse response = httpclient.execute(target, request);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

'module' object is not callable - calling method in another file

  • from a directory_of_modules, you can import a specific_module.py
  • this specific_module.py, can contain a Class with some_methods() or just functions()
  • from a specific_module.py, you can instantiate a Class or call functions()
  • from this Class, you can execute some_method()

Example:

#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()

Excerpts from PEP 8 - Style Guide for Python Code:

Modules should have short and all-lowercase names.

Notice: Underscores can be used in the module name if it improves readability.

A Python module is simply a source file(*.py), which can expose:

  • Class: names using the "CapWords" convention.

  • Function: names in lowercase, words separated by underscores.

  • Global Variables: the conventions are about the same as those for Functions.

Separating class code into a header and cpp file

It's important to point out to readers stumbling upon this question when researching the subject in a broader fashion that the accepted answer's procedure is not required in the case you just want to split your project into files. It's only needed when you need multiple implementations of single classes. If your implementation per class is one, just one header file for each is enough.

Hence, from the accepted answer's example only this part is needed:

#ifndef MYHEADER_H
#define MYHEADER_H

//Class goes here, full declaration AND implementation

#endif

The #ifndef etc. preprocessor definitions allow it to be used multiple times.

PS. The topic becomes clearer once you realize C/C++ is 'dumb' and #include is merely a way to say "dump this text at this spot".

Difference in Months between two dates in JavaScript

Difference in Months between two dates in JavaScript:

 start_date = new Date(year, month, day); //Create start date object by passing appropiate argument
 end_date = new Date(new Date(year, month, day)

total months between start_date and end_date :

 total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())

RunAs A different user when debugging in Visual Studio

As mentioned in have debugger run application as different user (linked above), another extremely simple way to do this which doesn't require any more tools:

  • Hold Shift + right-click to open a new instance of Visual Studio.
  • Click "Run as different user"

    Run as Different user

  • Enter credentials of the other user in the next pop-up window

  • Open the same solution you are working with

Now when you debug the solution it will be with the other user's permissions.

Hint: if you are going to run multiple instances of Visual Studio, change the theme of it (like to "dark") so you can keep track of which one is which easily).

What is middleware exactly?

Middleware is about how our application responds to incoming requests. Middlewares look into the incoming request, and make decisions based on this request. We can build entire applications only using middlewares. For e.g. ASP.NET is a web framework comprising of following chief HTTP middleware components.

  1. Exception/error handling
  2. Static file server
  3. Authentication
  4. MVC Middlewares

As shown in the above diagram, there are various middleware components in ASP.NET which receive the incoming request, and redirect it to a C# class (in this case a controller class).

Add data dynamically to an Array

You should use method array_push to add value or array to array exists

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

/** GENERATED OUTPUT
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
*/

What is the difference between static func and class func in Swift?

Is it simply that static is for static functions of structs and enums, and class for classes and protocols?

That's the main difference. Some other differences are that class functions are dynamically dispatched and can be overridden by subclasses.

Protocols use the class keyword, but it doesn't exclude structs from implementing the protocol, they just use static instead. Class was chosen for protocols so there wouldn't have to be a third keyword to represent static or class.

From Chris Lattner on this topic:

We considered unifying the syntax (e.g. using "type" as the keyword), but that doesn't actually simply things. The keywords "class" and "static" are good for familiarity and are quite descriptive (once you understand how + methods work), and open the door for potentially adding truly static methods to classes. The primary weirdness of this model is that protocols have to pick a keyword (and we chose "class"), but on balance it is the right tradeoff.

And here's a snippet that shows some of the override behavior of class functions:

class MyClass {
    class func myFunc() {
        println("myClass")
    }
}

class MyOtherClass: MyClass {
    override class func myFunc() {
        println("myOtherClass")
    }
}

var x: MyClass = MyOtherClass()
x.dynamicType.myFunc() //myOtherClass
x = MyClass()
x.dynamicType.myFunc() //myClass

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

How to order by with union in SQL?

If I want the sort to be applied to only one of the UNION if use Union all:

Select id,name,age
From Student
Where age < 15
Union all
Select id,name,age
From 
(
Select id,name,age
From Student
Where Name like "%a%"
Order by name
)

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had the same issue but it was because I copied and pasted the string as it is. Later when I manually typed the string as it is the error vanished.

I had the error due to the - sign. When I replaced it with manually inputting a - the error was solved.

Copied string 10 + 3 * 5/(16 - 4)

Manually typed string 10 + 3 * 5/(16 - 4)

you can clearly see there is a bit of difference between both the hyphens.

I think it's because of the different formatting used by different OS or maybe just different software.

Java: Multiple class declarations in one file

1.Is there a tidy name for this technique (analogous to inner, nested, anonymous)?

Multi-class single-file demo.

2.The JLS says the system may enforce the restriction that these secondary classes can't be referred to by code in other compilation units of the package, e.g., they can't be treated as package-private. Is that really something that changes between Java implementations?

I'm not aware of any which don't have that restriction - all the file based compilers won't allow you to refer to source code classes in files which are not named the same as the class name. ( if you compile a multi-class file, and put the classes on the class path, then any compiler will find them )

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

Simple file write function in C++

Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.

Update cordova plugins in one command

You can't update it. What you can do is uninstall the cordova plugin and add it again.

cordova plugin rm https://github.com/apache/cordova-plugin-camera --save
cordova plugin add https://github.com/apache/cordova-plugin-camera --save

How can I split a string into segments of n characters?

Building on the previous answers to this question; the following function will split a string (str) n-number (size) of characters.

function chunk(str, size) {
    return str.match(new RegExp('.{1,' + size + '}', 'g'));
}

Demo

_x000D_
_x000D_
(function() {_x000D_
  function chunk(str, size) {_x000D_
    return str.match(new RegExp('.{1,' + size + '}', 'g'));_x000D_
  }_x000D_
  _x000D_
  var str = 'HELLO WORLD';_x000D_
  println('Simple binary representation:');_x000D_
  println(chunk(textToBin(str), 8).join('\n'));_x000D_
  println('\nNow for something crazy:');_x000D_
  println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join('  '));_x000D_
  _x000D_
  // Utiliy functions, you can ignore these._x000D_
  function textToBin(text) { return textToBase(text, 2, 8); }_x000D_
  function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); }_x000D_
  function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); }_x000D_
  function print(text) { document.getElementById('out').innerHTML += (text || ''); }_x000D_
  function println(text) { print((text || '') + '\n'); }_x000D_
  function repeat(chr, n) { return new Array(n + 1).join(chr); }_x000D_
  function textToBase(text, radix, n) {_x000D_
    return text.split('').reduce(function(result, chr) {_x000D_
      return result + pad(chr.charCodeAt(0).toString(radix), n, '0');_x000D_
    }, '');_x000D_
  }_x000D_
  function roundUp(numToRound, multiple) { _x000D_
    if (multiple === 0) return numToRound;_x000D_
    var remainder = numToRound % multiple;_x000D_
    return remainder === 0 ? numToRound : numToRound + multiple - remainder;_x000D_
  }_x000D_
}());
_x000D_
#out {_x000D_
  white-space: pre;_x000D_
  font-size: 0.8em;_x000D_
}
_x000D_
<div id="out"></div>
_x000D_
_x000D_
_x000D_

Set encoding and fileencoding to utf-8 in Vim

TL;DR

In the first case with set encoding=utf-8, you'll change the output encoding that is shown in the terminal.

In the second case with set fileencoding=utf-8, you'll change the output encoding of the file that is written.

As stated by @Dennis, you can set them both in your ~/.vimrc if you always want to work in utf-8.

More details

From the wiki of VIM about working with unicode

"encoding sets how vim shall represent characters internally. Utf-8 is necessary for most flavors of Unicode."

"fileencoding sets the encoding for a particular file (local to buffer); :setglobal sets the default value. An empty value can also be used: it defaults to same as 'encoding'. Or you may want to set one of the ucs encodings, It might make the same disk file bigger or smaller depending on your particular mix of characters. Also, IIUC, utf-8 is always big-endian (high bit first) while ucs can be big-endian or little-endian, so if you use it, you will probably need to set 'bomb" (see below)."

Import SQL dump into PostgreSQL database

Here is the command you are looking for.

psql -h hostname -d databasename -U username -f file.sql

Difference between git stash pop and git stash apply

In git stash is a storage area where current changed files can be moved.

stash area is useful when you want to pull some changes from git repository and detected some changes in some mutual files available in git repo.

git stash apply //apply the changes without removing stored files from stash area.

git stash pop  // apply the changes as well as remove stored files from stash area.

Note :- git apply only apply the changes from stash area while git pop apply as well as remove change from stash area.

Get HTML code from website in C#

Try this solution. It works fine.

 try{
        String url = textBox1.Text;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.Load(sr);
        var aTags = doc.DocumentNode.SelectNodes("//a");
        int counter = 1;
        if (aTags != null)
        {
            foreach (var aTag in aTags)
            {
                richTextBox1.Text +=  aTag.InnerHtml +  "\n" ;
                counter++;
            }
        }
        sr.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to retrieve related keywords." + ex);
        }

Copying sets Java

Java 8+:

Set<String> copy = new HashSet<>(mySet); 

Insert line at middle of file with Python?

Below is a slightly awkward solution for the special case in which you are creating the original file yourself and happen to know the insertion location (e.g. you know ahead of time that you will need to insert a line with an additional name before the third line, but won't know the name until after you've fetched and written the rest of the names). Reading, storing and then re-writing the entire contents of the file as described in other answers is, I think, more elegant than this option, but may be undesirable for large files.

You can leave a buffer of invisible null characters ('\0') at the insertion location to be overwritten later:

num_names = 1_000_000    # Enough data to make storing in a list unideal
max_len = 20             # The maximum allowed length of the inserted line
line_to_insert = 2       # The third line is at index 2 (0-based indexing)

with open(filename, 'w+') as file:
    for i in range(line_to_insert):
        name = get_name(i)                    # Returns 'Alfred' for i = 0, etc.
        file.write(F'{i + 1}. {name}\n')

    insert_position = file.tell()             # Position to jump back to for insertion
    file.write('\0' * max_len + '\n')         # Buffer will show up as a blank line

    for i in range(line_to_insert, num_names):
        name = get_name(i)
        file.write(F'{i + 2}. {name}\n')      # Line numbering now bumped up by 1.

# Later, once you have the name to insert...
with open(filename, 'r+') as file:            # Must use 'r+' to write to middle of file 
    file.seek(insert_position)                # Move stream to the insertion line
    name = get_bonus_name()                   # This lucky winner jumps up to 3rd place
    new_line = F'{line_to_insert + 1}. {name}'
    file.write(new_line[:max_len])            # Slice so you don't overwrite next line

Unfortunately there is no way to delete-without-replacement any excess null characters that did not get overwritten (or in general any characters anywhere in the middle of a file), unless you then re-write everything that follows. But the null characters will not affect how your file looks to a human (they have zero width).

jQuery - how can I find the element with a certain id?

As all html ids are unique in a valid html document why not search for the ID directly? If you're concerned if they type in an id that isn't a table then you can inspect the tag type that way?

Just an idea!

S

How to add a tooltip to an svg graphic?

I came up with something using HTML + CSS only. Hope it works for you

_x000D_
_x000D_
.mzhrttltp {
  position: relative;
  display: inline-block;
}
.mzhrttltp .hrttltptxt {
  visibility: hidden;
  width: 120px;
  background-color: #040505;
  font-size:13px;color:#fff;font-family:IranYekanWeb;
  text-align: center;
  border-radius: 3px;
  padding: 4px 0;
  position: absolute;
  z-index: 1;
  top: 105%;
  left: 50%;
  margin-left: -60px;
}

.mzhrttltp .hrttltptxt::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent #040505 transparent;
}

.mzhrttltp:hover .hrttltptxt {
  visibility: visible;
}
_x000D_
<div class="mzhrttltp"><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#e2062c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg><div class="hrttltptxt">?????&zwnj;????&zwnj;??</div></div>
_x000D_
_x000D_
_x000D_

How to create a new object instance from a Type

I can across this question because I was looking to implement a simple CloneObject method for arbitrary class (with a default constructor)

With generic method you can require that the type implements New().

Public Function CloneObject(Of T As New)(ByVal src As T) As T
    Dim result As T = Nothing
    Dim cloneable = TryCast(src, ICloneable)
    If cloneable IsNot Nothing Then
        result = cloneable.Clone()
    Else
        result = New T
        CopySimpleProperties(src, result, Nothing, "clone")
    End If
    Return result
End Function

With non-generic assume the type has a default constructor and catch an exception if it doesn't.

Public Function CloneObject(ByVal src As Object) As Object
    Dim result As Object = Nothing
    Dim cloneable As ICloneable
    Try
        cloneable = TryCast(src, ICloneable)
        If cloneable IsNot Nothing Then
            result = cloneable.Clone()
        Else
            result = Activator.CreateInstance(src.GetType())
            CopySimpleProperties(src, result, Nothing, "clone")
        End If
    Catch ex As Exception
        Trace.WriteLine("!!! CloneObject(): " & ex.Message)
    End Try
    Return result
End Function

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


Regular Expression to get a string between parentheses in Javascript

Alternative:

var str = "I expect five hundred dollars ($500) ($1).";
str.match(/\(.*?\)/g).map(x => x.replace(/[()]/g, ""));
? (2) ["$500", "$1"]

It is possible to replace brackets with square or curly brackets if you need

Nginx: Job for nginx.service failed because the control process exited

The easiest way is kill all nginx processes

sudo killall nginx

then

sudo nginx

or

sudo service nginx start

Effects of the extern keyword on C functions

The reason it has no effect is because at the link-time the linker tries to resolve the extern definition (in your case extern int f()). It doesn't matter if it finds it in the same file or a different file, as long as it is found.

Hope this answers your question.

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

You opened the file in binary mode:

The following code will throw a TypeError: a bytes-like object is required, not 'str'.

for line in lines:
    print(type(line))# <class 'bytes'>
    if 'substring' in line:
       print('success')

The following code will work - you have to use the decode() function:

for line in lines:
    line = line.decode()
    print(type(line))# <class 'str'>
    if 'substring' in line:
       print('success')

Calling ASP.NET MVC Action Methods from JavaScript

You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d

jQuery post is the short version of jQuery ajax.

function addToCart(id)
{
  $.post('@Url.Action("Add","Cart")',{id:id } function(data) {
    //do whatever with the result.
  });
}

If you want more options like success callbacks and error handling, use jQuery ajax,

function addToCart(id)
{
  $.ajax({
  url: '@Url.Action("Add","Cart")',
  data: { id: id },
  success: function(data){
    //call is successfully completed and we got result in data
  },
  error:function (xhr, ajaxOptions, thrownError){
                  //some errror, some show err msg to user and log the error  
                  alert(xhr.responseText);

                }    
  });
}

When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.

This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.

How to replace existing value of ArrayList element in Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Checking Bash exit status of several commands efficiently

I have a set of scripting functions that I use extensively on my Red Hat system. They use the system functions from /etc/init.d/functions to print green [ OK ] and red [FAILED] status indicators.

You can optionally set the $LOG_STEPS variable to a log file name if you want to log which commands fail.

Usage

step "Installing XFS filesystem tools:"
try rpm -i xfsprogs-*.rpm
next

step "Configuring udev:"
try cp *.rules /etc/udev/rules.d
try udevtrigger
next

step "Adding rc.postsysinit hook:"
try cp rc.postsysinit /etc/rc.d/
try ln -s rc.d/rc.postsysinit /etc/rc.postsysinit
try echo $'\nexec /etc/rc.postsysinit' >> /etc/rc.sysinit
next

Output

Installing XFS filesystem tools:        [  OK  ]
Configuring udev:                       [FAILED]
Adding rc.postsysinit hook:             [  OK  ]

Code

#!/bin/bash

. /etc/init.d/functions

# Use step(), try(), and next() to perform a series of commands and print
# [  OK  ] or [FAILED] at the end. The step as a whole fails if any individual
# command fails.
#
# Example:
#     step "Remounting / and /boot as read-write:"
#     try mount -o remount,rw /
#     try mount -o remount,rw /boot
#     next
step() {
    echo -n "$@"

    STEP_OK=0
    [[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
}

try() {
    # Check for `-b' argument to run command in the background.
    local BG=

    [[ $1 == -b ]] && { BG=1; shift; }
    [[ $1 == -- ]] && {       shift; }

    # Run the command.
    if [[ -z $BG ]]; then
        "$@"
    else
        "$@" &
    fi

    # Check if command failed and update $STEP_OK if so.
    local EXIT_CODE=$?

    if [[ $EXIT_CODE -ne 0 ]]; then
        STEP_OK=$EXIT_CODE
        [[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$

        if [[ -n $LOG_STEPS ]]; then
            local FILE=$(readlink -m "${BASH_SOURCE[1]}")
            local LINE=${BASH_LINENO[0]}

            echo "$FILE: line $LINE: Command \`$*' failed with exit code $EXIT_CODE." >> "$LOG_STEPS"
        fi
    fi

    return $EXIT_CODE
}

next() {
    [[ -f /tmp/step.$$ ]] && { STEP_OK=$(< /tmp/step.$$); rm -f /tmp/step.$$; }
    [[ $STEP_OK -eq 0 ]]  && echo_success || echo_failure
    echo

    return $STEP_OK
}

ActiveMQ or RabbitMQ or ZeroMQ or

Edit: My initial answer had a strong focus on AMQP. I decided to rewrite it to offer a wider view on the topic.

These 3 messaging technologies have different approaches on building distributed systems :

RabbitMQ is one of the leading implementation of the AMQP protocol (along with Apache Qpid). Therefore, it implements a broker architecture, meaning that messages are queued on a central node before being sent to clients. This approach makes RabbitMQ very easy to use and deploy, because advanced scenarios like routing, load balancing or persistent message queuing are supported in just a few lines of code. However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big.

ZeroMq is a very lightweight messaging system specially designed for high throughput/low latency scenarios like the one you can find in the financial world. Zmq supports many advanced messaging scenarios but contrary to RabbitMQ, you’ll have to implement most of them yourself by combining various pieces of the framework (e.g : sockets and devices). Zmq is very flexible but you’ll have to study the 80 pages or so of the guide (which I recommend reading for anybody writing distributed system, even if you don’t use Zmq) before being able to do anything more complicated than sending messages between 2 peers.

ActiveMQ is in the middle ground. Like Zmq, it can be deployed with both broker and P2P topologies. Like RabbitMQ, it’s easier to implement advanced scenarios but usually at the cost of raw performance. It’s the Swiss army knife of messaging :-).

Finally, all 3 products:

  • have client apis for the most common languages (C++, Java, .Net, Python, Php, Ruby, …)
  • have strong documentation
  • are actively supported

Counting the number of elements with the values of x in a vector

You can change the number to whatever you wish in following line

length(which(numbers == 4))

What's the difference between TRUNCATE and DELETE in SQL

Summary of Delete Vs Truncate in SQL server
For Complete Article follow this link : http://codaffection.com/sql-server-article/delete-vs-truncate-in-sql-server/

enter image description here

Taken from dotnet mob article :Delete Vs Truncate in SQL Server

How to stop a thread created by implementing runnable interface?

If you use ThreadPoolExecutor, and you use submit() method, it will give you a Future back. You can call cancel() on the returned Future to stop your Runnable task.

list.clear() vs list = new ArrayList<Integer>();

I would suggest using list.clear() rather than allocating a new object. When you call the "new" keyword, you are creating more space in memory. In reality, it doesn't matter much. I suppose that if you know how large the list will be, it might be a good idea to create a new space but then specify how large the array will be.

The truth is, it's not going to matter unless you're doing scientific programming. In that case, you need to go learn C++.

ExtJs Gridpanel store refresh

Another approach in 3.4 (don't know if this is proper Ext): You can have a delete handler like this, assuming every row has a 'delete' button.

handler: function(grid, rowIndex, colIndex) {
    var rec = grid.getStore().getAt(rowIndex);
    var id = rec.get('id');
    // some DELETE/GET ajax callback here...
    // pass in 'id' var or some key
    // inside success
    grid.getStore().removeAt(rowIndex);
}

print spaces with String.format()

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

Find the day of a week

This should do the trick

df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
dow <- function(x) format(as.Date(x), "%A")
df$day <- dow(df$date)
df

#Returns:
        date       day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02  Thursday

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

List of macOS text editors and code editors

I used BBEdit for years, but recently converted to Panic's Coda.

I love Coda. It does everything that I need and now that I've begun programming plug-ins for it, it's become a far more rich tool. The support team are responsive and the community that is growing around it is fantastic. There is still a lot of room for improvement, but that's the cool thing about being part of the kind of community that surrounds it; you have a say in what that improvement is.

Panic - Coda

CSS3 equivalent to jQuery slideUp and slideDown?

    try this for slide up slide down with animation 
give your **height

        @keyframes slide_up{
            from{
                min-height: 0;
                height: 0px;
                opacity: 0;
            }
            to{
                height: 560px;
                opacity: 1;
            }
        }

        @keyframes slide_down{
            from{
                height: 560px;
                opacity: 1;
            }
            to{
                min-height: 0;
                height: 0px;
                opacity: 0;
            } 
        }

git undo all uncommitted or unsaved changes

States transitioning from one commit to new commit

0. last commit,i.e. HEAD commit
1. Working tree changes, file/directory deletion,adding,modification.
2. The changes are staged in index
3. Staged changes are committed

Action for state transitioning

0->1: manual file/directory operation
1->2: git add .
2->3: git commit -m "xxx"

Check diff

0->1: git diff
0->2: git diff --cached
0->1, and 0->2: git diff HEAD
last last commit->last commit: git diff HEAD^ HEAD

Revert to last commit

2->1: git reset
1->0: git checkout .     #only for tracked files/directories(actions include modifying/deleting tracked files/directories)
1->0: git clean -fdx     #only for untracked files/directories(action includes adding new files/directories)
2->1, and 1->0: git reset --hard HEAD

Equivalent of git clone, without re-downloading anything

git reset && git checkout . && git clean -fdx

console.log timestamps in Chrome?

ES6 solution:

const timestamp = () => `[${new Date().toUTCString()}]`
const log = (...args) => console.log(timestamp(), ...args)

where timestamp() returns actually formatted timestamp and log add a timestamp and propagates all own arguments to console.log

Anybody knows any knowledge base open source?

Since I don't have enough reputation points to comment on Bruno Shine's answer, I'll add this note as a new answer.

KBPublisher 2.0 is still available on Sourceforge: http://sourceforge.net/projects/kbpublisher/

The project hasn't been updated for years. I've been running it since v1.9 or something, and it works fine.

ImportError: No module named psycopg2

I faced same problem and waste almost a day to resolve this issue . I have done 2 things 1- use python 3.6 instead of 3.8 2- change django 2.2 version(may be working some higher but i change to 2.2)

Now its working fine

"The page you are requesting cannot be served because of the extension configuration." error message

In case this helps anyone, I was getting this error when attempting to run aspnet_regiis.exe:

Operation failed with 0x8007000B

An attempt was made to load a program with an incorrect format

As it turns out, the server was running 2008 64 bit and I was trying to run the 32 bit version of the utility. Running the version found in \Windows\Microsoft.NET\Framework64\v2.0.50727 fixed the issue.

c:\Windows\Microsoft.NET\Framework64\v2.0.50727>aspnet_regiis.exe -i

In SQL Server, what does "SET ANSI_NULLS ON" mean?

SET ANSI_NULLS ON

IT Returns all values including null values in the table

SET ANSI_NULLS off

it Ends when columns contains null values

Open soft keyboard programmatically

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Use above code in onResume() to open soft Keyboard

Proper way to make HTML nested list?

Option 2 is correct.

The nested list should be inside a <li> element of the list in which it is nested.

Link to the W3C Wiki on Lists (taken from comment below): HTML Lists Wiki.

Link to the HTML5 W3C ul spec: HTML5 ul. Note that a ul element may contain exactly zero or more li elements. The same applies to HTML5 ol. The description list (HTML5 dl) is similar, but allows both dt and dd elements.

More Notes:

  • dl = definition list.
  • ol = ordered list (numbers).
  • ul = unordered list (bullets).

mysql extract year from date format

try this code:

SELECT YEAR( str_to_date( subdateshow, '%m/%d/%Y' ) ) AS Mydate

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

it is due to incompatibility.

please upgrade classpath("com.android.tools.build:gradle:4.0.1") in build.gradle file under android folder.

Setting max width for body using Bootstrap

You don't have to modify bootstrap-responsive by removing @media (max-width:1200px) ...

My application has a max-width of 1600px. Here's how it worked for me:

  1. Create bootstrap-custom.css - As much as possible, I don't want to override my original bootstrap css.

  2. Inside bootstrap-custom.css, override the container-fluid by including this code:

Like this:

/* set a max-width for horizontal fluid layout and make it centered */
.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 1600px; /* or 950px */
}

browser sessionStorage. share between tabs?

Using sessionStorage for this is not possible.

From the MDN Docs

Opening a page in a new tab or window will cause a new session to be initiated.

That means that you can't share between tabs, for this you should use localStorage

Accessing nested JavaScript objects and arrays by string path

Building off of Alnitak's answer:

if(!Object.prototype.byString){
  //NEW byString which can update values
Object.prototype.byString = function(s, v, o) {
  var _o = o || this;
      s = s.replace(/\[(\w+)\]/g, '.$1'); // CONVERT INDEXES TO PROPERTIES
      s = s.replace(/^\./, ''); // STRIP A LEADING DOT
      var a = s.split('.'); //ARRAY OF STRINGS SPLIT BY '.'
      for (var i = 0; i < a.length; ++i) {//LOOP OVER ARRAY OF STRINGS
          var k = a[i];
          if (k in _o) {//LOOP THROUGH OBJECT KEYS
              if(_o.hasOwnProperty(k)){//USE ONLY KEYS WE CREATED
                if(v !== undefined){//IF WE HAVE A NEW VALUE PARAM
                  if(i === a.length -1){//IF IT'S THE LAST IN THE ARRAY
                    _o[k] = v;
                  }
                }
                _o = _o[k];//NO NEW VALUE SO JUST RETURN THE CURRENT VALUE
              }
          } else {
              return;
          }
      }
      return _o;
  };

}

This allows you to set a value as well!

I've created an npm package and github with this as well

PHP-FPM and Nginx: 502 Bad Gateway

I've also found this error can be caused when writing json_encoded() data to MySQL. To get around it I base64_encode() the JSON. Please not that when decoded, the JSON encoding can change values. Nb. 24 can become 24.00

How to format string to money

try

amtf =  amtf.Insert(amtf.Length - 2, ".");

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

The node REPL has a built-in solution for overriding how objects are displayed, see here.

The REPL module internally uses util.inspect(), when printing values. However, util.inspect delegates the call to the object's inspect() function, if it has one.

Is there a difference between `continue` and `pass` in a for loop in python?

Difference between pass and continue in a for loop:

So why pass in python?

If you want to create a empty class, method or block.

Examples:

class MyException(Exception):
    pass


try:
   1/0
 except:
   pass

without 'pass' in the above examples will throw IndentationError.

How to get the selected date value while using Bootstrap Datepicker?

I was able to find the moment.js object for the selected date with the following:

$('#datepicker').data('DateTimePicker').date()

More info about moment.js and how to format the date using the moment.js object

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

I got your point that you don't wanna use the built-in functions for merging or remove duplicates from the ArrayList. Your first code is running forever because the outer for loop condition is 'Always True'. Since you are adding elements to plusArray, so the size of the plusArray is increasing with every addition and hence 'i' is always less than it. As a result the condition never fails and the program runs forever. Tip: Try to first merge the list and then from the merged list remove the duplicate elements. :)

Creating a selector from a method name with parameters

You can't pass a parameter in a @selector().

It looks like you're trying to implement a callback. The best way to do that would be something like this:

[object setCallbackObject:self withSelector:@selector(myMethod:)];

Then in your object's setCallbackObject:withSelector: method: you can call your callback method.

-(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
    [anObject performSelector:selector];
}

POST: sending a post request in a url itself

You can use postman.

Where select Post as method. and In Request Body send JSON Object.

Getting error: ISO C++ forbids declaration of with no type

You forgot the return types in your member function definitions:

int ttTree::ttTreeInsert(int value) { ... }
^^^               

and so on.

Push existing project into Github

git init

Add the files in your new local repository. This stages them for the first commit.

git add .

Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.

Commit the files that you've staged in your local repository.

git commit -m "First commit"
# Commits the tracked changes and prepares them to be pushed to a remote

repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again. Copy remote repository URL fieldAt the top of your GitHub repository's Quick Setup page, click to copy the remote repository URL.

In the Command prompt, add the URL for the remote repository where your local repository will be pushed.

git remote add origin remote repository URL
# Sets the new remote
git remote -v
# Verifies the new remote URL

Push the changes in your local repository to GitHub.

git push origin master
# Pushes the changes in your local repository up to the remote repository you 

specified as the origin

Getting the object's property name

Using Object.keys() function for acquiring properties from an Object, and it can help search property by name, for example:

const Products = function(){
    this.Product = "Product A";
    this.Price = 9.99;
    this.Quantity = 112;
};

// Simple find function case insensitive
let findPropByName = function(data, propertyName){
 let props = [];
 Object.keys(data).forEach(element => {
    return props.push(element.toLowerCase());
  });
  console.log(props);
  let i = props.indexOf(propertyName.toLowerCase());

  if(i > -1){
    return props[i];
  }
  return false;
};

// calling the function
let products = new Products();
console.log(findPropByName(products, 'quantity'));

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

How to add display:inline-block in a jQuery show() function?

Best way is to add !important suffix to the selector .

Example:

 #selector{
     display: inline-block !important;                   
}

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

Generate Java classes from .XSD files...?

If you want to start coding Java to XML and XML to Java in less than 5 minutes, try Simple XML Serialization. Don't spend hours learning the JAXB API http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php

However, if you are really keen on learning JAXB, here's an excellent tutorial http://blogs.oracle.com/teera/entry/jaxb_for_simple_java_xml

Contents of tutorial:

JAXB for simple Java-XML serialization

There're a number of way to do XML serialization in Java. If you want fine-grained control over parsing and serialization you can go for SAX, DOM, or Stax for better performance. Yet, what I often want to do is a simple mapping between POJOs and XML. However, creating Java classes to do XML event parsing manually is not trivial. I recently found JAXB to be a quick and convenient Java-XML mapping or serialization.

JAXB contains a lot of useful features, you can check out the reference implementation here. Kohsuke's Blog is also a good resource to learn more about JAXB. For this blog entry, I'll show you how to do a simple Java-XML serialization with JAXB.

POJO to XML

Let's say I have an Item Java object. I want to serialize an Item object to XML format. What I have to do first is to annotate this POJO with a few XML annotation from javax.xml.bind.annotation.* package. See code listing 1 for Item.java

From the code

  • @XmlRootElement(name="Item") indicates that I want to be the root element.
  • @XmlType(propOrder = {"name", "price"}) indicates the order that I want the element to be arranged in XML output.
  • @XmlAttribute(name="id", ...) indicates that id is an attribute to root element.
  • @XmlElement(....) indicates that I want price and name to be element within Item.

My Item.java is ready. I can then go ahead and create JAXB script for marshaling Item.

//creating Item data object
Item item = new Item();
item.setId(2);
item.setName("Foo");
item.setPrice(200);
.....

JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
//I want to save the output file to item.xml
marshaller.marshal(item, new FileWriter("item.xml"));

For complete code Listing please see Code Listing 2 main.java. The output Code Listing 3 item.xml file is created. It looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">
  <ns1:itemName>Foo</ns1:itemName>
  <ns1:price>200</ns1:price>
</ns1:item>

Easy right? You can alternatively channel the output XML as text String, Stream, Writer, ContentHandler, etc by simply change the parameter of the marshal(...) method like

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
// save xml output to the OutputStream instance
marshaller.marshal(item, <java.io.OutputStream instance>);

...
JAXBContext context = JAXBContext.newInstance(item.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter sw = new StringWriter();
//save to StringWriter, you can then call sw.toString() to get java.lang.String
marshaller.marshal(item, sw);

XML to POJO

Let's reverse the process. Assume that I now have a piece of XML string data and I want to turn it into Item.java object. XML data (Code listing 3) looks like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:item ns1:id="2" xmlns:ns1="http://blogs.sun.com/teera/ns/item">
  <ns1:itemName>Bar</ns1:itemName>
  <ns1:price>80</ns1:price>
</ns1:item>

I can then unmarshal this xml code to Item object by

...
ByteArrayInputStream xmlContentBytes = new ByteArrayInputStream (xmlContent.getBytes());
JAXBContext context = JAXBContext.newInstance(Item.getClass());
Unmarshaller unmarshaller = context.createUnmarshaller();
//note: setting schema to null will turn validator off
unmarshaller.setSchema(null);
Object xmlObject = Item.getClass().cast(unmarshaller.unmarshal(xmlContentBytes));
return xmlObject;
...

For complete code Listing please see Code Listing 2 (main.java). The XML source can come in many forms both from Stream and file. The only difference, again, is the method parameter:

...
unmarshaller.unmarshal(new File("Item.xml")); // reading from file
...
// inputStream is an instance of java.io.InputStream, reading from stream
unmarshaller.unmarshal(inputStream);

Validation with XML Schema

Last thing I want to mention here is validating input XML with schema before unmarshalling to Java object. I create an XML schema file called item.xsd. For complete code Listing please see Code Listing 4 (Item.xsd). Now what I have to do is register this schema for validation.

...
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
.newSchema(new File("Item.xsd"));
unmarshaller.setSchema(schema); //register item.xsd shcema for validation
...

When I try to unmarshal XML data to POJO, if the input XML is not conformed to the schema, exception will be caught. For complete code Listing please see Code Listing 5 (invalid_item.xml).

javax.xml.bind.UnmarshalException
- with linked exception:
javax.xml.bind.JAXBException caught: null
[org.xml.sax.SAXParseException: cvc-datatype-valid.1.2.1: 'item1' is
                                not a valid value for 'integer'.]

Here I change the 'id' attribute to string instead of integer.

If XML input is valid against the schema, the XML data will be unmarshalled to Item.java object successfully.

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

Why use pointers?

In java and C# all the object references are pointers, the thing with c++ is that you have more control on where you pointer points. Remember With great power comes grand responsibility.

INNER JOIN ON vs WHERE clause

I'll also point out that using the older syntax is more subject to error. If you use inner joins without an ON clause, you will get a syntax error. If you use the older syntax and forget one of the join conditions in the where clause, you will get a cross join. The developers often fix this by adding the distinct keyword (rather than fixing the join because they still don't realize the join itself is broken) which may appear to cure the problem but will slow down the query considerably.

Additionally for maintenance if you have a cross join in the old syntax, how will the maintainer know if you meant to have one (there are situations where cross joins are needed) or if it was an accident that should be fixed?

Let me point you to this question to see why the implicit syntax is bad if you use left joins. Sybase *= to Ansi Standard with 2 different outer tables for same inner table

Plus (personal rant here), the standard using the explicit joins is over 20 years old, which means implicit join syntax has been outdated for those 20 years. Would you write application code using a syntax that has been outdated for 20 years? Why do you want to write database code that is?

How do you set the Content-Type header for an HttpClient request?

For those who troubled with charset

I had very special case that the service provider didn't accept charset, and they refuse to change the substructure to allow it... Unfortunately HttpClient was setting the header automatically through StringContent, and no matter if you pass null or Encoding.UTF8, it will always set the charset...

Today i was on the edge to change the sub-system; moving from HttpClient to anything else, that something came to my mind..., why not use reflection to empty out the "charset"? ... And before i even try it, i thought of a way, "maybe I can change it after initialization", and that worked.

Here's how you can set the exact "application/json" header without "; charset=utf-8".

var jsonRequest = JsonSerializeObject(req, options); // Custom function that parse object to string
var stringContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
stringContent.Headers.ContentType.CharSet = null;
return stringContent;

Note: The null value in following won't work, and append "; charset=utf-8"

return new StringContent(jsonRequest, null, "application/json");

EDIT

@DesertFoxAZ suggests that also the following code can be used and works fine. (didn't test it myself, if it work's rate and credit him in comments)

stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

What Java FTP client library should I use?

Apache commons-nets get updates more frequently recently, while Enterprise DT library seems to update even more frequently.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

Mysqli makes use of object oriented programming. Try using this approach instead:

function dbCon() {
        if($mysqli = new mysqli('$hostname','$username','$password','$databasename')) return $mysqli; else return false;
}

if(!dbCon())
exit("<script language='javascript'>alert('Unable to connect to database')</script>");
else $con=dbCon();

if (isset($_GET['part'])){
    $partid = $_GET['part'];
    $sql = "SELECT * 
        FROM $usertable 
        WHERE PartNumber = $partid";

    $result=$con->query($sql_query);
    $row = $result->fetch_assoc();

    $partnumber = $partid;
    $nsn = $row["NSN"];
    $description = $row["Description"];
    $quantity = $row["Quantity"];
    $condition = $row["Conditio"];
}

Let me know if you have any questions, I could not test this code so you might need to tripple check it!

Difference between style = "position:absolute" and style = "position:relative"

OK, very obvious answer here... basically relative position is relative to previous element or window, while absolute don't care about the other elements unless it's a parent if you using top and left...

Look at the example I create for you to show the differences...

enter image description here

Also you can see it in action, using the css I create for you, you can see how absolute and relative positions behave:

_x000D_
_x000D_
.parent {_x000D_
  display: inline-block;_x000D_
  width: 180px;_x000D_
  height: 160px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.black {_x000D_
  position: relative;_x000D_
  width: 100px;_x000D_
  height: 30px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.red {_x000D_
  width: 100px;_x000D_
  height: 30px;_x000D_
  margin: 5px;_x000D_
  top: 16px;_x000D_
  background: red;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
_x000D_
.red-1 {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.red-2 {_x000D_
  position: absolute;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="black">_x000D_
  </div>_x000D_
  <div class="red red-1">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="parent">_x000D_
  <div class="black">_x000D_
  </div>_x000D_
  <div class="red red-2">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I import .sql files into SQLite 3?

From a sqlite prompt:

sqlite> .read db.sql

Or:

cat db.sql | sqlite3 database.db

Also, your SQL is invalid - you need ; on the end of your statements:

create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);

How do I output the results of a HiveQL query to CSV?

You should use CREATE TABLE AS SELECT (CTAS) statement to create a directory in HDFS with the files containing the results of the query. After that you will have to export those files from HDFS to your regular disk and merge them into a single file.

You also might have to do some trickery to convert the files from '\001' - delimited to CSV. You could use a custom CSV SerDe or postprocess the extracted file.

Plot two graphs in same plot in R

Rather than keeping the values to be plotted in an array, store them in a matrix. By default the entire matrix will be treated as one data set. However if you add the same number of modifiers to the plot, e.g. the col(), as you have rows in the matrix, R will figure out that each row should be treated independently. For example:

x = matrix( c(21,50,80,41), nrow=2 )
y = matrix( c(1,2,1,2), nrow=2 )
plot(x, y, col("red","blue")

This should work unless your data sets are of differing sizes.

How to change the output color of echo in Linux

red='\e[0;31m'
NC='\e[0m' # No Color
echo -e "${red}Hello Stackoverflow${NC}"

This answer correct, except that the call to colors should not be inside the quotes.

echo -e ${red}"Hello Stackoverflow"${NC}

Should do the trick.

How to download PDF automatically using js?

Please try this

_x000D_
_x000D_
(function ($) {
    $(document).ready(function(){
       function validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
           }
       
       if($('.submitclass').length){
            $('.submitclass').click(function(){
                $email_id = $('.custom-email-field').val();
                if (validateEmail($email_id)) {
                  var url= $(this).attr('pdf_url');
                  var link = document.createElement('a');
                  link.href = url;
                  link.download = url.split("/").pop();
                  link.dispatchEvent(new MouseEvent('click'));
                }
            });
       }
    });
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
        <div class="form-item form-type-textfield form-item-email-id form-group">
            <input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
        </div>
        <button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
_x000D_
_x000D_
_x000D_

Or use download attribute to tag in HTML5

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should use semicolons after every statement in JavaScript.

How to clear Flutter's Build cache?

Same issue with mine.

New to Flutter. I'm using VS build-in terminal to do flutter run, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file..., which is an old code version in my code. I have changed it to lib/model/student_model.dart.

And I search this line 'lib/student_model.dart'in the project, it appears filekernel_snapshot.d` containing it. So, it build the project with old code version.

For me, Flutter clean is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?

And I'm wondering if there is some command to just build flutter project without run?

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

Simplest way is definitely to enter the following command in the terminal:

sudo gem update --system

You can add the flag --no-document if you do not want to download the documentation. Here is sample output after running the command:

sudo gem update --system
Password:
Updating rubygems-update
Fetching: rubygems-update-2.6.8.gem (100%)
Successfully installed rubygems-update-2.6.8
Parsing documentation for rubygems-update-2.6.8
Installing ri documentation for rubygems-update-2.6.8
Installing darkfish documentation for rubygems-update-2.6.8
Installing RubyGems 2.6.8
RubyGems 2.6.8 installed
Parsing documentation for rubygems-2.6.8
Installing ri documentation for rubygems-2.6.8

------------------------------------------------------------------------------

RubyGems installed the following executables:
    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/gem

Ruby Interactive (ri) documentation was installed. ri is kind of like man 
pages for ruby libraries. You may access it like this:
  ri Classname
  ri Classname.class_method
  ri Classname#instance_method

MVC Redirect to View from jQuery with parameters

If your click handler is successfully called then this should work:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = "/Artists/Details?NestId=" + NestId; 
            window.location.href = url; 
        })

EDIT: In this particular case given that the action method parameter is a string which is nullable, then if NestId == null, won't cause any exception at all, given that the ModelBinder won't complain about it.

How to uninstall mini conda? python

To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.

Best way to find if an item is in a JavaScript array?

As of ECMAScript 2016 you can use includes()

arr.includes(obj);

If you want to support IE or other older browsers:

function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

  1. Mozilla's (ECMA-262) version:

       if (!Array.prototype.indexOf)
       {
    
            Array.prototype.indexOf = function(searchElement /*, fromIndex */)
    
         {
    
    
         "use strict";
    
         if (this === void 0 || this === null)
           throw new TypeError();
    
         var t = Object(this);
         var len = t.length >>> 0;
         if (len === 0)
           return -1;
    
         var n = 0;
         if (arguments.length > 0)
         {
           n = Number(arguments[1]);
           if (n !== n)
             n = 0;
           else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
             n = (n > 0 || -1) * Math.floor(Math.abs(n));
         }
    
         if (n >= len)
           return -1;
    
         var k = n >= 0
               ? n
               : Math.max(len - Math.abs(n), 0);
    
         for (; k < len; k++)
         {
           if (k in t && t[k] === searchElement)
             return k;
         }
         return -1;
       };
    
     }
    
  2. Daniel James's version:

     if (!Array.prototype.indexOf) {
       Array.prototype.indexOf = function (obj, fromIndex) {
         if (fromIndex == null) {
             fromIndex = 0;
         } else if (fromIndex < 0) {
             fromIndex = Math.max(0, this.length + fromIndex);
         }
         for (var i = fromIndex, j = this.length; i < j; i++) {
             if (this[i] === obj)
                 return i;
         }
         return -1;
       };
     }
    
  3. roosteronacid's version:

     Array.prototype.hasObject = (
       !Array.indexOf ? function (o)
       {
         var l = this.length + 1;
         while (l -= 1)
         {
             if (this[l - 1] === o)
             {
                 return true;
             }
         }
         return false;
       } : function (o)
       {
         return (this.indexOf(o) !== -1);
       }
     );
    

How to write character & in android strings.xml

You can find all the HTML Special Characters in this page http://www.degraeve.com/reference/specialcharacters.php Just replace the code where you want to put that character. :-)

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

Formatting numbers (decimal places, thousands separators, etc) with CSS

Probably the best way to do so is combo of setting a span with a class denoting your formatting then use Jquery .each to do formatting on the spans when the DOM is loaded...

Javascript seconds to minutes and seconds

I prefer thinking of Millisecond as its own unit, rather than as a subunit of something else. In that sense, it will have values of 0-999, so youre going to want to Pad three instead of two like I have seen with other answers. Here is an implementation:

function format(n) {
   let mil_s = String(n % 1000).padStart(3, '0');
   n = Math.trunc(n / 1000);
   let sec_s = String(n % 60).padStart(2, '0');
   n = Math.trunc(n / 60);
   return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}

https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I believe James Hunt's answer will solve the problem.

@user3731784: In your new message, the compiler seems to be confused because of the "C:\Program Files\IAR systems\Embedded Workbench 7.0\430\lib\dlib\d1430fn.h" argument. Why are you giving this header file at the middle of other compiler switches? Please correct this and try again. Also, it probably is a good idea to give the source file name after all the compiler switches and not at the beginning.

How do I programmatically get the GUID of an application in .NET 2.0

For an out-of-the-box working example, this is what I ended up using based on the previous answers.

using System.Reflection;
using System.Runtime.InteropServices;

label1.Text = "GUID: " + ((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute), false)).Value.ToUpper();

Alternatively, this way allows you to use it from a static class:

    /// <summary>
    /// public GUID property for use in static class </summary>
    /// <returns>
    /// Returns the application GUID or "" if unable to get it. </returns>
    static public string AssemblyGuid
    {
        get
        {
            object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false);
            if (attributes.Length == 0) { return String.Empty; }
            return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value.ToUpper();
        }
    }

Best practice for localization and globalization of strings and labels

As far as I know, there's a good library called localeplanet for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)

Here's the website of library: http://www.localeplanet.com/

Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/

The common part of all those articles/libraries is that they use a i18n class and a get method (in some ways also defining an smaller function name like _) for retrieving/converting the key to the value. In my explaining the key means that string you want to translate and the value means translated string.
Then, you just need a JSON document to store key's and value's.

For example:

var _ = document.webL10n.get;
alert(_('test'));

And here the JSON:

{ test: "blah blah" }

I believe using current popular libraries solutions is a good approach.

How do I restart nginx only after the configuration test was successful on Ubuntu?

Actually, as far as I know, nginx would show an empty message and it wouldn't actually restart if the configuration is bad.

The only way to screw it up is by doing an nginx stop and then start again. It would succeed to stop, but fail to start.

Python calling method in class

The first argument of all methods is usually called self. It refers to the instance for which the method is being called.

Let's say you have:

class A(object):
    def foo(self):
        print 'Foo'

    def bar(self, an_argument):
        print 'Bar', an_argument

Then, doing:

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

There's nothing special about this being called self, you could do the following:

class B(object):
    def foo(self):
        print 'Foo'

    def bar(this_object):
        this_object.foo()

Then, doing:

b = B()
b.bar() # prints 'Foo'

In your specific case:

dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT) 

(As suggested in comments MissileDevice.RIGHT could be more appropriate here!)

You could declare all your constants at module level though, so you could do:

dangerous_device.move(RIGHT)

This, however, is going to depend on how you want your code to be organized!

Iteration over std::vector: unsigned vs signed index variable

Obscure but important detail: if you say "for(auto it)" as follows, you get a copy of the object, not the actual element:

struct Xs{int i} x;
x.i = 0;
vector <Xs> v;
v.push_back(x);
for(auto it : v)
    it.i = 1;         // doesn't change the element v[0]

To modify the elements of the vector, you need to define the iterator as a reference:

for(auto &it : v)

Excel VBA - read cell value from code

I think you need this ..

Dim n as Integer   

For n = 5 to 17
  msgbox cells(n,3) '--> sched waste
  msgbox cells(n,4) '--> type of treatm
  msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
  msgbox cells(n,6) '--> email col
Next

How do I install the OpenSSL libraries on Ubuntu?

sudo apt-get install libcurl4-openssl-dev

How can I execute Python scripts using Anaconda's version of Python?

I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your PYTHONPATH or PATH every time you want to use a different interpreter. Sure, from the command line, activate my-environment works, but OP specifically asked about double-clicking.

In this case, the correct thing to do is use the Python launcher for Windows. Then, all you have to do is add #! path\to\interpreter\python.exe to the top of your script. Unfortunately, although the launcher comes standard with Python 3.3+, it is not included with Anaconda (see Python & Windows: Where is the python launcher?), and the simplest thing to do is to install it separately from here.

How to return an array from a function?

Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.

So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:

int *gnabber(){
  static int foo[] = {1,2,3}
  return foo;
}

Insert line break inside placeholder attribute of a textarea?

I liked the work of Jason Gennaro and Denis Golomazov, but I wanted something that would be more globally useful. I have modified the concept so that it can be added to any page without repercussion.

http://jsfiddle.net/pdXRx/297/

<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>

<h2>Modified behaviors</h2>

<!-- To get simulated placeholder with New Lines behavior,
     add the placeholdernl attribute -->

<textarea placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address' placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<h2>Standard behaviors</h2>

<textarea placeholder='Address'>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address'></textarea>

The javascript is very simple

<script>
(function($){
var handleFocus = function(){
    var $this = $(this);
    if($this.val() === $this.attr('placeholdernl')){
        $this.attr('value', '');
        $this.css('color', '');
    }
};

var handleBlur = function(){
    var $this = $(this);
    if($this.val() == ''){
        $this.attr('value', $this.attr('placeholdernl'))
        $this.css('color', 'gray');
    }    
};

$('textarea[placeholdernl]').each(function(){
    var $this = $(this),
        value = $this.attr('value'),
        placeholder = $this.attr('placeholder');
    $this.attr('placeholdernl', value ? value : placeholder);
    $this.attr('value', '');
    $this.focus(handleFocus).blur(handleBlur).trigger('blur');
});
})(jQuery);
</script>

How to override and extend basic Django admin templates?

if you need to overwrite the admin/index.html, you can set the index_template parameter of the AdminSite.

e.g.

# urls.py
...
from django.contrib import admin

admin.site.index_template = 'admin/my_custom_index.html'
admin.autodiscover()

and place your template in <appname>/templates/admin/my_custom_index.html

Running an outside program (executable) in Python?

Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.system, subprocess methods, or whatever...

If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

While many of the above answers are completely valid, no one seems to answer your question completely, specifically the part:

I don't know if I am right, but to determine probabilities I think I need to fit my data to a theoretical distribution that is the most suitable to describe my data. I assume that some kind of goodness of fit test is needed to determine the best model.

The parametric approach

This is the process you're describing of using some theoretical distribution and fitting the parameters to your data and there's some excellent answers how to do this.

The non-parametric approach

However, it's also possible to use a non-parametric approach to your problem, which means you do not assume any underlying distribution at all.

By using the so-called Empirical distribution function which equals: Fn(x)= SUM( I[X<=x] ) / n. So the proportion of values below x.

As was pointed out in one of the above answers is that what you're interested in is the inverse CDF (cumulative distribution function), which is equal to 1-F(x)

It can be shown that the empirical distribution function will converge to whatever 'true' CDF that generated your data.

Furthermore, it is straightforward to construct a 1-alpha confidence interval by:

L(X) = max{Fn(x)-en, 0}
U(X) = min{Fn(x)+en, 0}
en = sqrt( (1/2n)*log(2/alpha)

Then P( L(X) <= F(X) <= U(X) ) >= 1-alpha for all x.

I'm quite surprised that PierrOz answer has 0 votes, while it's a completely valid answer to the question using a non-parametric approach to estimating F(x).

Note that the issue you mention of P(X>=x)=0 for any x>47 is simply a personal preference that might lead you to chose the parametric approach above the non-parametric approach. Both approaches however are completely valid solutions to your problem.

For more details and proofs of the above statements I would recommend having a look at 'All of Statistics: A Concise Course in Statistical Inference by Larry A. Wasserman'. An excellent book on both parametric and non-parametric inference.

EDIT: Since you specifically asked for some python examples it can be done using numpy:

import numpy as np

def empirical_cdf(data, x):
    return np.sum(x<=data)/len(data)

def p_value(data, x):
    return 1-empirical_cdf(data, x)

# Generate some data for demonstration purposes
data = np.floor(np.random.uniform(low=0, high=48, size=30000))

print(empirical_cdf(data, 20))
print(p_value(data, 20)) # This is the value you're interested in

string comparison in batch file

While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.

Example:

@echo off
SetLocal

set Lhs="
set Rhs="

if "%Lhs%" == "%Rhs%" echo Equal

Error:

echo was unexpected at this time.

Solution:

Enable delayed expansion and use ! instead of %.

@echo off
SetLocal EnableDelayedExpansion

set Lhs="
set Rhs="

if !Lhs! == !Rhs! echo Equal

:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal

I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.

Test:

@echo off
SetLocal EnableDelayedExpansion

:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.

Django - makemigrations - No changes detected

First of all, make sure your app is registered in the Installed_app in the setting.py Then the above answer works perfectly fine

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I think it is the version error.

try installing this in following order:

  1. sudo apt-get install python3-mysqldb

  2. pip3 install mysqlclient

  3. python3 manage.py makemigrations

  4. python3 manage.py migrate

Hard reset of a single file

you can use the below command for reset of single file

git checkout HEAD -- path_to_file/file_name

List all changed files to get path_to_file/filename with below command

git status

CodeIgniter: Load controller within controller

With the following code you can load the controller classes and execute the methods.

This code was written for codeigniter 2.1

First add a new file MY_Loader.php in your application/core directory. Add the following code to your newly created MY_Loader.php file:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// written by AJ  [email protected]

class MY_Loader extends CI_Loader 
{
    protected $_my_controller_paths     = array();  

    protected $_my_controllers          = array();


    public function __construct()
    {
        parent::__construct();

        $this->_my_controller_paths = array(APPPATH);
    }

    public function controller($controller, $name = '', $db_conn = FALSE)
    {
        if (is_array($controller))
        {
            foreach ($controller as $babe)
            {
                $this->controller($babe);
            }
            return;
        }

        if ($controller == '')
        {
            return;
        }

        $path = '';

        // Is the controller in a sub-folder? If so, parse out the filename and path.
        if (($last_slash = strrpos($controller, '/')) !== FALSE)
        {
            // The path is in front of the last slash
            $path = substr($controller, 0, $last_slash + 1);

            // And the controller name behind it
            $controller = substr($controller, $last_slash + 1);
        }

        if ($name == '')
        {
            $name = $controller;
        }

        if (in_array($name, $this->_my_controllers, TRUE))
        {
            return;
        }

        $CI =& get_instance();
        if (isset($CI->$name))
        {
            show_error('The controller name you are loading is the name of a resource that is already being used: '.$name);
        }

        $controller = strtolower($controller);

        foreach ($this->_my_controller_paths as $mod_path)
        {
            if ( ! file_exists($mod_path.'controllers/'.$path.$controller.'.php'))
            {
                continue;
            }

            if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
            {
                if ($db_conn === TRUE)
                {
                    $db_conn = '';
                }

                $CI->load->database($db_conn, FALSE, TRUE);
            }

            if ( ! class_exists('CI_Controller'))
            {
                load_class('Controller', 'core');
            }

            require_once($mod_path.'controllers/'.$path.$controller.'.php');

            $controller = ucfirst($controller);

            $CI->$name = new $controller();

            $this->_my_controllers[] = $name;
            return;
        }

        // couldn't find the controller
        show_error('Unable to locate the controller you have specified: '.$controller);
    }

}

Now you can load all the controllers in your application/controllers directory. for example:

load the controller class Invoice and execute the function test()

$this->load->controller('invoice','invoice_controller');

$this->invoice_controller->test();

or when the class is within a dir

$this->load->controller('/dir/invoice','invoice_controller');

$this->invoice_controller->test();

It just works the same like loading a model

How do I set GIT_SSL_NO_VERIFY for specific repos only?

On Linux, if you call this inside the git repository folder:

git config http.sslVerify false

this will add sslVerify = false in the [http] section of the config file in the .git folder, which can also be the solution, if you want to add this manually with nano .git/config:

...
[http]
  sslVerify = false

Functional style of Java 8's Optional.ifPresent and if-not-Present?

In case you want store the value:

Pair.of<List<>, List<>> output = opt.map(details -> Pair.of(details.a, details.b))).orElseGet(() -> Pair.of(Collections.emptyList(), Collections.emptyList()));

Change background image opacity

You can also simply use this:

_x000D_
_x000D_
.bg_rgba {
  background: linear-gradient(0deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)), url('https://picsum.photos/200');
  width: 200px;
  height: 200px;
  border: 1px solid black;
}
_x000D_
<div class='bg_rgba'></div>
_x000D_
_x000D_
_x000D_

You can change the opacity of the color to your preference.

Clear History and Reload Page on Login/Logout Using Ionic Framework

I found that JimTheDev's answer only worked when the state definition had cache:false set. With the view cached, you can do $ionicHistory.clearCache() and then $state.go('app.fooDestinationView') if you're navigating from one state to the one that is cached but needs refreshing.

See my answer here as it requires a simple change to Ionic and I created a pull request: https://stackoverflow.com/a/30224972/756177

How do I get the total number of unique pairs of a set in the database?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA), you can calculate the summation of 1 + 2 + ... + (n-1) where n is the number of items in the set.

The reasoning is as follows, say you have 4 items:

A
B
C
D

The number of items that can be paired with A is 3, or n-1:

AB
AC
AD

It follows that the number of items that can be paired with B is n-2 (because B has already been paired with A):

BC
BD

and so on...

(n-1) + (n-2) + ... + (n-(n-1))

which is the same as

1 + 2 + ... + (n-1)

or

n(n-1)/2

How to print out a variable in makefile

You can print out variables as the makefile is read (assuming GNU make as you have tagged this question appropriately) using this method (with a variable named "var"):

$(info $$var is [${var}])

You can add this construct to any recipe to see what make will pass to the shell:

.PHONY: all
all: ; $(info $$var is [${var}])echo Hello world

Now, what happens here is that make stores the entire recipe ($(info $$var is [${var}])echo Hello world) as a single recursively expanded variable. When make decides to run the recipe (for instance when you tell it to build all), it expands the variable, and then passes each resulting line separately to the shell.

So, in painful detail:

  • It expands $(info $$var is [${var}])echo Hello world
  • To do this it first expands $(info $$var is [${var}])
    • $$ becomes literal $
    • ${var} becomes :-) (say)
    • The side effect is that $var is [:-)] appears on standard out
    • The expansion of the $(info...) though is empty
  • Make is left with echo Hello world
    • Make prints echo Hello world on stdout first to let you know what it's going to ask the shell to do
  • The shell prints Hello world on stdout.