Programs & Examples On #Emgucv

Emgu CV is a cross-platform .NET wrapper to the OpenCV image processing library. Allowing OpenCV functions to be called from .NET compatible languages such as C#, VB, C++-CLI, IronPython etc. The wrapper can be compiled in Mono and run on Linux or Mac OS X.

Fetch the row which has the Max value for a column

I think this should work?

Select
T1.UserId,
(Select Top 1 T2.Value From Table T2 Where T2.UserId = T1.UserId Order By Date Desc) As 'Value'
From
Table T1
Group By
T1.UserId
Order By
T1.UserId

How do you read CSS rule values with JavaScript?

I added return of object where attributes are parsed out style/values:

var getClassStyle = function(className){
    var x, sheets,classes;
    for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){
        classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;
        for(x=0;x<classes.length;x++) {
            if(classes[x].selectorText===className){
                classStyleTxt = (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText).match(/\{\s*([^{}]+)\s*\}/)[1];
                var classStyles = {};
                var styleSets = classStyleTxt.match(/([^;:]+:\s*[^;:]+\s*)/g);
                for(y=0;y<styleSets.length;y++){
                    var style = styleSets[y].match(/\s*([^:;]+):\s*([^;:]+)/);
                    if(style.length > 2)
                        classStyles[style[1]]=style[2];
                }
                return classStyles;
            }
        }
    }
    return false;
};

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

I got the same error but from a backend job (SSIS job). Upon checking the database's Log file growth setting, the log file was limited growth of 1GB. So what happened is when the job ran and it asked SQL server to allocate more log space, but the growth limit of the log declined caused the job to failed. I modified the log growth and set it to grow by 50MB and Unlimited Growth and the error went away.

Is there a "do ... until" in Python?

I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break statement:

finished = False
while not finished:
    ... do something...
    finished = evaluate_end_condition()

pthread function from a class

You can't do it the way you've written it because C++ class member functions have a hidden this parameter passed in. pthread_create() has no idea what value of this to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this parameter), or a plain ordinary function to bootstrap the class:

class C
{
public:
    void *hello(void)
    {
        std::cout << "Hello, world!" << std::endl;
        return 0;
    }

    static void *hello_helper(void *context)
    {
        return ((C *)context)->hello();
    }
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);

Can (domain name) subdomains have an underscore "_" in it?

Here my 2 cents from Java world:

From a Spark Scala console, with Java 8:

scala> new java.net.URI("spark://spark_master").getHost
res10: String = null

scala> new java.net.URI("spark://spark-master").getHost
res11: String = spark-master

scala> new java.net.URI("spark://spark_master.google.fr").getHost
res12: String = null

scala> new java.net.URI("spark://spark.master.google.fr").getHost
res13: String = spark.master.google.fr

scala> new java.net.URI("spark://spark-master.google.fr:3434").getHost
res14: String = spark-master.google.fr

scala> new java.net.URI("spark://spark-master.goo_gle.fr:3434").getHost
res15: String = null

It's definitely a bad idea ^^

In .NET, which loop runs faster, 'for' or 'foreach'?

    internal static void Test()
    {
        int LOOP_LENGTH = 10000000;
        Random random = new Random((int)DateTime.Now.ToFileTime());

        {
            Dictionary<int, int> dict = new Dictionary<int, int>();
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();
            for (int i = 0; i < 64; i++)
            {
                dict.Add(i, i);
            }

            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                for (int k = 0; k < dict.Count; k++)
                {
                    if (dict[k] > 1000000) Console.WriteLine("Test");
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($"Dictionary for T:{stopWatch.Elapsed.TotalSeconds}s\t M:{last_memory - first_memory}");

            GC.Collect();
        }


        {
            Dictionary<int, int> dict = new Dictionary<int, int>();
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();
            for (int i = 0; i < 64; i++)
            {
                dict.Add(i, i);
            }

            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                foreach (var item in dict)
                {
                    if (item.Value > 1000000) Console.WriteLine("Test");
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($"Dictionary foreach T:{stopWatch.Elapsed.TotalSeconds}s\t M:{last_memory - first_memory}");

            GC.Collect();
        }

        {
            Dictionary<int, int> dict = new Dictionary<int, int>();
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();
            for (int i = 0; i < 64; i++)
            {
                dict.Add(i, i);
            }

            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                foreach (var item in dict.Values)
                {
                    if (item > 1000000) Console.WriteLine("Test");
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($"Dictionary foreach values T:{stopWatch.Elapsed.TotalSeconds}s\t M:{last_memory - first_memory}");

            GC.Collect();
        }


        {
            List<int> dict = new List<int>();
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();
            for (int i = 0; i < 64; i++)
            {
                dict.Add(i);
            }

            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                for (int k = 0; k < dict.Count; k++)
                {
                    if (dict[k] > 1000000) Console.WriteLine("Test");
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($"list for T:{stopWatch.Elapsed.TotalSeconds}s\t M:{last_memory - first_memory}");

            GC.Collect();
        }


        {
            List<int> dict = new List<int>();
            long first_memory = GC.GetTotalMemory(true);
            var stopWatch = Stopwatch.StartNew();
            for (int i = 0; i < 64; i++)
            {
                dict.Add(i);
            }

            for (int i = 0; i < LOOP_LENGTH; i++)
            {
                foreach (var item in dict)
                {
                    if (item > 1000000) Console.WriteLine("Test");
                }
            }
            stopWatch.Stop();
            var last_memory = GC.GetTotalMemory(true);
            Console.WriteLine($"list foreach T:{stopWatch.Elapsed.TotalSeconds}s\t M:{last_memory - first_memory}");

            GC.Collect();
        }
    }

Dictionary for T:10.1957728s M:2080
Dictionary foreach T:10.5900586s M:1952
Dictionary foreach values T:3.8294776s M:2088
list for T:3.7981471s M:320
list foreach T:4.4861377s M:648

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How to remove all white space from the beginning or end of a string?

use the String.Trim() function.

string foo = "   hello ";
string bar = foo.Trim();

Console.WriteLine(bar); // writes "hello"

How to get a reversed list view on a list in Java?

Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won't have to copy the list. Then just use Collections.

Ergo,

Collections.reverse(list.clone());

If you are using a List and don't have access to clone() you can use subList():

List<?> shallowCopy = list.subList(0, list.size());
Collections.reverse(shallowCopy);

Laravel - Session store not set on request

If Cas Bloem's answer does not apply (i.e. you've definitely got the web middleware on the applicable route), you might want to check the order of middlewares in your HTTP Kernel.

The default order in Kernel.php is this:

$middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];

Note that VerifyCsrfToken comes after StartSession. If you've got these in a different order, the dependency between them can also lead to the Session store not set on request. exception.

C++: Rounding up to the nearest multiple of a number

For negative numToRound:

It should be really easy to do this but the standard modulo % operator doesn't handle negative numbers like one might expect. For instance -14 % 12 = -2 and not 10. First thing to do is to get modulo operator that never returns negative numbers. Then roundUp is really simple.

public static int mod(int x, int n) 
{
    return ((x % n) + n) % n;
}

public static int roundUp(int numToRound, int multiple) 
{
    return numRound + mod(-numToRound, multiple);
}

Python urllib2, basic HTTP authentication, and tr.im

Same solutions as Python urllib2 Basic Auth Problem apply.

see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler to add the Authorization header to each request that matches the known url.

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

JavaScript equivalent of PHP’s die

You can only break a block scope if you label it. For example:

myBlock: {
  var a = 0;
  break myBlock;
  a = 1; // this is never run
};
a === 0;

You cannot break a block scope from within a function in the scope. This means you can't do stuff like:

foo: { // this doesn't work
  (function() {
    break foo;
  }());
}

You can do something similar though with functions:

function myFunction() {myFunction:{
  // you can now use break myFunction; instead of return;
}}

How to easily map c++ enums to strings

I just wanted to show this possible elegant solution using macros. This doesn t solve the problem but I think it is a good way to rethik about the problem.

#define MY_LIST(X) X(value1), X(value2), X(value3)

enum eMyEnum
    {
    MY_LIST(PLAIN)
    };

const char *szMyEnum[] =
    {
    MY_LIST(STRINGY)
    };


int main(int argc, char *argv[])
{

std::cout << szMyEnum[value1] << value1 <<" " <<  szMyEnum[value2] << value2 << std::endl;

return 0;
}

---- EDIT ----

After some internet research and some own experements I came to the following solution:

//this is the enum definition
#define COLOR_LIST(X) \
  X( RED    ,=21)      \
  X( GREEN  )      \
  X( BLUE   )      \
  X( PURPLE , =242)      \
  X( ORANGE )      \
  X( YELLOW )

//these are the macros
#define enumfunc(enums,value) enums,
#define enumfunc2(enums,value) enums value,
#define ENUM2SWITCHCASE(enums) case(enums): return #enums;

#define AUTOENUM(enumname,listname) enum enumname{listname(enumfunc2)};
#define ENUM2STRTABLE(funname,listname) char* funname(int val) {switch(val) {listname(ENUM2SWITCHCASE) default: return "undef";}}
#define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int values[] = {listname(enumfunc)};int N = sizeof(values)/sizeof(int);ENUM2STRTABLE(enum2str,listname)};

//here the enum and the string enum map table are generated
AUTOENUM(testenum,COLOR_LIST)
ENUM2STRTABLE(testfunenum,COLOR_LIST)
ENUM2STRUCTINFO(colorinfo,COLOR_LIST)//colorinfo structur {int values[]; int N; char * enum2str(int);}

//debug macros
#define str(a) #a
#define xstr(a) str(a)


int main( int argc, char** argv )
{
testenum x = YELLOW;
std::cout << testfunenum(GREEN) << "   " << testfunenum(PURPLE) << PURPLE << "  " << testfunenum(x);

for (int i=0;i< colorinfo::N;i++)
std::cout << std::endl << colorinfo::values[i] <<  "  "<< colorinfo::enum2str(colorinfo::values[i]);

  return EXIT_SUCCESS;
}

I just wanted to post it maybe someone could find this solution useful. There is no need of templates classes no need of c++11 and no need of boost so this could also be used for simple C.

---- EDIT2 ----

the information table can produce some problems when using more than 2 enums (compiler problem). The following workaround worked:

#define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int spacename##_##values[] = {listname(enumfunc)};int spacename##_##N = sizeof(spacename##_##values)/sizeof(int);ENUM2STRTABLE(spacename##_##enum2str,listname)};

What is SuppressWarnings ("unchecked") in Java?

Simply: It's a warning by which the compiler indicates that it cannot ensure type safety.

JPA service method for example:

@SuppressWarnings("unchecked")
public List<User> findAllUsers(){
    Query query = entitymanager.createQuery("SELECT u FROM User u");
    return (List<User>)query.getResultList();
}

If I didn'n anotate the @SuppressWarnings("unchecked") here, it would have a problem with line, where I want to return my ResultList.

In shortcut type-safety means: A program is considered type-safe if it compiles without errors and warnings and does not raise any unexpected ClassCastException s at runtime.

I build on http://www.angelikalanger.com/GenericsFAQ/FAQSections/Fundamentals.html

Prevent linebreak after </div>

display:inline;

OR

float:left;

OR

display:inline-block; -- Might not work on all browsers.

What is the purpose of using a div here? I'd suggest a span, as it is an inline-level element, whereas a div is a block-level element.


Do note that each option above will work differently.

display:inline; will turn the div into the equivalent of a span. It will be unaffected by margin-top, margin-bottom, padding-top, padding-bottom, height, etc.

float:left; keeps the div as a block-level element. It will still take up space as if it were a block, however the width will be fitted to the content (assuming width:auto;). It can require a clear:left; for certain effects.

display:inline-block; is the "best of both worlds" option. The div is treated as a block element. It responds to all of the margin, padding, and height rules as expected for a block element. However, it is treated as an inline element for the purpose of placement within other elements.

Read this for more information.

Why do I get permission denied when I try use "make" to install something?

The problem is frequently with 'secure' setup of mountpoints, such as /tmp

If they are mounted noexec (check with cat /etc/mtab and or sudo mount) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.

E.g. to remount temporarily:

 sudo mount -o remount,exec /tmp

Or to change permanently, remove noexec in /etc/fstab

How to change text color of simple list item

Another simplest way is to create a layout file containing the textview you want with textSize, textStyle, color etc preferred by you and then use it with the ArrayAdapter.

e.g. mytextview.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv"
    android:textColor="@color/font_content"
    android:padding="5sp"
    android:layout_width="fill_parent"
    android:background="@drawable/rectgrad"
    android:singleLine="true"
    android:gravity="center"
    android:layout_height="fill_parent"/>

and then use it with your ArrayAdapter as usual like

ListView lst = new ListView(context);
String[] arr = {"Item 1","Item 2"};
ArrayAdapter<String> ad = new ArrayAdapter<String>(context,R.layout.mytextview,arr);
lst.setAdapter(ad);

This way you won't need to create a custom adapter for it.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.

Filename too long in Git for Windows

Steps to follow (Windows):

  1. Run Git Bash as administrator
  2. Run the following command:
git config --system core.longpaths true

Note: if step 2 does not work or gives any error, you can also try running this command:

git config --global core.longpaths true

Read more about git config here.

Regex empty string or email

I prefer /^\s+$|^$/gi to match empty and empty spaces.

_x000D_
_x000D_
console.log("  ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
_x000D_
_x000D_

How do I change a single value in a data.frame?

Suppose your dataframe is df and you want to change gender from 2 to 1 in participant id 5 then you should determine the row by writing "==" as you can see

 df["rowName", "columnName"] <- value
 df[df$serial.id==5, "gender"] <- 1

Can I set max_retries for requests.request?

Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.

You can do this instead:

import requests
from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://www.github.com', HTTPAdapter(max_retries=5))

How to publish a website made by Node.js to Github Pages?

GitHub pages host only static HTML pages. No server side technology is supported, so Node.js applications won't run on GitHub pages. There are lots of hosting providers, as listed on the Node.js wiki.

App fog seems to be the most economical as it provides free hosting for projects with 2GB of RAM (which is pretty good if you ask me).
As stated here, AppFog removed their free plan for new users.

If you want to host static pages on GitHub, then read this guide. If you plan on using Jekyll, then this guide will be very helpful.

If file exists then delete the file

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

Remove Last Comma from a string

The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.

EDIT: Is it really that confusing?

'This, is a random string'

Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.

Prefer composition over inheritance?

This rule is a complete nonsense. Why?

The reason is that in every case it is possible to tell whether to use composition or inheritance. This is determined by the answer to a question: "IS something A something else" or "HAS something A something else".

You cannot "prefer" to make something to be something else or to have something else. Strict logical rules apply.

Also there are no "contrived examples" because in every situation an answer to this question can be given.

If you cannot answer this question there is something else wrong. This includes overlapping responsibilities of classess which are usually the result of wrong use of interfaces, less often by rewriting same code in different classess.

To avoid this situations I also recommend to use good names for classes , that fully resemble their responsibilities.

How to convert char* to wchar_t*?

Use a std::wstring instead of a C99 variable length array. The current standard guarantees a contiguous buffer for std::basic_string. E.g.,

std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );

C++ does not support C99 variable length arrays, and so if you compiled your code as pure C++, it would not even compile.

With that change your function return type should also be std::wstring.

Remember to set relevant locale in main.

E.g., setlocale( LC_ALL, "" ).

Cheers & hth.,

SVN remains in conflict?

Ok here's how to fix it:

svn remove --force filename
svn resolve --accept=working  filename
svn commit

more details are at: http://svnbook.red-bean.com/en/1.8/svn.tour.treeconflicts.html

How to print all information from an HTTP request to the screen, in PHP

If you want actual HTTP Headers (both request and response), give hurl.it a try.

You can use the PHP command apache_request_headers() to get the request headers and apache_response_headers() to get the current response headers. Note that response can be changed later in the PHP script as long as content has not been served.

How do you express binary literals in Python?

Another good method to get an integer representation from binary is to use eval()

Like so:

def getInt(binNum = 0):
    return eval(eval('0b' + str(n)))

I guess this is a way to do it too. I hope this is a satisfactory answer :D

How to submit a form on enter when the textarea has focus?

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

Join String list elements with a delimiter in one step

If you are using Spring you can use StringUtils.join() method which also allows you to specify prefix and suffix.

String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
                "\n", "<value>", "</value>");

Find the 2nd largest element in an array with minimum number of comparisons

A good way with O(1) time complexity would be to use a max-heap. Call the heapify twice and you have the answer.

Get file size before uploading

Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.

ActiveX warning

If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).

function getFileSize(fileInputElement){
    if (!fileInputElement.value ||
        typeof fileInputElement.files === 'undefined' ||
        typeof fileInputElement.files[0] === 'undefined' ||
        typeof fileInputElement.files[0].size !== 'number'
    ) {
        // File size is undefined.
        return undefined;
    }

    return fileInputElement.files[0].size;
}

What is event bubbling and capturing?

There's also the Event.eventPhase property which can tell you if the event is at target or comes from somewhere else, and it is fully supported by browsers.

Expanding on the already great snippet from the accepted answer, this is the output using the eventPhase property

_x000D_
_x000D_
var logElement = document.getElementById('log');

function log(msg) {
  if (logElement.innerHTML == "<p>No logs</p>")
    logElement.innerHTML = "";
  logElement.innerHTML += ('<p>' + msg + '</p>');
}

function humanizeEvent(eventPhase){
  switch(eventPhase){
    case 1: //Event.CAPTURING_PHASE
      return "Event is being propagated through the target's ancestor objects";
    case 2: //Event.AT_TARGET
      return "The event has arrived at the event's target";
    case 3: //Event.BUBBLING_PHASE
      return "The event is propagating back up through the target's ancestors in reverse order";
  }
}
function capture(e) {
  log('capture: ' + this.firstChild.nodeValue.trim() + "; " + 
  humanizeEvent(e.eventPhase));
}

function bubble(e) {
  log('bubble: ' + this.firstChild.nodeValue.trim() + "; " + 
  humanizeEvent(e.eventPhase));
}

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', capture, true);
  divs[i].addEventListener('click', bubble, false);
}
_x000D_
p {
  line-height: 0;
}

div {
  display:inline-block;
  padding: 5px;

  background: #fff;
  border: 1px solid #aaa;
  cursor: pointer;
}

div:hover {
  border: 1px solid #faa;
  background: #fdd;
}
_x000D_
<div>1
  <div>2
    <div>3
      <div>4
        <div>5</div>
      </div>
    </div>
  </div>
</div>
<button onclick="document.getElementById('log').innerHTML = '<p>No logs</p>';">Clear logs</button>
<section id="log"></section>
_x000D_
_x000D_
_x000D_

Ansible - read inventory hosts and variables to group_vars/all file

Just in case if the problem is still there, You can refer to ansible inventory through ‘hostvars’, ‘group_names’, and ‘groups’ ansible variables.

Example:

To be able to get ip addresses of all servers within group "mygroup", use the below construction:

- debug: msg="{{ hostvars[item]['ansible_eth0']['ipv4']['address'] }}" 
  with_items:
     - "{{ groups['mygroup'] }}"

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Type Checking: typeof, GetType, or is?

Performance test typeof() vs GetType():

using System;
namespace ConsoleApplication1
    {
    class Program
    {
        enum TestEnum { E1, E2, E3 }
        static void Main(string[] args)
        {
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test1(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test2(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            Console.ReadLine();
        }
        static Type Test1<T>(T value) => typeof(T);
        static Type Test2(object value) => value.GetType();
    }
}

Results in debug mode:

00:00:08.4096636
00:00:10.8570657

Results in release mode:

00:00:02.3799048
00:00:07.1797128

Using Java with Microsoft Visual Studio 2012

theoretically it could be done by defining a custom build step to the VS project. And you can make a file template to create a new java file, don't know if you could have it throw things in the right package or not, so you may end up writing quite a bit of the stuff a java ide would throw in already. it's not impossible, but from experience (I've used xcode on mac, vs in windows, eclipse, netbeans, code::blocks, and ended up compiling from command line for both java and c++ a lot) it's easier just to learn the new ide.

if you are insistent, i found this: http://improve.dk/compiling-java-in-visual-studio/

i plan on following and trying to modify it to create a general template for java

if possible (meaning if i understand enough of what im doing) im goint to implement a custom wizard for java projects and files.

Convert string to int array using LINQ

s1.Split(';').Select(s => Convert.ToInt32(s)).ToArray();

Untested and off the top of my head...testing now for correct syntax.

Tested and everything looks good.

Access files stored on Amazon S3 through web browser

I found this related question: Directory Listing in S3 Static Website

As it turns out, if you enable public read for the whole bucket, S3 can serve directory listings. Problem is they are in XML instead of HTML, so not very user-friendly.

There are three ways you could go for generating listings:

  • Generate index.html files for each directory on your own computer, upload them to s3, and update them whenever you add new files to a directory. Very low-tech. Since you're saying you're uploading build files straight from Travis, this may not be that practical since it would require doing extra work there.

  • Use a client-side S3 browser tool.

  • Use a server-side browser tool.

    • s3browser (PHP)
    • s3index Scala. Going by the existence of a Procfile, it may be readily deployable to Heroku. Not sure since I don't have any experience with Scala.

Landscape printing from HTML

My solution:

<style type="text/css" media="print">
    @page { 
        size: landscape;
    }
    body { 
        writing-mode: tb-rl;
    }
</style>

This works in IE, Firefox and Chrome

Strip last two characters of a column in MySQL

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
     , /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
     , /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
     , TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt

How to print pthread_t

You could try converting it to an unsigned short and then print just the last four hex digits. The resulting value might be unique enough for your needs.

Why is the <center> tag deprecated in HTML?

The <center> element was deprecated because it defines the presentation of its contents — it does not describe its contents.

One method of centering is to set the margin-left and margin-right properties of the element to auto, and then set the parent element’s text-align property to center. This guarantees that the element will be centered in all modern browsers.

Executing JavaScript without a browser?

I found this related question on the topic, but if you want direct links, here they are:

  • You can install Rhino as others have pointed out. This post shows an easy way to get it up and running and how to alias a command to invoke it easily
  • If you're on a Mac, you can use JavaScriptCore, which invokes WebKit's JavaScript engine. Here's a post on it
  • You can use Chome/Google's V8 interpreter as well. Here are instructions
  • The JavaScript as OSA is interesting because it lets you (AFAIK) interact with scriptable OS X apps as though you were in AppleScript (without the terrible syntax)

I'm surprised node.js doesn't come with a shell, but I guess it's really more like an epoll/selector-based callback/event-oriented webserver, so perhaps it doesn't need the full JS feature set, but I'm not too familiar with its inner workings.

Since you seem interested in node.js and since it's based on V8, it might be best to follow those instructions on getting a V8 environment set up so you can have a consistent basis for your JavaScript programming (I should hope JSC and V8 are mostly the same, but I'm not sure).

Closing a file after File.Create

File.Create(string) returns an instance of the FileStream class. You can call the Stream.Close() method on this object in order to close it and release resources that it's using:

var myFile = File.Create(myPath);
myFile.Close();

However, since FileStream implements IDisposable, you can take advantage of the using statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:

using (var myFile = File.Create(myPath))
{
   // interact with myFile here, it will be disposed automatically
}

linux script to kill java process

Use jps to list running java processes. The command returns the process id along with the main class. You can use kill command to kill the process with the returned id or use following one liner script.

kill $(jps | grep <MainClass> | awk '{print $1}')

MainClass is a class in your running java program which contains the main method.

How to get the Full file path from URI

one of the answers that exist on the current page (this), is correct but it has some mistakes. for example, it won't work on devices with API 29+. I'll update the above code and post its new version. I think this post should be marked as the final answer.

Updated code: (Added WhatsApp support)

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    private static Uri contentUri = null;

    Context context;

    public FileUtils( Context context) {
        this.context=context;
    }

    @SuppressLint("NewApi")
    public static String getPath( final Uri uri) {
        // check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        String selection = null;
        String[] selectionArgs = null;
        // DocumentProvider
        if (isKitKat ) {
            // ExternalStorageProvider

           if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                String fullPath = getPathFromExtSD(split);
                if (fullPath != "") {
                    return fullPath;
                } else {
                    return null;
                }
            }


            // DownloadsProvider

            if (isDownloadsDocument(uri)) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    final String id;
                    Cursor cursor = null;
                    try {
                        cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
                        if (cursor != null && cursor.moveToFirst()) {
                            String fileName = cursor.getString(0);
                            String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
                            if (!TextUtils.isEmpty(path)) {
                                return path;
                            }
                        }
                    }
                    finally {
                        if (cursor != null)
                            cursor.close();
                    }
                    id = DocumentsContract.getDocumentId(uri);
                    if (!TextUtils.isEmpty(id)) {
                        if (id.startsWith("raw:")) {
                            return id.replaceFirst("raw:", "");
                        }
                        String[] contentUriPrefixesToTry = new String[]{
                                "content://downloads/public_downloads",
                                "content://downloads/my_downloads"
                        };
                        for (String contentUriPrefix : contentUriPrefixesToTry) {
                            try {
                                final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));


                                return getDataColumn(context, contentUri, null, null);
                            } catch (NumberFormatException e) {
                                //In Android 8 and Android P the id is not a number
                                return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
                            }
                        }


                    }
                }
                else {
                    final String id = DocumentsContract.getDocumentId(uri);

                    if (id.startsWith("raw:")) {
                        return id.replaceFirst("raw:", "");
                    }
                    try {
                        contentUri = ContentUris.withAppendedId(
                                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    }
                    catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    if (contentUri != null) {

                        return getDataColumn(context, contentUri, null, null);
                    }
                }
            }


            // MediaProvider
           if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;

                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{split[1]};


                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }

           if (isGoogleDriveUri(uri)) {
                return getDriveFilePath(uri);
            }

           if(isWhatsAppFile(uri)){
                return getFilePathForWhatsApp(uri);
            }


           if ("content".equalsIgnoreCase(uri.getScheme())) {

                if (isGooglePhotosUri(uri)) {
                    return uri.getLastPathSegment();
                }
                if (isGoogleDriveUri(uri)) {
                    return getDriveFilePath(uri);
                }
                if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
                {

                    // return getFilePathFromURI(context,uri);
                    return copyFileToInternalStorage(uri,"userfiles");
                    // return getRealPathFromURI(context,uri);
                }
                else
                {
                    return getDataColumn(context, uri, null, null);
                }

           }
           if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
        }
        else {

            if(isWhatsAppFile(uri)){
                return getFilePathForWhatsApp(uri);
            }

            if ("content".equalsIgnoreCase(uri.getScheme())) {
                String[] projection = {
                        MediaStore.Images.Media.DATA
                };
                Cursor cursor = null;
                try {
                    cursor = context.getContentResolver()
                            .query(uri, projection, selection, selectionArgs, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    if (cursor.moveToFirst()) {
                        return cursor.getString(column_index);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }




        return null;
    }

    private  boolean fileExists(String filePath) {
        File file = new File(filePath);

        return file.exists();
    }

    private String getPathFromExtSD(String[] pathData) {
        final String type = pathData[0];
        final String relativePath = "/" + pathData[1];
        String fullPath = "";

        // on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
        // something like "71F8-2C0A", some kind of unique id per storage
        // don't know any API that can get the root path of that storage based on its id.
        //
        // so no "primary" type, but let the check here for other devices
        if ("primary".equalsIgnoreCase(type)) {
            fullPath = Environment.getExternalStorageDirectory() + relativePath;
            if (fileExists(fullPath)) {
                return fullPath;
            }
        }

        // Environment.isExternalStorageRemovable() is `true` for external and internal storage
        // so we cannot relay on it.
        //
        // instead, for each possible path, check if file exists
        // we'll start with secondary storage as this could be our (physically) removable sd card
        fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
        if (fileExists(fullPath)) {
            return fullPath;
        }

        fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
        if (fileExists(fullPath)) {
            return fullPath;
        }

        return fullPath;
    }

    private String getDriveFilePath(Uri uri) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getCacheDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
            Log.e("File Size", "Size " + file.length());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
        return file.getPath();
    }

    /***
     * Used for Android Q+
     * @param uri
     * @param newDirName if you want to create a directory, you can set this variable
     * @return
     */
    private String copyFileToInternalStorage(Uri uri,String newDirName) {
        Uri returnUri = uri;

        Cursor returnCursor = context.getContentResolver().query(returnUri, new String[]{
                OpenableColumns.DISPLAY_NAME,OpenableColumns.SIZE
        }, null, null, null);


        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));

        File output;
        if(!newDirName.equals("")) {
            File dir = new File(context.getFilesDir() + "/" + newDirName);
            if (!dir.exists()) {
                dir.mkdir();
            }
            output = new File(context.getFilesDir() + "/" + newDirName + "/" + name);
        }
        else{
            output = new File(context.getFilesDir() + "/" + name);
        }
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(output);
            int read = 0;
            int bufferSize = 1024;
            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }

            inputStream.close();
            outputStream.close();

        }
        catch (Exception e) {

            Log.e("Exception", e.getMessage());
        }

        return output.getPath();
    }

    private String getFilePathForWhatsApp(Uri uri){
            return  copyFileToInternalStorage(uri,"whatsapp");
    }

    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);

            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        }
        finally {
            if (cursor != null)
                cursor.close();
        }

        return null;
    }

    private  boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private  boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private  boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private  boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public boolean isWhatsAppFile(Uri uri){
        return "com.whatsapp.provider.media".equals(uri.getAuthority());
    }

    private  boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
    }


}

jQuery: get the file name selected from <input type="file" />

//get file input
var $el = $('input[type=file]');
//set the next siblings (the span) text to the input value 
$el.next().text( $el.val() );

How to create EditText accepts Alphabets only in android?

edittext.setFilters(new InputFilter[] {
    new InputFilter() {
        public CharSequence filter(CharSequence src, int start,
                int end, Spanned dst, int dstart, int dend) {
            if(src.equals("")){ // for backspace
                return src;
            }
            if(src.toString().matches("[a-zA-Z ]+")){
                return src;
            }
            return edittext.getText().toString();
        }
    }
});

please test thoroughly though !

Concatenate multiple files but include filename as section headers

When there is more than one input file, the more command concatenates them and also includes each filename as a header.

To concatenate to a file:

more *.txt > out.txt

To concatenate to the terminal:

more *.txt | cat

Example output:

::::::::::::::
file1.txt
::::::::::::::
This is
my first file.
::::::::::::::
file2.txt
::::::::::::::
And this is my
second file.

How to set password for Redis?

i couldnt find though what i should add exactly to the configuration file to set up the password.

Configuration file should be located at /etc/redis/redis.conf and password can be set up in SECURITY section which should be located between REPLICATION and LIMITS section. Password setup is done using the requirepass directive. For more information try to look at AUTH command description.

How to check string length with JavaScript

<html>
<head></head>
<title></title>
<script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<body>
Type here:<input type="text" id="inputbox" value="type here"/>
<br>
Length:<input type="text" id="length"/>
<script type='text/javascript'>
    $(window).keydown(function (e) {
    //use e.which
    var length = 0;
    if($('#inputbox').val().toString().trim().length > 0)
    {
        length = $('#inputbox').val().toString().trim().length;
    }

    $('#length').val(length.toString());
  })
</script>
</body>
</html>

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

How do I format a date with Dart?

You can use the intl package (installer) to format dates.

For en_US formats, it's quite simple:

import 'package:intl/intl.dart';

main() {
  final DateTime now = DateTime.now();
  final DateFormat formatter = DateFormat('yyyy-MM-dd');
  final String formatted = formatter.format(now);
  print(formatted); // something like 2013-04-20
}

There are many options for formatting. From the docs:

ICU Name                   Skeleton
--------                   --------
DAY                          d
ABBR_WEEKDAY                 E
WEEKDAY                      EEEE
ABBR_STANDALONE_MONTH        LLL
STANDALONE_MONTH             LLLL
NUM_MONTH                    M
NUM_MONTH_DAY                Md
NUM_MONTH_WEEKDAY_DAY        MEd
ABBR_MONTH                   MMM
ABBR_MONTH_DAY               MMMd
ABBR_MONTH_WEEKDAY_DAY       MMMEd
MONTH                        MMMM
MONTH_DAY                    MMMMd
MONTH_WEEKDAY_DAY            MMMMEEEEd
ABBR_QUARTER                 QQQ
QUARTER                      QQQQ
YEAR                         y
YEAR_NUM_MONTH               yM
YEAR_NUM_MONTH_DAY           yMd
YEAR_NUM_MONTH_WEEKDAY_DAY   yMEd
YEAR_ABBR_MONTH              yMMM
YEAR_ABBR_MONTH_DAY          yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY  yMMMEd
YEAR_MONTH                   yMMMM
YEAR_MONTH_DAY               yMMMMd
YEAR_MONTH_WEEKDAY_DAY       yMMMMEEEEd
YEAR_ABBR_QUARTER            yQQQ
YEAR_QUARTER                 yQQQQ
HOUR24                       H
HOUR24_MINUTE                Hm
HOUR24_MINUTE_SECOND         Hms
HOUR                         j
HOUR_MINUTE                  jm
HOUR_MINUTE_SECOND           jms
HOUR_MINUTE_GENERIC_TZ       jmv
HOUR_MINUTE_TZ               jmz
HOUR_GENERIC_TZ              jv
HOUR_TZ                      jz
MINUTE                       m
MINUTE_SECOND                ms
SECOND                       s

For non-en_US dates, you need to explicitly load in the locale. See the DateFormat docs for more info. The date_symbol_data_local.dart contains all of the formats for each country/language, if you would like a more in-depth look.

How to replace a character by a newline in Vim

You need to use:

:%s/,/^M/g

To get the ^M character, press Ctrl + v followed by Enter.

How to get an Instagram Access Token

Almost all of the replies that people have posted so far only cover how to handle access tokens on the front end, following Instagram's client-side "implicit authentication" procedure. This method is less secure and unrecommended according to Instagram's API docs.

Assuming you are using a server, the Instagram docs sort of fail in providing a clear answer about exchanging a code for a token, as they only give an example of a cURL request. Essentially you have to make a POST request to their server with the provided code and all of your app's information, and they will return a user object including user information and the token.

I don't know what language you are writing in, but I solved this in Node.js with the request npm module which you can find here.

I parsed through the url and used this information to send the post request

var code = req.url.split('code=')[1];

request.post(
  { form: { client_id: configAuth.instagramAuth.clientID,
            client_secret: configAuth.instagramAuth.clientSecret,
            grant_type: 'authorization_code',
            redirect_uri: configAuth.instagramAuth.callbackURL,
            code: code
          },
    url: 'https://api.instagram.com/oauth/access_token'
  },
  function (err, response, body) {
    if (err) {
      console.log("error in Post", err)
    }else{
      console.log(JSON.parse(body))
    }
  }
);

Of course replace the configAuth stuff with your own information. You probably aren't using Node.js, but hopefully this solution will help you translate your own solution into whatever language you are using it in.

When to favor ng-if vs. ng-show/ng-hide?

From my experience:

1) If your page has a toggle that uses ng-if/ng-show to show/hide something, ng-if causes more of a browser delay (slower). For example: if you have a button used to toggle between two views, ng-show seems to be faster.

2) ng-if will create/destroy scope when it evaluates to true/false. If you have a controller attached to the ng-if, that controller code will get executed every time the ng-if evaluates to true. If you are using ng-show, the controller code only gets executed once. So if you have a button that toggles between multiple views, using ng-if and ng-show would make a huge difference in how you write your controller code.

The APK file does not exist on disk

Click this option to solve the error:

Run: View > Tool Windows > Gradle > [project] > Tasks > build > build

Prevent flex items from overflowing a container

max-width works for me.

aside {
  flex: 0 1 200px;
  max-width: 200px;
}

Variables of CSS pre-processors allows to avoid hard-coding.

aside {
  $WIDTH: 200px;
  flex: 0 1 $WIDTH;
  max-width: $WIDTH;
}

overflow: hidden also works, but I lately I try do not use it because it hides the elements as popups and dropdowns.

Return from a promise then()

Promises don't "return" values, they pass them to a callback (which you supply with .then()).

It's probably trying to say that you're supposed to do resolve(someObject); inside the promise implementation.

Then in your then code you can reference someObject to do what you want.

AngularJS open modal on button click

Set Jquery in scope

$scope.$ = $;

and call in html

ng-click="$('#novoModelo').modal('show')"

getting file size in javascript

You could probably try this to get file sizes in kB and MB Until the file size in bytes would be upto 7 digits, the outcome would be in kbs. 7 seems to be the magic number here. After which, if the bytes would have 7 to 10 digits, we would have to divide it by 10**3(n) where n is the appending action . This pattern would repeat for every 3 digits added.

let fileSize = myInp.files[0].size.toString();

if(fileSize.length < 7) return `${Math.round(+fileSize/1024).toFixed(2)}kb`
    return `${(Math.round(+fileSize/1024)/1000).toFixed(2)}MB`

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

How to allow access outside localhost

Using ng serve --host 0.0.0.0 will allow you to connect to the ng serve using your ip instead of localhost.

EDIT

In newer versions of the cli, you have to provide your local ip address instead

EDIT 2

In newer versions of the cli (I think v5 and up) you can use 0.0.0.0 as the ip again to host it for anyone on your network to talk to.

Use of document.getElementById in JavaScript

It is just a selector that helps you select specific tag <p id = 'demo'></p> elements which help you change the behavior, in any event (either mouse or keyboard).

How to prevent a dialog from closing when a button is clicked

If you are using material design I would suggest checking out material-dialogs. It fixed several issues for me related to currently open Android bugs (see 78088), but most importantly for this ticket it has an autoDismiss flag that can be set when using the Builder.

How Stuff and 'For Xml Path' work in SQL Server?

Declare @Temp As Table (Id Int,Name Varchar(100))
Insert Into @Temp values(1,'A'),(1,'B'),(1,'C'),(2,'D'),(2,'E'),(3,'F'),(3,'G'),(3,'H'),(4,'I'),(5,'J'),(5,'K')
Select X.ID,
stuff((Select ','+ Z.Name from @Temp Z Where X.Id =Z.Id For XML Path('')),1,1,'')
from @Temp X
Group by X.ID

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

How to run an external program, e.g. notepad, using hyperlink?

Make a batch file and call the bacth file in Window.open. Here how it works

  1. make a file in notepad
  2. write your script : start wmplayer "\dotnet\sc\1234.mp4" /fullscreen
  3. save as : test.bat in \dotnet\sc\test.bat

in html

window.open('file://dotnet/sc/test.bat')

Enjoy..

Name node is in safe mode. Not able to leave

try this, it will work

sudo -u hdfs hdfs dfsadmin -safemode leave

Determining if Swift dictionary contains key and obtaining any of its values

Why not simply check for dict.keys.contains(key)? Checking for dict[key] != nil will not work in cases where the value is nil. As with a dictionary [String: String?] for example.

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

Hibernate Error executing DDL via JDBC Statement

Dialects are removed in recent SQL so use

  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>

What linux shell command returns a part of a string?

In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :

${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}

Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):

${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}

And of course, the much useful expansions that operate on whether the parameter is null:

${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}

They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being $(command substitution) combined with sed or any other external filter). But, they are so easily found by typing man bash that I don't feel it merits to further extend this post.

How to debug an apache virtual host configuration?

Syntax check

To check configuration files for syntax errors:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -t

# Debian-based (Ubuntu)
apache2ctl -t

# MacOS
apachectl -t

List virtual hosts

To list all virtual hosts, and their locations:

# Red Hat-based (Fedora, CentOS) and OSX
httpd -S

# Debian-based (Ubuntu)
apache2ctl -S

# MacOS
apachectl -S

How do I find out which keystore was used to sign an app?

Much easier way to view the signing certificate:

jarsigner.exe -verbose -verify -certs myapk.apk

This will only show the DN, so if you have two certs with the same DN, you might have to compare by fingerprint.

How to get datetime in JavaScript?

If the format is "fixed" meaning you don't have to use other format you can have pure JavaScript instead of using whole library to format the date:

_x000D_
_x000D_
//Pad given value to the left with "0"_x000D_
function AddZero(num) {_x000D_
    return (num >= 0 && num < 10) ? "0" + num : num + "";_x000D_
}_x000D_
_x000D_
window.onload = function() {_x000D_
    var now = new Date();_x000D_
    var strDateTime = [[AddZero(now.getDate()), _x000D_
        AddZero(now.getMonth() + 1), _x000D_
        now.getFullYear()].join("/"), _x000D_
        [AddZero(now.getHours()), _x000D_
        AddZero(now.getMinutes())].join(":"), _x000D_
        now.getHours() >= 12 ? "PM" : "AM"].join(" ");_x000D_
    document.getElementById("Console").innerHTML = "Now: " + strDateTime;_x000D_
};
_x000D_
<div id="Console"></div>
_x000D_
_x000D_
_x000D_

The variable strDateTime will hold the date/time in the format you desire and you should be able to tweak it pretty easily if you need.

I'm using join as good practice, nothing more, it's better than adding strings together.

ALTER COLUMN in sqlite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.

  1. BEGIN TRANSACTION;
  2. CREATE TEMPORARY TABLE t1_backup(a,b);
  3. INSERT INTO t1_backup SELECT a,b FROM t1;
  4. DROP TABLE t1;
  5. CREATE TABLE t1(a,b);
  6. INSERT INTO t1 SELECT a,b FROM t1_backup;
  7. DROP TABLE t1_backup;
  8. COMMIT

For more detail you can refer the link.

Android. Fragment getActivity() sometimes returns null

In Kotlin you can try this way to handle getActivity() null condition.

   activity.let { // activity == getActivity() in java

        //your code here

   }

It will check activity is null or not and if not null then execute inner code.

Gerrit error when Change-Id in commit messages are missing

Check if your commits have Change-Id: ... in their descriptions. Every commit should have them.

If no, use git rebase -i to reword the commit messages and add proper Change-Ids (usually this is a SHA1 of the first version of the reviewed commit).

For the future, you should install commit hook, which automatically adds the required Change-Id.

Execute scp -p -P 29418 username@your_gerrit_address:hooks/commit-msg .git/hooks/ in the repository directory or download them from http://your_gerrit_address/tools/hooks/commit-msg and copy to .git/hooks

Font Awesome 5 font-family issue

Using the fontawesome-all.css file: Changing the "Brands" font-family from "Font Awesome 5 Free" to "Font Awesome 5 Brands" fixed the issues I was having.

I can't take all of the credit - I fixed my own local issue right before looking at the CDN version: https://use.fontawesome.com/releases/v5.0.6/css/all.css

They've got the issue sorted out on the CDN as well.

_x000D_
_x000D_
 @font-face {_x000D_
    font-family: 'Font Awesome 5 Brands';_x000D_
    font-style: normal;_x000D_
    font-weight: normal;_x000D_
    src: url("../webfonts/fa-brands-400.eot");_x000D_
    src: url("../webfonts/fa-brands-400.eot?#iefix") format("embedded-opentype"), url("../webfonts/fa-brands-400.woff2") format("woff2"), url("../webfonts/fa-brands-400.woff") format("woff"), url("../webfonts/fa-brands-400.ttf") format("truetype"), url("../webfonts/fa-brands-400.svg#fontawesome") format("svg"); }_x000D_
_x000D_
    .fab {_x000D_
    font-family: 'Font Awesome 5 Brands'; }_x000D_
    @font-face {_x000D_
    font-family: 'Font Awesome 5 Brands';_x000D_
    font-style: normal;_x000D_
    font-weight: 400;_x000D_
    src: url("../webfonts/fa-regular-400.eot");_x000D_
  src: url("../webfonts/fa-regular-400.eot?#iefix") format("embedded-opentype"), url("../webfonts/fa-regular-400.woff2") format("woff2"), url("../webfonts/fa-regular-400.woff") format("woff"), url("../webfonts/fa-regular-400.ttf") format("truetype"), url("../webfonts/fa-regular-400.svg#fontawesome") format("svg"); }
_x000D_
_x000D_
_x000D_

Values of disabled inputs will not be submitted

disabled input will not submit data.

Use the readonly attribute:

<input type="text" readonly />

Source here

How to write text in ipython notebook?

Change the cell type to Markdown in the menu bar, from Code to Markdown. Currently in Notebook 4.x, the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown).

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

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

Manually switching system-default version without 3rd party tools:

As detailed in this older answer, on macOS /usr/bin/java is a wrapper tool that will use Java version pointed by JAVA_HOME or if that variable is not set will look for Java installations under /Library/Java/JavaVirtualMachines/ and will use the one with highest version. It determines versions by looking at Contents/Info.plist under each package.

Armed with this knowledge you can:

  • control which version the system will use by renaming Info.plist in versions you don't want to use as default (that file is not used by the actual Java runtime itself).
  • control which version to use for specific tasks by setting $JAVA_HOME

I've just verified this is still true with OpenJDK & Mojave.

On a brand new system, there is no Java version installed:

$ java -version
No Java runtime present, requesting install.

Cancel this, download OpenJDK 11 & 12ea on https://jdk.java.net ; install OpenJDK11:

$ cd /Library/Java/JavaVirtualMachines/
$ sudo tar xzf ~/Downloads/openjdk-11.0.1_osx-x64_bin.tar.gz

System java is now 11:

$ java -version
openjdk version "11.0.1" 2018-10-16
[...]

Install OpenJDK12 (early access at the moment):

$ sudo tar xzf ~/Downloads/openjdk-12-ea+17_osx-x64_bin.tar.gz 

System java is now 12:

$ java -version
openjdk version "12-ea" 2019-03-19
[...]

Now let's "hide" OpenJDK 12 from system java wrapper:

$ cd jdk-12.jdk/Contents/
$ sudo mv Info.plist Info.plist.disabled

System java is back to 11:

$ java -version
openjdk version "11.0.1" 2018-10-16
[...]

And you can still use version 12 punctually by manually setting JAVA_HOME:

$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
$ java -version
openjdk version "12-ea" 2019-03-19
[...]

Strange out of memory issue while loading an image to a Bitmap object

My 2 cents: i solved my OOM errors with bitmaps by:

a) scaling my images by a factor of 2

b) using Picasso library in my custom Adapter for a ListView, with a one-call in getView like this: Picasso.with(context).load(R.id.myImage).into(R.id.myImageView);

How to move (and overwrite) all files from one directory to another?

If you simply need to answer "y" to all the overwrite prompts, try this:

y | mv srcdir/* targetdir/

Routing with Multiple Parameters using ASP.NET MVC

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

First you enable attribute routing

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)
    {

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string albumRSS;
        string url = "http://www.SomeSite.com/rss?";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        r.Close();
        foreach (SyndicationItem album in albums.Items)
        {

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);

        }



    }

How do I find which rpm package supplies a file I'm looking for?

The most popular answer is incomplete:

Since this search will generally be performed only for files from installed packages, yum whatprovides is made blisteringly fast by disabling all external repos (the implicit "installed" repo can't be disabled).

yum --disablerepo=* whatprovides <file>

How to do a HTTP HEAD request from the windows command line?

If you cannot install aditional applications, then you can telnet (you will need to install this feature for your windows 7 by following this) the remote server:

TELNET server_name 80

followed by:

HEAD /virtual/directory/file.ext

or

GET /virtual/directory/file.ext

depending on if you want just the header (HEAD) or the full contents (GET)

Font size relative to the user's screen resolution?

This worked for me :

body {

  font-size: calc([minimum size] + ([maximum size] - [minimum size]) * ((100vw - [minimum 
viewport width]) / ([maximum viewport width] - [minimum viewport width])));

}

Explained in detail here: https://css-tricks.com/books/volume-i/scale-typography-screen-size/

What is the difference between dict.items() and dict.iteritems() in Python2?

In Py2.x

The commands dict.items(), dict.keys() and dict.values() return a copy of the dictionary's list of (k, v) pair, keys and values. This could take a lot of memory if the copied list is very large.

The commands dict.iteritems(), dict.iterkeys() and dict.itervalues() return an iterator over the dictionary’s (k, v) pair, keys and values.

The commands dict.viewitems(), dict.viewkeys() and dict.viewvalues() return the view objects, which can reflect the dictionary's changes. (I.e. if you del an item or add a (k,v) pair in the dictionary, the view object can automatically change at the same time.)

$ python2.7

>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>> 
>>> 
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>> 
>>> 
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>

While in Py3.x

In Py3.x, things are more clean, since there are only dict.items(), dict.keys() and dict.values() available, which return the view objects just as dict.viewitems() in Py2.x did.

But

Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

Python pip install module is not found. How to link python to pip location?

If your python and pip binaries are from different versions, modules installed using pip will not be available to python.

Steps to resolve:

  1. Open up a fresh terminal with a default environment and locate the binaries for pip and python.
readlink $(which pip)
../Cellar/python@2/2.7.15_1/bin/pip

readlink $(which python)
/usr/local/bin/python3      <-- another symlink

readlink /usr/local/bin/python3
../Cellar/python/3.7.2/bin/python3

Here you can see an obvious mismatch between the versions 2.7.15_1 and 3.7.2 in my case.

  1. Replace the pip symlink with the pip binary which matches your current version of python. Use your python version in the following command.
ln -is /usr/local/Cellar/python/3.7.2/bin/pip3 $(which pip)

The -i flag promts you to overwrite if the target exists.

That should do the trick.

Using json_encode on objects in PHP (regardless of scope)

Following code worked for me:

public function jsonSerialize()
{
    return get_object_vars($this);
}

Disable Drag and Drop on HTML elements?

This is a fiddle I always use with my Web applications:

$('body').on('dragstart drop', function(e){
    e.preventDefault();
    return false;
});

It will prevent anything on your app being dragged and dropped. Depending on tour needs, you can replace body selector with any container that childrens should not be dragged.

Python slice first and last element in list

Some people are answering the wrong question, it seems. You said you want to do:

>>> first_item, last_item = some_list[0,-1]
>>> print first_item
'1'
>>> print last_item
'F'

Ie., you want to extract the first and last elements each into separate variables.

In this case, the answers by Matthew Adams, pemistahl, and katrielalex are valid. This is just a compound assignment:

first_item, last_item = some_list[0], some_list[-1]

But later you state a complication: "I am splitting it in the same line, and that would have to spend time splitting it twice:"

x, y = a.split("-")[0], a.split("-")[-1]

So in order to avoid two split() calls, you must only operate on the list which results from splitting once.

In this case, attempting to do too much in one line is a detriment to clarity and simplicity. Use a variable to hold the split result:

lst = a.split("-")
first_item, last_item = lst[0], lst[-1]

Other responses answered the question of "how to get a new list, consisting of the first and last elements of a list?" They were probably inspired by your title, which mentions slicing, which you actually don't want, according to a careful reading of your question.

AFAIK are 3 ways to get a new list with the 0th and last elements of a list:

>>> s = 'Python ver. 3.4'
>>> a = s.split()
>>> a
['Python', 'ver.', '3.4']

>>> [ a[0], a[-1] ]        # mentioned above
['Python', '3.4']

>>> a[::len(a)-1]          # also mentioned above
['Python', '3.4']

>>> [ a[e] for e in (0,-1) ] # list comprehension, nobody mentioned?
['Python', '3.4']

# Or, if you insist on doing it in one line:
>>> [ s.split()[e] for e in (0,-1) ]
['Python', '3.4']

The advantage of the list comprehension approach, is that the set of indices in the tuple can be arbitrary and programmatically generated.

I want to get the type of a variable at runtime

I think the question is incomplete. if you meant that you wish to get the type information of some typeclass then below:

If you wish to print as you have specified then:

scala>  def manOf[T: Manifest](t: T): Manifest[T] = manifest[T]
manOf: [T](t: T)(implicit evidence$1: Manifest[T])Manifest[T]

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> println(manOf(x))
scala.collection.immutable.List[Int]

If you are in repl mode then

scala> :type List(1,2,3)
List[Int]

Or if you just wish to know what the class type then as @monkjack explains "string".getClass might solve the purpose

IIS7 folder permissions for web application

If it's any help to anyone, give permission to "IIS_IUSRS" group.

Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".

Apply CSS rules to a nested class inside a div

You use

#main_text .title {
  /* Properties */
}

If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, and not children of children, e.g.:

#main_text > .title {
  /* Properties */
}

Either will work in this case, but the first is more typically used.

How to make a div with a circular shape?

.circle {
    border-radius: 50%;
    width: 500px;
    height: 500px;
    background: red;
}

<div class="circle"></div>

see this FIDDLE

How to connect to local instance of SQL Server 2008 Express

var.connectionstring = "server=localhost; database=dbname; integrated security=yes"

or

var.connectionstring = "server=localhost; database=dbname; login=yourlogin; pwd=yourpass"

md-table - How to update the column width

Right now, it has not been exposed at API level yet. However you can achieve it using something similar to this

<ng-container cdkColumnDef="userId" >
  <md-header-cell *cdkHeaderCellDef [ngClass]="'customWidthClass'"> ID </md-header-cell>
  <md-cell *cdkCellDef="let row" [ngClass]="'customWidthClass'"> {{row.id}} </md-cell>
</ng-container>

In css, you need to add this custom class -

.customWidthClass{
   flex: 0 0 75px;
}

Feel free to enter the logic to append class or custom width in here. It will apply custom width for the column.

Since md-table uses flex, we need to give fixed width in flex manner. This simply explains -

0 = don't grow (shorthand for flex-grow)

0 = don't shrink (shorthand for flex-shrink)

75px = start at 75px (shorthand for flex-basis)

Plunkr here - https://plnkr.co/edit/v7ww6DhJ6zCaPyQhPRE8?p=preview

Why does ++[[]][+[]]+[+[]] return the string "10"?

The following is adapted from a blog post answering this question that I posted while this question was still closed. Links are to (an HTML copy of) the ECMAScript 3 spec, still the baseline for JavaScript in today's commonly used web browsers.

First, a comment: this kind of expression is never going to show up in any (sane) production environment and is only of any use as an exercise in just how well the reader knows the dirty edges of JavaScript. The general principle that JavaScript operators implicitly convert between types is useful, as are some of the common conversions, but much of the detail in this case is not.

The expression ++[[]][+[]]+[+[]] may initially look rather imposing and obscure, but is actually relatively easy break down into separate expressions. Below I’ve simply added parentheses for clarity; I can assure you they change nothing, but if you want to verify that then feel free to read up about the grouping operator. So, the expression can be more clearly written as

( ++[[]][+[]] ) + ( [+[]] )

Breaking this down, we can simplify by observing that +[] evaluates to 0. To satisfy yourself why this is true, check out the unary + operator and follow the slightly tortuous trail which ends up with ToPrimitive converting the empty array into an empty string, which is then finally converted to 0 by ToNumber. We can now substitute 0 for each instance of +[]:

( ++[[]][0] ) + [0]

Simpler already. As for ++[[]][0], that’s a combination of the prefix increment operator (++), an array literal defining an array with single element that is itself an empty array ([[]]) and a property accessor ([0]) called on the array defined by the array literal.

So, we can simplify [[]][0] to just [] and we have ++[], right? In fact, this is not the case because evaluating ++[] throws an error, which may initially seem confusing. However, a little thought about the nature of ++ makes this clear: it’s used to increment a variable (e.g. ++i) or an object property (e.g. ++obj.count). Not only does it evaluate to a value, it also stores that value somewhere. In the case of ++[], it has nowhere to put the new value (whatever it may be) because there is no reference to an object property or variable to update. In spec terms, this is covered by the internal PutValue operation, which is called by the prefix increment operator.

So then, what does ++[[]][0] do? Well, by similar logic as +[], the inner array is converted to 0 and this value is incremented by 1 to give us a final value of 1. The value of property 0 in the outer array is updated to 1 and the whole expression evaluates to 1.

This leaves us with

1 + [0]

... which is a simple use of the addition operator. Both operands are first converted to primitives and if either primitive value is a string, string concatenation is performed, otherwise numeric addition is performed. [0] converts to "0", so string concatenation is used, producing "10".

As a final aside, something that may not be immediately apparent is that overriding either one of the toString() or valueOf() methods of Array.prototype will change the result of the expression, because both are checked and used if present when converting an object into a primitive value. For example, the following

Array.prototype.toString = function() {
  return "foo";
};
++[[]][+[]]+[+[]]

... produces "NaNfoo". Why this happens is left as an exercise for the reader...

Why use pointers?

  • In some cases, function pointers are required to use functions that are in a shared library (.DLL or .so). This includes performing stuff across languages, where oftentimes a DLL interface is provided.
  • Making compilers
  • Making scientific calculators, where you have an array or vector or string map of function pointers?
  • Trying to modify video memory directly - making your own graphics package
  • Making an API!
  • Data structures - node link pointers for special trees you are making

There are Lots of reasons for pointers. Having C name mangling especially is important in DLLs if you want to maintain cross-language compatibility.

How to scale a UIImageView proportionally?

I think you can do something like

image.center = [[imageView window] center];

How to format number of decimal places in wpf using style/template?

The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format

<TextBox Text="{Binding Value,  StringFormat={}{0:#,0.0}}" 

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Exception : AAPT2 error: check logs for details

AAPT2 Error solution.

If your Android studio has been updated.

Maybe, you would face an error in the studio like "AAPT 2 error: check the log for details"

This error will occur when you have done something wrong in your .xml file such as incorrect value, content not found, etc.

But, At that time you will not have the error specification there. Because the new version of Android Studio does not give you a specific error. It gives like AAPT2 error.

If you want to know where the actual error is then

Follow step.

  1. Look at the panel which is at the right of your Android studio Check out the "Gradle" tab and click on it.
  2. You will see the "app" option. Click on it.
  3. In the app options you will see [Tasks -> build] click on it.
  4. Then you will get options list and see "assembleDebug" double click on it.
  5. Keep the patience and See build tab at the bottom panel of Android studios, you will get an exact error there what you made a mistake in which file and which position.

Click on assembleDebug and see log you can get the actual error is where

What does the question mark in Java generics' type parameter mean?

Perhaps a contrived "real world" example would help.

At my place of work we have rubbish bins that come in different flavours. All bins contain rubbish, but some bins are specialist and do not take all types of rubbish. So we have Bin<CupRubbish> and Bin<RecylcableRubbish>. The type system needs to make sure I can't put my HalfEatenSandwichRubbish into either of these types, but it can go into a general rubbish bin Bin<Rubbish>. If I wanted to talk about a Bin of Rubbish which may be specialised so I can't put in incompatible rubbish, then that would be Bin<? extends Rubbish>.

(Note: ? extends does not mean read-only. For instance, I can with proper precautions take out a piece of rubbish from a bin of unknown speciality and later put it back in a different place.)

Not sure how much that helps. Pointer-to-pointer in presence of polymorphism isn't entirely obvious.

Convert DataTable to CSV stream

You can just write something quickly yourself:

public static class Extensions
{
    public static string ToCSV(this DataTable table)
    {
        var result = new StringBuilder();
        for (int i = 0; i < table.Columns.Count; i++)
        {
            result.Append(table.Columns[i].ColumnName);
            result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
        }

        foreach (DataRow row in table.Rows)
        {
            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(row[i].ToString());
                result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
            }
        }

        return result.ToString();
    }
}

And to test:

  public static void Main()
  {
        DataTable table = new DataTable();
        table.Columns.Add("Name");
        table.Columns.Add("Age");
        table.Rows.Add("John Doe", "45");
        table.Rows.Add("Jane Doe", "35");
        table.Rows.Add("Jack Doe", "27");
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(table.ToCSV());
        MemoryStream stream = new MemoryStream(bytes);

        StreamReader reader = new StreamReader(stream);
        Console.WriteLine(reader.ReadToEnd());
  }

EDIT: Re your comments:

It depends on how you want your csv formatted but generally if the text contains special characters, you want to enclose it in double quotes ie: "my,text". You can add checking in the code that creates the csv to check for special characters and encloses the text in double quotes if it is. As for the .NET 2.0 thing, just create it as a helper method in your class or remove the word this in the method declaration and call it like so : Extensions.ToCsv(table);

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

How do I refresh a DIV content?

This one $("#yourDiv").load(" #yourDiv > *"); is the best if you are planning to just reload a <div>

Make sure to use an id and not a class. Also, remember to paste <script src="https://code.jquery.com/jquery-3.5.1.js"></script> in the <head> section of the html file, if you haven't already. In opposite case it won't work.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

You can put the jQuery's Ajax setup in synchronous mode by calling

jQuery.ajaxSetup({async:false});

And then perform your Ajax calls using jQuery.get( ... );

Then just turning it on again once

jQuery.ajaxSetup({async:true});

I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their jQuery.get() or jQuery.post() to the more elaborate jQuery.ajax() syntax.

How to get a single value from FormGroup

Another option:

this.form.value['nameOfControl']

How do you add CSS with Javascript?

You can add classes or style attributes on an element by element basis.

For example:

<a name="myelement" onclick="this.style.color='#FF0';">text</a>

Where you could do this.style.background, this.style.font-size, etc. You can also apply a style using this same method ala

this.className='classname';

If you want to do this in a javascript function, you can use getElementByID rather than 'this'.

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

How can I require at least one checkbox be checked before a form can be submitted?

The issue with the accepted solution above is that is does not allow for the else condition on form submit (if a box has been selected), thereby preventing form submission - at least when I tried it.

I discovered another solution that effects the desired result more completely IMHO, here:

Making sure at least one checkbox is checked

Code as follows:

function valthis() {
var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'At least one checkbox checked!' );
        } else {
            alert( 'Please, check at least one checkbox!' );
        }   
}

Fiddle

That code & answer by Vell

Best implementation for Key Value Pair Data Structure?

There is a KeyValuePair built-in type. As a matter of fact, this is what the IDictionary is giving you access to when you iterate in it.

Also, this structure is hardly a tree, finding a more representative name might be a good exercise.

How can I add a variable to console.log?

You can use another console method:

let name = prompt("what is your name?");
console.log(`story ${name} story`);

Access an arbitrary element in a dictionary in Python

As others mentioned, there is no "first item", since dictionaries have no guaranteed order (they're implemented as hash tables). If you want, for example, the value corresponding to the smallest key, thedict[min(thedict)] will do that. If you care about the order in which the keys were inserted, i.e., by "first" you mean "inserted earliest", then in Python 3.1 you can use collections.OrderedDict, which is also in the forthcoming Python 2.7; for older versions of Python, download, install, and use the ordered dict backport (2.4 and later) which you can find here.

Python 3.7 Now dicts are insertion ordered.

Caesar Cipher Function in Python

>>> def rotate(txt, key):
...   def cipher(i, low=range(97,123), upper=range(65,91)):
...     if i in low or i in upper:
...       s = 65 if i in upper else 97
...       i = (i - s + key) % 26 + s
...     return chr(i)
...   return ''.join([cipher(ord(s)) for s in txt])

# test
>>> rotate('abc', 2)
'cde'
>>> rotate('xyz', 2)
'zab'
>>> rotate('ab', 26)
'ab'
>>> rotate('Hello, World!', 7)
'Olssv, Dvysk!'

Datatables - Setting column width

you should use "bAutoWidth" property of datatable and give width to each td/column in %

 $(".table").dataTable({"bAutoWidth": false , 
aoColumns : [
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "10%"},
    ]
});

Hope this will help.

sudo echo "something" >> /etc/privilegedFile doesn't work

The issue is that it's your shell that handles redirection; it's trying to open the file with your permissions not those of the process you're running under sudo.

Use something like this, perhaps:

sudo sh -c "echo 'something' >> /etc/privilegedFile"

Why maven? What are the benefits?

I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.

It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.

An "and" operator for an "if" statement in Bash

Try this:

if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]

or

if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]

Automatically create requirements.txt

I created this bash command.

for l in $(pip freeze); do p=$(echo "$l" | cut -d'=' -f1); f=$(find . -type f -exec grep "$p" {} \; | grep 'import'); [[ ! -z "$f" ]] && echo "$l" ; done;

Powershell: How can I stop errors from being displayed in a script?

Add -ErrorAction SilentlyContinue to your script and you'll be good to go.

How to copy a row and insert in same table with a autoincrement field in MySQL?

INSERT INTO `dbMyDataBase`.`tblMyTable` 
(
    `IdAutoincrement`, 
    `Column2`, 
    `Column3`, 
    `Column4` 
) 

SELECT 
    NULL,  
    `Column2`, 
    `Column3`, 
    'CustomValue' AS Column4 
FROM `dbMyDataBase`.`tblMyTable` 
WHERE `tblMyTable`.`Column2` = 'UniqueValueOfTheKey' 
; 
/* mySQL 5.6 */

PHP foreach loop key value

foreach($shipmentarr as $index=>$val){    
    $additionalService = array();

    foreach($additionalService[$index] as $key => $value) {

        array_push($additionalService,$value);

    }
}

Difference between window.location.href=window.location.href and window.location.reload()

A difference in Firefox (12.0) is that on a page rendered from a POST, reload() will pop up a warning and do a re-post, while a URL assignment will do a GET.

Google Chrome does a GET for both.

How to get the current user in ASP.NET MVC

This page could be what you looking for:
Using Page.User.Identity.Name in MVC3

You just need User.Identity.Name.

HTML "overlay" which allows clicks to fall through to elements behind it

My team ran into this issue and resolved it very nicely.

  • add a class "passthrough" or something to each element you want clickable and which is under the overlay.
  • for each ".passthrough" element append a div and position it exactly on top of its parent. add class "element-overlay" to this new div.
  • The ".element-overlay" css should have a high z-index (above the page's overlay), and the elements should be transparent.

This should resolve your problem as the events on the ".element-overlay" should bubble up to ".passthrough". If you still have problems (we did not see any so far) you can play around with the binding.

This is an enhancement to @jvenema's solution.

The nice thing about this is that

  • you don't pass through ALL events to ALL elements. Just the ones you want. (resolved @jvenema's argument)
  • All events will work properly. (hover for example).

If you have any problems please let me know so I can elaborate.

How to increase Bootstrap Modal Width?

The simplest way to do it is:

$(".modal-dialog").css("width", "80%");

where we can specify the width of the modal in terms of percentage of the screen.

Here is a working example to demonstrate the same:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>_x000D_
  <script type="text/javascript">_x000D_
  $(document).ready(function () {_x000D_
    $(".modal-dialog").css("width", "90%");_x000D_
  });_x000D_
  </script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Modal Example</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
        <div class="modal-footer">_x000D_
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        </div>_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Plot inline or a separate window using Matplotlib in Spyder IDE

type

%matplotlib qt

when you want graphs in a separate window and

%matplotlib inline

when you want an inline plot

How can I format DateTime to web UTC format?

string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow)

returns 2017-02-10T08:12:39.483Z

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.

For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:

sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now   # to exit the container

Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.

How can you float: right in React Native?

why does the Text take up the full space of the View, instead of just the space for "Hello"?

Because the View is a flex container and by default has flexDirection: 'column' and alignItems: 'stretch', which means that its children should be stretched out to fill its width.

(Note, per the docs, that all components in React Native are display: 'flex' by default and that display: 'inline' does not exist at all. In this way, the default behaviour of a Text within a View in React Native differs from the default behaviour of span within a div on the web; in the latter case, the span would not fill the width of the div because a span is an inline element by default. There is no such concept in React Native.)

How can the Text be floated / aligned to the right?

The float property doesn't exist in React Native, but there are loads of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:

1. Use textAlign: 'right' on the Text element

<View>
  <Text style={{textAlign: 'right'}}>Hello, World!</Text>
</View>

(This approach doesn't change the fact that the Text fills the entire width of the View; it just right-aligns the text within the Text.)

2. Use alignSelf: 'flex-end' on the Text

<View>
  <Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>
</View>

This shrinks the Text element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the View.

3. Use alignItems: 'flex-end' on the View

<View style={{alignItems: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

This is equivalent to setting alignSelf: 'flex-end' on all the View's children.

4. Use flexDirection: 'row' and justifyContent: 'flex-end' on the View

<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

flexDirection: 'row' sets the main direction of layout to be horizontal instead of vertical; justifyContent is just like alignItems, but controls alignment in the main direction instead of the cross direction.

5. Use flexDirection: 'row' on the View and marginLeft: 'auto' on the Text

<View style={{flexDirection: 'row'}}>
  <Text style={{marginLeft: 'auto'}}>Hello, World!</Text>
</View>

This approach is demonstrated, in the context of the web and real CSS, at https://stackoverflow.com/a/34063808/1709587.

6. Use position: 'absolute' and right: 0 on the Text:

<View>
  <Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>
</View>

Like in real CSS, this takes the Text "out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the View by default (although you can explicitly set a distance from the top of the View using the top style property).


Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.

Are there any standard exit status codes in Linux?

None of the older answers describe exit status 2 correctly. Contrary to what they claim, status 2 is what your command line utilities actually return when called improperly. (Yes, an answer can be nine years old, have hundreds of upvotes, and still be wrong.)

Here is the real, long-standing exit status convention for normal termination, i.e. not by signal:

  • Exit status 0: success
  • Exit status 1: "failure", as defined by the program
  • Exit status 2: command line usage error

For example, diff returns 0 if the files it compares are identical, and 1 if they differ. By long-standing convention, unix programs return exit status 2 when called incorrectly (unknown options, wrong number of arguments, etc.) For example, diff -N, grep -Y or diff a b c will all result in $? being set to 2. This is and has been the practice since the early days of Unix in the 1970s.

The accepted answer explains what happens when a command is terminated by a signal. In brief, termination due to an uncaught signal results in exit status 128+[<signal number>. E.g., termination by SIGINT (signal 2) results in exit status 130.

Notes

  1. Several answers define exit status 2 as "Misuse of bash builtins". This applies only when bash (or a bash script) exits with status 2. Consider it a special case of incorrect usage error.

  2. In sysexits.h, mentioned in the most popular answer, exit status EX_USAGE ("command line usage error") is defined to be 64. But this does not reflect reality: I am not aware of any common Unix utility that returns 64 on incorrect invocation (examples welcome). Careful reading of the source code reveals that sysexits.h is aspirational, rather than a reflection of true usage:

     *    This include file attempts to categorize possible error
     *    exit statuses for system programs, notably delivermail
     *    and the Berkeley network.
    
     *    Error numbers begin at EX__BASE [64] to reduce the possibility of 
     *    clashing with oth­er exit statuses that random programs may 
     *    already return. 
    

    In other words, these definitions do not reflect the common practice at the time (1993) but were intentionally incompatible with it. More's the pity.

pass array to method Java

Simply remove the brackets from your original code.

PrintA(arryw);

private void PassArray(){
    String[] arrayw = new String[4];
    //populate array
    PrintA(arrayw);
}
private void PrintA(String[] a){
    //do whatever with array here
}

That is all.

How to view the Folder and Files in GAC?

Install:

gacutil -i "path_to_the_assembly"

View:

Open in Windows Explorer folder

  • .NET 1.0 - NET 3.5: c:\windows\assembly (%systemroot%\assembly)
  • .NET 4.x: %windir%\Microsoft.NET\assembly

OR gacutil –l

When you are going to install an assembly you have to specify where gacutil can find it, so you have to provide a full path as well. But when an assembly already is in GAC - gacutil know a folder path so it just need an assembly name.

MSDN:

Permanently add a directory to PYTHONPATH?

Fix Python Path issues when you switch from bash to zsh

I ran into Python Path problems when I switched to zsh from bash.

The solution was simple, but I failed to notice.

Pip was showing me, that the scripts blah blah or package blah blah is installed in ~/.local/bin which is not in path.

After reading some solutions to this question, I opened my .zshrc to find that the solution already existed.

I had to simply uncomment a line:

Take a look

Screenshot from 2020-10-07 13-38-17

How to split a file into equal parts, without breaking individual lines?

If you mean an equal number of lines, split has an option for this:

split --lines=75

If you need to know what that 75 should really be for N equal parts, its:

lines_per_part = int(total_lines + N - 1) / N

where total lines can be obtained with wc -l.

See the following script for an example:

#!/usr/bin/bash

# Configuration stuff

fspec=qq.c
num_files=6

# Work out lines per file.

total_lines=$(wc -l <${fspec})
((lines_per_file = (total_lines + num_files - 1) / num_files))

# Split the actual file, maintaining lines.

split --lines=${lines_per_file} ${fspec} xyzzy.

# Debug information

echo "Total lines     = ${total_lines}"
echo "Lines  per file = ${lines_per_file}"    
wc -l xyzzy.*

This outputs:

Total lines     = 70
Lines  per file = 12
  12 xyzzy.aa
  12 xyzzy.ab
  12 xyzzy.ac
  12 xyzzy.ad
  12 xyzzy.ae
  10 xyzzy.af
  70 total

More recent versions of split allow you to specify a number of CHUNKS with the -n/--number option. You can therefore use something like:

split --number=l/6 ${fspec} xyzzy.

(that's ell-slash-six, meaning lines, not one-slash-six).

That will give you roughly equal files in terms of size, with no mid-line splits.

I mention that last point because it doesn't give you roughly the same number of lines in each file, more the same number of characters.

So, if you have one 20-character line and 19 1-character lines (twenty lines in total) and split to five files, you most likely won't get four lines in every file.

How long will my session last?

If session.cookie_lifetime is 0, the session cookie lives until the browser is quit.

EDIT: Others have mentioned the session.gc_maxlifetime setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime seconds. To set the time-to-live for the session cookie, call session_set_cookie_params() or define the session.cookie_lifetime PHP setting. If this setting is greater than session.gc_maxlifetime, you should increase session.gc_maxlifetime to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.

How to determine SSL cert expiration date from a PEM encoded certificate?

Same as accepted answer, But note that it works even with .crt file and not just .pem file, just in case if you are not able to find .pem file location.

openssl x509 -enddate -noout -in e71c8ea7fa97ad6c.crt

Result:

notAfter=Mar 29 06:15:00 2020 GMT

PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

How to implement LIMIT with SQL Server?

Clunky, but it'll work.

SELECT TOP 10 * FROM table WHERE id NOT IN (SELECT TOP 10 id FROM table ORDER BY id) FROM table ORDER BY id

MSSQL's omission of a LIMIT clause is criminal, IMO. You shouldn't have to do this kind of kludgy workaround.

Ubuntu, how do you remove all Python 3 but not 2

neither try any above ways nor sudo apt autoremove python3 because it will remove all gnome based applications from your system including gnome-terminal. In case if you have done that mistake and left with kernal only than trysudo apt install gnome on kernal.

try to change your default python version instead removing it. you can do this through bashrc file or export path command.

static function in C

Making a function static hides it from other translation units, which helps provide encapsulation.

helper_file.c

int f1(int);        /* prototype */
static int f2(int); /* prototype */

int f1(int foo) {
    return f2(foo); /* ok, f2 is in the same translation unit */
                    /* (basically same .c file) as f1         */
}

int f2(int foo) {
    return 42 + foo;
}

main.c:

int f1(int); /* prototype */
int f2(int); /* prototype */

int main(void) {
    f1(10); /* ok, f1 is visible to the linker */
    f2(12); /* nope, f2 is not visible to the linker */
    return 0;
}

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

What's the most efficient way to check if a record exists in Oracle?

select count(1) into existence 
   from sales where sales_type = 'Accessories' and rownum=1;

Oracle plan says that it costs 1 if seles_type column is indexed.

Add a CSS border on hover without moving the element

You can make the border transparent. In this way it exists, but is invisible, so it doesn't push anything around:

_x000D_
_x000D_
.jobs .item {
   background: #eee;
   border: 1px solid transparent;
}

.jobs .item:hover {
   background: #e1e1e1;
   border: 1px solid #d0d0d0;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

For elements that already have a border, and you don't want them to move, you can use negative margins:

_x000D_
_x000D_
.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
   background: #e1e1e1;
    border: 3px solid #d0d0d0;
    margin: -2px;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

Another possible trick for adding width to an existing border is to add a box-shadow with the spread attribute of the desired pixel width.

_x000D_
_x000D_
.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
    background: #e1e1e1;
    box-shadow: 0 0 0 2px #d0d0d0;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

How can I find the first and last date in a month using PHP?

$month=01;
$year=2015;
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo $num;

display 31 last day of date

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

How do I convert a float to an int in Objective C?

int myInt = (int) myFloat;

Worked fine for me.

int myInt = [[NSNumber numberWithFloat:myFloat] intValue];

Well, that is one option. If you like the detour, I could think of some using NSString. Why easy, when there is a complicated alternative? :)

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

The key issue is that a glyph in a string takes 32 bits (16 bits for a character code) but a byte only has 8 bits to spare. A one-to-one mapping doesn't exist unless you restrict yourself to strings that only contain ASCII characters. System.Text.Encoding has lots of ways to map a string to byte[], you need to pick one that avoids loss of information and that is easy to use by your client when she needs to map the byte[] back to a string.

Utf8 is a popular encoding, it is compact and not lossy.

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

How to set Status Bar Style in Swift 3

If you want to change the statusBar's color to white, for all of the views contained in a UINavigationController, add this inside AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UINavigationBar.appearance().barStyle = .blackOpaque
    return true
}

This code:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

does not work for UIViewControllers contained in a UINavigationController, because the compiler looks for the statusBarStyle of the UINavigationController, not for the statusBarStyle of the ViewControllers contained by it.

Hope this helps those who haven't succeeded with the accepted answer!

MySQL join with where clause

You need to put it in the join clause, not the where:

SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON 
    user_category_subscriptions.category_id = categories.category_id
    and user_category_subscriptions.user_id =1

See, with an inner join, putting a clause in the join or the where is equivalent. However, with an outer join, they are vastly different.

As a join condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1 first, and takes the subset of user_category_subscriptions with a user_id of 1 to join to all of the rows in categories. This will give you all of the rows in categories, while only the categories that this particular user has subscribed to will have any information in the user_category_subscriptions columns. Of course, all other categories will be populated with null in the user_category_subscriptions columns.

Conversely, a where clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id doesn't equal 1. You're left with an inefficient way to get an inner join.

Hopefully this helps!

Converting Java objects to JSON with Jackson

This might be useful:

objectMapper.writeValue(new File("c:\\employee.json"), employee);

// display to console
Object json = objectMapper.readValue(
     objectMapper.writeValueAsString(employee), Object.class);

System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
     .writeValueAsString(json));

Better way to convert an int to a boolean

I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0;

How can I make a weak protocol reference in 'pure' Swift (without @objc)

protocol must be subClass of AnyObject, class

example given below

    protocol NameOfProtocol: class {
   // member of protocol
    }
   class ClassName: UIViewController {
      weak var delegate: NameOfProtocol? 
    }

Run bash script from Windows PowerShell

It also can be run by exporting the bash and sh of the gitbash C:\Program Files\git\bin\ in the Advance section of the environment variable of the Windows Server.

In Advance section in the path var kindly add the C:\Program Files\git\bin\ which will make the bash and the sh of the git-bash to be executable from the window cmd.

Then,

Run the shell file as

bash shellscript.sh or sh shellscript.sh

Display image as grayscale using matplotlib

@unutbu's answer is quite close to the right answer.

By default, plt.imshow() will try to scale your (MxN) array data to 0.0~1.0. And then map to 0~255. For most natural taken images, this is fine, you won't see a different. But if you have narrow range of pixel value image, say the min pixel is 156 and the max pixel is 234. The gray image will looks totally wrong. The right way to show an image in gray is

from matplotlib.colors import NoNorm
...
plt.imshow(img,cmap='gray',norm=NoNorm())
...

Let's see an example:

this is the origianl image: original

this is using defaul norm setting,which is None: wrong pic

this is using NoNorm setting,which is NoNorm(): right pic

Forking / Multi-Threaded Processes | Bash

Here's my thread control function:

#!/bin/bash
# This function just checks jobs in background, don't do more things.
# if jobs number is lower than MAX, then return to get more jobs;
# if jobs number is greater or equal to MAX, then wait, until someone finished.

# Usage:
#   thread_max 8
#   thread_max 0    # wait, until all jobs completed

thread_max() {
    local CHECK_INTERVAL="3s"
    local CUR_THREADS=
    local MAX=
    [[ $1 ]] && MAX=$1 || return 127

    # reset MAX value, 0 is easy to remember
    [ $MAX -eq 0 ] && {
        MAX=1
        DEBUG "waiting for all tasks finish"
    }

    while true; do
        CUR_THREADS=`jobs -p | wc -w`

        # workaround about jobs bug. If don't execute it explicitily,
        # CUR_THREADS will stick at 1, even no jobs running anymore.
        jobs &>/dev/null

        DEBUG "current thread amount: $CUR_THREADS"
        if [ $CUR_THREADS -ge $MAX ]; then
            sleep $CHECK_INTERVAL
        else
            return 0
        fi
    done
}

Remove Fragment Page from ViewPager in Android

2020 now.

Simple add this to PageAdapter:

override fun getItemPosition(`object`: Any): Int {
    return PagerAdapter.POSITION_NONE
}

How to model type-safe enum types?

A slightly less verbose way of declaring named enumerations:

object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
  type WeekDay = Value
  val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value
}

WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString   // returns Fri

Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.

Python find min max and average of a list (array)

Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...

from operator import lt, gt
def ultimate (l,op,c=1,u=0):
    try:
        if op(l[c],l[u]): 
            u = c
        c += 1
        return ultimate(l,op,c,u)
    except IndexError:
        return l[u]
def minimum (l):
    return ultimate(l,lt)
def maximum (l):
    return ultimate(l,gt)

The solution is simple. Use this to set yourself apart from obvious choices.

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

Java 8 Stream and operation on arrays

Please note that Arrays.stream(arr) create a LongStream (or IntStream, ...) instead of Stream so the map function cannot be used to modify the type. This is why .mapToLong, mapToObject, ... functions are provided.

Take a look at why-cant-i-map-integers-to-strings-when-streaming-from-an-array

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to install Visual Studio 2015 on a different drive

I found these two links which might help you:

  1. https://www.reddit.com/r/csharp/comments/2agecc/why_must_visual_studio_be_installed_on_my_system/

  2. http://www.placona.co.uk/1196/dotnet/installing-visual-studio-on-a-different-drive/

Basically, at least a portion needs to be installed on a system drive. I'm not sure if your D:\ corresponds to some external drive or an actual system drive but the symlink solution might help.

Good luck

How to scroll to an element in jQuery?

Use

$(window).scrollTop()

It'll scroll the window to the item.

 var scrollPos =  $("#branch1").offset().top;
 $(window).scrollTop(scrollPos);

Static methods - How to call a method from another method?

NOTE - it looks like the question has changed some. The answer to the question of how you call an instance method from a static method is that you can't without passing an instance in as an argument or instantiating that instance inside the static method.

What follows is mostly to answer "how do you call a static method from another static method":

Bear in mind that there is a difference between static methods and class methods in Python. A static method takes no implicit first argument, while a class method takes the class as the implicit first argument (usually cls by convention). With that in mind, here's how you would do that:

If it's a static method:

test.dosomethingelse()

If it's a class method:

cls.dosomethingelse()

How do I start PowerShell from Windows Explorer?

The following is a concise (and updated) summation of the earlier solutions. Here's what to do:

Add these strings and their respective parent keys:

pwrshell\(Default) < Open PowerShell Here
pwrshell\command\(Default) < powershell -NoExit -Command Set-Location -LiteralPath '%V'
pwrshelladmin\(Default) < Open PowerShell (Admin)
pwrshelladmin\command\(Default) < powershell -Command Start-Process -verb runAs -ArgumentList '-NoExit','cd','%V' powershell

at these locations

HKCR\Directory\shell (for folders)
HKCR\Directory\Background\shell (Explorer window)
HKCR\Drive\shell (for root drives)

That's it. Add the "Extended" strings for the commands only to be visible if you hold the "Shift" key, everything else is superfluous.

How do I run all Python unit tests in a directory?

In case of a packaged library or application, you don't want to do it. setuptools will do it for you.

To use this command, your project’s tests must be wrapped in a unittest test suite by either a function, a TestCase class or method, or a module or package containing TestCase classes. If the named suite is a module, and the module has an additional_tests() function, it is called and the result (which must be a unittest.TestSuite) is added to the tests to be run. If the named suite is a package, any submodules and subpackages are recursively added to the overall test suite.

Just tell it where your root test package is, like:

setup(
    # ...
    test_suite = 'somepkg.test'
)

And run python setup.py test.

File-based discovery may be problematic in Python 3, unless you avoid relative imports in your test suite, because discover uses file import. Even though it supports optional top_level_dir, but I had some infinite recursion errors. So a simple solution for a non-packaged code is to put the following in __init__.py of your test package (see load_tests Protocol).

import unittest

from . import foo, bar


def load_tests(loader, tests, pattern):
    suite = unittest.TestSuite()
    suite.addTests(loader.loadTestsFromModule(foo))
    suite.addTests(loader.loadTestsFromModule(bar))

    return suite

jQuery: get parent, parent id?

Here are 3 examples:

_x000D_
_x000D_
$(document).on('click', 'ul li a', function (e) {_x000D_
    e.preventDefault();_x000D_
_x000D_
    var example1 = $(this).parents('ul:first').attr('id');_x000D_
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');_x000D_
_x000D_
    var example2 = $(this).parents('ul:eq(0)').attr('id');_x000D_
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');_x000D_
  _x000D_
    var example3 = $(this).closest('ul').attr('id');_x000D_
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');_x000D_
  _x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<ul id ="myList">_x000D_
  <li><a href="www.example.com">Click here</a></li>_x000D_
</ul>_x000D_
_x000D_
<div id="results">_x000D_
  <h1>Results:</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Let me know whether it was helpful.

How to get form values in Symfony2 controller

If you're using Symfony 2 security management, you don't need to get posted values, you only need to manage form template (see documentation).

If you aren't using Symfony 2 security management, I advise you strongly to use it. If you don't want to or if you can't, can you give us the LoginType's sources ?

How to set image button backgroundimage for different state?

what you are trying to do is more a segmentedbutton than an imagebutton list.

here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need

Pandas Merging 101

This post will go through the following topics:

  • how to correctly generalize to multiple DataFrames (and why merge has shortcomings here)
  • merging on unique keys
  • merging on non-unqiue keys

BACK TO TOP



Generalizing to multiple DataFrames

Oftentimes, the situation arises when multiple DataFrames are to be merged together. Naively, this can be done by chaining merge calls:

df1.merge(df2, ...).merge(df3, ...)

However, this quickly gets out of hand for many DataFrames. Furthermore, it may be necessary to generalise for an unknown number of DataFrames.

Here I introduce pd.concat for multi-way joins on unique keys, and DataFrame.join for multi-way joins on non-unique keys. First, the setup.

# Setup.
np.random.seed(0)
A = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})    
B = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C] 

# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')

dfs2 = [A2, B2, C2]

Multiway merge on unique keys

If your keys (here, the key could either be a column or an index) are unique, then you can use pd.concat. Note that pd.concat joins DataFrames on the index.

# merge on `key` column, you'll need to set the index before concatenating
pd.concat([
    df.set_index('key') for df in dfs], axis=1, join='inner'
).reset_index()

  key    valueA    valueB  valueC
0   D  2.240893 -0.977278     1.0

# merge on `key` index
pd.concat(dfs2, axis=1, sort=False, join='inner')

       valueA    valueB  valueC
key                            
D    2.240893 -0.977278     1.0

Omit join='inner' for a FULL OUTER JOIN. Note that you cannot specify LEFT or RIGHT OUTER joins (if you need these, use join, described below).


Multiway merge on keys with duplicates

concat is fast, but has its shortcomings. It cannot handle duplicates.

A3 = pd.DataFrame({'key': ['A', 'B', 'C', 'D', 'D'], 'valueA': np.random.randn(5)})
pd.concat([df.set_index('key') for df in [A3, B, C]], axis=1, join='inner')
ValueError: Shape of passed values is (3, 4), indices imply (3, 2)

In this situation, we can use join since it can handle non-unique keys (note that join joins DataFrames on their index; it calls merge under the hood and does a LEFT OUTER JOIN unless otherwise specified).

# join on `key` column, set as the index first
# For inner join. For left join, omit the "how" argument.
A.set_index('key').join(
    [df.set_index('key') for df in (B, C)], how='inner').reset_index()

  key    valueA    valueB  valueC
0   D  2.240893 -0.977278     1.0

# join on `key` index
A3.set_index('key').join([B2, C2], how='inner')

       valueA    valueB  valueC
key                            
D    1.454274 -0.977278     1.0
D    0.761038 -0.977278     1.0


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

How to navigate to a directory in C:\ with Cygwin?

As you'll probably want to do this often, add aliases into your .bashrc file, like:

alias cdc='cd /cygdrive/c'
alias cdp='cd /cygdrive/p'

Then you can just type on the command line:

cdc

How to link external javascript file onclick of button

If you want your button to call the routine you have written in filename.js you have to edit filename.js so that the code you want to run is the body of a function. For you can call a function, not a source file. (A source file has no entry point)

If the current content of your filename.js is:

_x000D_
_x000D_
alert('Hello world');
_x000D_
_x000D_
_x000D_

you have to change it to:

_x000D_
_x000D_
function functionName(){_x000D_
 alert('Hello world');_x000D_
}
_x000D_
_x000D_
_x000D_

Then you have to load filename.js in the header of your html page by the line:

_x000D_
_x000D_
<head>_x000D_
 <script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

so that you can call the function contained in filename.js by your button:

_x000D_
_x000D_
<button onclick="functionName()">Call the function</button>
_x000D_
_x000D_
_x000D_

I have made a little working example. A simple HTML page asks the user to input her name, and when she clicks the button, the function inside Public/Scripts/filename.js is called passing the inserted string as a parameter so that a popup says "Hello, <insertedName>!".

Here is the calling HTML page:

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
 </head>_x000D_
_x000D_
 <body>_x000D_
  What's your name? <input  id="insertedName" />_x000D_
  <button onclick="functionName(insertedName.value)">Say hello</button>_x000D_
 </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

And here is Public/Scripts/filename.js

_x000D_
_x000D_
function functionName( s ){_x000D_
 alert('Hello, ' + s + '!');_x000D_
}
_x000D_
_x000D_
_x000D_

CSS to select/style first word

Same thing, with jQuery:

$('#links a').each(function(){
    var me = $(this);
    me.html( me.text().replace(/(^\w+)/,'<strong>$1</strong>') );
  });

or

$('#links a').each(function(){
    var me = $(this)
       , t = me.text().split(' ');
    me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );
  });

(Via 'Wizzud' on the jQuery Mailing List)

How to solve error: "Clock skew detected"?

One of the reason may be improper date/time of your PC.

In Ubuntu PC to check the date and time using:

date

Example, One of the ways to update date and time is:

date -s "23 MAR 2017 17:06:00"

Ternary operators in JavaScript without an "else"

To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

And for objects:

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

Original source

What is the equivalent to getch() & getche() in Linux?

You can use the curses.h library in linux as mentioned in the other answer.

You can install it in Ubuntu by:

sudo apt-get update

sudo apt-get install ncurses-dev

I took the installation part from here.

What is the largest Safe UDP Packet Size on the Internet

This article describes maximum transmission unit (MTU) http://en.wikipedia.org/wiki/Maximum_transmission_unit. It states that IP hosts must be able to process 576 bytes for an IP packet. However, it notes the minumum is 68. RFC 791: "Every internet module must be able to forward a datagram of 68 octets without further fragmentation. This is because an internet header may be up to 60 octets, and the minimum fragment is 8 octets."

Thus, safe packet size of 508 = 576 - 60 (IP header) - 8 (udp header) is reasonable.

As mentioned by user607811, fragmentation by other network layers must be reassembled. https://tools.ietf.org/html/rfc1122#page-56 3.3.2 Reassembly The IP layer MUST implement reassembly of IP datagrams. We designate the largest datagram size that can be reassembled by EMTU_R ("Effective MTU to receive"); this is sometimes called the "reassembly buffer size". EMTU_R MUST be greater than or equal to 576

How can I create an utility class?

Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.