Programs & Examples On #Treemap

An implementation of a mapping (dictionary) using a tree. This tag is also used for treemapping, an information visualization method for displaying hierarchical data with nested rectangles.

Java TreeMap Comparator

You can not sort TreeMap on values.

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare on keys.

To provide sort on values you will need SortedSet. Use

SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
            new Comparator<Map.Entry<String, Double>>() {
                @Override
                public int compare(Map.Entry<String, Double> e1,
                        Map.Entry<String, Double> e2) {
                    return e1.getValue().compareTo(e2.getValue());
                }
            });

  sortedset.addAll(myMap.entrySet());

To give you an example

    SortedMap<String, Double> myMap = new TreeMap<String, Double>();
    myMap.put("a", 10.0);
    myMap.put("b", 9.0);
    myMap.put("c", 11.0);
    myMap.put("d", 2.0);
    sortedset.addAll(myMap.entrySet());
    System.out.println(sortedset);

Output:

  [d=2.0, b=9.0, a=10.0, c=11.0]

How to iterate over a TreeMap?

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
    }
    }

What are Makefile.am and Makefile.in?

Makefile.am is a programmer-defined file and is used by automake to generate the Makefile.in file (the .am stands for automake). The configure script typically seen in source tarballs will use the Makefile.in to generate a Makefile.

The configure script itself is generated from a programmer-defined file named either configure.ac or configure.in (deprecated). I prefer .ac (for autoconf) since it differentiates it from the generated Makefile.in files and that way I can have rules such as make dist-clean which runs rm -f *.in. Since it is a generated file, it is not typically stored in a revision system such as Git, SVN, Mercurial or CVS, rather the .ac file would be.

Read more on GNU Autotools. Read about make and Makefile first, then learn about automake, autoconf, libtool, etc.

Set today's date as default date in jQuery UI datepicker

You need to make the call to setDate separately from the initialization call. So to create the datepicker and set the date in one go:

$("#mydate").datepicker().datepicker("setDate", new Date());

Why it is like this I do not know. If anyone did, that would be interesting information.

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

Address already in use: JVM_Bind java

Is it possible that MySql listening on the same port as JBoss?

Is there a port number given in the error message - something like Address already in use: JVM_Bind:8080

You can change the port in JBoss server.xml to test this.

How do you read a file into a list in Python?

If you have multiple numbers per line and you have multiple lines, you can read them in like this:

    #!/usr/bin/env python

    from os.path import dirname

    with open(dirname(__file__) + '/data/path/filename.txt') as input_data:
        input_list= [map(int,num.split()) for num in input_data.readlines()]

"No X11 DISPLAY variable" - what does it mean?

you must enable X11 forwarding in you PuTTy

to do so open PuTTy, go to Connection => SSH => Tunnels and check mark the Enable X11 forwarding

Also sudo to server and export the below variable here IP is your local machine's IP

export DISPLAY=10.75.75.75:0.0

enter image description here

Get the short Git version hash

A simple way to see the Git commit short version and the Git commit message is:

git log --oneline

Note that this is shorthand for

git log --pretty=oneline --abbrev-commit

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

CSS: Center block, but align contents to the left

THIS works

<div style="display:inline-block;margin:10px auto;">
    <ul style="list-style-type:none;">
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>root keyword text box</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube.com website <em>video search text box</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>scraped keywords listbox</em>.</li>
        <li style="text-align:left;"><span class="red">?</span> YouTube AutoComplete Keyword Scraper software <em>right click context menu</em>.</li>
    </ul>
</div>

How to get a property value based on the name

Simple sample (without write reflection hard code in the client)

class Customer
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    // approach here
    public string GetPropertyValue(string propertyName)
    {
        try
        {
            return this.GetType().GetProperty(propertyName).GetValue(this, null) as string;
        }
        catch { return null; }
    }
}
//use sample
static void Main(string[] args)
    {
        var customer = new Customer { CustomerName = "Harvey Triana", Address = "Something..." };
        Console.WriteLine(customer.GetPropertyValue("CustomerName"));
    }

What is Scala's yield?

val aList = List( 1,2,3,4,5 )

val res3 = for ( al <- aList if al > 3 ) yield al + 1
val res4 = aList.filter(_ > 3).map(_ + 1)

println( res3 )
println( res4 )

These two pieces of code are equivalent.

val res3 = for (al <- aList) yield al + 1 > 3
val res4 = aList.map( _+ 1 > 3 )

println( res3 ) 
println( res4 )

These two pieces of code are also equivalent.

Map is as flexible as yield and vice-versa.

Method List in Visual Studio Code

It is an extra part to the answer to this question here but I thought it might be useful. As many people mentioned, Visual Studio Code has the OUTLINE part which provides the ability to browse to different function and show them on the side.

I also wanted to add that if you check the follow cursor mark, it highlights that function name in the OUTLINE view, which is very helpful in browsing and seeing which function you are in.

enter image description here

How do I rename the android package name?

If you want to rename full android package, this is the best way to do that:

  1. Mark as checked - Comapct Emty Middle Packages

  2. Right click on the packcage you want to change, and then Refactor->Rename->Rename all

You can find video tutorial on this link: https://www.youtube.com/watch?v=A-rITYZQj0A

Current timestamp as filename in Java

try this one

String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

regex pattern to match the end of a string

Something like this should work: /([^/]*)$

What language are you using? End-of-string regex signifiers can vary in different languages.

Getting NetworkCredential for current user (C#)

If the web service being invoked uses windows integrated security, creating a NetworkCredential from the current WindowsIdentity should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.

Edit: To get the credentials for the current identity, use the following:

Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");

Is it possible to specify the schema when connecting to postgres with JDBC?

Don't forget SET SCHEMA 'myschema' which you could use in a separate Statement

SET SCHEMA 'value' is an alias for SET search_path TO value. Only one schema can be specified using this syntax.

And since 9.4 and possibly earlier versions on the JDBC driver, there is support for the setSchema(String schemaName) method.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Make Enable32bit Application to TRUE in the IIS App pool which you are consuming

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

MrOBrian's answer shows why your current code doesn't work, with the missing trailing ] and quotes, but here's an easier way to make it work:

onchange='mySelectHandler(this)'

And then:

function mySelectHandler(el){
     var mySelect = $(el)
     // get selected value
     alert ("selected " + mySelect.val())
  }

Or better still, remove the inline event handler altogether and bind the event handler with jQuery:

$('select[name="a[b]"]').change(function() {
    var mySelect = $(this);
    alert("selected " mySelect.val());
});

That last would need to be in a document.ready handler or in a script block that appears after the select element. If you want to run the same function for other selects simply change the selector to something that applies to all, e.g., all selects would be $('select'), or all with a particular class would be $('select.someClass').

Simple example of threading in C++

Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in c++0x, which was just nailed down and hasn't yet been implemented. The problem is somewhat systemic, technically the existing c++ memory model isn't strict enough to allow for well defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the c++0x standard on the topic.

http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html

That said there are several cross-platform thread C++ libraries that work just fine in practice. Intel thread building blocks contains a tbb::thread object that closely approximates the c++0x standard and Boost has a boost::thread library that does the same.

http://www.threadingbuildingblocks.org/

http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

Using boost::thread you'd get something like:

#include <boost/thread.hpp>

void task1() { 
    // do stuff
}

void task2() { 
    // do stuff
}

int main (int argc, char ** argv) {
    using namespace boost; 
    thread thread_1 = thread(task1);
    thread thread_2 = thread(task2);

    // do other stuff
    thread_2.join();
    thread_1.join();
    return 0;
}

C++ unordered_map using a custom class type as the key

For enum type, I think this is a suitable way, and the difference between class is how to calculate hash value.

template <typename T>
struct EnumTypeHash {
  std::size_t operator()(const T& type) const {
    return static_cast<std::size_t>(type);
  }
};

enum MyEnum {};
class MyValue {};

std::unordered_map<MyEnum, MyValue, EnumTypeHash<MyEnum>> map_;

How to calculate an angle from three points?

I ran into a similar problem recently, only I needed to differentiate between a positive and negative angles. In case this is of use to anyone, I recommend the code snippet I grabbed from this mailing list about detecting rotation over a touch event for Android:

 @Override
 public boolean onTouchEvent(MotionEvent e) {
    float x = e.getX();
    float y = e.getY();
    switch (e.getAction()) {
    case MotionEvent.ACTION_MOVE:
       //find an approximate angle between them.

       float dx = x-cx;
       float dy = y-cy;
       double a=Math.atan2(dy,dx);

       float dpx= mPreviousX-cx;
       float dpy= mPreviousY-cy;
       double b=Math.atan2(dpy, dpx);

       double diff  = a-b;
       this.bearing -= Math.toDegrees(diff);
       this.invalidate();
    }
    mPreviousX = x;
    mPreviousY = y;
    return true;
 }

Select query with date condition

The semicolon character is used to terminate the SQL statement.

You can either use # signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME function CDATE(). As its name suggests, DATETIME always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.

Best not to use BETWEEN for DATETIME in Access: it's modelled using a floating point type and anyhow time is a continuum ;)

DATE and TABLE are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:

Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):

SELECT my_date
  FROM MyTable
 WHERE my_date >= #2008-09-01 00:00:00#
       AND my_date < #2010-09-01 00:00:00#;

Alternatively:

SELECT my_date
  FROM MyTable
 WHERE my_date >= CDate('2008-09-01 00:00:00')
       AND my_date < CDate('2010-09-01 00:00:00'); 

How to execute a command prompt command from python

Why do you want to call cmd.exe ? cmd.exe is a command line (shell). If you want to change directory, use os.chdir("C:\\"). Try not to call external commands if Python can provide it. In fact, most operating system commands are provide through the os module (and sys). I suggest you take a look at os module documentation to see the various methods available.

how to empty recyclebin through command prompt?

Yes, you can Make a Batch file with the following code:

cd \Desktop

echo $Shell = New-Object -ComObject Shell.Application >>FILENAME.ps1
echo $RecBin = $Shell.Namespace(0xA) >>FILENAME.ps1
echo $RecBin.Items() ^| %%{Remove-Item $_.Path -Recurse -Confirm:$false} >>FILENAME.ps1


REM The actual lines being writen are right, exept for the last one, the actual thigs being writen are "$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}"   
But since | and % screw things up, i had to make some changes.

Powershell.exe -executionpolicy remotesigned -File  C:\Desktop\FILENAME.ps1

This basically creates a powershell script that empties the trash in the \Desktop directory, then runs it.

Store query result in a variable using in PL/pgSQL

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided.

This works, too:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.

I shortened the syntax with a table alias additionally.
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel.

What is let-* in Angular 2 templates?

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

Templates (<template>, or <ng-template> since 4.x) are added as embedded views and get passed a context.

With let-col the context property $implicit is made available as col within the template for bindings. With let-foo="bar" the context property bar is made available as foo.

For example if you add a template

<ng-template #myTemplate let-col let-foo="bar">
  <div>{{col}}</div>
  <div>{{foo}}</div>
</ng-template>

<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
             [ngTemplateOutletContext]="{
                                           $implicit: 'some col value',
                                           bar: 'some bar value'
                                        }"
></ng-template>

See also this answer and ViewContainerRef#createEmbeddedView.

*ngFor also works this way. The canonical syntax makes this more obvious

<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
  <div>{{item}}</div>
</ng-template>

where NgFor adds the template as embedded view to the DOM for each item of items and adds a few values (item, index, odd) to the context.

See also Using $implict to pass multiple parameters

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

I had the same problem and I found that it is because of some characters in project path like [ or ] I correct the project path and it worked fine!

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How do I debug jquery AJAX calls?

Firebug as Firefox (FF) extension is currently (as per 01/2017) the only way to debug direct javascript responses from AJAX calls. Unfortunately, it's development is discontinued. And since Firefox 50, the Firebug also cannot be installed anymore due to compatability issues :-( They kind of emulated FF developer tools UI to recall Firebug UI in some way.

Unfortunatelly, FF native developer tools are not able to debug javascript returned directly by AJAX calls. Same applies to Chrome devel. tools.

I must have disabled upgrades of FF due to this issue, since I badly need to debug JS from XHR calls on current project. So not good news here - let's hope the feature to debug direct JS responses will be incorporated into FF/Chrome developer tools soon.

CSS body background image fixed to full screen even when zooming in/out

You can do quite a lot with plain css...the css property background-size can be set to a number of things as well as just cover as Ranjith pointed out.

The background-size: cover setting scales the image to cover the entire screen but may mean that some of the image is off screen if the aspect ratio of the screen and image are different.

A good alternative is background-size: contain which resizes the background image to fit the smaller of width and height, ensuring that the whole image is visible but may lead to letterboxing if the aspect ratios are different.

For example:

body {
      background: url(/images/bkgd.png) no-repeat rgb(30,30,30) fixed center center;
      background-size: contain;
     }

The other options that I find less useful are: background-size: length <widthpx> <heightpx> which sets the absolute size of the background image. background-size: percentage <width> <height> background image is a percentage of the window size. (see w3schools.com's page)

adding classpath in linux

Important difference between setting Classpath in Windows and Linux is path separator which is ";" (semi-colon) in Windows and ":" (colon) in Linux. Also %PATH% is used to represent value of existing path variable in Windows while ${PATH} is used for same purpose in Linux (in the bash shell). Here is the way to setup classpath in Linux:

export CLASSPATH=${CLASSPATH}:/new/path

but as such Classpath is very tricky and you may wonder why your program is not working even after setting correct Classpath. Things to note:

  1. -cp options overrides CLASSPATH environment variable.
  2. Classpath defined in Manifest file overrides both -cp and CLASSPATH envorinment variable.

Reference: How Classpath works in Java.

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

Hide div after a few seconds

Probably the easiest way is to use the timers plugin. http://plugins.jquery.com/project/timers and then call something like

$(this).oneTime(1000, function() {
    $("#something").hide();
  });

Remove element by id

It's what the DOM supports. Search that page for "remove" or "delete" and removeChild is the only one that removes a node.

Is it possible in Java to catch two exceptions in the same catch block?

http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.

 try {
     // your code
} catch (Exception1 | Exception2 ex) {
     // Handle 2 exceptions in Java 7
}

I'm making study cards, and this thread was helpful, just wanted to put in my two cents.

What is boilerplate code?

Joshua Bloch has a talk about API design that covers how bad ones make boilerplate code necessary. (Minute 46 for reference to boilerplate, listening to this today)

How do I upgrade to Python 3.6 with conda?

Creating a new environment will install python 3.6:

$ conda create --name 3point6 python=3.6
Fetching package metadata .......
Solving package specifications: ..........

Package plan for installation in environment /Users/dstansby/miniconda3/envs/3point6:

The following NEW packages will be INSTALLED:

    openssl:    1.0.2j-0     
    pip:        9.0.1-py36_1 
    python:     3.6.0-0      
    readline:   6.2-2        
    setuptools: 27.2.0-py36_0
    sqlite:     3.13.0-0     
    tk:         8.5.18-0     
    wheel:      0.29.0-py36_0
    xz:         5.2.2-1      
    zlib:       1.2.8-3 

What are type hints in Python 3.5?

Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int) doesn't result in an error until the next return... line:

class C1:
    def __init__(self):
        self.idn = 1
    def add(self, ic: int):
        return self.idn + ic

c1 = C1()
c1.add(2)

c1.add(c1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'

concatenate two database columns into one resultset column

Normal behaviour with NULL is that any operation including a NULL yields a NULL...

- 9 * NULL  = NULL  
- NULL + '' = NULL  
- etc  

To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..

SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1

Split comma-separated input box values into array in jquery, and loop through it

use js split() method to create an array

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentation says:

In the case of an array, the callback is passed an array index and a corresponding array value each time

$.each(keywords, function(i, keyword){
   console.log(keyword);
});

How do I read the first line of a file using cat?

You dont need any external command if you have bash v4+

< file.txt mapfile -n1 && echo ${MAPFILE[0]}

or if you really want cat

cat file.txt | mapfile -n1 && echo ${MAPFILE[0]}

:)

How to center cards in bootstrap 4?

Add the css for .card

.card {
        margin: 0 auto; /* Added */
        float: none; /* Added */
        margin-bottom: 10px; /* Added */
}

here is the pen

UPDATE: You can use the class .mx-auto available in bootstrap 4 to center cards.

How can I create a dynamically sized array of structs?

Another option for you is a linked list. You'll need to analyze how your program will use the data structure, if you don't need random access it could be faster than reallocating.

javascript - match string against the array of regular expressions

You can join all regular expressions into single one. This way the string is scanned only once. Even with a sligthly more complex regular expression.

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';


function matchInArray(str, expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )
    return str.match(fullExpr);

};


if (matchInArray(thisString, thisExpressions)) {
    console.log ("Match!!");
} 

In fact, even with this approach, if you need check the same expression set against multiple strings, this is a few suboptimal because you are building (and compiling) the same regular expression each time the function is called.

Better approach would be to use a function builder like this:

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray_builder(expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )   

    return function (str) {
        return str.match(fullExpr);

    };
};  

var matchInArray = matchInArray_builder(thisExpressions);

if (matchInArray(thisString)) {
    console.log ("Match!!");
} 

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}}" 

const char* concatenation

The C way:

char buf[100];
strcpy(buf, one);
strcat(buf, two);

The C++ way:

std::string buf(one);
buf.append(two);

The compile-time way:

#define one "hello "
#define two "world"
#define concat(first, second) first second

const char* buf = concat(one, two);

Java 8 lambda get and remove element from list

As others have suggested, this might be a use case for loops and iterables. In my opinion, this is the simplest approach. If you want to modify the list in-place, it cannot be considered "real" functional programming anyway. But you could use Collectors.partitioningBy() in order to get a new list with elements which satisfy your condition, and a new list of those which don't. Of course with this approach, if you have multiple elements satisfying the condition, all of those will be in that list and not only the first.

Adding images to an HTML document with javascript

This works:

var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)

Or using jQuery:

$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');

Why won't my PHP app send a 404 error?

If you want to show the server’s default 404 page, you can load it in a frame like this:

echo '<iframe src="/something-bogus" width="100%" height="100%" frameBorder="0" border="0" scrolling="no"></iframe>';

How to get an Android WakeLock to work?

WakeLock doesn't usually cause Reboot problems. There may be some other issues in your coding. WakeLock hogs battery heavily, if not released after usage.

WakeLock is an Inefficient way of keeping the screen on. Instead use the WindowManager to do the magic. The following one line will suffice the WakeLock. The WakeLock Permission is also needed for this to work. Also this code is more efficient than the wakeLock.

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

You need not relase the WakeLock Manually. This code will allow the Android System to handle the Lock Automatically. When your application is in the Foreground then WakeLock is held and else android System releases the Lock automatically.

Try this and post your comment...

What's the most elegant way to cap a number to a segment?

This expands the ternary option into if/else which minified is equivalent to the ternary option but doesn't sacrifice readability.

const clamp = (value, min, max) => {
  if (value < min) return min;
  if (value > max) return max;
  return value;
}

Minifies to 35b (or 43b if using function):

const clamp=(c,a,l)=>c<a?a:c>l?l:c;

Also, depending on what perf tooling or browser you use you get various outcomes of whether the Math based implementation or ternary based implementation is faster. In the case of roughly the same performance, I would opt for readability.

Convert string to nullable type (int, double, etc...)

There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/

This allows you to write very clean code like this:

string value = null;
int? x = value.ConvertOrDefault<int?>();

and also:

object obj = 1;  

string value = null;
int x = 5;
if (value.TryConvert(out x))
    Console.WriteLine("TryConvert example: " + x); 

bool boolean = "false".ConvertOrDefault<bool>();
bool? nullableBoolean = "".ConvertOrDefault<bool?>();
int integer = obj.ConvertOrDefault<int>();
int negativeInteger = "-12123".ConvertOrDefault<int>();
int? nullableInteger = value.ConvertOrDefault<int?>();
MyEnum enumValue = "SecondValue".ConvertOrDefault<MyEnum>();

MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault<MyObjectClassA>();

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

Find the day of a week

Use the lubridate package and function wday:

library(lubridate)
df$date <- as.Date(df$date)
wday(df$date, label=TRUE)
[1] Wed   Wed   Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat

Checking if a list of objects contains a property with a specific value

using System.Linq;    
list.Where(x=> x.Name == nameToExtract);

Edit: misread question (now all matches)

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

Checking if a number is a prime number in Python

This is the most efficient way to see if a number is prime, if you only have a few query. If you ask a lot of numbers if they are prime try Sieve of Eratosthenes.

import math

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False

    sqr = int(math.sqrt(n)) + 1

    for divisor in range(3, sqr, 2):
        if n % divisor == 0:
            return False
    return True

in python how do I convert a single digit number into a double digits string?

In Python 3.6 you can use so called f-strings. In my opinion this method is much clearer to read.

>>> f'{a:02d}'
'05'

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

setting the proxy address explicitly in web.config solved my problem

<system.net> 
    <defaultProxy> 
            <proxy usesystemdefault = "false" proxyaddress="http://address:port" bypassonlocal="false"/> 
    </defaultProxy> 
</system.net>

Resolving the “TCP error code 10060: A connection attempt failed…” while consuming a web service

Altering user-defined table types in SQL Server

As of my knowledge it is impossible to alter/modify a table type.You can create the type with a different name and then drop the old type and modify it to the new name

Credits to jkrajes

As per msdn, it is like 'The user-defined table type definition cannot be modified after it is created'.

How do I perform HTML decoding/encoding using Python/Django?

Below is a python function that uses module htmlentitydefs. It is not perfect. The version of htmlentitydefs that I have is incomplete and it assumes that all entities decode to one codepoint which is wrong for entities like &NotEqualTilde;:

http://www.w3.org/TR/html5/named-character-references.html

NotEqualTilde;     U+02242 U+00338    ??

With those caveats though, here's the code.

def decodeHtmlText(html):
    """
    Given a string of HTML that would parse to a single text node,
    return the text value of that node.
    """
    # Fast path for common case.
    if html.find("&") < 0: return html
    return re.sub(
        '&(?:#(?:x([0-9A-Fa-f]+)|([0-9]+))|([a-zA-Z0-9]+));',
        _decode_html_entity,
        html)

def _decode_html_entity(match):
    """
    Regex replacer that expects hex digits in group 1, or
    decimal digits in group 2, or a named entity in group 3.
    """
    hex_digits = match.group(1)  # '&#10;' -> unichr(10)
    if hex_digits: return unichr(int(hex_digits, 16))
    decimal_digits = match.group(2)  # '&#x10;' -> unichr(0x10)
    if decimal_digits: return unichr(int(decimal_digits, 10))
    name = match.group(3)  # name is 'lt' when '&lt;' was matched.
    if name:
        decoding = (htmlentitydefs.name2codepoint.get(name)
            # Treat &GT; like &gt;.
            # This is wrong for &Gt; and &Lt; which HTML5 adopted from MathML.
            # If htmlentitydefs included mappings for those entities,
            # then this code will magically work.
            or htmlentitydefs.name2codepoint.get(name.lower()))
        if decoding is not None: return unichr(decoding)
    return match.group(0)  # Treat "&noSuchEntity;" as "&noSuchEntity;"

AngularJS + JQuery : How to get dynamic content working in angularjs

Another Solution in Case You Don't Have Control Over Dynamic Content

This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).

Wrap up Your Content

Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.

<div class="selector">
    <grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>

Use Angular Injector

You can use the following code to get a reference to $compile if you don't have one.

$(".selector").each(function () {
    var content = $(this);
    angular.element(document).injector().invoke(function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    });
});

Summary

The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.

One Caveat of the previous code

If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.

Here is the way to remedy it:

Replace the prevous code snippet with the following overload.

...
angular.element(document).injector().invoke(
[
    "$compile", function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    }
]);
...

This caused a lot of grief for me before I pieced it together.

Does an HTTP Status code of 0 have any meaning?

Short Answer

It's not a HTTP response code, but it is documented by WhatWG as a valid value for the status attribute of an XMLHttpRequest or a Fetch response.

Broadly speaking, it is a default value used when there is no real HTTP status code to report and/or an error occurred sending the request or receiving the response. Possible scenarios where this is the case include, but are not limited to:

  • The request hasn't yet been sent, or was aborted.
  • The browser is still waiting to receive the response status and headers.
  • The connection dropped during the request.
  • The request timed out.
  • The request encountered an infinite redirect loop.
  • The browser knows the response status, but you're not allowed to access it due to security restrictions related to the Same-origin Policy.

Long Answer

First, to reiterate: 0 is not a HTTP status code. There's a complete list of them in RFC 7231 Section 6.1, that doesn't include 0, and the intro to section 6 states clearly that

The status-code element is a three-digit integer code

which 0 is not.

However, 0 as a value of the .status attribute of an XMLHttpRequest object is documented, although it's a little tricky to track down all the relevant details. We begin at https://xhr.spec.whatwg.org/#the-status-attribute, documenting the .status attribute, which simply states:

The status attribute must return the response’s status.

That may sound vacuous and tautological, but in reality there is information here! Remember that this documentation is talking here about the .response attribute of an XMLHttpRequest, not a response, so this tells us that the definition of the status on an XHR object is deferred to the definition of a response's status in the Fetch spec.

But what response object? What if we haven't actually received a response yet? The inline link on the word "response" takes us to https://xhr.spec.whatwg.org/#response, which explains:

An XMLHttpRequest has an associated response. Unless stated otherwise it is a network error.

So the response whose status we're getting is by default a network error. And by searching for everywhere the phrase "set response to" is used in the XHR spec, we can see that it's set in five places:

Looking in the Fetch standard, we can see that:

A network error is a response whose status is always 0

so we can immediately tell that we'll see a status of 0 on an XHR object in any of the cases where the XHR spec says the response should be set to a network error. (Interestingly, this includes the case where the body's stream gets "errored", which the Fetch spec tells us can happen during parsing the body after having received the status - so in theory I suppose it is possible for an XHR object to have its status set to 200, then encounter an out-of-memory error or something while receiving the body and so change its status back to 0.)

We also note in the Fetch standard that a couple of other response types exist whose status is defined to be 0, whose existence relates to cross-origin requests and the same-origin policy:

An opaque filtered response is a filtered response whose ... status is 0...

An opaque-redirect filtered response is a filtered response whose ... status is 0...

(various other details about these two response types omitted).

But beyond these, there are also many cases where the Fetch algorithm (rather than the XHR spec, which we've already looked at) calls for the browser to return a network error! Indeed, the phrase "return a network error" appears 40 times in the Fetch standard. I will not try to list all 40 here, but I note that they include:

  • The case where the request's scheme is unrecognised (e.g. trying to send a request to madeupscheme://foobar.com)
  • The wonderfully vague instruction "When in doubt, return a network error." in the algorithms for handling ftp:// and file:// URLs
  • Infinite redirects: "If request’s redirect count is twenty, return a network error."
  • A bunch of CORS-related issues, such as "If httpRequest’s response tainting is not "cors" and the cross-origin resource policy check with request and response returns blocked, then return a network error."
  • Connection failures: "If connection is failure, return a network error."

In other words: whenever something goes wrong other than getting a real HTTP error status code like a 500 or 400 from the server, you end up with a status attribute of 0 on your XHR object or Fetch response object in the browser. The number of possible specific causes enumerated in spec is vast.

Finally: if you're interested in the history of the spec for some reason, note that this answer was completely rewritten in 2020, and that you may be interested in the previous revision of this answer, which parsed essentially the same conclusions out of the older (and much simpler) W3 spec for XHR, before these were replaced by the more modern and more complicated WhatWG specs this answers refers to.

C++ Calling a function from another class

Here's my solution to the issue. Tried to keep it straight and simple.

#include <iostream>
using namespace std;

class Game{
public:
  void init(){
    cout << "Hi" << endl;
  }
}g;

class b : Game{  //class b uses/imports class Game
public:
  void h(){
    init(); //Use function from class Game
  }
}A;

int main()
{
  A.h();
  return 0;
}

Could not obtain information about Windows NT group user

We encountered similar errors in a testing environment on a virtual machine. If the machine name changes due to VM cloning from a template, you can get this error.

If the computer name changed from OLD to NEW.

A job uses this stored procedure:

msdb.dbo.sp_sqlagent_has_server_access @login_name = 'OLD\Administrator'

Which uses this one:

EXECUTE master.dbo.xp_logininfo 'OLD\Administrator'

Which gives this SQL error 15404

select text from sys.messages where message_id = 15404;
Could not obtain information about Windows NT group/user '%ls', error code %#lx.

Which I guess is correct, under the circumstances. We added a script to the VM cloning/deployment process that re-creates the SQL login.

Binding an enum to a WinForms combo box, and then setting it

To simplify:

First Initialize this command: (e.g. after InitalizeComponent())

yourComboBox.DataSource =  Enum.GetValues(typeof(YourEnum));

To retrieve selected item on combobox:

YourEnum enum = (YourEnum) yourComboBox.SelectedItem;

If you want to set value for the combobox:

yourComboBox.SelectedItem = YourEnem.Foo;

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Difference between objectForKey and valueForKey?

When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.

In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an @, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.

What's an object file in C?

An object file is just what you get when you compile one (or several) source file(s).

It can be either a fully completed executable or library, or intermediate files.

The object files typically contain native code, linker information, debugging symbols and so forth.

Input type DateTime - Value format?

That one shows up correctly as HTML5-Tag for those looking for this:

<input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Creating a triangle with for loops

I appreciate the OP is new to Java, so methods might be considered "advanced", however I think it's worth using this problem to show how you can attack a problem by breaking it into pieces.

Let's think about writing a method to print a single line, telling the method which number line it is:

public void printTriangleLine(int rowNumber) {
    // we have to work out what to put here
}

We have to print some number of spaces, then some number of stars.

Looking at the example, I can see that (if the first row is 0) it's (5-rowNumber) spaces and (2*rowNumber + 1) stars.

Let's invent a method that prints the rows of characters for us, and use it:

public void printTriangleLine(int rowNumber) {
    printSequence(" ", 5 - rowNumber);
    printSequence("*", 2 * rowNumber + 1);
    System.out.println(); 
}

That won't compile until we actually write printSequence(), so let's do that:

public void printSequence(String s, int repeats) {
    for(int i=0; i<repeats; i++) {
        System.out.print(s);
    }
}

Now you can test printSequence on its own, and you can test printTriangleLine on its own. For now you can just try it out by calling those methods directly in main()

public static void main(String [] args) {
    printSequence("a",3);
    System.out.println();
    printTriangleLine(2);
}

... run it and verify (with your eyes) that it outputs:

aaa
   *****

When you get further into programming, you'll want to use a unit testing framework like jUnit. Instead of printing, you'd more likely write things like printTriangleLine to return a String (which you'd print from higher up in your program), and you would automate your testing with commands like:

assertEquals("   *****", TriangleDrawer.triangleLine(2));
assertEquals("     *", TriangleDrawer.triangleLine(0))

Now we have the pieces we need to draw a triangle.

public void drawTriangle() {
    for(int i=0; i<5; i++) {
        printTriangleLine(i);
    }
}

The code we have written is a bit longer than the answers other people have given. But we have been able to test each step, and we have methods that we can use again in other problems. In real life, we have to find the right balance between breaking a problem into too many methods, or too few. I tend to prefer lots of really short methods.

For extra credit:

  • adapt this so that instead of printing to System.out, the methods return a String -- so in your main() you can use System.out.print(drawTriangle())
  • adapt this so that you can ask drawTriangle() for different sizes -- that is, you can call drawTriangle(3) or drawTriangle(5)
  • make it work for bigger triangles. Hint: you will need to add a new "width" parameter to printTriangleLine().

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

How do I recognize "#VALUE!" in Excel spreadsheets?

in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.

Allow only numeric value in textbox using Javascript

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

from here

Checking if a double (or float) is NaN in C++

A possible solution that would not depend on the specific IEEE representation for NaN used would be the following:

template<class T>
bool isnan( T f ) {
    T _nan =  (T)0.0/(T)0.0;
    return 0 == memcmp( (void*)&f, (void*)&_nan, sizeof(T) );
}

php random x digit number

do it with a loop:

function randomWithLength($length){

    $number = '';
    for ($i = 0; $i < $length; $i++){
        $number .= rand(0,9);
    }

    return (int)$number;

}

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

I solved it by putting this:

@Override
protected void onDestroy() {
    accessTokenTracker.stopTracking();
    super.onDestroy();
}

How to filter WooCommerce products by custom attribute

A plugin is probably your best option. Look in the wordpress plugins directory or google to see if you can find one. I found the one below and that seemed to work perfect.

https://wordpress.org/plugins/woocommerce-products-filter/

This one seems to do exactly what you are after

How to read a string one letter at a time in python

# Open the file
f = open('morseCode.txt', 'r')

# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
    if not Line.strip(): break
    letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
    letters.append((letter.lower(), code))
f.close()

# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ") 

# Convert the codes to morse code
out = []
for c in i:
    found = False
    for letter, code in letters:
        if letter == c.lower():
            found = True
            out.append(code)
            break

    if not found: 
        raise Exception('invalid character: %s' % c)

# Print the output
print ' '.join(out)

How to add anchor tags dynamically to a div in Javascript?

here's a pure Javascript alternative:

var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerText = "link text";
mydiv.appendChild(aTag);

QByteArray to QString

You may find QString::fromUtf8() also useful.

For QByteArray input of "\010" and "\000",

QString::fromLocal8Bit(input, 1) returns "\010" and ""

QString::fromUtf8(input, 1) correctly returns "\010" and "\000".

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

How to group an array of objects by key

There is absolutely no reason to download a 3rd party library to achieve this simple problem, like the above solutions suggest.

The one line version to group a list of objects by a certain key in es6:

const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})

The longer version that filters out the objects without the key:

_x000D_
_x000D_
function groupByKey(array, key) {
   return array
     .reduce((hash, obj) => {
       if(obj[key] === undefined) return hash; 
       return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
     }, {})
}


var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

console.log(groupByKey(cars, 'make'))
_x000D_
_x000D_
_x000D_

NOTE: It appear the original question asks how to group cars by make, but omit the make in each group. So the short answer, without 3rd party libraries, would look like this:

_x000D_
_x000D_
const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {})

var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

console.log(groupByKey(cars, 'make', {omitKey:true}))
_x000D_
_x000D_
_x000D_

Normalization in DOM parsing with java - how does it work?

The rest of the sentence is:

where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello 
wor
ld</foo>

could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"

When normalized, the node will look like this

Element foo
    Text node: "Hello world"

And the same goes for attributes: <foo bar="Hello world"/>, comments, etc.

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

Steps to send a https request to a rest service in Node js

just use the core https module with the https.request function. Example for a POST request (GET would be similar):

var https = require('https');

var options = {
  host: 'www.google.com',
  port: 443,
  path: '/upload',
  method: 'POST'
};

var req = https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

Questions every good PHP Developer should be able to answer

Why you should never output user input directly!

Printing things like data from GET directly can lead to Cross-site scripting (XSS) vulnerabilities. Thats why you should always send input from the client through htmlspecialchars() first.

jQuery change method on input type="file"

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });

update:

from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

Center/Set Zoom of Map to cover all visible Markers?

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

The activity must be exported or contain an intent-filter

just add intent-filter Tag inside your activity

for example ::

    <activity
        android:name=".activityName">
        <intent-filter>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Type of expression is ambiguous without more context Swift

This might not be very applicable to others, but my problem was that the changes I made was NOT saved yet! Press CMD + S and save your work before building on top of it.

Sorting a list with stream.sorted() in Java

This is not like Collections.sort() where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());

You've just missed to assign the result

How to select/get drop down option in Selenium 2

Take a look at the section about filling in forms using webdriver in the selenium documentation and the javadoc for the Select class.

To select an option based on the label:

Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");

To get the first selected value:

WebElement option = select.getFirstSelectedOption()

Using Selenium Web Driver to retrieve value of a HTML input

element.GetAttribute("value");

Eventhough if you don't see the "value" attribute in html dom, you will get the field value displayed on the GUI.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

submit a form in a new tab

Add target="_blank" to the <form> tag.

How do I get a reference to the app delegate in Swift?

Here's an extension for UIApplicationDelegate that avoids hardcoding the AppDelegate class name:

extension UIApplicationDelegate {

    static var shared: Self {    
        return UIApplication.shared.delegate! as! Self
    }
}

// use like this:
let appDelegate = MyAppDelegate.shared // will be of type MyAppDelegate

using c# .net libraries to check for IMAP messages from gmail servers

LumiSoft.ee - works great, fairly easy. Compiles with .NET 4.0.

Here are the required links to their lib and examples. Downloads Main:

http://www.lumisoft.ee/lsWWW/Download/Downloads/

Code Examples:

are located here: ...lsWWW/Download/Downloads/Examples/

.NET:

are located here: ...lsWWW/Download/Downloads/Net/

I am putting a SIMPLE sample up using their lib on codeplex (IMAPClientLumiSoft.codeplex.com). You must get their libraries directly from their site. I am not including them because I don't maintain their code nor do I have any rights to the code. Go to the links above and download it directly. I set LumiSoft project properties in my VS2010 to build all of it in .NET 4.0 which it did with no errors. Their samples are fairly complex and maybe even overly tight coding when just an example. Although I expect that these are aimed at advanced level developers in general.

Their project worked with minor tweaks. The tweaks: Their IMAP Client Winform example is set in the project properties as "Release" which prevents VS from breaking on debug points. You must use the solution "Configuration Manager" to set the project to "Active(Debug)" for breakpoints to work. Their examples use anonymous methods for event handlers which is great tight coding... not real good as a teaching tool. My project uses "named" event method handlers so you can set breakpoints inside the handlers. However theirs is an excellent way to handle inline code. They might have used the newer Lambda methods available since .NET 3.0 but did not and I didn't try to convert them.

From their samples I simplified the IMAP client to bare minimum.

How to delete rows in tables that contain foreign keys to other tables

First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

DELETE 
  FROM ReferencingTable 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM MainTable AS T1
                    WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                  );

Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

ALTER TABLE ReferencingTable ADD 
   CONSTRAINT fk__ReferencingTable__MainTable 
      FOREIGN KEY (pk_col_1)
      REFERENCES MainTable (pk_col_1)
      ON DELETE CASCADE;

Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

JavaScript replace/regex

You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

  "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")

Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

Why should I prefer to use member initialization lists?

Before the body of the constructor is run, all of the constructors for its parent class and then for its fields are invoked. By default, the no-argument constructors are invoked. Initialization lists allow you to choose which constructor is called and what arguments that constructor receives.

If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

How to find whether or not a variable is empty in Bash?

The question asks how to check if a variable is an empty string and the best answers are already given for that.

But I landed here after a period passed programming in PHP, and I was actually searching for a check like the empty function in PHP working in a Bash shell.

After reading the answers I realized I was not thinking properly in Bash, but anyhow in that moment a function like empty in PHP would have been soooo handy in my Bash code.

As I think this can happen to others, I decided to convert the PHP empty function in Bash.

According to the PHP manual:

a variable is considered empty if it doesn't exist or if its value is one of the following:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • an empty array
  • a variable declared, but without a value

Of course the null and false cases cannot be converted in bash, so they are omitted.

function empty
{
    local var="$1"

    # Return true if:
    # 1.    var is a null string ("" as empty string)
    # 2.    a non set variable is passed
    # 3.    a declared variable or array but without a value is passed
    # 4.    an empty array is passed
    if test -z "$var"
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is zero (0 as an integer or "0" as a string)
    elif [ "$var" == 0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is 0.0 (0 as a float)
    elif [ "$var" == 0.0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return
    fi

    [[ $( echo "" ) ]]
}



Example of usage:

if empty "${var}"
    then
        echo "empty"
    else
        echo "not empty"
fi



Demo:
The following snippet:

#!/bin/bash

vars=(
    ""
    0
    0.0
    "0"
    1
    "string"
    " "
)

for (( i=0; i<${#vars[@]}; i++ ))
do
    var="${vars[$i]}"

    if empty "${var}"
        then
            what="empty"
        else
            what="not empty"
    fi
    echo "VAR \"$var\" is $what"
done

exit

outputs:

VAR "" is empty
VAR "0" is empty
VAR "0.0" is empty
VAR "0" is empty
VAR "1" is not empty
VAR "string" is not empty
VAR " " is not empty

Having said that in a Bash logic the checks on zero in this function can cause side problems imho, anyone using this function should evaluate this risk and maybe decide to cut those checks off leaving only the first one.

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

Are there dictionaries in php?

No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array but would give an error if it was a dictionary.

print $array[0]

Python has both arrays and dictionaries.

Use custom build output folder when using create-react-app

Open Command Prompt inside your Application's source. Run the Command

npm run eject

Open your scripts/build.js file and add this at the beginning of the file after 'use strict' line

'use strict';
....
process.env.PUBLIC_URL = './' 
// Provide the current path
.....

enter image description here

Open your config/paths.js and modify the buildApp property in the exports object to your destination folder. (Here, I provide 'react-app-scss' as the destination folder)

module.exports = {
.....
appBuild: resolveApp('build/react-app-scss'),
.....
}

enter image description here

Run

npm run build

Note: Running Platform dependent scripts are not advisable

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Here is what I used to call something I couldn't change using NSInvocation:

SEL theSelector = NSSelectorFromString(@"setOrientation:animated:");
NSInvocation *anInvocation = [NSInvocation
            invocationWithMethodSignature:
            [MPMoviePlayerController instanceMethodSignatureForSelector:theSelector]];

[anInvocation setSelector:theSelector];
[anInvocation setTarget:theMovie];
UIInterfaceOrientation val = UIInterfaceOrientationPortrait;
BOOL anim = NO;
[anInvocation setArgument:&val atIndex:2];
[anInvocation setArgument:&anim atIndex:3];

[anInvocation performSelector:@selector(invoke) withObject:nil afterDelay:1];

Reading all files in a directory, store them in objects, and send the object

async/await

const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)

try {
  async function emitData(directory) {
    let filenames = await pathnames
    var ob = {}
    const data = filenames.map(async function(filename, i) {
      if (filename.includes(".")) {
        var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
          encoding: "utf8",
        })
        ob[filename.replace(".js", "")] = await storedFile
        socket.emit("init", { data: ob })
      }
      return ob
    })
  }

  emitData(directory)
} catch (err) {
  console.log(err)
}

Who wants to try with generators?

Vertically centering Bootstrap modal window

To make Modal verically Align Middle All dialog.

/* Note:

1.Even you don't need to assign selector , it will find all modal from the document and make it vertically middle

2.To avoid middle some specific modal to be it center you can use :not selector in click event

*/

 $( "[data-toggle='modal']" ).click(function(){
     var d_tar = $(this).attr('data-target'); 
     $(d_tar).show();   
     var modal_he = $(d_tar).find('.modal-dialog .modal-content').height(); 
     var win_height = $(window).height();
     var marr = win_height - modal_he;
     $('.modal-dialog').css('margin-top',marr/2);
  });

From Milan Pandya

ssh script returns 255 error

This error will also occur when using pdsh to hosts which are not contained in your "known_hosts" file.

I was able to correct this by SSH'ing into each host manually and accepting the question "Do you want to add this to known hosts".

How to send image to PHP file using Ajax?

Use JavaScript's formData API and set contentType and processData to false

$("form[name='uploader']").on("submit", function(ev) {
  ev.preventDefault(); // Prevent browser default submit.

  var formData = new FormData(this);
    
  $.ajax({
    url: "page.php",
    type: "POST",
    data: formData,
    success: function (msg) {
      alert(msg)
    },
    cache: false,
    contentType: false,
    processData: false
  });
    
});

MongoDB inserts float when trying to insert integer

Well, it's JavaScript, so what you have in 'value' is a Number, which can be an integer or a float. But there's not really a difference in JavaScript. From Learning JavaScript:

The Number Data Type

Number data types in JavaScript are floating-point numbers, but they may or may not have a fractional component. If they don’t have a decimal point or fractional component, they’re treated as integers—base-10 whole numbers in a range of –253 to 253.

How to avoid precompiled headers

Right click project solution

Properties -> Configuration Properties -> C/C++ -> Precompiled Headers

  1. Click on "Precompiled Headers" change to "Not Using Precompiled Headers".

  2. Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.

  3. Then you can feel free to delete the pch./stdafx. files in your project

Browser: Identifier X has already been declared

I had a very close issue but in my case, it was Identifier 'e' has already been declared.

In my case caused because of using try {} catch (e) { var e = ... } where letter e is generated via minifier (uglifier).

So better solution could be use catch(ex){} (ex as an Excemption)

Hope somebody who searched with the similar question could find this question helpful.

How do you post to an iframe?

An iframe is used to embed another document inside a html page.

If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.

Set the target attribute of the form to the name of the iframe tag.

<form action="action" method="post" target="output_frame">
    <!-- input elements here --> 
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>           

Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files

The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.

Exmaple

<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,                 
            open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });

function startUpload()
{            
    $("#uploadDialog").dialog("open");
}

function stopUpload()
{            
    $("#uploadDialog").dialog("close");
}
</script>

<div id="uploadDialog" title="Please Wait!!!">
            <center>
            <img src="/imagePath/loading.gif" width="100" height="100"/>
            <br/>
            Loading Details...
            </center>
 </div>

<FORM  ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()"> 
<!-- input file elements here--> 
</FORM>

<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">   
        </iframe>

Check whether $_POST-value is empty

isset is testing whether or not the key you are checking in the hash (or associative array) is "set". Set in this context just means if it knows the value. Nothing is a value. So it is defined as being an empty string.

For that reason, as long as you have an input field named userName, regardless of if they fill it in, this will be true. What you really want to do is check if the userName is equal to an empty string ''

Change a column type from Date to DateTime during ROR migration

In Rails 3.2 and Rails 4, Benjamin's popular answer has a slightly different syntax.

First in your terminal:

$ rails g migration change_date_format_in_my_table

Then in your migration file:

class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def up
   change_column :my_table, :my_column, :datetime
  end

  def down
   change_column :my_table, :my_column, :date
  end
end

HTML: Image won't display?

I confess to not having read the whole thread. However when I faced a similar issue I found that checking carefully the case of the file name and correcting that in the HTML reference fixed a similar issue. So local preview on Windows worked but when I published to my server (hosted Linux) I had to make sure "mugshot.jpg" was changed to "mugshot.JPG". Part of the problem is the defaults in Windows hiding full file names behind file type indications.

How is Pythons glob.glob ordered?

I had a similar issue, glob was returning a list of file names in an arbitrary order but I wanted to step through them in numerical order as indicated by the file name. This is how I achieved it:

My files were returned by glob something like:

myList = ["c:\tmp\x\123.csv", "c:\tmp\x\44.csv", "c:\tmp\x\101.csv", "c:\tmp\x\102.csv", "c:\tmp\x\12.csv"]

I sorted the list in place, to do this I created a function:

def sortKeyFunc(s):
    return int(os.path.basename(s)[:-4])

This function returns the numeric part of the file name and converts to an integer.I then called the sort method on the list as such:

myList.sort(key=sortKeyFunc)

This returned a list as such:

["c:\tmp\x\12.csv", "c:\tmp\x\44.csv", "c:\tmp\x\101.csv", "c:\tmp\x\102.csv", "c:\tmp\x\123.csv"]

What is the HTML5 equivalent to the align attribute in table cells?

You can use inline css :
<td style = "text-align: center;">

How to run docker-compose up -d at system start up?

I tried restart: always, it works at some containers(like php-fpm), but i faced the problem that some containers(like nginx) is still not restarting after reboot.

Solved the problem.

crontab -e

@reboot (sleep 30s ; cd directory_has_dockercomposeyml ; /usr/local/bin/docker-compose up -d )&

How to make a Div appear on top of everything else on the screen?

Try setting position to absolute, ie.

#yourDiv{
    position: absolute;
    z-index: 10;
};

.NET code to send ZPL to Zebra printers

VB Version (using port 9100 - tested on Zebra ZM400)

Sub PrintZPL(ByVal pIP As String, ByVal psZPL As String)
    Dim lAddress As Net.IPEndPoint
    Dim lSocket As System.Net.Sockets.Socket = Nothing
    Dim lNetStream As System.Net.Sockets.NetworkStream = Nothing
    Dim lBytes As Byte()

    Try
        lAddress = New Net.IPEndPoint(Net.IPAddress.Parse(pIP), 9100)
        lSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, _                       ProtocolType.Tcp)
        lSocket.Connect(lAddress)
        lNetStream = New NetworkStream(lSocket)

        lBytes = System.Text.Encoding.ASCII.GetBytes(psZPL)
        lNetStream.Write(lBytes, 0, lBytes.Length)
    Catch ex As Exception When Not App.Debugging
        Msgbox ex.message & vbnewline & ex.tostring
    Finally
        If Not lNetStream Is Nothing Then
            lNetStream.Close()
        End If
        If Not lSocket Is Nothing Then
            lSocket.Close()
        End If
    End Try
End Sub

How does setTimeout work in Node.JS?

setTimeout is a kind of Thread, it holds a operation for a given time and execute.

setTimeout(function,time_in_mills);

in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.

setTimeout(function(){console.log('your name')},3000);

Key point to remember is, what ever you want to do by using the setTimeout method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:

setTimeout(function(){yourOtherMethod(parameter);},3000);

Running multiple commands in one line in shell

You are using | (pipe) to direct the output of a command into another command. What you are looking for is && operator to execute the next command only if the previous one succeeded:

cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple

Or

cp /templates/apple /templates/used && mv /templates/apple /templates/inuse

To summarize (non-exhaustively) bash's command operators/separators:

  • | pipes (pipelines) the standard output (stdout) of one command into the standard input of another one. Note that stderr still goes into its default destination, whatever that happen to be.
  • |&pipes both stdout and stderr of one command into the standard input of another one. Very useful, available in bash version 4 and above.
  • && executes the right-hand command of && only if the previous one succeeded.
  • || executes the right-hand command of || only it the previous one failed.
  • ; executes the right-hand command of ; always regardless whether the previous command succeeded or failed. Unless set -e was previously invoked, which causes bash to fail on an error.

How to fix SSL certificate error when running Npm on Windows?

TL;DR - Just run this and don't disable your security:

Replace existing certs

# Windows/MacOS/Linux 
npm config set cafile "<path to your certificate file>"

# Check the 'cafile'
npm config get cafile

or extend existing certs

Set this environment variable to extend pre-defined certs: NODE_EXTRA_CA_CERTS to "<path to certificate file>"

Full story

I've had to work with npm, pip, maven etc. behind a corporate firewall under Windows - it's not fun. I'll try and keep this platform agnostic/aware where possible.

HTTP_PROXY & HTTPS_PROXY

HTTP_PROXY & HTTPS_PROXY are environment variables used by lots of software to know where your proxy is. Under Windows, lots of software also uses your OS specified proxy which is a totally different thing. That means you can have Chrome (which uses the proxy specified in your Internet Options) connecting to the URL just fine, but npm, pip, maven etc. not working because they use HTTPS_PROXY (except when they use HTTP_PROXY - see later). Normally the environment variable would look something like:

http://proxy.example.com:3128

But you're getting a 403 which suggests you're not being authenticated against your proxy. If it is basic authentication on the proxy, you'll want to set the environment variable to something of the form:

http://user:[email protected]:3128

The dreaded NTLM

There is an HTTP status code 407 (proxy authentication required), which is the more correct way of saying it's the proxy rather than the destination server that's rejecting your request. That code plagued me for the longest time until after a lot of time on Google, I learned my proxy used NTLM authentication. HTTP basic authentication wasn't enough to satisfy whatever proxy my corporate overlords had installed. I resorted to using Cntlm on my local machine (unauthenticated), then had it handle the NTLM authentication with the upstream proxy. Then I had to tell all the programs that couldn't do NTLM to use my local machine as the proxy - which is generally as simple as setting HTTP_PROXY and HTTPS_PROXY. Otherwise, for npm use (as @Agus suggests):

npm config set proxy http://proxy.example.com:3128
npm config set https-proxy http://proxy.example.com:3128

"We need to decrypt all HTTPS traffic because viruses"

After this set-up had been humming along (clunkily) for about a year, the corporate overlords decided to change the proxy. Not only that, but it would no longer use NTLM! A brave new world to be sure. But because those writers of malicious software were now delivering malware via HTTPS, the only way they could protect we poor innocent users was to man-in-the-middle every connection to scan for threats before they even reached us. As you can imagine, I was overcome with the feeling of safety.

To cut a long story short, the self-signed certificate needs to be installed into npm to avoid SELF_SIGNED_CERT_IN_CHAIN:

npm config set cafile "<path to certificate file>"

Alternatively, the NODE_EXTRA_CA_CERTS environment variable can be set to the certificate file.

I think that's everything I know about getting npm to work behind a proxy/firewall. May someone find it useful.

Edit: It's a really common suggestion to turn off HTTPS for this problem either by using an HTTP registry or setting NODE_TLS_REJECT_UNAUTHORIZED. These are not good ideas because you're opening yourself up to further man-in-the-middle or redirection attacks. A quick spoof of your DNS records on the machine doing the package installation and you'll find yourself trusting packages from anywhere. It may seem like a lot of work to make HTTPS work, but it is highly recommended. When you're the one responsible for allowing untrusted code into the company, you'll understand why.

Edit 2: Keep in mind that setting npm config set cafile <path> causes npm to only use the certs provided in that file, instead of extending the existing ones with it.

If you want to extend the existing certs (e.g. with a company cert) using the environment variable NODE_EXTRA_CA_CERTS to link to the file is the way to go and can save you a lot of hassle. See how-to-add-custom-certificate-authority-ca-to-nodejs

"getaddrinfo failed", what does that mean?

It most likely means the hostname can't be resolved.

import socket
socket.getaddrinfo('localhost', 8080)

If it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem.

How can I hide a TD tag using inline JavaScript or CSS?

What do you expect to happen in it's place? The table can't reflow to fill the space left - this seems like a recipe for buggy browser responses.

Think about hiding the contents of the td, not the td itself.

What is a "bundle" in an Android application

bundle is used to share data between activities , and to save state of app in oncreate() method so that app will come to know where it was stopped ... I hope it helps :)

Strange Jackson exception being thrown when serializing Hibernate object

I had the same problem. See if you are using hibernatesession.load(). If so, try converting to hibernatesession.get(). This solved my problem.

How to uninstall pip on OSX?

Aditionally to the answer from @srk, you should uninstall package setuptools:

python -m pip uninstall pip setuptools

If you want to uninstall all other packages first, this answer has some hints: https://stackoverflow.com/a/11250821/265954

Note: before you use the commands from that answer, please carefully read the comments about side effects and how to avoid uninstalling pip and setuptools too early. E.g. pip freeze | grep -v "^-e" | grep -v "^(setuptools|pip)" | xargs pip uninstall -y

Do fragments really need an empty constructor?

Yes they do.

You shouldn't really be overriding the constructor anyway. You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

For example:

public static final MyFragment newInstance(int title, String message) {
    MyFragment f = new MyFragment();
    Bundle bdl = new Bundle(2);
    bdl.putInt(EXTRA_TITLE, title);
    bdl.putString(EXTRA_MESSAGE, message);
    f.setArguments(bdl);
    return f;
}

And of course grabbing the args this way:

@Override
public void onCreate(Bundle savedInstanceState) {
    title = getArguments().getInt(EXTRA_TITLE);
    message = getArguments().getString(EXTRA_MESSAGE);

    //...
    //etc
    //...
}

Then you would instantiate from your fragment manager like so:

@Override
public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState == null){
        getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.content, MyFragment.newInstance(
                R.string.alert_title,
                "Oh no, an error occurred!")
            )
            .commit();
    }
}

This way if detached and re-attached the object state can be stored through the arguments. Much like bundles attached to Intents.

Reason - Extra reading

I thought I would explain why for people wondering why.

If you check: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/Fragment.java

You will see the instantiate(..) method in the Fragment class calls the newInstance method:

public static Fragment instantiate(Context context, String fname, @Nullable Bundle args) {
    try {
        Class<?> clazz = sClassMap.get(fname);
        if (clazz == null) {
            // Class not found in the cache, see if it's real, and try to add it
            clazz = context.getClassLoader().loadClass(fname);
            if (!Fragment.class.isAssignableFrom(clazz)) {
                throw new InstantiationException("Trying to instantiate a class " + fname
                        + " that is not a Fragment", new ClassCastException());
            }
            sClassMap.put(fname, clazz);
        }
        Fragment f = (Fragment) clazz.getConstructor().newInstance();
        if (args != null) {
            args.setClassLoader(f.getClass().getClassLoader());
            f.setArguments(args);
        }
        return f;
    } catch (ClassNotFoundException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (java.lang.InstantiationException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (IllegalAccessException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": make sure class name exists, is public, and has an"
                + " empty constructor that is public", e);
    } catch (NoSuchMethodException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": could not find Fragment constructor", e);
    } catch (InvocationTargetException e) {
        throw new InstantiationException("Unable to instantiate fragment " + fname
                + ": calling Fragment constructor caused an exception", e);
    }
}

http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance() Explains why, upon instantiation it checks that the accessor is public and that that class loader allows access to it.

It's a pretty nasty method all in all, but it allows the FragmentManger to kill and recreate Fragments with states. (The Android subsystem does similar things with Activities).

Example Class

I get asked a lot about calling newInstance. Do not confuse this with the class method. This whole class example should show the usage.

/**
 * Created by chris on 21/11/2013
 */
public class StationInfoAccessibilityFragment extends BaseFragment implements JourneyProviderListener {

    public static final StationInfoAccessibilityFragment newInstance(String crsCode) {
        StationInfoAccessibilityFragment fragment = new StationInfoAccessibilityFragment();

        final Bundle args = new Bundle(1);
        args.putString(EXTRA_CRS_CODE, crsCode);
        fragment.setArguments(args);

        return fragment;
    }

    // Views
    LinearLayout mLinearLayout;

    /**
     * Layout Inflater
     */
    private LayoutInflater mInflater;
    /**
     * Station Crs Code
     */
    private String mCrsCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCrsCode = getArguments().getString(EXTRA_CRS_CODE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mInflater = inflater;
        return inflater.inflate(R.layout.fragment_station_accessibility, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLinearLayout = (LinearLayout)view.findViewBy(R.id.station_info_accessibility_linear);
        //Do stuff
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().getSupportActionBar().setTitle(R.string.station_info_access_mobility_title);
    }

    // Other methods etc...
}

Global Git ignore

  1. Create a .gitignore file in your home directory
touch ~/.gitignore
  1. Add files to it (folders aren't recognised)

Example

# these work
*.gz
*.tmproj
*.7z

# these won't as they are folders
.vscode/
build/

# but you can do this
.vscode/*
build/*
  1. Check if a git already has a global gitignore
git config --get core.excludesfile
  1. Tell git where the file is
git config --global core.excludesfile '~/.gitignore'

Voila!!

Sleep for milliseconds

To stay portable you could use Boost::Thread for sleeping:

#include <boost/thread/thread.hpp>

int main()
{
    //waits 2 seconds
    boost::this_thread::sleep( boost::posix_time::seconds(1) );
    boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );

    return 0;
}

This answer is a duplicate and has been posted in this question before. Perhaps you could find some usable answers there too.

CSS Selector "(A or B) and C"?

If you have this:

<div class="a x">Foo</div>
<div class="b x">Bar</div>
<div class="c x">Baz</div>

And you only want to select the elements which have .x and (.a or .b), you could write:

.x:not(.c) { ... }

but that's convenient only when you have three "sub-classes" and you want to select two of them.

Selecting only one sub-class (for instance .a): .a.x

Selecting two sub-classes (for instance .a and .b): .x:not(.c)

Selecting all three sub-classes: .x

Pretty-Print JSON in Java

Underscore-java has static method U.formatJson(json). Five format types are supported: 2, 3, 4, tabs and compact. I am the maintainer of the project. Live example

import com.github.underscore.lodash.U;

import static com.github.underscore.lodash.Json.JsonStringBuilder.Step.TABS;
import static com.github.underscore.lodash.Json.JsonStringBuilder.Step.TWO_SPACES;

public class MyClass {

    public static void main(String args[]) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.formatJson(json, TWO_SPACES)); 
        System.out.println(U.formatJson(json, TABS)); 
    }
}

Output:

{
  "Price": {
    "LineItems": {
      "LineItem": {
        "UnitOfMeasure": "EACH",
        "Quantity": 2,
        "ItemID": "ItemID"
      }
    },
    "Currency": "USD",
    "EnterpriseCode": "EnterpriseCode"
  }
}
{
    "Price": {
        "LineItems": {
            "LineItem": {
                "UnitOfMeasure": "EACH",
                "Quantity": 2,
                "ItemID": "ItemID"
            }
        },
        "Currency": "USD",
        "EnterpriseCode": "EnterpriseCode"
    }
}    

How do you make Git work with IntelliJ?

git.exe is common for any git based applications like GitHub, Bitbucket etc. Some times it is possible that you have already installed another git based application so git.exe will be present in the bin folder of that application.

For example if you installed bitbucket before github in your PC, you will find git.exe in C:\Users\{username}\AppData\Local\Atlassian\SourceTree\git_local\bin instead of C:\Users\{username}\AppData\Local\GitHub\PortableGit.....\bin.

JavaScript, get date of the next day

Copy-pasted from here: Incrementing a date in JavaScript

Three options for you:

Using just JavaScript's Date object (no libraries):

var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));

Or if you don't mind changing the date in place (rather than creating a new date):

var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));

Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);

Using MomentJS:

var today = moment();
var tomorrow = moment(today).add(1, 'days');

(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)

Using DateJS, but it hasn't been updated in a long time:

var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

The preferred way of creating a new element with jQuery

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

Laravel Eloquent LEFT JOIN WHERE NULL

You can also specify the columns in a select like so:

$c = Customer::select('*', DB::raw('customers.id AS id, customers.first_name AS first_name, customers.last_name AS last_name'))
->leftJoin('orders', function($join) {
  $join->on('customers.id', '=', 'orders.customer_id') 
})->whereNull('orders.customer_id')->first();

click command in selenium webdriver does not work

This is a long standing issue with chromedriver(still present in 2020).

In Chrome I changed from a zoom of 90% to 100% and that solved the problem. ref

I find TheLifeOfSteve's answer more reliable.

Mysql Compare two datetime fields

Do you want to order it?

Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;

Extract the first (or last) n characters of a string

Make it simple and use R basic functions:

# To get the LEFT part:
> substr(a, 1, 4)
[1] "left"
> 
# To get the MIDDLE part:
> substr(a, 3, 7)
[1] "ftrig"
> 
# To get the RIGHT part:
> substr(a, 5, 10)
[1] "right"

The substr() function tells you where start and stop substr(x, start, stop)

Loading PictureBox Image from resource file with path (Part 3)

The path should be something like: "Images\a.bmp". (Note the lack of a leading slash, and the slashes being back slashes.)

And then:

pictureBox1.Image = Image.FromFile(@"Images\a.bmp");

I just tried it to make sure, and it works. This is besides the other answer that you got - to "copy always".

How can I find non-ASCII characters in MySQL?

You can define ASCII as all characters that have a decimal value of 0 - 127 (0x00 - 0x7F) and find columns with non-ASCII characters using the following query

SELECT * FROM TABLE WHERE NOT HEX(COLUMN) REGEXP '^([0-7][0-9A-F])*$';

This was the most comprehensive query I could come up with.

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

C compiling - "undefined reference to"?

Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.

JSON post to Spring Controller

Convert your JSON object to JSON String using

JSON.stringify({"name":"testName"})

or manually. @RequestBody expecting json string instead of json object.

Note:stringify function having issue with some IE version, firefox it will work

verify the syntax of your ajax request for POST request. processData:false property is required in ajax request

$.ajax({ 
    url:urlName,
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser  
     processData:false, //To avoid making query String instead of JSON
     success: function(resposeJsonObject){
        // Success Action
    }
});

Controller

@RequestMapping(value = urlPattern , method = RequestMethod.POST)

public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {

    //do business logic
    return test;
}

@RequestBody -Covert Json object to java

@ResponseBody - convert Java object to json

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value. NODE_ENV specifically is used (by convention) to state whether a particular environment is a production or a development environment. A common use-case is running additional debugging or logging code if running in a development environment.

Accessing NODE_ENV

You can use the following code to access the environment variable yourself so that you can perform your own checks and logic:

var environment = process.env.NODE_ENV

Assume production if you don't recognise the value:

var isDevelopment = environment === 'development'

if (isDevelopment) {
  setUpMoreVerboseLogging()
}

You can alternatively using express' app.get('env') function, but note that this is NOT RECOMMENDED as it defaults to "development", which may result in development code being accidentally run in a production environment - it's much safer if your app throws an error if this important value is not set (or if preferred, defaults to production logic as above).

Be aware that if you haven't explicitly set NODE_ENV for your environment, it will be undefined if you access it from process.env, there is no default.

Setting NODE_ENV

How to actually set the environment variable varies from operating system to operating system, and also depends on your user setup.

If you want to set the environment variable as a one-off, you can do so from the command line:

  • linux & mac: export NODE_ENV=production
  • windows: $env:NODE_ENV = 'production'

In the long term, you should persist this so that it isn't unset if you reboot - rather than list all the possible methods to do this, I'll let you search how to do that yourself!

Convention has dictated that there are two 'main' values you should use for NODE_ENV, either production or development, all lowercase. There's nothing to stop you from using other values, (test, for example, if you wish to use some different logic when running automated tests), but be aware that if you are using third-party modules, they may explicitly compare with 'production' or 'development' to determine what to do, so there may be side effects that aren't immediately obvious.

Finally, note that it's a really bad idea to try to set NODE_ENV from within a node application itself - if you do, it will only be applied to the process from which it was set, so things probably won't work like you'd expect them to. Don't do it - you'll regret it.

How to read an external properties file in Maven

This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).

The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.

Check if element is visible in DOM

This is a way to determine it for all css properties including visibility:

html:

<div id="element">div content</div>

css:

#element
{
visibility:hidden;
}

javascript:

var element = document.getElementById('element');
 if(element.style.visibility == 'hidden'){
alert('hidden');
}
else
{
alert('visible');
}

It works for any css property and is very versatile and reliable.

Adding System.Web.Script reference in class library

The ScriptIgnoreAttribute class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.

You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.

Maven dependencies are failing with a 501 error

This error occured to me too. I did what Muhammad umer said above. But, it only solved error for spring-boot-dependencies and spring-boot-dependencies has child dependencies. Now, there were 21 errors. Previously, it was 2 errors. Like this:

Non-resolvable import POM: Could not transfer artifact org.springframework.cloud:spring-cloud-dependencies:pom:Hoxton.SR3 from/to central

and also https required in the error message.

I updated the maven version from 3.2.2 to 3.6.3 and java version from 8 to 11. Now, all errors of https required are gone.

To update maven version

  1. Download latest maven from here: download maven
  2. Unzip and move it to /opt/maven/
  3. Set the path export PATH=$PATH:/opt/maven/bin
  4. And, also remove old maven from PATH

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

A bit late, but try this one.

function Set-Files($Path) {
    if(Test-Path $Path -PathType Leaf) {
        # Do any logic on file
        Write-Host $Path
        return
    }

    if(Test-Path $path -PathType Container) {
        # Do any logic on folder use exclude on get-childitem
        # cycle again
        Get-ChildItem -Path $path | foreach { Set-Files -Path $_.FullName }
    }
}

# call
Set-Files -Path 'D:\myFolder'

Password encryption/decryption code in .NET

 string clearText = txtPassword.Text;
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }

Tab separated values in awk

You need to set the OFS variable (output field separator) to be a tab:

echo "$line" | 
awk -v var="$mycol_new" -F $'\t' 'BEGIN {OFS = FS} {$3 = var; print}'

(make sure you quote the $line variable in the echo statement)

editing PATH variable on mac

environment.plst file loads first on MAC so put the path on it.

For 1st time use, use the following command

export PATH=$PATH: /path/to/set

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

URLs use forward slashes (/), not backward ones (as windows). Try:

serverURLS = "https://abc.my.domain.com:55555/update";

The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host is null.

How would you do a "not in" query with LINQ?

 DynamicWebsiteEntities db = new DynamicWebsiteEntities();
    var data = (from dt_sub in db.Subjects_Details
                                //Sub Query - 1
                            let sub_s_g = (from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId)
                            //Where Cause
                            where !sub_s_g.Contains(dt_sub.Id) && dt_sub.IsLanguage == false
                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)
                           .AsEnumerable();
                  
                                SelectList multiSelect = new SelectList(data, "Id", "Subject_Name", selectedValue);

    //======================================OR===========================================

    var data = (from dt_sub in db.Subjects_Details

                               
                            //Where Cause
                            where !(from sg in db.Subjects_In_Group
                                           where sg.GroupId == groupId
                                           select sg.SubjectId).Contains(dt_sub.Id) && dt_sub.IsLanguage == false

                            //Order By Cause
                            orderby dt_sub.Subject_Name

                            select dt_sub)

                           .AsEnumerable();

Printing Mongo query output to a file while in the mongo shell

We can do it this way -

mongo db_name --quiet --eval 'DBQuery.shellBatchSize = 2000; db.users.find({}).limit(2000).toArray()' > users.json

The shellBatchSize argument is used to determine how many rows is the mongo client allowed to print. Its default value is 20.

How to get the current time in Google spreadsheet using script editor?

Anyone who says that getting the current time in Google Sheets is not unique to Google's scripting environment obviously has never used Google Apps Script.

That being said, do you want to return current time as to what? The script user's timezone? The script owner's timezone?

The script timezone is set in the Script Editor, by the script owner. But different authorized users of the script can set timezone for the spreadsheet they are using from File/Spreadsheet settings menu of Google Sheets.

I guess you want the first option. You can use the built in function to get the spreadsheet timezone, and then use the Utilities class to format date.

var timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();

var date = Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE, d MMM yyyy HH:mm")

Alternatively, get the timezone offset from UTC time using Javascript's date method, format the timezone, and pass it into Utilities.formatDate().

This requires one minor adjustment though. The offset returned by getTimezoneOffset() runs contradictory to how we often think of timezone. If the offset is positive, the local timezone is behind UTC, like US timezones. If the offset is negative, the local timezone is ahead UTC, like Asia/Bangkok, Australian Eastern Standard Time etc.

const now = new Date();
// getTimezoneOffset returns the offset in minutes, so we have to divide it by 60 to get the hour offset.
const offset = now.getTimezoneOffset() / 60
// Change the sign of the offset and format it
const timeZone = "GMT+" + offset * (-1) 
Logger.log(Utilities.formatDate(now, timeZone, 'EEE, d MMM yyyy HH:mm');

How to add number of days to today's date?

If the times in the Date are not needed, then you can simply use the date object's methods to extract the Month,Year and Day and add "n" number of days to the Day part.

var n=5; //number of days to add. 
var today=new Date(); //Today's Date
var requiredDate=new Date(today.getFullYear(),today.getMonth(),today.getDate()+n)

Ref:Mozilla Javascript GetDate

Edit: Ref: Mozilla JavaScript Date

SQL Server PRINT SELECT (Print a select query result)?

If you want to print multiple rows, you can iterate through the result by using a cursor. e.g. print all names from sys.database_principals

DECLARE @name nvarchar(128)

DECLARE cur CURSOR FOR
SELECT name FROM sys.database_principals

OPEN cur

FETCH NEXT FROM cur INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN   
PRINT @name
FETCH NEXT FROM cur INTO @name;
END

CLOSE cur;
DEALLOCATE cur;

Illegal mix of collations MySQL Error

I found that using cast() was the best solution for me:

cast(Format(amount, "Standard") AS CHAR CHARACTER SET utf8) AS Amount

There is also a convert() function. More details on it here

Another resource here

Connecting to SQL Server using windows authentication

Just replace the first line with the below;

SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");

Regards.

Recursively looping through an object to build a property list

You can use a recursive Object.keys to achieve that.

var keys = []

const findKeys = (object, prevKey = '') => {
  Object.keys(object).forEach((key) => {
    const nestedKey = prevKey === '' ? key : `${prevKey}.${key}`

    if (typeof object[key] !== 'object') return keys.push(nestedKey)

    findKeys(object[key], nestedKey)
  })
}

findKeys(object)

console.log(keys)

Which results in this array

[
  "aProperty.aSetting1",
  "aProperty.aSetting2",
  "aProperty.aSetting3",
  "aProperty.aSetting4",
  "aProperty.aSetting5",
  "bProperty.bSetting1.bPropertySubSetting",
  "bProperty.bSetting2",
  "cProperty.cSetting"
]

To test, you can provide your object:

object = {
  aProperty: {
    aSetting1: 1,
    aSetting2: 2,
    aSetting3: 3,
    aSetting4: 4,
    aSetting5: 5
  },
  bProperty: {
    bSetting1: {
      bPropertySubSetting: true
    },
    bSetting2: "bString"
  },
  cProperty: {
    cSetting: "cString"
  }
}

How to center a subview of UIView

You can use

yourView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds))

And In Swift 3.0

yourView.center = CGPoint(x: superview.bounds.midX, y: superview.bounds.midY)

React Native Border Radius with background color

Remember if you want to give Text a backgroundcolor and then also borderRadius in that case also write overflow:'hidden' your text having a background colour will also get the radius otherwise it's impossible to achieve until unless you wrap it with View and give backgroundcolor and radius to it.

<Text style={{ backgroundColor: 'black', color:'white', borderRadius:10, overflow:'hidden'}}>Dummy</Text>

Ping all addresses in network, windows

Open the Command Prompt and type in the following:

FOR /L %i IN (1,1,254) DO ping -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt

Change 192.168.10 to match you own network.

By using -n 1 you are asking for only 1 packet to be sent to each computer instead of the usual 4 packets.

The above command will ping all IP Addresses on the 192.168.10.0 network and create a text document in the C:\ drive called ipaddresses.txt. This text document should only contain IP Addresses that replied to the ping request.

Although it will take quite a bit longer to complete, you can also resolve the IP Addresses to HOST names by simply adding -a to the ping command.

FOR /L %i IN (1,1,254) DO ping -a -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt

This is from Here

Hope this helps

Fatal error: Class 'SoapClient' not found

For PHP 8:

sudo apt update
sudo apt-get install php8.0-soap

How to select the first row for each group in MySQL?

Why not use MySQL LIMIT keyword?

SELECT [t2].[AnotherColumn], [t2].[SomeColumn]
FROM [Table] AS [t2]
WHERE (([t1].[SomeColumn] IS NULL) AND ([t2].[SomeColumn] IS NULL))
  OR (([t1].[SomeColumn] IS NOT NULL) AND ([t2].[SomeColumn] IS NOT NULL)
    AND ([t1].[SomeColumn] = [t2].[SomeColumn]))
ORDER BY [t2].[AnotherColumn]
LIMIT 1

Formatting doubles for output in C#

Use

Console.WriteLine(String.Format("  {0:G17}", i));

That will give you all the 17 digits it have. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. {0:R} will not always give you 17 digits, it will give 15 if the number can be represented with that precision.

which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision. There isn't any thing you can to do to make the the double return more digits that is the way it's implemented. If you don't like it do a new double class yourself...

.NET's double cant store any more digits than 17 so you cant see 6.89999999999999946709 in the debugger you would see 6.8999999999999995. Please provide an image to prove us wrong.

JavaScript property access: dot notation vs. brackets?

The two most common ways to access properties in JavaScript are with a dot and with square brackets. Both value.x and value[x] access a property on value—but not necessarily the same property. The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.

So if you know that the property you are interested in is called “length”, you say value.length. If you want to extract the property named by the value held in the variable i, you say value[i]. And because property names can be any string, if you want to access a property named “2” or “John Doe”, you must use square brackets: value[2] or value["John Doe"]. This is the case even though you know the precise name of the property in advance, because neither “2” nor “John Doe” is a valid variable name and so cannot be accessed through dot notation.

In case of Arrays

The elements in an array are stored in properties. Because the names of these properties are numbers and we often need to get their name from a variable, we have to use the bracket syntax to access them. The length property of an array tells us how many elements it contains. This property name is a valid variable name, and we know its name in advance, so to find the length of an array, you typically write array.length because that is easier to write than array["length"].

Importing modules from parent folder

Our folder structure:

/myproject
  project_using_ptdraft/
    main.py
  ptdraft/
    __init__.py
    nib.py
    simulations/
      __init__.py
      life/
        __init__.py
        life.py

The way I understand this is to have a package-centric view. The package root is ptdraft, since it's the top most level that contains __init__.py

All the files within the package can use absolute paths (that are relative to package root) for imports, for example in life.py, we have simply:

import ptdraft.nib

However, to run life.py for package dev/testing purposes, instead of python life.py, we need to use:

cd /myproject
python -m ptdraft.simulations.life.life

Note that we didn't need to fiddle with any path at all at this point.


Further confusion is when we complete the ptdraft package, and we want to use it in a driver script, which is necessarily outside of the ptdraft package folder, aka project_using_ptdraft/main.py, we would need to fiddle with paths:

import sys
sys.path.append("/myproject")  # folder that contains ptdraft
import ptdraft
import ptdraft.simulations

and use python main.py to run the script without problem.

Helpful links:

How to obtain the total numbers of rows from a CSV file in Python?

I think we can improve the best answer a little bit, I'm using:

len = sum(1 for _ in reader)

Moreover, we shouldnt forget pythonic code not always have the best performance in the project. In example: If we can do more operations at the same time in the same data set Its better to do all in the same bucle instead make two or more pythonic bucles.

Removing the password from a VBA project

I found another way to solve this one to avoid password of VBA Project,with out loosing excel password.

use Hex-editor XVI32 for the process

if the file type is XLSM files:

  1. Open the XLSM file with 7-Zip (right click -> 7-Zip -> Open archive).
  2. Copy the xl/vbaProject.bin file out of the file (you can drag and drop from 7-Zip), don't close 7-Zip
  3. Open the vbaProject.bin file with HexEdit
  4. Search for "DPB=" and replace it with "DPx="
  5. Save the file
  6. Copy this file back into 7-Zip (again, drag and drop works)
  7. Open the XLSX file in Excel, if prompted to "Continue Loading Project", click Yes. If prompted with errors, click OK.
  8. Press Alt+ F11 to open the VBA editor.
  9. While press it will show error “Unexpected error (40230)”, just click OK (6 or 7 times) until it goes away.
  10. Then it will open Automatically

How can I remove a button or make it invisible in Android?

button.setVisibility(button.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);

Makes it visible if invisible and invisible if visible

Bootstrap collapse animation not smooth

I think there can be several situations that cause the jerking. In my example, the issue deals with bottom margin on the non-animated child (even though the animated parent has no margin / padding). When removing the margin, the animation becomes smooth.

<div class="form-group">
    <a for="collapseJerky" data-toggle="collapse" href="#collapseJerky" aria-expanded="true" aria-controls="collapseJerky">+ Jerky</a>
    <div class="collapse" id="collapseJerky" style="margin:0; padding: 0;">
        <textarea class="form-control" rows="4" style="margin-bottom: 20px;">No margin or padding on animated element. Margin on child.</textarea>
    </div>
</div>
<div class="form-group">
    <a data-toggle="collapse" href="#collapseNotJerky" aria-expanded="true" aria-controls="collapseNotJerky">+ Not Jerky</a>
    <div class="collapse" id="collapseNotJerky" style="margin:0 padding: 0;">
        <textarea class="form-control" rows="4" style="margin-bottom: 0;">No margin or padding on animated element or on child.</textarea>
    </div>
</div>
<p>
    Moles and trolls, moles and trolls, work, work, work, work, work. We never see the light of day. This is just content below the "Not Jerky" to show that the animation is smooth.
</p>

Fiddle

How to simulate browsing from various locations?

Sometimes a website doesn't work on my PC and I want to know if it's the website or a problem local to me(e.g. my ISP, my router, etc).

The simplest way to check a website and avoid using your local network resources(and thus avoid any problems caused by them) is using a web proxy such as Proxy.org.

How to use comparison and ' if not' in python?

Operator precedence in python
You can see that not X has higher precedence than and. Which means that the not only apply to the first part (u0 <= u). Write:

if not (u0 <= u and u < u0+step):  

or even

if not (u0 <= u < u0+step):  

How to create a date object from string in javascript

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

Then,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

What are the basic rules and idioms for operator overloading?

The General Syntax of operator overloading in C++

You cannot change the meaning of operators for built-in types in C++, operators can only be overloaded for user-defined types1. That is, at least one of the operands has to be of a user-defined type. As with other overloaded functions, operators can be overloaded for a certain set of parameters only once.

Not all operators can be overloaded in C++. Among the operators that cannot be overloaded are: . :: sizeof typeid .* and the only ternary operator in C++, ?:

Among the operators that can be overloaded in C++ are these:

  • arithmetic operators: + - * / % and += -= *= /= %= (all binary infix); + - (unary prefix); ++ -- (unary prefix and postfix)
  • bit manipulation: & | ^ << >> and &= |= ^= <<= >>= (all binary infix); ~ (unary prefix)
  • boolean algebra: == != < > <= >= || && (all binary infix); ! (unary prefix)
  • memory management: new new[] delete delete[]
  • implicit conversion operators
  • miscellany: = [] -> ->* , (all binary infix); * & (all unary prefix) () (function call, n-ary infix)

However, the fact that you can overload all of these does not mean you should do so. See the basic rules of operator overloading.

In C++, operators are overloaded in the form of functions with special names. As with other functions, overloaded operators can generally be implemented either as a member function of their left operand's type or as non-member functions. Whether you are free to choose or bound to use either one depends on several criteria.2 A unary operator @3, applied to an object x, is invoked either as operator@(x) or as x.operator@(). A binary infix operator @, applied to the objects x and y, is called either as operator@(x,y) or as x.operator@(y).4

Operators that are implemented as non-member functions are sometimes friend of their operand’s type.

1 The term “user-defined” might be slightly misleading. C++ makes the distinction between built-in types and user-defined types. To the former belong for example int, char, and double; to the latter belong all struct, class, union, and enum types, including those from the standard library, even though they are not, as such, defined by users.

2 This is covered in a later part of this FAQ.

3 The @ is not a valid operator in C++ which is why I use it as a placeholder.

4 The only ternary operator in C++ cannot be overloaded and the only n-ary operator must always be implemented as a member function.


Continue to The Three Basic Rules of Operator Overloading in C++.

What is the difference between .text, .value, and .value2?

Except first answer form Bathsheba, except MSDN information for:

.Value
.Value2
.Text

you could analyse these tables for better understanding of differences between analysed properties.

enter image description here

javascript cell number validation

function IsMobileNumber(txtMobId) {
    var mob = /^[1-9]{1}[0-9]{9}$/;
    var txtMobile = document.getElementById(txtMobId);
    if (mob.test(txtMobile.value) == false) {
        alert("Please enter valid mobile number.");
        txtMobile.focus();
        return false;
    }
    return true;
}

Calling Validation Mobile Number Function HTML Code -

Find the paths between two given nodes?

The original code is a bit cumbersome and you might want to use the collections.deque instead if you want to use BFS to find if a path exists between 2 points on the graph. Here is a quick solution I hacked up:

Note: this method might continue infinitely if there exists no path between the two nodes. I haven't tested all cases, YMMV.

from collections import deque

# a sample graph
  graph = {'A': ['B', 'C','E'],
           'B': ['A','C', 'D'],
           'C': ['D'],
           'D': ['C'],
           'E': ['F','D'],
           'F': ['C']}

   def BFS(start, end):
    """ Method to determine if a pair of vertices are connected using BFS

    Args:
      start, end: vertices for the traversal.

    Returns:
      [start, v1, v2, ... end]
    """
    path = []
    q = deque()
    q.append(start)
    while len(q):
      tmp_vertex = q.popleft()
      if tmp_vertex not in path:
        path.append(tmp_vertex)

      if tmp_vertex == end:
        return path

      for vertex in graph[tmp_vertex]:
        if vertex not in path:
          q.append(vertex)

What's the best mock framework for Java?

I've had good success using Mockito.

When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).

I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp.

Here's an (abridged) example from the Mockito homepage:

import static org.mockito.Mockito.*;

List mockedList = mock(List.class);
mockedList.clear();
verify(mockedList).clear();

It doesn't get much simpler than that.

The only major downside I can think of is that it won't mock static methods.

PHP: get the value of TEXTBOX then pass it to a VARIABLE

I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.

if((isset($_POST['name'])) && !empty($_POST['name']))
{
    $name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
    echo $name;
}

Ubuntu says "bash: ./program Permission denied"

Try this:

sudo chmod +x program_name
./program_name 

C non-blocking keyboard input

Here's a function to do this for you. You need termios.h which comes with POSIX systems.

#include <termios.h>
void stdin_set(int cmd)
{
    struct termios t;
    tcgetattr(1,&t);
    switch (cmd) {
    case 1:
            t.c_lflag &= ~ICANON;
            break;
    default:
            t.c_lflag |= ICANON;
            break;
    }
    tcsetattr(1,0,&t);
}

Breaking this down: tcgetattr gets the current terminal information and stores it in t. If cmd is 1, the local input flag in t is set to non-blocking input. Otherwise it is reset. Then tcsetattr changes standard input to t.

If you don't reset standard input at the end of your program you will have problems in your shell.

Are there constants in JavaScript?

Are you trying to protect the variables against modification? If so, then you can use a module pattern:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.

If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.