Programs & Examples On #Enterprise library 4.1

What's the @ in front of a string in C#?

It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.

So "C:\\Users\\Rich" is the same as @"C:\Users\Rich"

There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @"""" evaluates to ".

Add querystring parameters to link_to

In case you want to pass in a block, say, for a glyphicon button, as in the following:

<%= link_to my_url, class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Then passing querystrings params could be accomplished through:

<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

How to find the installed pandas version


pip freeze

It works the same as above.

pip show pandas

Displays information about a specific package. For more information, check out pip help

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

Could you use an insert trigger? If it fails, do an update.

In the shell, what does " 2>&1 " mean?

From a programmer's point of view, it means precisely this:

dup2(1, 2);

See the man page.

Understanding that 2>&1 is a copy also explains why ...

command >file 2>&1

... is not the same as ...

command 2>&1 >file

The first will send both streams to file, whereas the second will send errors to stdout, and ordinary output into file.

What's the best practice to "git clone" into an existing folder?

I'd git clone to a new directory and copy the content of the existing directory to the new clone.

How to stop text from taking up more than 1 line?

Using ellipsis will add the ... at the last.

   <style type="text/css">
    div {
      white-space: nowrap;
      overflow: hidden;
text-overflow: ellipsis;

Output (echo/print) everything from a PHP Array

This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.

function print_array($title,$array){


            echo $title."<br/>".
            echo "</pre>".
            "END ".$title."<br/>".

             echo $title." is not an array.";

Basic usage:

//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
print_array("PETS", $array);



    [0] => cat
    [1] => dog
    [2] => bird
    [3] => mouse
    [4] => fish
    [5] => gerbil


HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\ in line no 124 you are trying to access a null object which results in null pointer exception.

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

For directories dirname gets tripped for ../ and returns ./.

nolan6000's function can be modified to fix that:

get_abs_filename() {
  # $1 : relative filename
  if [ -d "${1%/*}" ]; then
    echo "$(cd ${1%/*}; pwd)/${1##*/}"

Which mime type should I use for mp3

I had a problem with mime types and where making tests for few file types. It looks like each browser sends it's variation of a mime type for a specific file. I was trying to upload mp3 and zip files with open source php class, that what I have found:

  • Firefox (mp3): audio/mpeg
  • Firefox (zip): application/zip
  • Chrome (mp3): audio/mp3
  • Chrome (zip): application/octet-stream
  • Opera (mp3): audio/mp3
  • Opera (zip): application/octet-stream
  • IE (mp3): audio/mpeg
  • IE (zip): application/x-zip-compressed

So if you need several file types to upload, you better make some tests so that every browser could upload a file and pass mime type check.

Python: Fetch first 10 results from a list

Use the slicing operator:

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

WARNING: Exception encountered during context initialization - cancelling refresh attempt

This was my stupidity, but a stupidity that was not easy to identify :).


  1. My code is compiled on Jdk 1.8.
  2. My eclipse, had JDK 1.8 as the compiler.
  3. My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.
  4. To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
    1. Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.

If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

How do I add a ToolTip to a control?

ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.

This is how to do it-

  1. Add a ToolTip object to your form. One object is enough for the entire form. ToolTip toolTip = new ToolTip();

  2. Add the control to the tooltip with the desired text.

    toolTip.SetToolTip(Button1,"Click here");

best way to create object

Decide if you need an immutable object or not.

If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:

public class Person
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(){}
    public Person(string name, int age)
        Name = name;
        Age = age;
    //Other properties, methods, events...

In that case, having a Person(string name, int age) constructor is not so useful.

The second option is to implement an immutable type. For example:

public class Person
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person(string name, int age)
        Name = name;
        Age = age;
    //Other properties, methods, events...

Now you have a constructor that sets the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.

A best practice is to define classes as immutable every time if possible. To understand advantages of immutable classes I suggest you read this article.

Finding even or odd ID values

ID % 2 is checking what the remainder is if you divide ID by 2. If you divide an even number by 2 it will always have a remainder of 0. Any other number (odd) will result in a non-zero value. Which is what is checking for.

How to bring view in front of everything?

bringToFront() is the right way, but, NOTE that you must call bringToFront() and invalidate() method on highest-level view (under your root view), for e.g.:

Your view's hierarchy is:


So, when you animate back your buttons (1->6), your buttons will under (below) the ImageView. To bring it over (above) the ImageView you must call bringToFront() and invalidate() method on your LinearLayouts. Then it will work :) **NOTE: Remember to set android:clipChildren="false" for your root layout or animate-view's gradparent_layout. Let's take a look at my real code:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:orientation="vertical" >

        hw:titleText="@string/app_name" >

        android:clipChildren="false" >

            android:orientation="horizontal" >

            android:src="@drawable/ic_launcher" />

            android:orientation="horizontal" >


Some code in .java

private LinearLayout layoutTop, layoutBottom;
layoutTop = (LinearLayout) rootView.findViewById(;
layoutBottom = (LinearLayout) rootView.findViewById(;
//when animate back
//dragedView is my layoutTop's child view (i added programmatically) (like buttons in above example) 
dragedView.startAnimation(animation); // TranslateAnimation


Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

How to have an automatic timestamp in SQLite?

To complement answers above...

If you are using EF, adorn the property with Data Annotation [Timestamp], then go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:

                .Property(b => b.Timestamp)

It will make a default value to every data that will be insert into this table.

R cannot be resolved - Android error

I had this problem as well. It turned out that I had inadvertently deleted the "app_name" string resource from the strings.xml file, which was causing a silent error. Once I added it back, the R class was generated successfully and everything was back up and running.

How to use MySQL DECIMAL?

Although the answers above seems correct, just a simple explanation to give you an idea of how it works.

Suppose that your column is set to be DECIMAL(13,4). This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.

So, in summary, for that column you would have a max value of: 999999999.9999

offsetTop vs. jQuery.offset().top

I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...

MySQL check if a table exists without throwing an exception

If you're using MySQL 5.0 and later, you could try:

FROM information_schema.tables 
WHERE table_schema = '[database name]' 
AND table_name = '[table name]';

Any results indicate the table exists.


Illegal Character when trying to compile java code

That's a byte order mark, as everyone says.

javac does not understand the BOM, not even when you try something like

javac -encoding UTF8

You need to strip the BOM or convert your source file to another encoding. Notepad++ can convert a single files encoding, I'm not aware of a batch utility on the Windows platform for this.

The java compiler will assume the file is in your platform default encoding, so if you use this, you don't have to specify the encoding.

Comparing two hashmaps for equal values and same key sets?

Make an equals check on the keySet() of both HashMaps.


If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

In Javascript/jQuery what does (e) mean?

DISCLAIMER: This is a very late response to this particular post but as I've been reading through various responses to this question, it struck me that most of the answers use terminology that can only be understood by experienced coders. This answer is an attempt to address the original question with a novice audience in mind.


The little '(e)' thing is actually part of broader scope of something in Javascript called an event handling function. Every event handling function receives an event object. For the purpose of this discussion, think of an object as a "thing" that holds a bunch of properties (variables) and methods (functions), much like objects in other languages. The handle, the 'e' inside the little (e) thing, is like a variable that allows you to interact with the object (and I use the term variable VERY loosely).

Consider the following jQuery examples:

$("#someLink").on("click", function(e){ // My preferred method

$("#someLink").click(function(e){ // Some use this method too


  • "#someLink" is your element selector (which HTML tag will trigger this).
  • "click" is an event (when the selected element is clicked).
  • "function(e)" is the event handling function (on event, object is created).
  • "e" is the object handler (object is made accessible).
  • "preventDefault()" is a method (function) provided by the object.

What's happening?
When a user clicks on the element with the id "#someLink" (probably an anchor tag), call an anonymous function, "function(e)", and assign the resulting object to a handler, "e". Now take that handler and call one of its methods, "e.preventDefault()", which should prevent the browser from performing the default action for that element.

Note: The handle can pretty much be named anything you want (i.e. 'function(billybob)'). The 'e' stands for 'event', which seems to be pretty standard for this type of function.

Although 'e.preventDefault()' is probably the most common use of the event handler, the object itself contains many properties and methods that can be accessed via the event handler.

Some really good information on this topic can be found at jQuery's learning site, Pay special attention to the Using jQuery Core and Events sections.

Creating all possible k combinations of n items in C++

The basic idea of this solution is to mimic the way you enumerate all the combinations without repetitions by hand in high school. Let com be List[int] of length k and nums be List[int] the given n items, where n >= k. The idea is as follows:

for x[0] in nums[0,...,n-1] 
    for x[1] in nums[idx_of_x[0] + 1,..,n-1]
        for x[2] in nums [idx_of_x[1] + 1,...,n-1]
            for x[k-1] in nums [idx_of_x[k-2]+1, ..,n-1]

Obviously, k and n are variable arguments, which makes it impossible to write explicit multiple nested for-loops. This is where the recursion comes to rescue the issue. Statement len(com) + len(nums[i:]) >= k checks whether the remaining unvisited forward list of items can provide k iitems. By forward, I mean you should not walk the nums backward for avoiding the repeated combination, which consists of same set of items but in different order. Put it in another way, in these different orders, we can choose the order these items appear in the list by scaning the list forward. More importantly, this test clause internally prunes the recursion tree such that it only contains n choose k recursive calls. Hence, the running time is O(n choose k).

from typing import List

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        assert 1 <= n <= 20
        assert 1 <= k <= n
        com_sets = []
        self._combine_recurse(k, list(range(1, n+1)), [], com_sets)
        return com_sets

    def _combine_recurse(self, k: int, nums: List[int], com: List[int], com_set: List[List[int]]):
        if len(com) < k:
            for i in range(len(nums)):
            # Once again, don't com.append() since com should not be global!
                if len(com) + len(nums[i:]) >= k:
                    self._combine_recurse(k, nums[i+1:], com + [nums[i]], com_set)
            if len(com) == k:
sol = Solution()
sol.combine(5, 3)

[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]

How do you convert WSDLs to Java classes using Eclipse?

You need to do next in command line:

wsimport -keep -s (name of folder where you want to store generated code) urlToWsdl

for example:

wsimport -keep -s C://NewFolder

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

Java web start - Unable to load resource

this also worked for me , thanks a lot

changing java proxy settings to direct connection did not fix my issue.

What worked for me:

Run "Configure Java" as administrator.
Go to Advanced
Scroll to bottom
Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"

How can I close a window with Javascript on Mozilla Firefox 3?

This code will work it out definitely

function closing() {
var answer = confirm("Do you wnat to close this window ?");
    if (answer){'UniversalBrowserWrite');

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

Check whether an array is empty

Try to check it's size with sizeof if 0 no elements.

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I have added for this:

Server compression


taken from

How do you connect to multiple MySQL databases on a single webpage?

Try below code:

    $conn = mysql_connect("hostname","username","password");

    $query1 = "SELECT * FROM db1.table";
    $query2 = "SELECT * FROM db2.table";

You can fetch data of above query from both database as below

$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
    $data1[] = $row;

$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
    $data2[] = $row;


How to send a pdf file directly to the printer using JavaScript?

There are two steps you need to take.

First, you need to put the PDF in an iframe.

  <iframe id="pdf" name="pdf" src="document.pdf"></iframe>

To print the iframe you can look at the answers here:

Javascript Print iframe contents only

If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>:

  <iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>

the loader can look like this:

function isLoaded()
  var pdfFrame = window.frames["pdf"];

This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).

I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.

MySQL show status - active or total connections?

In order to check the maximum allowed connections, you can run the following query:

SHOW VARIABLES LIKE "max_connections";

To check the number of active connections, you can run the following query:

SHOW VARIABLES LIKE "max_used_connections";

Hope it helps.

Detecting Enter keypress on VB.NET

I had the same problem and I could not make this answer work on Framework 2.0 so I dug deeper.

You would have to first handle the PreviewKeyDown on the textbox so when ENTER came along you would set IsInputKey so that it could be handled by or forwarded to the keyDown event on the textbox. Like this:

Private Sub txtFiltro_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtFiltro.PreviewKeyDown
    Select Case e.KeyCode
        Case Keys.Enter
            e.IsInputKey = True
    End Select
 End Sub

and then you would handle the event keydown on the textbox. One of the answer was on the right track but missed setting the e.IsInputKey.

Private Sub txtFiltro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltro.KeyDown
    If e.KeyCode = Keys.Enter Then
        e.handled = True
    End If
End Sub

How can I simulate a print statement in MySQL?

This is an old post, but thanks to this post I have found this:

\! echo 'some text';

Tested with MySQL 8 and working correctly. Cool right? :)

Current date and time - Default in MVC razor

You could initialize ReturnDate on the model before sending it to the view.

In the controller:

public ActionResult SomeAction()
    var viewModel = new MyActionViewModel
        ReturnDate = System.DateTime.Now

    return View(viewModel);

What is 'Currying'?

The "currying" is the process of taking the function of multiple arguments and converting it into a serious of functions that each take a single argument and return a function of a single argument, or in the case of the final function, return the actual result.

NoClassDefFoundError - Eclipse and Android

The solution here worked for me. It's a matter of importing the library to the libs folder, then modifying the build.gradle file and then cleaning with gradlew.

Gson: Directly convert String to JsonObject (no POJO)

String jsonStr = "{\"a\": \"A\"}";

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();

How do I include a newline character in a string in Delphi?

In the System.pas (which automatically gets used) the following is defined:

  sLineBreak = {$IFDEF LINUX} AnsiChar(#10) {$ENDIF} 
               {$IFDEF MSWINDOWS} AnsiString(#13#10) {$ENDIF};

This is from Delphi 2009 (notice the use of AnsiChar and AnsiString). (Line wrap added by me.)

So if you want to make your TLabel wrap, make sure AutoSize is set to true, and then use the following code:

label1.Caption := 'Line one'+sLineBreak+'Line two';

Works in all versions of Delphi since sLineBreak was introduced, which I believe was Delphi 6.

Fastest way to zero out a 2d array in C?

This happens because sizeof(array) gives you the allocation size of the object pointed to by array. (array is just a pointer to the first row of your multidimensional array). However, you allocated j arrays of size i. Consequently, you need to multiply the size of one row, which is returned by sizeof(array) with the number of rows you allocated, e.g.:

bzero(array, sizeof(array) * j);

Also note that sizeof(array) will only work for statically allocated arrays. For a dynamically allocated array you would write

size_t arrayByteSize = sizeof(int) * i * j; 
int *array = malloc(array2dByteSite);
bzero(array, arrayByteSize);

Read response body in JAX-RS client from a post request

Try this:

String output = response.getEntity(String.class);


Thanks to @Martin Spamer to mention that it will work for Jersey 1.x jars only. For Jersey 2.x use

String output = response.readEntity(String.class);

How to right-align and justify-align in Markdown?

In a generic Markdown document, use:

<style>body {text-align: right}</style>


<style>body {text-align: justify}</style>

Does not seem to work with Jupyter though.

Does Visual Studio have code coverage for unit tests?

Toni's answer is very useful, but I thought a quick start for total beginners to test coverage assessment (like I am).

As already mentioned, Visual Studio Professional and Community Editions do not have built-in test coverage support. However, it can be obtained quite easily. I will write step-by-step configuration for use with NUnit tests within Visual Studion 2015 Professional.

  1. Install OpenCover NUGet component using NuGet interface

  2. Get OpenCoverUI extension. This can be installed directly from Visual Studio by using Tools -> Extensions and Updates

  3. Configure OpenCoverUI to use the appropriate executables, by accessing Tools -> Options -> OpenCover.UI Options -> General

NUnit Path: must point to the `nunit-console.exe file. This can be found only within NUnit 2.xx version, which can be downloaded from here.

OpenCover Path: this should point to the installed package, usually <solution path>\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe

  1. Install ReportGenerator NUGet package

  2. Access OpenCover Test Explorer from OpenCover menu. Try discovering tests from there. If it fails, check Output windows for more details.

  3. Check OpenCover Results (within OpenCover menu) for more details. It will output details such as Code Coverage in a tree based view. You can also highlight code that is or is not covered (small icon in the top-left).

NOTE: as mentioned, OpenCoverUI does not support latest major version of NUnit (3.xx). However, if nothing specific to this version is used within tests, it will work with no problems, regardless of having installed NUnit 3.xx version.

This covers the quick start. As already mentioned in the comments, for more advanced configuration and automation check this article.

Inserting Data into Hive Table

Hive apparently supports INSERT...VALUES starting in Hive 0.14.

Please see the section 'Inserting into tables from SQL' at:

Substring in VBA



Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.




How to check if a character in a string is a digit or letter

import java.util.*;

public class String_char 

    public static void main(String arg[]){   

        Scanner in = new Scanner(;
        System.out.println("Enter the value");
        String data;
        data =;

        int len = data.length();
        for (int i = 0 ; i < len ; i++){
            char ch = data.charAt(i);

            if ((ch >= '0' && ch <= '9')){
                System.out.println("Number ");
            else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){

How to access route, post, get etc. parameters in Zend Framework 2

The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:

'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/save-json/',
                'defaults' => array(
                    'controller' => 'CDB\Controller\Index',
                    'action'     => 'save-json',

and i wanted to post data to it using Angular's $ The post was fine but the retrive method in Zend


didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':

$content = file_get_contents('php://input');

I got my json array in the end. Hope this helps.

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

Bash: Syntax error: redirection unexpected


I was getting this problem from my Dockerfile as I had:

RUN bash < <(curl -s -S -L

However, according to this issue, it was solved:

The exec form makes it possible to avoid shell string munging, and to RUN commands using a base image that does not contain /bin/sh.


To use a different shell, other than /bin/sh, use the exec form passing in the desired shell. For example,

RUN ["/bin/bash", "-c", "echo hello"]


RUN ["/bin/bash", "-c", "bash < <(curl -s -S -L"]

Notice the quotes around each parameter.

New features in java 7

Java SE 7 Features and Enhancements from JDK 7 Release Notes

This is the Java 7 new features summary from the OpenJDK 7 features page:

vm  JSR 292: Support for dynamically-typed languages (InvokeDynamic)
        Strict class-file checking
lang    JSR 334: Small language enhancements (Project Coin)
core    Upgrade class-loader architecture
        Method to close a URLClassLoader
        Concurrency and collections updates (jsr166y)
i18n    Unicode 6.0
        Locale enhancement
        Separate user locale and user-interface locale
ionet   JSR 203: More new I/O APIs for the Java platform (NIO.2)
        NIO.2 filesystem provider for zip/jar archives
        SCTP (Stream Control Transmission Protocol)
        SDP (Sockets Direct Protocol)
        Use the Windows Vista IPv6 stack
        TLS 1.2
sec     Elliptic-curve cryptography (ECC)
jdbc    JDBC 4.1
client  XRender pipeline for Java 2D
        Create new platform APIs for 6u10 graphics features
        Nimbus look-and-feel for Swing
        Swing JLayer component
        Gervill sound synthesizer [NEW]
web     Update the XML stack
mgmt    Enhanced MBeans [UPDATED]

Code examples for new features in Java 1.7

Try-with-resources statement


BufferedReader br = new BufferedReader(new FileReader(path));
try {
   return br.readLine();
} finally {


try (BufferedReader br = new BufferedReader(new FileReader(path)) {
   return br.readLine();

You can declare more than one resource to close:

try (
   InputStream in = new FileInputStream(src);
   OutputStream out = new FileOutputStream(dest))
 // code

Underscores in numeric literals

int one_million = 1_000_000;

Strings in switch

String s = ...
switch(s) {
 case "quux":
    // fall-through

  case "foo":
  case "bar":

  case "baz":
    // fall-through


Binary literals

int binary = 0b1001_1001;

Improved Type Inference for Generic Instance Creation

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();


Map<String, List<String>> anagrams = new HashMap<>();

Multiple exception catching


} catch (FirstException ex) {
     throw ex;
} catch (SecondException ex) {
     throw ex;


} catch (FirstException | SecondException ex) {
    throw ex;



@SuppressWarnings({"unchecked", "varargs"})
public static void printAll(List<String>... lists){
    for(List<String> list : lists){


public static void printAll(List<String>... lists){
    for(List<String> list : lists){

How can I change the app display name build with Flutter?

There is a plugin, flutter_launcher_name.

Write file pubspec.yaml:

  flutter_launcher_name: "^0.0.1"

  name: "yourNewAppLauncherName"

And run:

flutter pub get
flutter pub run flutter_launcher_name:main

You can get the same result as editing AndroidManifes.xml and Info.plist.

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")

Can you check if this code works for you? Maybe something overwrites them later?

How to find out if an item is present in a std::vector?

(C++17 and above):

can use std::search also

This is also useful for searching sequence of elements.

#include <algorithm>
#include <iostream>
#include <vector>

template <typename Container>
bool search_vector(const Container& vec, const Container& searchvec)
    return std::search(vec.begin(), vec.end(), searchvec.begin(), searchvec.end()) != vec.end();

int main()
     std::vector<int> v = {2,4,6,8};

     std::vector<int> searchVector1 = {2};
         std::cout<<"searchVector1 found"<<std::endl;
         std::cout<<"searchVector1 not found"<<std::endl;

     std::vector<int> searchVector2 = {6,8};
         std::cout<<"searchVector2 found"<<std::endl;
         std::cout<<"searchVector2 not found"<<std::endl;

     std::vector<int> searchVector3 = {8,6};
         std::cout<<"searchVector3 found"<<std::endl;
         std::cout<<"searchVector3 not found"<<std::endl;

Also there is flexibility of passing some search algorithms. Refer here.

How can I install Python's pip3 on my Mac?

Similar to Oksana but add python3

$ brew rm python 
$ brew rm python3 
$ rm -rf /usr/local/opt/python
$ rm -rf /usr/local/opt/python3
$ brew prune 
$ brew install python3
$ brew postinstall python3

Seem now work for pip3 under mac os x 10.13.3 Xcode 9.2

Is it possible to install another version of Python to Virtualenv?

The usual approach is to download the source and build and install locally (but not directly in virtualenv), and then create a new virtualenv using that local Python install. On some systems, it may be possible to download and install a prebuilt python, rather than building from source.

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)

To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]


map(lambda axi: axi.set_axis_off(), ax.ravel())

Javascript onHover event

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

How do I auto-hide placeholder text upon focus using css or jquery?

I like the css approach spiced with transitions. On Focus the placeholder fades out ;) Works also for textareas.

Thanks @Casey Chu for the great idea.

textarea::-webkit-input-placeholder, input::-webkit-input-placeholder { 
    color: #fff;
    opacity: 0.4;
    transition: opacity 0.5s;
    -webkit-transition: opacity 0.5s; 

textarea:focus::-webkit-input-placeholder, input:focus::-webkit-input-placeholder  { 
    opacity: 0;

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

it's very easy, you just grant the /tmp folder as 777 permission. just type:

chmod -R 777 /tmp

Is it safe to delete the "InetPub" folder?

it is safe to delete the inetpub it is only a cache.

Difference between SelectedItem, SelectedValue and SelectedValuePath

inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog

SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.

SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.

How to open a new form from another form

If I got you right, are you trying like this?

alt text

into this?
alt text

in your Form1, add this event in your button:

    // button event in your Form1
    private void button1_Click(object sender, EventArgs e)
        Form2 f2 = new Form2();
        f2.ShowDialog(); // Shows Form2

then, in your Form2 add also this event in your button:

    // button event in your Form2
    private void button1_Click(object sender, EventArgs e)
        Form3 f3 = new Form3(); // Instantiate a Form3 object.
        f3.Show(); // Show Form3 and
        this.Close(); // closes the Form2 instance.

How to append one file to another in Linux from the shell?

cat file2 >> file1

The >> operator appends the output to the named file or creates the named file if it does not exist.

cat file1 file2 > file3

This concatenates two or more files to one. You can have as many source files as you need. For example,

cat *.txt >> newfile.txt

Update 20130902
In the comments eumiro suggests "don't try cat file1 file2 > file1." The reason this might not result in the expected outcome is that the file receiving the redirect is prepared before the command to the left of the > is executed. In this case, first file1 is truncated to zero length and opened for output, then the cat command attempts to concatenate the now zero-length file plus the contents of file2 into file1. The result is that the original contents of file1 are lost and in its place is a copy of file2 which probably isn't what was expected.

Update 20160919
In the comments tpartee suggests linking to backing information/sources. For an authoritative reference, I direct the kind reader to the sh man page at which states:

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell.

While that does tell the reader what they need to know it is easy to miss if you aren't looking for it and parsing the statement word by word. The most important word here being 'before'. The redirection is completed (or fails) before the command is executed.

In the example case of cat file1 file2 > file1 the shell performs the redirection first so that the I/O handles are in place in the environment in which the command will be executed before it is executed.

A friendlier version in which the redirection precedence is covered at length can be found at Ian Allen's web site in the form of Linux courseware. His I/O Redirection Notes page has much to say on the topic, including the observation that redirection works even without a command. Passing this to the shell:

$ >out

...creates an empty file named out. The shell first sets up the I/O redirection, then looks for a command, finds none, and completes the operation.

How to run a PowerShell script without displaying a window?

I got really tired of going through answers only to find it did not work as expected.


Make a vbs script to run a hidden batch file which launches the powershell script. Seems silly to make 3 files for this task but atleast the total size is less than 2KB and it runs perfect from tasker or manually (you dont see anything).


Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\Users\leathan\Documents\scriptName.bat" & Chr(34), 0
Set WinScriptHost = Nothing


powershell.exe -ExecutionPolicy Bypass C:\Users\leathan\Documents\scriptName.ps1


Your magical code here.

Angular 2 ngfor first, last, index loop

Here is how its done in Angular 6

<li *ngFor="let user of userObservable ; first as isFirst">
   <span *ngIf="isFirst">default</span>

Note the change from let first = first to first as isFirst

How to autosize a textarea using Prototype?

Here is a function I just wrote in jQuery to do it - you can port it to Prototype, but they don't support the "liveness" of jQuery so elements added by Ajax requests will not respond.

This version not only expands, but it also contracts when delete or backspace is pressed.

This version relies on jQuery 1.4.2.

Enjoy ;)



or (any jQuery selector for example)


It was tested on Internet Explorer 7/Internet Explorer 8, Firefox 3.5, and Chrome. All works fine.

Angular window resize event

I wrote this lib to find once component boundary size change (resize) in Angular, may this help other people. You may put it on the root component, will do the same thing as window resize.

Step 1: Import the module

import { BoundSensorModule } from 'angular-bound-sensor';

  imports: [
export class AppModule { }

Step 2: Add the directive like below

<simple-component boundSensor></simple-component>

Step 3: Receive the boundary size details

import { HostListener } from '@angular/core';

  selector: 'simple-component'
class SimpleComponent {
  @HostListener('resize', ['$event'])
  onResize(event) {

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

I've just cleaned up my disk space and restart computer. That have helped me.

$('body').on('click', '.anything', function(){})

You can try this:

You must follow the following format

    $('element,id,class').on('click', function(){....});

*JQuery code*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e

How can a windows service programmatically restart itself?

It would depend on why you want it to restart itself.

If you are just looking for a way to have the service clean itself out periodically then you could have a timer running in the service that periodically causes a purge routine.

If you are looking for a way to restart on failure - the service host itself can provide that ability when it is setup.

So why do you need to restart the server? What are you trying to achieve?

New self vs. new static

If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this).

class A {
    public function create1() {
        $class = get_class($this);
        return new $class();
    public function create2() {
        return new static();

class B extends A {


$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

The results:

string(1) "B"
string(1) "B"

What exactly does a jar file contain?

However, I got curious to what each class contained and when I try to open one of the classes in the jar file, it tells me that I need a source file.

A jar file is basically a zip file containing .class files and potentially other resources (and metadata about the jar itself). It's hard to compare C to Java really, as Java byte code maintains a lot more metadata than most binary formats - but the class file is compiled code instead of source code.

If you either open the jar file with a zip utility or run jar xf foo.jar you can extract the files from it, and have a look at them. Note that you don't need a jar file to run Java code - classloaders can load class data directly from the file system, or from URLs, as well as from jar files.

using setTimeout on promise chain

To keep the promise chain going, you can't use setTimeout() the way you did because you aren't returning a promise from the .then() handler - you're returning it from the setTimeout() callback which does you no good.

Instead, you can make a simple little delay function like this:

function delay(t, v) {
   return new Promise(function(resolve) { 
       setTimeout(resolve.bind(null, v), t)

And, then use it like this:

    let all_links = (JSON.parse(links));

    return getLinks(globalObj["one"]+".txt");

    // return a promise here that will be chained to prior promise
    return delay(1000).then(function() {
        return getLinks(globalObj["two"]+".txt");

Here you're returning a promise from the .then() handler and thus it is chained appropriately.

You can also add a delay method to the Promise object and then directly use a .delay(x) method on your promises like this:

function delay(t, v) {_x000D_
   return new Promise(function(resolve) { _x000D_
       setTimeout(resolve.bind(null, v), t)_x000D_
Promise.prototype.delay = function(t) {_x000D_
    return this.then(function(v) {_x000D_
        return delay(t, v);_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_

Or, use the Bluebird promise library which already has the .delay() method built-in.

VMware Workstation and Device/Credential Guard are not compatible


Fixed error in VMware Workstation on Windows 10 host Transport (VMDB) error -14: Pipe connection has been broken.

Today we will be fixing VMWare error on a windows 10 computer.

  1. In RUN box type "gpedit" then Goto [ERROR SEE POINT 3]

1- Computer Configuration

2- Administrative Templates

3- System - Device Guard : IF NO DEVICE GUARD : (DOWNLOAD install this "c:\Program Files (x86)\Microsoft Group Policy\Windows 10 November 2019 Update (1909)\PolicyDefinitions" COPY to c:\windows\PolicyDefinitions )

4- Turn on Virtualization Based Security. Now Double click that and "Disable"

  1. Open Command Prompt as Administrator and type the following gpupdate /force [DONT DO IF YOU DONT HAVE DEVICE GUARD ELSE IT WILL GO AGAIN]

  2. Open Registry Editor, now Go to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\DeviceGuard. Add a new DWORD value named EnableVirtualizationBasedSecurity and set it to 0 to disable it. Next Go to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA. Add a new DWORD value named LsaCfgFlags and set it to 0 to disable it.

  3. In RUN box, type Turn Windows features on or off, now uncheck Hyper-V and restart system.

  4. Open command prompt as a administrator and type the following commands

    bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"

    bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}
    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO,DISABLE-VBS

    bcdedit /set hypervisorlaunchtype off

Now, Restart your system

OWIN Startup Class Missing

This could be faced in Visual Studio 2015 as well when you use the Azure AD with a MVC project. Here it create the startup file as Startup.Auth.cs in App_Start folder but it will be missing the

[assembly: OwinStartup(typeof(MyWebApp.Startup))]

So add it and you should be good to go. This goes before the namespace start.

How do I disable a jquery-ui draggable?

In the case of a dialog, it has a property called draggable, set it to false.

    draggable: false

Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.

Waiting for Target Device to Come Online

Did not read all the answers. Anyway Accepted one didn't work for me. What did was upgrading the android studio to last stable version and then created a new virtual device. I guess my nexus 5p virtual device got out of sync with the android studio environment.

Disable back button in android

Just override the onBackPressed() method and no need to call the super class of onBackPressed method or others..

public void onBackPressed()


Or pass your current activity into the onBackPressed() method.

public void onBackPressed()
   startActivity(new Intent(this, myActivity.class));  

Replace your require activity name to myActivity.

if you are using fragment then first of all call the callParentMethod() method

public void callParentMethod(){
    context.onBackPressed(); // instead of context use getActivity or something related

then call the empty method

public void onBackPressed()


Making a cURL call in C#

Call cURL from your console app is not a good idea.

But you can use TinyRestClient which make easier to build requests :

var client = new TinyRestClient(new HttpClient(),"");

AddQueryParameter("text", "").

How do I mock an open used in a with statement (using the Mock framework in Python)?

With the latest versions of mock, you can use the really useful mock_open helper:

mock_open(mock=None, read_data=None)

A helper function to create a mock to replace the use of open. It works for open called directly or used as a context manager.

The mock argument is the mock object to configure. If None (the default) then a MagicMock will be created for you, with the API limited to methods or attributes available on standard file handles.

read_data is a string for the read method of the file handle to return. This is an empty string by default.

>>> from mock import mock_open, patch
>>> m = mock_open()
>>> with patch('{}.open'.format(__name__), m, create=True):
...    with open('foo', 'w') as h:
...        h.write('some stuff')

>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

How about playing with these two properties?

disableClose: boolean - Whether the user can use escape or clicking on the backdrop to close the modal.

hasBackdrop: boolean - Whether the dialog has a backdrop.

memcpy() vs memmove()

The code given in the links for memcpy seems to confuse me a bit, as it does not give the same output when I implemented it using the below example.

#include <memory.h>
#include <string.h>
#include <stdio.h>

char str1[11] = "abcdefghij";

void *memcpyCustom(void *dest, const void *src, size_t n)
    char *dp = (char *)dest;
    const char *sp = (char *)src;
    while (n--)
        *dp++ = *sp++;
    return dest;

void *memmoveCustom(void *dest, const void *src, size_t n)
    unsigned char *pd = (unsigned char *)dest;
    const unsigned char *ps = (unsigned char *)src;
    if ( ps < pd )
        for (pd += n, ps += n; n--;)
            *--pd = *--ps;
            *pd++ = *ps++;
    return dest;

int main( void )
    printf( "The string: %s\n", str1 );
    memcpy( str1 + 1, str1, 9 );
    printf( "Actual memcpy output: %s\n", str1 );

    strcpy_s( str1, sizeof(str1), "abcdefghij" );   // reset string

    memcpyCustom( str1 + 1, str1, 9 );
    printf( "Implemented memcpy output: %s\n", str1 );

    strcpy_s( str1, sizeof(str1), "abcdefghij" );   // reset string

    memmoveCustom( str1 + 1, str1, 9 );
    printf( "Implemented memmove output: %s\n", str1 );

Output :

The string: abcdefghij
Actual memcpy output: aabcdefghi
Implemented memcpy output: aaaaaaaaaa
Implemented memmove output: aabcdefghi

But you can now understand why memmove will take care of overlapping issue.

How to center a label text in WPF?

You have to use HorizontalContentAlignment="Center" and! Width="Auto".

Adding git branch on the Bash command prompt

1- If you don't have bash-completion ... : sudo apt-get install bash-completion

2- Edit your .bashrc file and check (or add) :

if [ -f /etc/bash_completion ]; then
  . /etc/bash_completion

3- ... before your prompt line : export PS1='$(__git_ps1) \w\$ '
(__git_ps1 will show your git branch)

4- do source .bashrc


Further readings : Don’t Reinvent the Wheel

constant pointer vs pointer on a constant value

Trying to answer in simple way:

char * const a;  => a is (const) constant (*) pointer of type char {L <- R}. =>( Constant Pointer )
const char * a;  => a is (*) pointer to char constant             {L <- R}. =>( Pointer to Constant)

Constant Pointer:

pointer is constant !!. i.e, the address it is holding can't be changed. It will be stored in read only memory.

Let's try to change the address of pointer to understand more:

char * const a = &b; 
char c;
a = &c; // illegal , you can't change the address. `a` is const at L-value, so can't change. `a` is read-only variable.

It means once constant pointer points some thing it is forever.

pointer a points only b.

However you can change the value of b eg:

char b='a';
char * const a =&b;

printf("\n print a  : [%c]\n",*a);
*a = 'c';
printf("\n now print a  : [%c]\n",*a);

Pointer to Constant:

Value pointed by the pointer can't be changed.

const char *a;
char b = 'b';
const char * a =&b;
char c;
a=&c; //legal

*a = 'c'; // illegal , *a is pointer to constant can't change!.

How to center horizontal table-cell

If you add text-align: center to the declarations for .columns-container then they align centrally:

.columns-container {
    display: table-cell;
    height: 100%;
    text-align: center;

 * Sticky footer hack_x000D_
 * Source:
/* Stretching all container's parents to full height */_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
#container {_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
.section {_x000D_
  display: table-row;_x000D_
  height: 1px;_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
.section.expand {_x000D_
  height: auto;_x000D_
 * Full height columns_x000D_
/* We need one extra container, setting it to full width */_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
text-align: center;_x000D_
/* Creating columns */_x000D_
.column {_x000D_
  /* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
  display: inline-block;_x000D_
  /* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
  vertical-align: top;_x000D_
  height: 100%;_x000D_
  width: 100px;_x000D_
 * Just some coloring so that we're able to see height of columns_x000D_
header {_x000D_
  background-color: yellow;_x000D_
#a {_x000D_
  background-color: pink;_x000D_
#b {_x000D_
  background-color: lightgreen;_x000D_
#c {_x000D_
  background-color: lightblue;_x000D_
footer {_x000D_
  background-color: purple;_x000D_
<div id="container">_x000D_
  <header class="section">_x000D_
  <div class="section expand">_x000D_
    <div class="columns-container">_x000D_
      <div class="column" id="a">_x000D_
        <p>Contents A</p>_x000D_
      <div class="column" id="b">_x000D_
        <p>Contents B</p>_x000D_
      <div class="column" id="c">_x000D_
        <p>Contents C</p>_x000D_
  <footer class="section">_x000D_

This does, though, require that you reset the .column elements to text-align: left (assuming you want them left-aligned, obviously (JS Fiddle demo).

When should I use cross apply over inner join?

The essence of the APPLY operator is to allow correlation between left and right side of the operator in the FROM clause.

In contrast to JOIN, the correlation between inputs is not allowed.

Speaking about correlation in APPLY operator, I mean on the right hand side we can put:

  • a derived table - as a correlated subquery with an alias
  • a table valued function - a conceptual view with parameters, where the parameter can refer to the left side

Both can return multiple columns and rows.

How to open a page in a new window or tab from code-behind


Target= "_blank" property of anchor tag

Make Div Draggable using CSS

This is the best you can do without JavaScript:

[draggable=true] {_x000D_
  cursor: move;_x000D_
.resizable {_x000D_
  overflow: scroll;_x000D_
  resize: both;_x000D_
  max-width: 300px;_x000D_
  max-height: 460px;_x000D_
  border: 1px solid black;_x000D_
  min-width: 50px;_x000D_
  min-height: 50px;_x000D_
  background-color: skyblue;_x000D_
<div draggable="true" class="resizable"></div>


How to clamp an integer to some range?

sorted((minval, value, maxval))[1]

for example:

>>> minval=3
>>> maxval=7
>>> for value in range(10):
...   print sorted((minval, value, maxval))[1]

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

CSS disable hover effect

I have really simple solution for this.

just create a new class

    pointer-events: none;

and use this to disable any event on it. use it like:

<a href='' class='btn noHover'>You cant touch ME :P</a>

Django template how to look up a dictionary value with a variable

env: django 2.1.7


dict_objs[] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})


{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are


  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>


  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [

Your Models

export class SearchModel {
    code: string;

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];

//Custom exception thrown by the API.
export class APIException {
    className: string;

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';

export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {


    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    

    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);


Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

Classpath resource not found when running as jar

to get list of data from src/main/resources/data folder --
first of all mention your folder location in properties file as - 

inside class declare your location. 

    private String location;

    private final ResourceLoader resourceLoader;

public void readallfilesfromresources() {
       Resource[] resources;

        try {
            resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "/*.json");
            for (int i = 0; i < resources.length; i++) {
                try {
                InputStream is = resources[i].getInputStream();
                byte[] encoded = IOUtils.toByteArray(is);
                String content = new String(encoded, Charset.forName("UTF-8"));
        } catch (IOException e) {
            throw new UncheckedIOException(e);

Edit line thickness of CSS 'underline' attribute

Another way to do this is using ":after" (pseudo-element) on the element you want to underline.



python and sys.argv

In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:

sys.stderr.write("Usage: " + sys.argv[0])


sys.stderr.write("Usage: %s" % sys.argv[0])

Also, you may want to consider using the following syntax of print (for Python earlier than 3.x):

print >>sys.stderr, "Usage:", sys.argv[0]

Using print arguably makes the code easier to read. Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example.

In Python 3.x, you would use the print function:

print("Usage:", sys.argv[0], file=sys.stderr)

Finally, in Python 2.6 and later you can use .format:

print >>sys.stderr, "Usage: {0}".format(sys.argv[0])

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

Having included a dependency on spring-boot-configuration-processor in build.gradle:

annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:2.4.1"

the only thing that worked for me, besides invalidating caches of IntelliJ and restarting, is

  1. Refresh button in side panel Reload All Gradle Projects
  2. Gradle task Clean
  3. Gradle task Build

Check with jquery if div has overflowing elements

In plain English: Get the parent element. Check it's height, and save that value. Then loop through all the child elements and check their individual heights.

This is dirty, but you might get the basic idea:

Add a default value to a column through a migration

For Rails 4+, use change_column_default

def change
  change_column_default :table, :column, value

Passing dynamic javascript values using Url.action()

In my case it worked great just by doing the following:

The Controller:

public ActionResult DoSomething(int custNum)
    // Some magic code here...

Create the form with no action:

<form id="frmSomething" method="post">
        <!-- Some magic html here... -->
    <button id="btnSubmit" type="submit">Submit</button>

Set button click event to trigger submit after adding the action to the form:

var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;
        frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);


Hope this helps vatos!

How to install MySQLdb package? (ImportError: No module named setuptools)

well installing C compiler or GCC didn't work but I found a way to successfully install mysqldb package

kindly follow Mike schrieb's (Thanks to him) instructions here . In my case, I used setuptools-0.6c11-py2.7.egg and setuptools-0.6c11 . Then download the executable file here then install that file. hope it helps :)

Crontab Day of the Week syntax

    :-) Sunday    |    0  ->  Sun
        Monday    |    1  ->  Mon
       Tuesday    |    2  ->  Tue
     Wednesday    |    3  ->  Wed
      Thursday    |    4  ->  Thu
        Friday    |    5  ->  Fri
      Saturday    |    6  ->  Sat
    :-) Sunday    |    7  ->  Sun

As you can see above, and as said before, the numbers 0 and 7 are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.

Examples of Number or Abbreviation Use

15 09 * * 5,6,0             command
15 09 * * 5,6,7             command
15 09 * * 5-7               command
15 09 * * Fri,Sat,Sun       command

The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.

In Detail

Having two numbers 0 and 7 for Sunday can be useful for writing weekday ranges starting with 0 or ending with 7. So you can write ranges starting with Sunday or ending with it, like 0-2 or 5-7 for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);


RLS_strid_panel p = new RLS_strid_panel();

Saving response from Requests to file

As Peter already pointed out:

In [1]: import requests

In [2]: r = requests.get('')

In [3]: type(r)
Out[3]: requests.models.Response

In [4]: type(r.content)
Out[4]: str

You may also want to check r.text.


How to set DateTime to null

DateTime is a non-nullable value type

DateTime? newdate = null;

You can use a Nullable<DateTime>

c# Nullable Datetime

Convert String to SecureString

below method helps to convert string to secure string

private SecureString ConvertToSecureString(string password)
    if (password == null)
        throw new ArgumentNullException("password");

    var securePassword = new SecureString();

    foreach (char c in password)

    return securePassword;

UITableViewCell, show delete button on swipe

I had a problem which I have just managed to solve so I am sharing it as it may help someone.

I have a UITableView and added the methods shown to enable swipe to delete:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete

I am working on an update that allows me to put the table into edit mode and enables multiselect. To do that I added the code from Apple's TableMultiSelect sample. Once I got that working I found that my swipe the delete function had stopped working.

It turns out that adding the following line to viewDidLoad was the issue:

self.tableView.allowsMultipleSelectionDuringEditing = YES;

With this line in, the multiselect would work but the swipe to delete wouldn't. Without the line it was the other way around.

The fix:

Add the following method to your viewController:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
    self.tableView.allowsMultipleSelectionDuringEditing = editing; 
    [super setEditing:editing animated:animated];

Then in your method that puts the table into editing mode (from a button press for example) you should use:

[self setEditing:YES animated:YES];

instead of:

[self.tableView setEditing:YES animated:YES];

This means that multiselect is only enabled when the table is in editing mode.

How do I post form data with fetch api?

// Write Data

async function write(param) {
  var zahl = param.getAttribute("data-role");

  let mood = {
    appId: app_ID,
    key: "",
    value: zahl

  let response = await fetch(web_api, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    body: JSON.stringify(mood)

// Get Data

async function get() {

  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"

  let todos = await response.json();

// Remove Data

function remove(id) {
  return fetch(web_api" + id, {
    method: "DELETE"
  }).then(response => {
    if (!response.ok) {
      throw new Error("Todo konnte nicht entfernt werden.");

async function removeAll() {
  let response = await fetch(web_api + "/App/" + app_ID, {
    method: "GET",
    headers: {
      "Content-Typ": "application/jason"
  let todos = await response.json();

  for (let todo of todos) {
    await remove(;

// Update Data

  function updateTodo(todo) {
return fetch(`https://__________________/api/items/${}`, {
  method: "PUT",
  body: JSON.stringify(todo),
  headers: {
    "Content-Type": "application/json",
}).then((response) => {
  if (!response.ok) {
    throw new Error("Todo konnte nicht upgedated werden.");


Using Laravel Homestead: 'no input file specified'

I was just struggling with same situation. Following solved the issue:

If you have directory structure like this:

    - map: /Users/me/code/exampleproject
      to: /home/vagrant/code/exampleproject

Just create 'public' folder within exampleproject on your host machine.

Multiple Where clauses in Lambda expressions

x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty).Where(l => l.Internal NAme != String.Empty)


x=> x.Lists.Include(l => l.Title).Where(l=>l.Title != String.Empty && l.Internal NAme != String.Empty)

Box shadow for bottom side only

Try using online generator Change the value and get the code, pretty simple.

How do you push just a single Git branch (and no other branches)?

yes, just do the following

git checkout feature_x
git push origin feature_x

Maven Installation OSX Error Unsupported major.minor version 51.0

Please rather try:

$JAVA_HOME/bin/java -version

Maven uses $JAVA_HOME for classpath resolution of JRE libs. To be sure to use a certain JDK, set it explicitly before compiling, for example:

export JAVA_HOME=/usr/java/jdk1.7.0_51

Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite:

__proto__ VS. prototype in JavaScript

Every function you create has a property called prototype, and it starts off its life as an empty object. This property is of no use until you use this function as constructor function i.e. with the 'new' keyword.

This is often confused with the __proto__ property of an object. Some might get confused and except that the prototype property of an object might get them the proto of an object. But this is not case. prototype is used to get the __proto__ of an object created from a function constructor.

In the above example:

function Person(name){_x000D_ = name_x000D_
}; _x000D_
var eve = new Person("Eve");_x000D_
console.log(eve.__proto__ == Person.prototype) // true_x000D_
// this is exactly what prototype does, made Person.prototype equal to eve.__proto__

I hope it makes sense.

Custom header to HttpClient request

I have found the answer to my question.


That should add a custom header to your request

How to JUnit test that two List<E> contain the same elements in the same order?

Why not simply use List#equals?

assertEquals(argumentComponents, imapPathComponents);

Contract of List#equals:

two lists are defined to be equal if they contain the same elements in the same order.

How can I load Partial view inside the view?

RenderParital is Better to use for performance.


Duplicate headers received from server

Double quotes around the filename in the header is the standard per MDN web docs. Omitting the quotes creates multiple opportunities for problems arising from characters in the filename.

Changing plot scale by a factor in matplotlib

To set the range of the x-axis, you can use set_xlim(left, right), here are the docs


It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:

ticks = your_plot.get_xticks()*10**9

How can I hide the Android keyboard using JavaScript?

I found a simpler solution that requires neither adding element nor a special class. found it there:

And converted the code to jquery :

function hideKeyboard(element) {
    element.attr('readonly', 'readonly'); // Force keyboard to hide on input field.
    element.attr('disabled', 'true'); // Force keyboard to hide on textarea field.
    setTimeout(function() {
        element.blur();  //actually close the keyboard
        // Remove readonly attribute after keyboard is hidden.
    }, 100);

You call the function by passing it the input from which the keyboard was opened, or just passing $('input') should also work.

Javascript - Regex to validate date format

You could use a character class ([./-]) so that the seperators can be any of the defined characters

var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/

Or better still, match the character class for the first seperator, then capture that as a group ([./-]) and use a reference to the captured group \1 to match the second seperator, which will ensure that both seperators are the same:

var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/

"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches

Ascii/Hex convert in bash

SteinAir's answer above was helpful to me -- thank you! And below is a way it inspired, to convert hex strings to ascii:

for h in $(echo "4161" | sed "s/\(..\)/\1 /g"); do printf `echo "\x$h"`;done

how concatenate two variables in batch script?

The way is correct, but can be improved a bit with the extended set-syntax.

set "var=xyz"

Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.

Your code would look like

set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

What is trunk, branch and tag in Subversion?

If you're new to Subversion you may want to check out this post on, appropriately titled Ultimate Round-Up for Version Control with SubVersion.

It covers getting started with SubVersion with links to tutorials, reference materials, & book suggestions.

It covers tools (many are compatible windows), and it mentions AnkhSVN as a Visual Studio compatible plugin. The comments also mention VisualSVN as an alternative.

How to increase number of threads in tomcat thread pool?

Sounds like you should stay with the defaults ;-)

Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor => more parallel threads that can be executed.

See here how to configure...

Tomcat 9:

Tomcat 8:

Tomcat 7:

Tomcat 6:

VBA: Selecting range by variables

I recorded a macro with 'Relative References' and this is what I got :

ActiveCell.Offset(0, 3).Range("A1:D11").Select

Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following:

Dim MyRange as String
MyRange = "A1:D11"

And it worked :) ie.. just create a string using your variables, make sure to dimension it as a STRING variables and Excel will read right off of it ;)

Following tested and found working :

Sub Macro04()

Dim Copyrange As String

Startrow = 1
Lastrow = 11
Let Copyrange = "A" & Startrow & ":" & "D" & Lastrow
End Sub

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

If you are using visual studio dataset designer to get the data table, and it is throwing an error 'Failed to Enable constraints'. I've faced the same problem, try to preview the data from the dataset designer itself and match it with table inside your database.

The best way to solve this issue is to delete the table adapter and create a new one instead.

How to round up with excel VBA round()?

This worked for me

Function round_Up_To_Int(n As Double)
    If Math.Round(n) = n Or Math.Round(n) = 0 Then
        round_Up_To_Int = Math.Round(n)
    Else: round_Up_To_Int = Math.Round(n + 0.5)
    End If
End Function

OpenSSL and error in reading openssl.conf file

  1. first, make sure you have an openssl.cnf file in the right path;
  2. if you can't find it, just download one and copy it to your setting path.

$ set OPENSSL_CONF=C:\OpenSSL\bin\openssl.cnf

Ajax request returns 200 OK, but an error event is fired instead of success

Your script demands a return in JSON data type.

Try this:

private string test() {
  JavaScriptSerializer js = new JavaScriptSerializer();
 return js.Serialize("hello world");

Button inside of anchor link works in Firefox but not in Internet Explorer?

Why not just convert all <button> to <span> with type="button" and then style with your normal css button classes? Just confirmed that this works in IE11.

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).

Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.

It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.

  • This article on gives instructions for setting up OSX under Virtual Box and depends on hardware virtualization. It seems that the Cluster Compute instances (and Cluster GPU, but ignore these) are the only ones supporting hardware virtualization.
  • This article gives instructions for transferring a VirtualBox image to EC2.

Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.

I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.

Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).

After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.

How to pass event as argument to an inline event handler in JavaScript?

Since inline events are executed as functions you can simply use arguments.

<p id="p" onclick="doSomething.apply(this, arguments)">


function doSomething(e) {
  if (!e) e = window.event;
  // 'e' is the event.
  // 'this' is the P element

The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.

Convert and format a Date in JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
 <!DOCTYPE html>
 <html dir="ltr" lang="en-US">
 <meta charset="UTF-8" />
  <title>JSP with the current date</title>
 <%java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy"); %>
<h1>Current Date: <%= df.format(new java.util.Date()) %> </h1>

Output: Current Date: 10/03/2010

Radio button validation in javascript

You could do something like this

var option=document.getElementsByName('Gender');

if (!(option[0].checked || option[1].checked)) {
    alert("Please Select Your Gender");
    return false;

How to make an alert dialog fill 90% of screen size?

The following worked fine for me:

    <style name="MyAlertDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
        <item name="windowFixedWidthMajor">90%</item>
        <item name="windowFixedWidthMinor">90%</item>

(note: windowMinWidthMajor/Minor as suggested in previous answers didn't do the trick. My dialogs kept changing sizes depending on the content)

and then:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),;

Sequence contains no elements?

Well, what is ID here? In particular, is it a local variable? There are some scope / capture issues, which mean that it may be desirable to use a second variable copy, just for the query:

var id = ID;
BlogPost post = (from p in dc.BlogPosts
                 where p.BlogPostID == id
                 select p).Single();

Also; if this is LINQ-to-SQL, then in the current version you get a slightly better behaviour if you use the form:

var id = ID;
BlogPost post = dc.BlogPosts.Single(p => p.BlogPostID == id);

Markdown to create pages and table of contents?

You could try this ruby script to generate the TOC from a markdown file.

 #!/usr/bin/env ruby

require 'uri'

fileName = ARGV[0]
fileName = "" if !fileName, 'r') do |f|
  inside_code_snippet = false
  f.each_line do |line|
    forbidden_words = ['Table of contents', 'define', 'pragma']
    inside_code_snippet = !inside_code_snippet if line.start_with?('```')
    next if !line.start_with?("#") || forbidden_words.any? { |w| line =~ /#{w}/ } || inside_code_snippet

    title = line.gsub("#", "").strip
    href = URI::encode title.gsub(" ", "-").downcase
    puts "  " * (line.count("#")-1) + "* [#{title}](\##{href})"

Remove ALL white spaces from text

Use replace(/\s+/g,''),

for example:

const stripped = '    My String With A    Lot Whitespace  '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'

How can I wrap text in a label using WPF?

You can put a TextBlock inside the label:

  <TextBlock Text="Long Text . . . ." TextWrapping="Wrap" /> 

Undoing a 'git push'

I believe that you can also do this:

git checkout alpha-0.3.0
git reset --hard cc4b63bebb6
git push origin +alpha-0.3.0

This is very similar to the last method, except you don't have to muck around in the remote repo.

How to make background of table cell transparent

You can do it setting the transparency via style right within the table tag:

<table id="Main table" style="background-color:rgba(0, 0, 0, 0);">

The last digit in the rgba function is for transparency. 1 means 100% opaque, while 0 stands for 100% transparent.

Regular Expression usage with ls

You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:

$ ls | egrep '.+\..+'

Convert varchar to float IF ISNUMERIC

I found this very annoying bug while converting EmployeeID values with ISNUMERIC:

ISNUMERIC(ISNULL([EmployeeID], '')) AS [IsNumericResult],

CASE WHEN COALESCE(NULLIF(tmpImport.[EmployeeID], ''), 'Z')
    LIKE '%[^0-9]%' THEN 'NonNumeric' ELSE 'Numeric'
END AS [IsDigitsResult]
FROM [MyTable]

This returns:

EmployeeID IsNumericResult MyCustomResult
---------- --------------- --------------
           0               NonNumeric
00000000c  0               NonNumeric
00D026858  1               NonNumeric

(3 row(s) affected)

Hope this helps!

Remove blank values from array using C#

I write below code to remove the blank value in the array string.

string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();

Is it possible to view RabbitMQ message contents directly from the command line?

Here are the commands I use to get the contents of the queue:

RabbitMQ version 3.1.5 on Fedora linux using

Here are my exchanges:

eric@dev ~ $ sudo python rabbitmqadmin list exchanges
| vhost |        name        |  type   | auto_delete | durable | internal |
| /     |                    | direct  | False       | True    | False    |
| /     | kowalski           | topic   | False       | True    | False    |

Here is my queue:

eric@dev ~ $ sudo python rabbitmqadmin list queues
| vhost |   name   | auto_delete | consumers | durable | exclusive_consumer_tag |     idle_since      | memory | messages | messages_ready | messages_unacknowledged |        node         | policy | status  |
| /     | myqueue  | False       | 0         | True    |                        | 2014-09-10 13:32:18 | 13760  | 0        | 0              | 0                       |rabbit@ip-11-1-52-125|        | running |

Cram some items into myqueue:

curl -i -u guest:guest http://localhost:15672/api/exchanges/%2f/kowalski/publish -d '{"properties":{},"routing_key":"abcxyz","payload":"foobar","payload_encoding":"string"}'
HTTP/1.1 200 OK
Server: MochiWeb/1.1 WebMachine/1.10.0 (never breaks eye contact)
Date: Wed, 10 Sep 2014 17:46:59 GMT
content-type: application/json
Content-Length: 15
Cache-Control: no-cache


RabbitMQ see messages in queue:

eric@dev ~ $ sudo python rabbitmqadmin get queue=myqueue requeue=true count=10
| routing_key | exchange | message_count |                        payload        | payload_bytes | payload_encoding | properties | redelivered |
| abcxyz      | kowalski | 10            | foobar                                | 6             | string           |            | True        |
| abcxyz      | kowalski | 9             | {'testdata':'test'}                   | 19            | string           |            | True        |
| abcxyz      | kowalski | 8             | {'mykey':'myvalue'}                   | 19            | string           |            | True        |
| abcxyz      | kowalski | 7             | {'mykey':'myvalue'}                   | 19            | string           |            | True        |

Initializing select with AngularJS and ng-repeat

OK. If you don't want to use the correct way ng-options, you can add ng-selected attribute with a condition check logic for the option directive to to make the pre-select work.

<select ng-model="filterCondition.operator">
    <option ng-selected="{{operator.value == filterCondition.operator}}"
            ng-repeat="operator in operators"

Working Demo

Change grid interval and specify tick labels in Matplotlib

There are several problems in your code.

First the big ones:

  1. You are creating a new figure and a new axes in every iteration of your loop ? put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop.

  2. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords.

  3. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal').

The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b)

This should be a working minimal example:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

# Major ticks every 20, minor ticks every 5
major_ticks = np.arange(0, 101, 20)
minor_ticks = np.arange(0, 101, 5)

ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(minor_ticks, minor=True)

# And a corresponding grid

# Or if you want different settings for the grids:
ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=0.5)

Output is this:


When should I use the new keyword in C++?

The second method creates the instance on the stack, along with such things as something declared int and the list of parameters that are passed into the function.

The first method makes room for a pointer on the stack, which you've set to the location in memory where a new MyClass has been allocated on the heap - or free store.

The first method also requires that you delete what you create with new, whereas in the second method, the class is automatically destructed and freed when it falls out of scope (the next closing brace, usually).

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

how to install apk application from my pc to my mobile android

1) Put the apk on your SDKCard and install file browsers like "Estrongs File Explorer", "Easy Installer", etc...

2) Go to your mobile settings - applications- debuging - and thick "USB debugging" enter image description here

Setting background-image using jQuery CSS property

You'll want to include double quotes (") before and after the imageUrl like this:

$('myOjbect').css('background-image', 'url("' + imageUrl + '")');

This way, if the image has spaces it will still be set as a property.

How is a tag different from a branch in Git? Which should I use, here?

The Git Parable explains how a typical DVCS gets created and why their creators did what they did. Also, you might want to take a look at Git for Computer Scientist; it explains what each type of object in Git does, including branches and tags.

How do I properly compare strings in C?

    int main()
        char s1[50],s2[50];
        printf("Enter the character of strings: ");
        printf("\nEnter different character of string to repeat: \n");
        return 0;

This is very simple solution in which you will get your output as you want.

Converting any object to a byte array in java

Yeah. Just use binary serialization. You have to have each object use implements Serializable but it's straightforward from there.

Your other option, if you want to avoid implementing the Serializable interface, is to use reflection and read and write data to/from a buffer using a process this one below:

 * Sets all int fields in an object to 0.
 * @param obj The object to operate on.
 * @throws RuntimeException If there is a reflection problem.
 public static void initPublicIntFields(final Object obj) {
    try {
       Field[] fields = obj.getClass().getFields();
       for (int idx = 0; idx < fields.length; idx++) {
          if (fields[idx].getType() == int.class) {
              fields[idx].setInt(obj, 0);
    } catch (final IllegalAccessException ex) {
       throw new RuntimeException(ex);


Get full path of the files in PowerShell

Get-ChildItem -Recurse *.txt | Format-Table FullName

That is what I used. I feel it is more understandable as it doesn't contain any loop syntax.

What is the most effective way for float and double comparison?

/// testing whether two doubles are almost equal. We consider two doubles
/// equal if the difference is within the range [0, epsilon).
/// epsilon: a positive number (supposed to be small)
/// if either x or y is 0, then we are comparing the absolute difference to
/// epsilon.
/// if both x and y are non-zero, then we are comparing the relative difference
/// to epsilon.
bool almost_equal(double x, double y, double epsilon)
    double diff = x - y;
    if (x != 0 && y != 0){
        diff = diff/y; 

    if (diff < epsilon && -1.0*diff < epsilon){
        return true;
    return false;

I used this function for my small project and it works, but note the following:

Double precision error can create a surprise for you. Let's say epsilon = 1.0e-6, then 1.0 and 1.000001 should NOT be considered equal according to the above code, but on my machine the function considers them to be equal, this is because 1.000001 can not be precisely translated to a binary format, it is probably 1.0000009xxx. I test it with 1.0 and 1.0000011 and this time I get the expected result.

Pinging an IP address using PHP and echoing the result

This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,

function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);  
    if ($status==0) {
    $status = "alive";
    } else {
    $status = "dead";
    $message .= '<div id="dialog-block-left">';
    $message .= '<div id="ip-status">The IP address, '.$ip.', is  '.$status.'</div><div style="clear:both"></div>';    
    return $message;
// Some IP Address

This worked perfectly for me, finally. I referred this from Hope this will help

Well I want to modify this as it is working fine on my localhost but not on my live server For live server, I got another thing which now works for both local as well as live.

$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }

Then I show the Server is up for 0 and down for 1.

This works perfectly for me. I got this from Ping site and return result in PHP Thanks @karim79

How to launch Safari and open URL from iOS app

The non deprecated Objective-C version would be:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@""] options:@{} completionHandler:nil];

How to clear form after submit in Angular 2?

See also (section "reset the form flags")


In RC.6 it should be supported to update the form model. Creating a new form group and assigning to myForm


will also be supported (



In the new forms module (>= RC.5) NgForm has a reset() method and also supports a forms reset event.


This will work:

onSubmit(value:any):void {
  //send some data to backend
  for(var name in form.controls) {
    /*(<FormControl>form.controls[name]).updateValue('');*/ this should work in RC4 if `Control` is not working, working same in my case

See also

Recommended way to get hostname in Java

Just one-liner ... cross platform (Windows-Linux-Unix-Mac(Unix)) [Always works, No DNS required]:

String hostname = new BufferedReader(
    new InputStreamReader(Runtime.getRuntime().exec("hostname").getInputStream()))

You're done !!

Remove a character at a certain position in a string - javascript

var str = 'Hello World',
    i = 3,
    result = str.substr(0, i-1)+str.substring(i);


Value of i should not be less then 1.

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000

How to solve WAMP and Skype conflict on Windows 7?

A small update for the new Skype options window. Please follow this:

Go to Tools ? Options ? Advanced ? Connection and uncheck the box use port 80 and 443 as alternatives for incoming connections. mvc3 return raw html to view

In controller you can use MvcHtmlString

public class HomeController : Controller
    public ActionResult Index()
        string rawHtml = "<HTML></HTML>";
        ViewBag.EncodedHtml = MvcHtmlString.Create(rawHtml);
        return View();

In your View you can simply use that dynamic property which you set in your Controller like below


Adding three months to a date in PHP

The following should work, but you may need to change the format:

echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

malloc for struct and pointer in C

When you allocate memory for struct Vector you just allocate memory for pointer x, i.e. for space, where its value, which contains address, will be placed. So such way you do not allocate memory for the block, on which y.x will reference.

Search in lists of lists by given index

Here's the Pythonic way to do it:

data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
any(e[1] == search for e in data)

Or... well, I'm not going to claim this is the "one true Pythonic way" to do it because at some point it becomes a little subjective what is Pythonic and what isn't, or which method is more Pythonic than another. But using any() is definitely more typical Python style than a for loop as in e.g. RichieHindle's answer,

Of course there is a hidden loop in the implementation of any, although it breaks out of the loop as soon as it finds a match.

Since I was bored I made a timing script to compare performance of the different suggestions, modifying some of them as necessary to make the API the same. Now, we should bear in mind that fastest is not always best, and being fast is definitely not the same thing as being Pythonic. That being said, the results are... strange. Apparently for loops are very fast, which is not what I expected, so I'd take these with a grain of salt without understanding why they've come out the way they do.

Anyway, when I used the list defined in the question with three sublists of two elements each, from fastest to slowest I get these results:

  1. RichieHindle's answer with the for loop, clocking in at 0.22 µs
  2. Terence Honles' first suggestion which creates a list, at 0.36 µs
  3. Pierre-Luc Bedard's answer (last code block), at 0.43 µs
  4. Essentially tied between Markus's answer and the for loop from the original question, at 0.48 µs
  5. Coady's answer using operator.itemgetter(), at 0.53 µs
  6. Close enough to count as a tie between Alex Martelli's answer with ifilter() and Anon's answer, at 0.67 µs (Alex's is consistently about half a microsecond faster)
  7. Another close-enough tie between jojo's answer, mine, Brandon E Taylor's (which is identical to mine), and Terence Honles' second suggestion using any(), all coming in at 0.81-0.82 µs
  8. And then user27221's answer using nested list comprehensions, at 0.95 µs

Obviously the actual timings are not meaningful on anyone else's hardware, but the differences between them should give some idea of how close the different methods are.

When I use a longer list, things change a bit. I started with the list in the question, with three sublists, and appended another 197 sublists, for a total of 200 sublists each of length two. Using this longer list, here are the results:

  1. RichieHindle's answer, at the same 0.22 µs as with the shorter list
  2. Coady's answer using operator.itemgetter(), again at 0.53 µs
  3. Terence Honles' first suggestion which creates a list, at 0.36 µs
  4. Another virtual tie between Alex Martelli's answer with ifilter() and Anon's answer, at 0.67 µs
  5. Again a close-enough tie between my answer, Brandon E Taylor's identical method, and Terence Honles' second suggestion using any(), all coming in at 0.81-0.82 µs

Those are the ones that keep their original timing when the list is extended. The rest, which don't, are

  1. The for loop from the original question, at 1.24 µs
  2. Terence Honles' first suggestion which creates a list, at 7.49 µs
  3. Pierre-Luc Bedard's answer (last code block), at 8.12 µs
  4. Markus's answer, at 10.27 µs
  5. jojo's answer, at 19.87 µs
  6. And finally user27221's answer using nested list comprehensions, at 60.59 µs

Unexpected character encountered while parsing value

When I encountered a similar problem, I fixed it by substituting &mode=xml for &mode=json in the request.

Set style for TextView programmatically

You can create a generic style and re-use it on multiple textviews like the one below:


Edit: this refers to Context

mysql query: SELECT DISTINCT column1, GROUP BY column2

Somehow your requirement sounds a bit contradictory ..

group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

What do you think should happen if two people (names) worked from the same IP within the time period specified?

Did you try this?

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday AND time <$today 
GROUP BY name,ip

How to use ScrollView in Android?

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android=""

    android:layout_height="fill_parent" >

        android:stretchColumns="1" >

            android:layout_height="wrap_content" >

                android:layout_height="match_parent" >

                    android:text="@string/buton1Text" />

                    android:text="@string/buton2Text" />

            android:layout_height="wrap_content" >

                android:visibility="invisible" >

                    android:layout_height="wrap_content" >

                        android:inputType="textMultiLine" />

            android:layout_height="wrap_content" >

                android:text="deneme" />

            android:layout_height="wrap_content" >

                android:text="deneme" />


Can Keras with Tensorflow backend be forced to use CPU or GPU at will?

If you want to force Keras to use CPU

Way 1

import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""

before Keras / Tensorflow is imported.

Way 2

Run your script as


See also


Setting Elastic search limit to "unlimited"

Another approach is to first do a searchType: 'count', then and then do a normal search with size set to results.count.

The advantage here is it avoids depending on a magic number for UPPER_BOUND as suggested in this similar SO question, and avoids the extra overhead of building too large of a priority queue that Shay Banon describes here. It also lets you keep your results sorted, unlike scan.

The biggest disadvantage is that it requires two requests. Depending on your circumstance, this may be acceptable.

What is the purpose of the return statement?

Best thing about return function is you can return a value from function but you can do same with print so whats the difference ? Basically return not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do with print because its same like stdout/cout in C Programming.

Follow below code for better understanding


def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b

print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

We are now doing our own math functions for add, subtract, multiply, and divide. The important thing to notice is the last line where we say return a + b (in add). What this does is the following:

  1. Our function is called with two arguments: a and b.
  2. We print out what our function is doing, in this case "ADDING."
  3. Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them."
  4. Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
for i in "$list"; do
    echo $i
for i in ${array[@]}; do
    echo $i

How to add a line to a multiline TextBox?

The adding of Environment.NewLine or \r\n was not working for me, initially, with my textbox. I found I had forgotten to go into the textbox's Behavior properties and set the "Multiline" property to "True" for it to add the lines! I just thought I'd add this caveat since no one else did in the answers, above, and I had thought the box was just going to auto-expand and forgot I needed to actually set the Mulitline property for it to work. I know it's sort of a bonehead thing (which is the kind of thing that happens to us late on a Friday afternoon), but it might help someone remember to check that. Also, in the Appearance section is the "ScrollBars" property that I needed to set to "Both", to get both horizontal and vertical bars so that text could actually be scrolled and seen in its entirety. So the answer here isn't just a code one by appending Environment.NewLine or \r\n to the .Text, but also make sure your box is set up properly with the right properties.

String replace method is not replacing characters

You should re-assign the result of the replacement, like this:

 sentence = sentence.replace("and", " ");

Be aware that the String class is immutable, meaning that all of its methods return a new string and never modify the original string in-place, so the result of invoking a method in an instance of String must be assigned to a variable or used immediately for the change to take effect.

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

AS Scott mentioned here After windows installed security update for .net framework, you will meet this problem. just modify the configuration section in your web.config file and switch to a different cookie name.

How to pass a value to razor variable from javascript variable?

Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.

I have a List<QuestionType> that I fill a drop down with. I want to put that selection into the QuestionType property on the Question object that I'm creating in the form. I'm using Knockout.js for the select binding. This sets the self.QuestionType knockout observable property to a QuestionType object when the user selects one.

<select class="form-control form-control-sm"
    data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">

I have a hidden field that will hold this object:

@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)

In the subscription for the observable, I set the hidden field to a JSON.stringify-ed version of the object.

self.QuestionType.subscribe(function(newValue) {
    if (newValue !== null && newValue !== undefined) {                       
        document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);

In the Question object, I have a field called QuestionTypeJson that is filled when the user selects a question type. I use this field to get the QuestionType in the Question object like this:

public string QuestionTypeJson { get; set; }

private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
    get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
    set => _questionType = value;

So if the QuestionTypeJson field contains something, it will deserialize that and use it for QuestionType, otherwise it'll just use what is in the backing field.

I have essentially 'passed' a JavaScript object to my model without using Razor or an Ajax call. You can probably do something similar to this without using Knockout.js, but that's what I'm using so...

Computing cross-correlation function?

I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.

It will calculate cross-correlation either directly, using scipy.ndimage.correlate, or in the frequency domain, using scipy.fftpack.fftn/ifftn depending on whichever will be quickest.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

You can use hibernate lazy initializer.

Below is the code you can refer.
Here PPIDO is the data object which I want to retrieve

if (ppiDO instanceof HibernateProxy) {
    ppiDO = (PolicyProductInsuredDO) ((HibernateProxy) ppiDO).getHibernateLazyInitializer()
    proxyFl = true;

tomcat - CATALINA_BASE and CATALINA_HOME variables


If you're running multiple instances, then you need both variables, otherwise only CATALINA_HOME.

In other words: CATALINA_HOME is required and CATALINA_BASE is optional.

CATALINA_HOME represents the root of your Tomcat installation.

Optionally, Tomcat may be configured for multiple instances by defining $CATALINA_BASE for each instance. If multiple instances are not configured, $CATALINA_BASE is the same as $CATALINA_HOME.

See: Apache Tomcat 7 - Introduction

Running with separate CATALINA_HOME and CATALINA_BASE is documented in RUNNING.txt which say:

The CATALINA_HOME and CATALINA_BASE environment variables are used to specify the location of Apache Tomcat and the location of its active configuration, respectively.

You cannot configure CATALINA_HOME and CATALINA_BASE variables in the setenv script, because they are used to find that file.

For example:

(4.1) Tomcat can be started by executing one of the following commands:

  %CATALINA_HOME%\bin\startup.bat         (Windows)

  $CATALINA_HOME/bin/           (Unix)


  %CATALINA_HOME%\bin\catalina.bat start  (Windows)

  $CATALINA_HOME/bin/ start    (Unix)

Multiple Tomcat Instances

In many circumstances, it is desirable to have a single copy of a Tomcat binary distribution shared among multiple users on the same server. To make this possible, you can set the CATALINA_BASE environment variable to the directory that contains the files for your 'personal' Tomcat instance.

When running with a separate CATALINA_HOME and CATALINA_BASE, the files and directories are split as following:


  • bin - Only: (*nix) or setenv.bat (Windows), tomcat-juli.jar
  • conf - Server configuration files (including server.xml)
  • lib - Libraries and classes, as explained below
  • logs - Log and output files
  • webapps - Automatically loaded web applications
  • work - Temporary working directories for web applications
  • temp - Directory used by the JVM for temporary files>


  • bin - Startup and shutdown scripts
  • lib - Libraries and classes, as explained below
  • endorsed - Libraries that override standard "Endorsed Standards". By default it's absent.

How to check

The easiest way to check what's your CATALINA_BASE and CATALINA_HOME is by running, for example:

$ /usr/share/tomcat7/bin/
Using CATALINA_BASE:   /usr/share/tomcat7
Using CATALINA_HOME:   /usr/share/tomcat7

You may also check where the Tomcat files are installed, by dpkg tool as below (Debian/Ubuntu):

dpkg -L tomcat7-common

How do I test for an empty JavaScript object?

Here is a fast, simple, function:

function isEmptyFunction () {
  for (const i in this) return false
  return true

Implemented as a getter:

Object.defineProperty(Object.prototype, 'isEmpty', { get: isEmptyFunction })

console.log({}.isEmpty) // true

Implemented as a separate function:

const isEmpty =

console.log(isEmpty({})) // true

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.