Programs & Examples On #Strong typing

A typing system that enforces restrictions on which operations or methods may be called on an object based on type.

Is Python strongly typed?

There are some important issues that I think all of the existing answers have missed.


Weak typing means allowing access to the underlying representation. In C, I can create a pointer to characters, then tell the compiler I want to use it as a pointer to integers:

char sz[] = "abcdefg";
int *i = (int *)sz;

On a little-endian platform with 32-bit integers, this makes i into an array of the numbers 0x64636261 and 0x00676665. In fact, you can even cast pointers themselves to integers (of the appropriate size):

intptr_t i = (intptr_t)&sz;

And of course this means I can overwrite memory anywhere in the system.*

char *spam = (char *)0x12345678
spam[0] = 0;

* Of course modern OS's use virtual memory and page protection so I can only overwrite my own process's memory, but there's nothing about C itself that offers such protection, as anyone who ever coded on, say, Classic Mac OS or Win16 can tell you.

Traditional Lisp allowed similar kinds of hackery; on some platforms, double-word floats and cons cells were the same type, and you could just pass one to a function expecting the other and it would "work".

Most languages today aren't quite as weak as C and Lisp were, but many of them are still somewhat leaky. For example, any OO language that has an unchecked "downcast",* that's a type leak: you're essentially telling the compiler "I know I didn't give you enough information to know this is safe, but I'm pretty sure it is," when the whole point of a type system is that the compiler always has enough information to know what's safe.

* A checked downcast doesn't make the language's type system any weaker just because it moves the check to runtime. If it did, then subtype polymorphism (aka virtual or fully-dynamic function calls) would be the same violation of the type system, and I don't think anyone wants to say that.

Very few "scripting" languages are weak in this sense. Even in Perl or Tcl, you can't take a string and just interpret its bytes as an integer.* But it's worth noting that in CPython (and similarly for many other interpreters for many languages), if you're really persistent, you can use ctypes to load up libpython, cast an object's id to a POINTER(Py_Object), and force the type system to leak. Whether this makes the type system weak or not depends on your use cases—if you're trying to implement an in-language restricted execution sandbox to ensure security, you do have to deal with these kinds of escapes…

* You can use a function like struct.unpack to read the bytes and build a new int out of "how C would represent these bytes", but that's obviously not leaky; even Haskell allows that.


Meanwhile, implicit conversion is really a different thing from a weak or leaky type system.

Every language, even Haskell, has functions to, say, convert an integer to a string or a float. But some languages will do some of those conversions for you automatically—e.g., in C, if you call a function that wants a float, and you pass it in int, it gets converted for you. This can definitely lead to bugs with, e.g., unexpected overflows, but they're not the same kinds of bugs you get from a weak type system. And C isn't really being any weaker here; you can add an int and a float in Haskell, or even concatenate a float to a string, you just have to do it more explicitly.

And with dynamic languages, this is pretty murky. There's no such thing as "a function that wants a float" in Python or Perl. But there are overloaded functions that do different things with different types, and there's a strong intuitive sense that, e.g., adding a string to something else is "a function that wants a string". In that sense, Perl, Tcl, and JavaScript appear to do a lot of implicit conversions ("a" + 1 gives you "a1"), while Python does a lot fewer ("a" + 1 raises an exception, but 1.0 + 1 does give you 2.0*). It's just hard to put that sense into formal terms—why shouldn't there be a + that takes a string and an int, when there are obviously other functions, like indexing, that do?

* Actually, in modern Python, that can be explained in terms of OO subtyping, since isinstance(2, numbers.Real) is true. I don't think there's any sense in which 2 is an instance of the string type in Perl or JavaScript… although in Tcl, it actually is, since everything is an instance of string.


Finally, there's another, completely orthogonal, definition of "strong" vs. "weak" typing, where "strong" means powerful/flexible/expressive.

For example, Haskell lets you define a type that's a number, a string, a list of this type, or a map from strings to this type, which is a perfectly way to represent anything that can be decoded from JSON. There's no way to define such a type in Java. But at least Java has parametric (generic) types, so you can write a function that takes a List of T and know that the elements are of type T; other languages, like early Java, forced you to use a List of Object and downcast. But at least Java lets you create new types with their own methods; C only lets you create structures. And BCPL didn't even have that. And so on down to assembly, where the only types are different bit lengths.

So, in that sense, Haskell's type system is stronger than modern Java's, which is stronger than earlier Java's, which is stronger than C's, which is stronger than BCPL's.

So, where does Python fit into that spectrum? That's a bit tricky. In many cases, duck typing allows you to simulate everything you can do in Haskell, and even some things you can't; sure, errors are caught at runtime instead of compile time, but they're still caught. However, there are cases where duck typing isn't sufficient. For example, in Haskell, you can tell that an empty list of ints is a list of ints, so you can decide that reducing + over that list should return 0*; in Python, an empty list is an empty list; there's no type information to help you decide what reducing + over it should do.

* In fact, Haskell doesn't let you do this; if you call the reduce function that doesn't take a start value on an empty list, you get an error. But its type system is powerful enough that you could make this work, and Python's isn't.

What is the difference between a strongly typed language and a statically typed language?

Strongly typed means that there are restrictions between conversions between types.

Statically typed means that the types are not dynamic - you can not change the type of a variable once it has been created.

How to create a JPA query with LEFT OUTER JOIN

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

Does HTML5 <video> playback support the .avi format?

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.

http://en.wikipedia.org/wiki/HTML5_video

What is Bootstrap?

Bootstrap is an open-source Javascript framework developed by the team at Twitter. It is a combination of HTML, CSS, and Javascript code designed to help build user interface components. Bootstrap was also programmed to support both HTML5 and CSS3.

Also it is called Front-end-framework.

Bootstrap is a free collection of tools for creating a websites and web applications.

It contains HTML and CSS-based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions.

Some Reasons for programmers preferred Bootstrap Framework

  1. Easy to get started

  2. Great grid system

  3. Base styling for most HTML elements(Typography,Code,Tables,Forms,Buttons,Images,Icons)

  4. Extensive list of components

  5. Bundled Javascript plugins

Taken from About Bootstrap Framework

Python and SQLite: insert into table

Adapted from http://docs.python.org/library/sqlite3.html:

# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

Add a scrollbar to a <textarea>

HTML:

<textarea rows="10" cols="20" id="text"></textarea>

CSS:

#text
{
    overflow-y:scroll;
}

how to inherit Constructor from super class to sub class

Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?

It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.

Why do python lists have pop() but not push()

Push is a defined stack behaviour; if you pushed A on to stack (B,C,D) you would get (A,B,C,D).

If you used python append, the resulting dataset would look like (B,C,D,A)

Edit: Wow, holy pedantry.

I would assume that it would be clear from my example which part of the list is the top, and which part is the bottom. Assuming that most of us here read from left to right, the first element of any list is always going to be on the left.

How can I symlink a file in Linux?

How to create symlink in vagrant. Steps:

  1. In vagrant file create a synced folder. e.g config.vm.synced_folder "F:/Sunburst/source/sunburst/lms", "/source" F:/Sunburst/source/sunburst/lms :- where the source code, /source :- directory path inside the vagrant
  2. Vagrant up and type vagrant ssh and go to source directory e.g cd source
  3. Verify your source code folder structure is available in the source directory. e.g /source/local
  4. Then go to the guest machine directory where the files which are associate with the browser. After get backup of the file. e.g sudo mv local local_bk
  5. Then create symlink e.g sudo ln -s /source/local local. local mean link-name (folder name in guest machine which you are going to link) if you need to remove the symlink :- Type sudo rm local

How to hide soft keyboard on android after clicking outside EditText?

setupUI((RelativeLayout) findViewById(R.id.activity_logsign_up_RelativeLayout));

Pass the method into your layout file. You must choose your common layout file in XML. Because, keyboard hide works with whole layout.

public void setupUI(View view) {
        // Set up touch listener for non-text box views to hide keyboard.
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard(Your Context); // Pass your context
                    return false;
                }
            });
        }
        //If a layout container, iterate over children and seed recursion.
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setupUI(innerView);
            }
        }
    }

iPhone App Development on Ubuntu

There are several way to do it, may decide to go the native way by downloading a VM application for linux and the install Mac OS in your VM and then download the Xcode application for mac But the true is i tried this path but it was really long so i decide to get sencha touch and phonegap for mobile phone,here the sencha-touch is a javascript framework that will help you in developing the interfaces and the phonegap is also javascript library which will help to access the feature of your Iphone or any oher mobile platform I'm using sencha-touch and phonegap ,its really work for me

converting Java bitmap to byte array

CompressFormat is too slow...

Try ByteBuffer.

???Bitmap to byte???

width = bitmap.getWidth();
height = bitmap.getHeight();

int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byteArray = byteBuffer.array();

???byte to bitmap???

Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name());
Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
bitmap_tmp.copyPixelsFromBuffer(buffer);

How to copy from CSV file to PostgreSQL table with headers in CSV file?

You can use d6tstack which creates the table for you and is faster than pd.to_sql() because it uses native DB import commands. It supports Postgres as well as MYSQL and MS SQL.

import pandas as pd
df = pd.read_csv('table.csv')
uri_psql = 'postgresql+psycopg2://usr:pwd@localhost/db'
d6tstack.utils.pd_to_psql(df, uri_psql, 'table')

It is also useful for importing multiple CSVs, solving data schema changes and/or preprocess with pandas (eg for dates) before writing to db, see further down in examples notebook

d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'), 
    apply_after_read=apply_fun).to_psql_combine(uri_psql, 'table')

How to add a second css class with a conditional value in razor MVC 4

I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:

Your answer (assuming this works, I haven't tried this):

<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">

Second option:

@if (Model.Details.Count > 0) {
    <div class="details show">
}
else {
    <div class="details hide">
}

Third option:

<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">

What is the difference between % and %% in a cmd file?

(Explanation in more details can be found in an archived Microsoft KB article.)

Three things to know:

  1. The percent sign is used in batch files to represent command line parameters: %1, %2, ...
  2. Two percent signs with any characters in between them are interpreted as a variable:

    echo %myvar%

  3. Two percent signs without anything in between (in a batch file) are treated like a single percent sign in a command (not a batch file): %%f

Why's that?

For example, if we execute your (simplified) command line

FOR /f %f in ('dir /b .') DO somecommand %f

in a batch file, rule 2 would try to interpret

%f in ('dir /b .') DO somecommand %

as a variable. In order to prevent that, you have to apply rule 3 and escape the % with an second %:

FOR /f %%f in ('dir /b .') DO somecommand %%f

How to find all occurrences of an element in a list

Or Use range (python 3):

l=[i for i in range(len(lst)) if lst[i]=='something...']

For (python 2):

l=[i for i in xrange(len(lst)) if lst[i]=='something...']

And then (both cases):

print(l)

Is as expected.

How to check if a column exists in a datatable

DataColumnCollection col = datatable.Columns;        
if (!columns.Contains("ColumnName1"))
{
   //Column1 Not Exists
}

if (columns.Contains("ColumnName2"))
{
   //Column2 Exists
}

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

Trying to add adb to PATH variable OSX

Just encase anyone finds this SO post when using Android Studio which includes the SDK has part of the App package (on Mac OSX).

So as @davecaunt and @user1281750 noted but insert the following line to .bash_profile

export PATH=/Applications/Android\ Studio.app/sdk/tools:/Applications/Android\ Studio.app/sdk/platform-tools:$PATH

Why does the Visual Studio editor show dots in blank spaces?

In Visual Studio vesrion 1.34.0 View -> Toggle Render Whitespace

How to download a file with Node.js (without using third-party libraries)?

Writing my own solution since the existing didn't fit my requirements.

What this covers:

  • HTTPS download (switch package to http for HTTP downloads)
  • Promise based function
  • Handle forwarded path (status 302)
  • Browser header - required on a few CDNs
  • Filename from URL (as well as hardcoded)
  • Error handling

It's typed, it's safer. Feel free to drop the types if you're working with plain JS (no Flow, no TS) or convert to a .d.ts file

index.js

import httpsDownload from httpsDownload;
httpsDownload('https://example.com/file.zip', './');

httpsDownload.[js|ts]

import https from "https";
import fs from "fs";
import path from "path";

function download(
  url: string,
  folder?: string,
  filename?: string
): Promise<void> {
  return new Promise((resolve, reject) => {
    const req = https
      .request(url, { headers: { "User-Agent": "javascript" } }, (response) => {
        if (response.statusCode === 302 && response.headers.location != null) {
          download(
            buildNextUrl(url, response.headers.location),
            folder,
            filename
          )
            .then(resolve)
            .catch(reject);
          return;
        }

        const file = fs.createWriteStream(
          buildDestinationPath(url, folder, filename)
        );
        response.pipe(file);
        file.on("finish", () => {
          file.close();
          resolve();
        });
      })
      .on("error", reject);
    req.end();
  });
}

function buildNextUrl(current: string, next: string) {
  const isNextUrlAbsolute = RegExp("^(?:[a-z]+:)?//").test(next);
  if (isNextUrlAbsolute) {
    return next;
  } else {
    const currentURL = new URL(current);
    const fullHost = `${currentURL.protocol}//${currentURL.hostname}${
      currentURL.port ? ":" + currentURL.port : ""
    }`;
    return `${fullHost}${next}`;
  }
}

function buildDestinationPath(url: string, folder?: string, filename?: string) {
  return path.join(folder ?? "./", filename ?? generateFilenameFromPath(url));
}

function generateFilenameFromPath(url: string): string {
  const urlParts = url.split("/");
  return urlParts[urlParts.length - 1] ?? "";
}

export default download;

Restore the mysql database from .frm files

I just copy pasted the database folders to data folder in MySQL, i.e. If you have a database called alto then find the folder alto in your MySQL -> Data folder in your backup and copy the entire alto folder and past it to newly installed MySQL -> data folder, restart the MySQL and this works perfect.

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

Save results to csv file with Python

This is how I do it

 import csv
    file = open('???.csv', 'r')
    read = csv.reader(file)
    for column in read:
            file = open('???.csv', 'r')
            read = csv.reader(file)
            file.close()
            file = open('????.csv', 'a', newline='')
            write = csv.writer(file, delimiter = ",")
            write.writerow((, ))
            file.close()

Commit empty folder structure (with git)

Just add a file .gitkeep in every folder you want committed.

On windows do so by right clicking when in the folder and select: Git bash from here. Then type: touch .gitkeep

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Static constant string (class member)

Fast forward to 2018 and C++17.

  • do not use std::string, use std::string_view literals
  • please do notice the 'constexpr' bellow. This is also an "compile time" mechanism.
  • no inline does not mean repetition
  • no cpp files are not necessary for this
  • static_assert 'works' at compile time only

    using namespace std::literals;
    
    namespace STANDARD {
    constexpr 
    inline 
    auto 
    compiletime_static_string_view_constant() {
    // make and return string view literal
    // will stay the same for the whole application lifetime
    // will exhibit standard and expected interface
    // will be usable at both
    // runtime and compile time
    // by value semantics implemented for you
        auto when_needed_ =  "compile time"sv;
        return when_needed_  ;
    }
    

    };

Above is a proper and legal standard C++ citizen. It can get readily involved in any and all std:: algorithms, containers, utilities and a such. For example:

// test the resilience
auto return_by_val = []() {
    auto return_by_val = []() {
        auto return_by_val = []() {
            auto return_by_val = []() {
return STANDARD::compiletime_static_string_view_constant();
            };
            return return_by_val();
        };
        return return_by_val();
    };
    return return_by_val();
};

// actually a run time 
_ASSERTE(return_by_val() == "compile time");

// compile time 
static_assert(
   STANDARD::compiletime_static_string_view_constant() 
   == "compile time" 
 );

Enjoy the standard C++

Behaviour of increment and decrement operators in Python

When you want to increment or decrement, you typically want to do that on an integer. Like so:

b++

But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:

>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162334512
>>> a is b
True

a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:

b = b + 1

Or simpler:

b += 1

Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.

In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.

How do I fit an image (img) inside a div and keep the aspect ratio?

Unfortunately max-width + max-height do not fully cover my task... So I have found another solution:

To save the Image ratio while scaling you also can use object-fit CSS3 propperty.

Useful article: Control image aspect ratios with CSS3

img {
    width: 100%; /* or any custom size */
    height: 100%; 
    object-fit: contain;
}

Bad news: IE not supported (Can I Use)

How do I list all tables in a schema in Oracle SQL?

select * from cat;

it will show all tables in your schema cat synonym of user_catalog

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

Output Django queryset as JSON

You can use JsonResponse with values. Simple example:

from django.http import JsonResponse

def some_view(request):
    data = list(SomeModel.objects.values())  # wrap in list(), because QuerySet is not JSON serializable
    return JsonResponse(data, safe=False)  # or JsonResponse({'data': data})

Or another approach with Django's built-in serializers:

from django.core import serializers
from django.http import HttpResponse

def some_view(request):
    qs = SomeModel.objects.all()
    qs_json = serializers.serialize('json', qs)
    return HttpResponse(qs_json, content_type='application/json')

In this case result is slightly different (without indent by default):

[
    {
        "model": "some_app.some_model",
        "pk": 1,
        "fields": {
            "name": "Elon",
            "age": 48,
            ...
        }
    },
    ...
]

I have to say, it is good practice to use something like marshmallow to serialize queryset.

...and a few notes for better performance:

  • use pagination if your queryset is big;
  • use objects.values() to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields to serializers.serialize);

Reload .profile in bash shell script (in unix)?

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

DLL and LIB files - what and why?

One other difference lies in the performance.

As the DLL is loaded at runtime by the .exe(s), the .exe(s) and the DLL work with shared memory concept and hence the performance is low relatively to static linking.

On the other hand, a .lib is code that is linked statically at compile time into every process that requests. Hence the .exe(s) will have single memory, thus increasing the performance of the process.

How to change the DataTable Column Name?

try this

"columns": [
{data: "id", name: "aaa", sortable: false},
{data: "userid", name: "userid", sortable: false},
{data: "group_id", name: "group_id", sortable: false},
{data: "group_name", name: "group_name", sortable: false},
{data: "group_member", name: "group_member"},
{data: "group_fee", name: "group_fee"},
{data: "dynamic_type", name: "dynamic_type"},
{data: "dynamic_id", name: "dynamic_id"},
{data: "content", name: "content", sortable: false},
{data: "images", name: "images", sortable: false},
{data: "money", name: "money"},
{data: "is_audit", name: "is_audit", sortable: false},
{data: "audited_at", name: "audited_at", sortable: false}

]

enter image description here

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.

\begin{description} 
     <YOUR TEXT HERE> 
\end{description}
  • This only worked on windows latex compiler

Build and Install unsigned apk on device without the development server?

Just in case someone else is recently getting into this same issue, I'm using React Native 0.59.8 (tested with RN 0.60 as well) and I can confirm some of the other answers, here are the steps:

  1. Uninstall the latest compiled version of your app installed you have on your device

  2. Run react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

  3. run cd android/ && ./gradlew assembleDebug

  4. Get your app-debug.apk in folder android/app/build/outputs/apk/debug

good luck!

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I faced the same error when displaying YouTube links. For example: https://www.youtube.com/watch?v=8WkuChVeL0s

I replaced watch?v= with embed/ so the valid link will be: https://www.youtube.com/embed/8WkuChVeL0s

It works well.

Try to apply the same rule on your case.

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

You are looking at sqljdbc4.2 version like :

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

but, for sqljdbc4 version statement should be:

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

I think if you change your first version to write the correct Class.forName , your application will run.

How to style the parent element when hovering a child element?

I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).

If you set the parent to be with no pointer-events, and then a child div with pointer-events set to auto, it works:)
Note that <img> tag (for example) doesn't do the trick.
Also remember to set pointer-events to auto for other children which have their own event listener, or otherwise they will lose their click functionality.

_x000D_
_x000D_
div.parent {  _x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
div.child {_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
div.parent:hover {_x000D_
    background: yellow;_x000D_
}    
_x000D_
<div class="parent">_x000D_
  parent - you can hover over here and it won't trigger_x000D_
  <div class="child">hover over the child instead!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)

ImportError: No module named sklearn.cross_validation

Past : from sklearn.cross_validation (This package is deprecated in 0.18 version from 0.20 onwards it is changed to from sklearn import model_selection).

Present: from sklearn import model_selection

Example 2:

Past : from sklearn.cross_validation import cross_val_score (Version 0.18 which is deprecated)

Present : from sklearn.model_selection import cross_val_score

SQL Server Pivot Table with multiple column aggregates

The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.

WITH PivotCTE AS
(
    select * from  mytransactions
    pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
    numericmonth,
    chardate,
    SUM(totalamount) AS totalamount,
    SUM(ISNULL(Australia, 0)) AS Australia,
    SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate

The ISNULL is to stop a NULL value from nullifying the sum (because NULL + any value = NULL)

Number of elements in a javascript object

To do this in any ES5-compatible environment

Object.keys(obj).length

(Browser support from here)
(Doc on Object.keys here, includes method you can add to non-ECMA5 browsers)

How to check if a map contains a key in Go?

As noted by other answers, the general solution is to use an index expression in an assignment of the special form:

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
var v, ok T = a[x]

This is nice and clean. It has some restrictions though: it must be an assignment of special form. Right-hand side expression must be the map index expression only, and the left-hand expression list must contain exactly 2 operands, first to which the value type is assignable, and a second to which a bool value is assignable. The first value of the result of this special form will be the value associated with the key, and the second value will tell if there is actually an entry in the map with the given key (if the key exists in the map). The left-hand side expression list may also contain the blank identifier if one of the results is not needed.

It's important to know that if the indexed map value is nil or does not contain the key, the index expression evaluates to the zero value of the value type of the map. So for example:

m := map[int]string{}
s := m[1] // s will be the empty string ""
var m2 map[int]float64 // m2 is nil!
f := m2[2] // f will be 0.0

fmt.Printf("%q %f", s, f) // Prints: "" 0.000000

Try it on the Go Playground.

So if we know that we don't use the zero value in our map, we can take advantage of this.

For example if the value type is string, and we know we never store entries in the map where the value is the empty string (zero value for the string type), we can also test if the key is in the map by comparing the non-special form of the (result of the) index expression to the zero value:

m := map[int]string{
    0: "zero",
    1: "one",
}

fmt.Printf("Key 0 exists: %t\nKey 1 exists: %t\nKey 2 exists: %t",
    m[0] != "", m[1] != "", m[2] != "")

Output (try it on the Go Playground):

Key 0 exists: true
Key 1 exists: true
Key 2 exists: false

In practice there are many cases where we don't store the zero-value value in the map, so this can be used quite often. For example interfaces and function types have a zero value nil, which we often don't store in maps. So testing if a key is in the map can be achieved by comparing it to nil.

Using this "technique" has another advantage too: you can check existence of multiple keys in a compact way (you can't do that with the special "comma ok" form). More about this: Check if key exists in multiple maps in one condition

Getting the zero value of the value type when indexing with a non-existing key also allows us to use maps with bool values conveniently as sets. For example:

set := map[string]bool{
    "one": true,
    "two": true,
}

fmt.Println("Contains 'one':", set["one"])

if set["two"] {
    fmt.Println("'two' is in the set")
}
if !set["three"] {
    fmt.Println("'three' is not in the set")
}

It outputs (try it on the Go Playground):

Contains 'one': true
'two' is in the set
'three' is not in the set

See related: How can I create an array that contains unique strings?

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I did it this way (you need to add a class text to <td> and put the text between a <span>:

HTML

<td class="text"><span>looooooong teeeeeeeeext</span></td>

SASS

.table td.text {
    max-width: 177px;
    span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
        max-width: 100%;
    }
}

CSS equivalent

.table td.text {
    max-width: 177px;
}
.table td.text span {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}

And it will still be mobile responsive (forget it with layout=fixed) and will keep the original behaviour.

PS: Of course 177px is a custom size (put whatever you need).

Cannot create SSPI context

We had this issue on instances in which we changed the service user from Domain1\ServiceUser to Domain2\ServiceUser. The SPNs remained registered under Domain1\ServiceUser, and never registered under Domain2\ServiceUser. We registered the SPNs under Domain2\ServiceUser, but the issue persisted. We then removed the SPNs under Domain1\ServiceUser, and the issue was resolved.

Make JQuery UI Dialog automatically grow or shrink to fit its contents

var w = $('#dialogText').text().length;

$("#dialog").dialog('option', 'width', (w * 10));

did what i needed it to do for resizing the width of the dialog.

Print array without brackets and commas

Just initialize a String object with your array

String s=new String(array);

how to start the tomcat server in linux?

Go to the appropriate subdirectory of the EDQP Tomcat installation directory. The default directories are:

On Linux: /opt/server/tomcat/bin

On Windows: c:\server\tomcat\bin

Run the startup command:

On Linux: ./startup.sh

On Windows: % startup.bat

Run the shutdown command:

On Linux: ./shutdown.sh

On Windows: % shutdown.bat

How to set transparent background for Image Button in code?

Do it in your xml

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtonSettings"
        android:layout_gravity="right|bottom"
        android:src="@drawable/tabbar_settings_icon"
        android:background="@android:color/transparent"/>

How to make a UILabel clickable?

Good and convenient solution:

In your ViewController:

@IBOutlet weak var label: LabelButton!

override func viewDidLoad() {
    super.viewDidLoad()

    self.label.onClick = {
        // TODO
    }
}

You can place this in your ViewController or in another .swift file(e.g. CustomView.swift):

@IBDesignable class LabelButton: UILabel {
    var onClick: () -> Void = {}
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        onClick()
    }
}

In Storyboard select Label and on right pane in "Identity Inspector" in field class select LabelButton.

Don't forget to enable in Label Attribute Inspector "User Interaction Enabled"

phpmailer error "Could not instantiate mail function"

You need to make sure that your from address is a valid email account setup on that server.

Rotating and spacing axis labels in ggplot2

OUTDATED - see this answer for a simpler approach


To obtain readable x tick labels without additional dependencies, you want to use:

  ... +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
  ...

This rotates the tick labels 90° counterclockwise and aligns them vertically at their end (hjust = 1) and their centers horizontally with the corresponding tick mark (vjust = 0.5).

Full example:

library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))


Note, that vertical/horizontal justification parameters vjust/hjust of element_text are relative to the text. Therefore, vjust is responsible for the horizontal alignment.

Without vjust = 0.5 it would look like this:

q + theme(axis.text.x = element_text(angle = 90, hjust = 1))

Without hjust = 1 it would look like this:

q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

If for some (wired) reason you wanted to rotate the tick labels 90° clockwise (such that they can be read from the left) you would need to use: q + theme(axis.text.x = element_text(angle = -90, vjust = 0.5, hjust = -1)).

All of this has already been discussed in the comments of this answer but I come back to this question so often, that I want an answer from which I can just copy without reading the comments.

How to stop (and restart) the Rails Server?

Press Ctrl+C

When you start the server it mentions this in the startup text.

Get MAC address using shell script

I know that is a little bit dated, but with basic commands, we can take the mac address of an interface:

ip link show eth0 | grep link/ether | awk '{print $2}'

Have a nice day!

How do multiple clients connect simultaneously to one port, say 80, on a server?

Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.

When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.

Words in italics are system calls.

Ref

http://www.scs.stanford.edu/07wi-cs244b/refs/net2.pdf

Make HTML5 video poster be same size as video itself

This worked

<video class="video-box" poster="/" controls>
    <source src="some source" type="video/mp4">
</video>

And the CSS

.video-box{
 background-image: 'some image';
 background-size: cover;
}

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

I had this segmentation fault error because of Memory issues. My struct having many variables and arrays, had this Array of size 1024.

Reducing the size to 512, the error was gone.

P.S: This is a workaround and not a solution. It is necessary to find the struct size and dynamic memory allocation is a better option.

AngularJS - get element attributes values

<button class="myButton" data-id="345" ng-click="doStuff($element.target)">Button</button>

I added class to button to get by querySelector, then get data attribute

var myButton = angular.element( document.querySelector( '.myButton' ) );
console.log( myButton.data( 'id' ) );

How do I remove all null and empty string values from an object?

_x000D_
_x000D_
var data = [_x000D_
   { "name": "bill", "age": 20 },_x000D_
   { "name": "jhon", "age": 19 },_x000D_
   { "name": "steve", "age": 16 },_x000D_
   { "name": "larry", "age": 22 },_x000D_
   null, null, null_x000D_
];_x000D_
_x000D_
//eliminate all the null values from the data_x000D_
data = data.filter(function(x) { return x !== null }); _x000D_
_x000D_
console.log("data: " + JSON.stringify(data));
_x000D_
_x000D_
_x000D_

Heatmap in matplotlib with pcolor?

Someone edited this question to remove the code I used, so I was forced to add it as an answer. Thanks to all who participated in answering this question! I think most of the other answers are better than this code, I'm just leaving this here for reference purposes.

With thanks to Paul H, and unutbu (who answered this question), I have some pretty nice-looking output:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()

And here's the output:

Matplotlib HeatMap

What is the simplest SQL Query to find the second largest value?

select * from emp e where 3>=(select count(distinct salary)
    from emp where s.salary<=salary)

This query selects the maximum three salaries. If two emp get the same salary this does not affect the query.

Extract a substring using PowerShell

Not sure if this is efficient or not, but strings in PowerShell can be referred to using array index syntax, in a similar fashion to Python.

It's not completely intuitive because of the fact the first letter is referred to by index = 0, but it does:

  • Allow a second index number that is longer than the string, without generating an error
  • Extract substrings in reverse
  • Extract substrings from the end of the string

Here are some examples:

PS > 'Hello World'[0..2]

Yields the result (index values included for clarity - not generated in output):

H [0]
e [1]
l [2]

Which can be made more useful by passing -join '':

PS > 'Hello World'[0..2] -join ''
Hel

There are some interesting effects you can obtain by using different indices:

Forwards

Use a first index value that is less than the second and the substring will be extracted in the forwards direction as you would expect. This time the second index value is far in excess of the string length but there is no error:

PS > 'Hello World'[3..300] -join ''
lo World

Unlike:

PS > 'Hello World'.Substring(3,300)
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within
the string.

Backwards

If you supply a second index value that is lower than the first, the string is returned in reverse:

PS > 'Hello World'[4..0] -join ''
olleH

From End

If you use negative numbers you can refer to a position from the end of the string. To extract 'World', the last 5 letters, we use:

PS > 'Hello World'[-5..-1] -join ''
World

How to create a css rule for all elements except one class?

Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?

Returning Promises from Vuex actions

Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:

Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

Example:

    export const loginForm = ({ commit }, data) => {
      return axios
        .post('http://localhost:8000/api/login', data)
        .then((response) => {
          commit('logUserIn', response.data);
        })
        .catch((error) => {
          commit('unAuthorisedUser', { error:error.response.data });
        })
    }

Another example:

    addEmployee({ commit, state }) {       
      return insertEmployee(state.employee)
        .then(result => {
          commit('setEmployee', result.data);
          return result.data; // resolve 
        })
        .catch(err => {           
          throw err.response.data; // reject
        })
    }

Another example with async-await

    async getUser({ commit }) {
        try {
            const currentUser = await axios.get('/user/current')
            commit('setUser', currentUser)
            return currentUser
        } catch (err) {
            commit('setUser', null)
            throw 'Unable to fetch current user'
        }
    },

When is the @JsonProperty property used and what is it used for?

From JsonProperty javadoc,

Defines name of the logical property, i.e. JSON object field name to use for the property. If value is empty String (which is the default), will try to use name of the field that is annotated.

Why is it that "No HTTP resource was found that matches the request URI" here?

I got the similiar issue, and resolved it by the following. The issue looks not related to the Route definition but definition of the parameters, just need to give it a default value.

----Code with issue: Message: "No HTTP resource was found that matches the request URI

    [HttpGet]
    [Route("students/list")]
    public StudentListResponse GetStudents(int? ClassId, int? GradeId)
    {
       ...
    }

----Code without issue.

    [HttpGet]
    [Route("students/list")]
    public StudentListResponse GetStudents(int? ClassId=null, int? GradeId=null)
    {
       ...
    }

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

java: Class.isInstance vs Class.isAssignableFrom

I think the result for those two should always be the same. The difference is that you need an instance of the class to use isInstance but just the Class object to use isAssignableFrom.

Java Regex Capturing Groups

The issue you're having is with the type of quantifier. You're using a greedy quantifier in your first group (index 1 - index 0 represents the whole Pattern), which means it'll match as much as it can (and since it's any character, it'll match as many characters as there are in order to fulfill the condition for the next groups).

In short, your 1st group .* matches anything as long as the next group \\d+ can match something (in this case, the last digit).

As per the 3rd group, it will match anything after the last digit.

If you change it to a reluctant quantifier in your 1st group, you'll get the result I suppose you are expecting, that is, the 3000 part.

Note the question mark in the 1st group.

String line = "This order was placed for QT3000! OK?";
Pattern pattern = Pattern.compile("(.*?)(\\d+)(.*)");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    System.out.println("group 1: " + matcher.group(1));
    System.out.println("group 2: " + matcher.group(2));
    System.out.println("group 3: " + matcher.group(3));
}

Output:

group 1: This order was placed for QT
group 2: 3000
group 3: ! OK?

More info on Java Pattern here.

Finally, the capturing groups are delimited by round brackets, and provide a very useful way to use back-references (amongst other things), once your Pattern is matched to the input.

In Java 6 groups can only be referenced by their order (beware of nested groups and the subtlety of ordering).

In Java 7 it's much easier, as you can use named groups.

Restoring database from .mdf and .ldf files of SQL Server 2008

I have an answer for you Yes, It is possible.

Go to

SQL Server Management Studio > select Database > click on attach

Then select and add .mdf and .ldf file. Click on OK.

Package signatures do not match the previously installed version

I met this problem on my project too.

This helped me, so hopefuly will help someone else:

adb uninstall "com.domain.yourapp"

Solution is from here.

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

What is javax.inject.Named annotation supposed to be used for?

Use @Named to differentiate between different objects of the same type bound in the same scope.

@Named("maxWaitTime")
public long maxWaitTimeMs;

@Named("minWaitTime")
public long minWaitTimeMs;

Without the @Named qualifier, the injector would not know which long to bind to which variable.

  • If you want to create annotations that act like @Named, use the @Qualifier annotation when creating them.

  • If you look at @Named, it is itself annotated with @Qualifier.

Git fails when pushing commit to github

I tried to push to my own hosted bonobo-git server, and did not realise, that the http.postbuffer meant the project directory ...

so just for other confused ones:

why? In my case, I had large zip files with assets and some PSDs pushed as well - to big for the buffer I guess.

How to do this http.postbuffer: execute that command within your project src directory, next to the .git folder, not on the server.

be aware, large temp (chunk) files will be created of that buffer size.

Note: Just check your largest files, then set the buffer.

How to make a simple rounded button in Storyboard?

Short Answer: YES

You can absolutely make a simple rounded button without the need of an additional background image or writing any code for the same. Just follow the screenshot given below, to set the runtime attributes for the button, to get the desired result.

It won't show in the Storyboard but it will work fine when you run the project.

enter image description here

Note:
The 'Key Path' layer.cornerRadius and value is 5. The value needs to be changed according to the height and width of the button. The formula for it is the height of button * 0.50. So play around the value to see the expected rounded button in the simulator or on the physical device. This procedure will look tedious when you have more than one button to be rounded in the storyboard.

How to pass a PHP variable using the URL

In your link.php your echo statement must be like this:

echo '<a href="pass.php?link=' . $a . '>Link 1</a>';
echo '<a href="pass.php?link=' . $b . '">Link 2</a>';

Then in your pass.php you cannot use $a because it was not initialized with your intended string value.

You can directly compare it to a string like this:

if($_GET['link'] == 'Link1')

Another way is to initialize the variable first to the same thing you did with link.php. And, a much better way is to include the $a and $b variables in a single PHP file, then include that in all pages where you are going to use those variables as Tim Cooper mention on his post. You can also include this in a session.

What is the difference between int, Int16, Int32 and Int64?

EDIT: This isn't quite true for C#, a tag I missed when I answered this question - if there is a more C# specific answer, please vote for that instead!


They all represent integer numbers of varying sizes.

However, there's a very very tiny difference.

int16, int32 and int64 all have a fixed size.

The size of an int depends on the architecture you are compiling for - the C spec only defines an int as larger or equal to a short though in practice it's the width of the processor you're targeting, which is probably 32bit but you should know that it might not be.

How do I get row id of a row in sql server

SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id is an IDENTITY column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON). If employee_id is an IDENTITY column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:

SELECT 
   ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID, 
   EMPLOYEE_ID,
   EMPLOYEE_NAME 
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;

You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).

ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743 
-- wow, who named this?
  ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES() - e.g. you may have to revisit your code and define a proper, explicit column list.

Are the shift operators (<<, >>) arithmetic or logical in C?

In terms of the type of shift you get, the important thing is the type of the value that you're shifting. A classic source of bugs is when you shift a literal to, say, mask off bits. For example, if you wanted to drop the left-most bit of an unsigned integer, then you might try this as your mask:

~0 >> 1

Unfortunately, this will get you into trouble because the mask will have all of its bits set because the value being shifted (~0) is signed, thus an arithmetic shift is performed. Instead, you'd want to force a logical shift by explicitly declaring the value as unsigned, i.e. by doing something like this:

~0U >> 1;

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use <script>'s defer attribute. It specifies that the script will be executed when the page has finished parsing.

<script defer src="path/to/yourscript.js">

A nice article about this: http://davidwalsh.name/script-defer

Browser support seems pretty good: http://caniuse.com/#search=defer

Another great article about loading JS using defer and async: https://flaviocopes.com/javascript-async-defer/

PHP validation/regex for URL

"/(http(s?):\/\/)([a-z0-9\-]+\.)+[a-z]{2,4}(\.[a-z]{2,4})*(\/[^ ]+)*/i"
  1. (http(s?)://) means http:// or https://

  2. ([a-z0-9-]+.)+ => 2.0[a-z0-9-] means any a-z character or any 0-9 or (-)sign)

                 2.1 (+) means the character can be one or more ex: a1w, 
                     a9-,c559s, f)
    
                 2.2 \. is (.)sign
    
                 2.3. the (+) sign after ([a-z0-9\-]+\.) mean do 2.1,2.2,2.3 
                    at least 1 time 
                  ex: abc.defgh0.ig, aa.b.ced.f.gh. also in case www.yyy.com
    
                 3.[a-z]{2,4} mean a-z at least 2 character but not more than 
                              4 characters for check that there will not be 
                              the case 
                              ex: https://www.google.co.kr.asdsdagfsdfsf
    
                 4.(\.[a-z]{2,4})*(\/[^ ]+)* mean 
    
                   4.1 \.[a-z]{2,4} means like number 3 but start with 
                       (.)sign 
    
                   4.2 * means (\.[a-z]{2,4})can be use or not use never mind
    
                   4.3 \/ means \
                   4.4 [^ ] means any character except blank
                   4.5 (+) means do 4.3,4.4,4.5 at least 1 times
                   4.6 (*) after (\/[^ ]+) mean use 4.3 - 4.5 or not use 
                       no problem
    
                   use for case https://stackoverflow.com/posts/51441301/edit
    
                   5. when you use regex write in "/ /" so it come
    

    "/(http(s?)://)([a-z0-9-]+.)+[a-z]{2,4}(.[a-z]{2,4})(/[^ ]+)/i"

                   6. almost forgot: letter i on the back mean ignore case of 
                      Big letter or small letter ex: A same as a, SoRRy same 
                      as sorry.
    

Note : Sorry for bad English. My country not use it well.

Styles.Render in MVC4

src="@url.content("~/Folderpath/*.css")" should render styles

Return index of highest value in an array

I know it's already answered but here is a solution I find more elegant:

arsort($array);
reset($array);
echo key($array);

and voila!

No Title Bar Android Theme

use android:theme="@android:style/Theme.NoTitleBar in manifest file's application tag to remove the title bar for whole application or put it in activity tag to remove the title bar from a single activity screen.

Proper use of const for defining functions in JavaScript

There are special cases where arrow functions just won't do the trick:

  1. If we're changing a method of an external API, and need the object's reference.

  2. If we need to use special keywords that are exclusive to the function expression: arguments, yield, bind etc. For more information: Arrow function expression limitations

Example:

I assigned this function as an event handler in the Highcharts API. It's fired by the library, so the this keyword should match a specific object.

export const handleCrosshairHover = function (proceed, e) {
  const axis = this; // axis object
  proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // method arguments
};

With an arrow function, this would match the declaration scope, and we won't have access to the API obj:

export const handleCrosshairHover = (proceed, e) => {
  const axis = this; // this = undefined
  proceed.apply(axis, Array.prototype.slice.call(arguments, 1)); // compilation error
};

How to set HTML Auto Indent format on Sublime Text 3?

One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.

Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:

p [tab][enter] Hello world!

When you type p [tab] Emmet expands it to:

<p></p>

Pressing [enter] then further expands it to:

<p>

</p>

With the cursor indented and on the line between the tags. Meaning that typing text results in:

<p>
    Hello, world!
</p>

How to check if a "lateinit" variable has been initialized?

Try to use it and you will receive a UninitializedPropertyAccessException if it is not initialized.

lateinit is specifically for cases where fields are initialized after construction, but before actual use (a model which most injection frameworks use). If this is not your use case lateinit might not be the right choice.

EDIT: Based on what you want to do something like this would work better:

val chosenFile = SimpleObjectProperty<File?>
val button: Button

// Disables the button if chosenFile.get() is null
button.disableProperty.bind(chosenFile.isNull())

Webpack not excluding node_modules

try this below solution:

exclude:path.resolve(__dirname, "node_modules")

Excel - Combine multiple columns into one column

Not sure if this completely helps, but I had an issue where I needed a "smart" merge. I had two columns, A & B. I wanted to move B over only if A was blank. See below. It is based on a selection Range, which you could use to offset the first row, perhaps.

Private Sub MergeProjectNameColumns()
    Dim rngRowCount As Integer
    Dim i As Integer

    'Loop through column C and simply copy the text over to B if it is not blank
    rngRowCount = Range(dataRange).Rows.Count
    ActiveCell.Offset(0, 0).Select
    ActiveCell.Offset(0, 2).Select
    For i = 1 To rngRowCount
        If (Len(RTrim(ActiveCell.Value)) > 0) Then
            Dim currentValue As String
            currentValue = ActiveCell.Value
            ActiveCell.Offset(0, -1) = currentValue
        End If
        ActiveCell.Offset(1, 0).Select
    Next i

    'Now delete the unused column
    Columns("C").Select

    selection.Delete Shift:=xlToLeft
End Sub

How do I close an Android alertdialog

I tried the solution of PowerAktar, but the AlertDialog and the Builder always kept seperate parts. So how to get the "true" AlertDialog?

I found my solutions in the show-Dialog: You write

ad.show();

to display the dialog. In the help of show it says "Creates a AlertDialog with the arguments supplied to this builder and Dialog.show()'s the dialog." So the dialog is finally created here. The result of the show()-Command is the AlertDialog itself. So you can use this result:

AlertDialog adTrueDialog;
adTrueDialog = ad.show();

With this adTrueDialog it is possible to cancel() ...

adTrueDialog.cancel()

or to execute a buttons command within the dialog:

Button buttonPositive = adTrueDialog.getButton(Dialog.BUTTON_POSITIVE);
buttonPositive.performClick();

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

To make child div as wide as the content, try this:

.child{
    position:absolute;
    left:0;
    overflow:visible;
    white-space:nowrap;
}

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

For Java, from a command line:

java -version

will indicate whether it's 64-bit or not.

Output from the console on my Ubuntu box:

java version "1.6.0_12-ea"
Java(TM) SE Runtime Environment (build 1.6.0_12-ea-b03)
Java HotSpot(TM) 64-Bit Server VM (build 11.2-b01, mixed mode)

IE will indicate 64-bit versions in the About dialog, I believe.

How to make an AlertDialog in Flutter?

You can use this code snippet for creating a two buttoned Alert box,

import 'package:flutter/material.dart';

class BaseAlertDialog extends StatelessWidget {

  //When creating please recheck 'context' if there is an error!

  Color _color = Color.fromARGB(220, 117, 218 ,255);

  String _title;
  String _content;
  String _yes;
  String _no;
  Function _yesOnPressed;
  Function _noOnPressed;

  BaseAlertDialog({String title, String content, Function yesOnPressed, Function noOnPressed, String yes = "Yes", String no = "No"}){
    this._title = title;
    this._content = content;
    this._yesOnPressed = yesOnPressed;
    this._noOnPressed = noOnPressed;
    this._yes = yes;
    this._no = no;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: new Text(this._title),
      content: new Text(this._content),
      backgroundColor: this._color,
      shape:
          RoundedRectangleBorder(borderRadius: new BorderRadius.circular(15)),
      actions: <Widget>[
        new FlatButton(
          child: new Text(this._yes),
          textColor: Colors.greenAccent,
          onPressed: () {
            this._yesOnPressed();
          },
        ),
        new FlatButton(
          child: Text(this._no),
          textColor: Colors.redAccent,
          onPressed: () {
            this._noOnPressed();
          },
        ),
      ],
    );
  }
}

To show the dialog you can have a method that calls it NB after importing BaseAlertDialog class

_confirmRegister() {
var baseDialog = BaseAlertDialog(
    title: "Confirm Registration",
    content: "I Agree that the information provided is correct",
    yesOnPressed: () {},
    noOnPressed: () {},
    yes: "Agree",
    no: "Cancel");
showDialog(context: context, builder: (BuildContext context) => baseDialog);
}

OUTPUT WILL BE LIKE THIS

Output

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

How to find index of all occurrences of element in array?

You can use Polyfill

if (!Array.prototype.filterIndex) {
Array.prototype.filterIndex = function (func, thisArg) {

    'use strict';
    if (!((typeof func === 'Function' || typeof func === 'function') && this))
        throw new TypeError();

    let len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;

    let kValue;
    if (thisArg === undefined) {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i]; // in case t is changed in callback
                if (func(t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }
    else {
        while (++i !== len) {
            // checks to see if the key was set
            if (i in this) {
                kValue = t[i];
                if (func.call(thisArg, t[i], i, t)) {
                    res[c++] = i;
                }
            }
        }
    }

    res.length = c; // shrink down array to proper size
    return res;
};

}

Use it like this:

[2,23,1,2,3,4,52,2].filterIndex(element => element === 2)

result: [0, 3, 7]

Finding the type of an object in C++

You are looking for dynamic_cast<B*>(pointer)

How do I use reflection to call a generic method?

Just an addition to the original answer. While this will work:

MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

It is also a little dangerous in that you lose compile-time check for GenericMethod. If you later do a refactoring and rename GenericMethod, this code won't notice and will fail at run time. Also, if there is any post-processing of the assembly (for example obfuscating or removing unused methods/classes) this code might break too.

So, if you know the method you are linking to at compile time, and this isn't called millions of times so overhead doesn't matter, I would change this code to be:

Action<> GenMethod = GenericMethod<int>;  //change int by any base type 
                                          //accepted by GenericMethod
MethodInfo method = this.GetType().GetMethod(GenMethod.Method.Name);
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);

While not very pretty, you have a compile time reference to GenericMethod here, and if you refactor, delete or do anything with GenericMethod, this code will keep working, or at least break at compile time (if for example you remove GenericMethod).

Other way to do the same would be to create a new wrapper class, and create it through Activator. I don't know if there is a better way.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Git: How to return from 'detached HEAD' state

You may have made some new commits in the detached HEAD state. I believe if you do as other answers advise:

git checkout master
# or
git checkout -

then you may lose your commits!! Instead, you may want to do this:

# you are currently in detached HEAD state
git checkout -b commits-from-detached-head

and then merge commits-from-detached-head into whatever branch you want, so you don't lose the commits.

Node.js/Express routing with get params

Your route isn't ok, it should be like this (with ':')

app.get('/documents/:format/:type', function (req, res) {
   var format = req.params.format,
       type = req.params.type;
});

Also you cannot interchange parameter order unfortunately. For more information on req.params (and req.query) check out the api reference here.

Iterating over every two elements in a list

In case you're interested in the performance, I did a small benchmark (using my library simple_benchmark) to compare the performance of the solutions and I included a function from one of my packages: iteration_utilities.grouper

from iteration_utilities import grouper
import matplotlib as mpl
from simple_benchmark import BenchmarkBuilder

bench = BenchmarkBuilder()

@bench.add_function()
def Johnsyweb(l):
    def pairwise(iterable):
        "s -> (s0, s1), (s2, s3), (s4, s5), ..."
        a = iter(iterable)
        return zip(a, a)

    for x, y in pairwise(l):
        pass

@bench.add_function()
def Margus(data):
    for i, k in zip(data[0::2], data[1::2]):
        pass

@bench.add_function()
def pyanon(l):
    list(zip(l,l[1:]))[::2]

@bench.add_function()
def taskinoor(l):
    for i in range(0, len(l), 2):
        l[i], l[i+1]

@bench.add_function()
def mic_e(it):
    def pairwise(it):
        it = iter(it)
        while True:
            try:
                yield next(it), next(it)
            except StopIteration:
                return

    for a, b in pairwise(it):
        pass

@bench.add_function()
def MSeifert(it):
    for item1, item2 in grouper(it, 2):
        pass

bench.use_random_lists_as_arguments(sizes=[2**i for i in range(1, 20)])
benchmark_result = bench.run()
mpl.rcParams['figure.figsize'] = (8, 10)
benchmark_result.plot_both(relative_to=MSeifert)

enter image description here

So if you want the fastest solution without external dependencies you probably should just use the approach given by Johnysweb (at the time of writing it's the most upvoted and accepted answer).

If you don't mind the additional dependency then the grouper from iteration_utilities will probably be a bit faster.

Additional thoughts

Some of the approaches have some restrictions, that haven't been discussed here.

For example a few solutions only work for sequences (that is lists, strings, etc.), for example Margus/pyanon/taskinoor solutions which uses indexing while other solutions work on any iterable (that is sequences and generators, iterators) like Johnysweb/mic_e/my solutions.

Then Johnysweb also provided a solution that works for other sizes than 2 while the other answers don't (okay, the iteration_utilities.grouper also allows setting the number of elements to "group").

Then there is also the question about what should happen if there is an odd number of elements in the list. Should the remaining item be dismissed? Should the list be padded to make it even sized? Should the remaining item be returned as single? The other answer don't address this point directly, however if I haven't overlooked anything they all follow the approach that the remaining item should be dismissed (except for taskinoors answer - that will actually raise an Exception).

With grouper you can decide what you want to do:

>>> from iteration_utilities import grouper

>>> list(grouper([1, 2, 3], 2))  # as single
[(1, 2), (3,)]

>>> list(grouper([1, 2, 3], 2, truncate=True))  # ignored
[(1, 2)]

>>> list(grouper([1, 2, 3], 2, fillvalue=None))  # padded
[(1, 2), (3, None)]

Create an ArrayList with multiple object types?

You can just add objects of diffefent "Types" to an instance of ArrayList. No need create an ArrayList. Have a look at the below example, You will get below output:

Beginning....
Contents of array: [String, 1]
Size of the list: 2
This is not an Integer String
This is an Integer 1

package com.viswa.examples.programs;

import java.util.ArrayList;
import java.util.Arrays;

public class VarArrayListDemo {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        System.out.println(" Beginning....");

        ArrayList varTypeArray = new ArrayList();
        varTypeArray.add("String");
        varTypeArray.add(1); //Stored as Integer

        System.out.println(" Contents of array: " + varTypeArray + "\n Size of the list: " + varTypeArray.size());

        Arrays.stream(varTypeArray.toArray()).forEach(VarArrayListDemo::checkType);
    }

    private static <T> void checkType(T t) {

        if (Integer.class.isInstance(t)) {
            System.out.println(" This is an Integer " + t);
        } else {
            System.out.println(" This is not an Integer" + t);
        }
    }

}

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

How to prevent the "Confirm Form Resubmission" dialog?

You could try using AJAX calls with jQuery. Like how youtube adds your comment without refreshing. This would remove the problem with refreshing overal.

You'd need to send the info necessary trough the ajax call.
I'll use the youtube comment as example.

$.ajax({
    type: 'POST',
    url: 'ajax/comment-on-video.php',
    data: {
        comment: $('#idOfInputField').val();
     },
    success: function(obj) {
        if(obj === 'true') {
            //Some code that recreates the inserted comment on the page.
        }
    }
});

You can now create the file comment-on-video.php and create something like this:

<?php
    session_start();

    if(isset($_POST['comment'])) {
        $comment = mysqli_real_escape_string($db, $_POST['comment']);
        //Given you are logged in and store the user id in the session.
        $user = $_SESSION['user_id'];

        $query = "INSERT INTO `comments` (`comment_text`, `user_id`) VALUES ($comment, $user);";
        $result = mysqli_query($db, $query);

        if($result) {
            echo true;
            exit();
        }
    }
    echo false;
    exit();
?>

Specify sudo password for Ansible

You can set the password for a group or for all servers at once:

[all:vars]
ansible_sudo_pass=default_sudo_password_for_all_hosts

[group1:vars]
ansible_sudo_pass=default_sudo_password_for_group1

How do I set response headers in Flask?

Use make_response of Flask something like

@app.route("/")
def home():
    resp = make_response("hello") #here you could use make_response(render_template(...)) too
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

From flask docs,

flask.make_response(*args)

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

Asking the user for input until they give a valid response

While a try/except block will work, a much faster and cleaner way to accomplish this task would be to use str.isdigit().

while True:
    age = input("Please enter your age: ")
    if age.isdigit():
        age = int(age)
        break
    else:
        print("Invalid number '{age}'. Try again.".format(age=age))

if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

nodemon not working: -bash: nodemon: command not found

I ran into the same problem since I had changed my global path of npm packages before.

Here's how I fixed it :

When I installed nodemon using : npm install nodemon -g --save , my path for the global npm packages was not present in the PATH variable .

If you just add it to the $PATH variable it will get fixed.

Edit the ~/.bashrc file in your home folder and add this line :-

export PATH=$PATH:~/npm

Here "npm" is the path to my global npm packages . Replace it with the global path in your system

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

You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

_x000D_
_x000D_
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
_x000D_
_x000D_

String interpolation:

_x000D_
_x000D_
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
_x000D_
_x000D_

How do I get the current absolute URL in Ruby on Rails?

I think request.domain would work, but what if you're in a sub directory like blah.blah.com? Something like this could work:

<%= request.env["HTTP_HOST"] + page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>

Change the parameters based on your path structure.

Hope that helps!

Oracle: How to find out if there is a transaction pending?

you can check if your session has a row in V$TRANSACTION (obviously that requires read privilege on this view):

SQL> SELECT COUNT(*)
       FROM v$transaction t, v$session s, v$mystat m
      WHERE t.ses_addr = s.saddr
        AND s.sid = m.sid
        AND ROWNUM = 1;

  COUNT(*)
----------
         0

SQL> insert into a values (1);

1 row inserted

SQL> SELECT COUNT(*)
       FROM v$transaction t, v$session s, v$mystat m
      WHERE t.ses_addr = s.saddr
        AND s.sid = m.sid
        AND ROWNUM = 1;

  COUNT(*)
----------
         1

SQL> commit;

Commit complete

SQL> SELECT COUNT(*)
       FROM v$transaction t, v$session s, v$mystat m
      WHERE t.ses_addr = s.saddr
        AND s.sid = m.sid
        AND ROWNUM = 1;

  COUNT(*)
----------
         0

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Code for Greatest Common Divisor in Python

using recursion,

def gcd(a,b):
    return a if not b else gcd(b, a%b)

using while,

def gcd(a,b):
  while b:
    a,b = b, a%b
  return a

using lambda,

gcd = lambda a,b : a if not b else gcd(b, a%b)

>>> gcd(10,20)
>>> 10

Android EditText Hint

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            et.setHint(temp +" Characters");
        }
    });

updating nodejs on ubuntu 16.04

Using Node Version Manager (NVM):

Install it:

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Test your installation:

close your current terminal, open a new terminal, and run:

command -v nvm

Use it to install as many versions as u like:

nvm install 8              # Install nodejs 8
nvm install --lts          # Install latest LTS (Long Term Support) version

List installed versions:

nvm ls

Use a specific version:

nvm use 8                  # Use this version on this shell

Set defaults:

nvm alias default 8        # Default to nodejs 8 on this shell
nvm alias default node     # always use latest available as default nodejs for all shells

IndexError: list index out of range and python

Yes,

You are trying to access an element of the list that does not exist.

MyList = ["item1", "item2"]
print MyList[0] # Will work
print MyList[1] # Will Work
print MyList[2] # Will crash.

Have you got an off-by-one error?

Store boolean value in SQLite

SQLite Boolean Datatype:
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

You can convert boolean to int in this way:

int flag = (boolValue)? 1 : 0;

You can convert int back to boolean as follows:

 // Select COLUMN_NAME  values from db. 
 // This will be integer value, you can convert this int value back to Boolean as follows
Boolean flag2 = (intValue == 1)? true : false;

If you want to explore sqlite, here is a tutorial.
I have given one answer here. It is working for them.

How to read from stdin with fgets()?

Exits the loop if the line is empty(Improving code).

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

// The value BUFFERSIZE can be changed to customer's taste . Changes the
// size of the base array (string buffer )    
#define BUFFERSIZE 10

int main(void)
{
    char buffer[BUFFERSIZE];
    char cChar;
    printf("Enter a message: \n");
    while(*(fgets(buffer, BUFFERSIZE, stdin)) != '\n')
    {
        // For concatenation
        // fgets reads and adds '\n' in the string , replace '\n' by '\0' to 
        // remove the line break .
/*      if(buffer[strlen(buffer) - 1] == '\n')
            buffer[strlen(buffer) - 1] = '\0'; */
        printf("%s", buffer);
        // Corrects the error mentioned by Alain BECKER.       
        // Checks if the string buffer is full to check and prevent the 
        // next character read by fgets is '\n' .
        if(strlen(buffer) == (BUFFERSIZE - 1) && (buffer[strlen(buffer) - 1] != '\n'))
        {
            // Prevents end of the line '\n' to be read in the first 
            // character (Loop Exit) in the next loop. Reads
            // the next char in stdin buffer , if '\n' is read and removed, if
            // different is returned to stdin 
            cChar = fgetc(stdin);
            if(cChar != '\n')
                ungetc(cChar, stdin);
            // To print correctly if '\n' is removed.
            else
                printf("\n");
        }
    }
    return 0;
}

Exit when Enter is pressed.

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#define BUFFERSIZE 16

int main(void)
{
    char buffer[BUFFERSIZE];
    printf("Enter a message: \n");
    while(true)
    {
        assert(fgets(buffer, BUFFERSIZE, stdin) != NULL);
        // Verifies that the previous character to the last character in the
        // buffer array is '\n' (The last character is '\0') if the
        // character is '\n' leaves loop.
        if(buffer[strlen(buffer) - 1] == '\n')
        {
            // fgets reads and adds '\n' in the string, replace '\n' by '\0' to 
            // remove the line break .
            buffer[strlen(buffer) - 1] = '\0';
            printf("%s", buffer);
            break;
        }
        printf("%s", buffer);   
    }
    return 0;
}

Concatenation and dinamic allocation(linked list) to a single string.

/* Autor : Tiago Portela
   Email : [email protected]
   Sobre : Compilado com TDM-GCC 5.10 64-bit e LCC-Win32 64-bit;
   Obs : Apenas tentando aprender algoritimos, sozinho, por hobby. */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#define BUFFERSIZE 8

typedef struct _Node {
    char *lpBuffer;
    struct _Node *LpProxNode;
} Node_t, *LpNode_t;

int main(void)
{
    char acBuffer[BUFFERSIZE] = {0};
    LpNode_t lpNode = (LpNode_t)malloc(sizeof(Node_t));
    assert(lpNode!=NULL);
    LpNode_t lpHeadNode = lpNode;
    char* lpBuffer = (char*)calloc(1,sizeof(char));
    assert(lpBuffer!=NULL);
    char cChar;


    printf("Enter a message: \n");
    // Exit when Enter is pressed
/*  while(true)
    {
        assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
        lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
        assert(lpNode->lpBuffer!=NULL);
        strcpy(lpNode->lpBuffer, acBuffer);
        if(lpNode->lpBuffer[strlen(acBuffer) - 1] == '\n')
        {
            lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
            lpNode->LpProxNode = NULL;
            break;
        }
        lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
        lpNode = lpNode->LpProxNode;
        assert(lpNode!=NULL);
    }*/

    // Exits the loop if the line is empty(Improving code).
    while(true)
    {
        assert(fgets(acBuffer, BUFFERSIZE, stdin)!=NULL);
        lpNode->lpBuffer = (char*)malloc((strlen(acBuffer) + 1) * sizeof(char));
        assert(lpNode->lpBuffer!=NULL);
        strcpy(lpNode->lpBuffer, acBuffer);
        if(acBuffer[strlen(acBuffer) - 1] == '\n')
            lpNode->lpBuffer[strlen(acBuffer) - 1] = '\0';
        if(strlen(acBuffer) == (BUFFERSIZE - 1) && (acBuffer[strlen(acBuffer) - 1] != '\n'))
        {
            cChar = fgetc(stdin);
            if(cChar != '\n')
                ungetc(cChar, stdin);
        }
        if(acBuffer[0] == '\n')
        {
            lpNode->LpProxNode = NULL;
            break;
        }
        lpNode->LpProxNode = (LpNode_t)malloc(sizeof(Node_t));
        lpNode = lpNode->LpProxNode;
        assert(lpNode!=NULL);
    }


    printf("\nPseudo String :\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        printf("%s", lpNode->lpBuffer);
        lpNode = lpNode->LpProxNode;
    }


    printf("\n\nMemory blocks:\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        printf("Block \"%7s\" size = %lu\n", lpNode->lpBuffer, (long unsigned)(strlen(lpNode->lpBuffer) + 1));
        lpNode = lpNode->LpProxNode;
    }


    printf("\nConcatenated string:\n");
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        lpBuffer = (char*)realloc(lpBuffer, (strlen(lpBuffer) + strlen(lpNode->lpBuffer)) + 1);
        strcat(lpBuffer, lpNode->lpBuffer);
        lpNode = lpNode->LpProxNode;
    }
    printf("%s", lpBuffer);
    printf("\n\n");

    // Deallocate memory
    lpNode = lpHeadNode;
    while(lpNode != NULL)
    {
        lpHeadNode = lpNode->LpProxNode;
        free(lpNode->lpBuffer);
        free(lpNode);
        lpNode = lpHeadNode;
    }
    lpBuffer = (char*)realloc(lpBuffer, 0);
    lpBuffer = NULL;
    if((lpNode == NULL) && (lpBuffer == NULL))
    {

        printf("Deallocate memory = %s", (char*)lpNode);
    }
    printf("\n\n");

    return 0;
}

How can I count text lines inside an DOM element? Can I?

For those who use jQuery http://jsfiddle.net/EppA2/3/

function getRows(selector) {
    var height = $(selector).height();
    var line_height = $(selector).css('line-height');
    line_height = parseFloat(line_height)
    var rows = height / line_height;
    return Math.round(rows);
}

TypeError: $.ajax(...) is not a function?

If you are using bootstrap html template remember to remove the link to jquery slim at the bottom of the template. I post this detail here as I cannot comment answers yet..

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Print a variable in hexadecimal in Python

You can try something like this I guess:

new_str = ""
str_value = "rojbasr"
for i in str_value:
    new_str += "0x%s " % (i.encode('hex'))
print new_str

Your output would be something like this:

0x72 0x6f 0x6a 0x62 0x61 0x73 0x72

Is there a function to copy an array in C/C++?

I give here 2 ways of coping array, for C and C++ language. memcpy and copy both ar usable on C++ but copy is not usable for C, you have to use memcpy if you are trying to copy array in C.

#include <stdio.h>
#include <iostream>
#include <algorithm> // for using copy (library function)
#include <string.h> // for using memcpy (library function)


int main(){

    int arr[] = {1, 1, 2, 2, 3, 3};
    int brr[100];

    int len = sizeof(arr)/sizeof(*arr); // finding size of arr (array)

    std:: copy(arr, arr+len, brr); // which will work on C++ only (you have to use #include <algorithm>
    memcpy(brr, arr, len*(sizeof(int))); // which will work on both C and C++

    for(int i=0; i<len; i++){ // Printing brr (array).
        std:: cout << brr[i] << " ";
    }

    return 0;
}

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

NSURLErrorDomain error codes description

The NSURLErrorDomain error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes

However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.

HttpURLConnection timeout settings

HttpURLConnection has a setConnectTimeout method.

Just set the timeout to 5000 milliseconds, and then catch java.net.SocketTimeoutException

Your code should look something like this:


try {
   HttpURLConnection.setFollowRedirects(false);
   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds

   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}


Differences between MySQL and SQL Server

I can't believe that no one mentioned that MySQL doesn't support Common Table Expressions (CTE) / "with" statements. It's a pretty annoying difference.

AngularJs $http.post() does not send data

Just put the data you want to send as second parameter:

$http.post('request-url',  message);

Another form which also works is:

$http.post('request-url',  { params: { paramName: value } });

Make sure that paramName exactly matches the name of the parameter of the function you are calling.

Source: AngularJS post shortcut method

iPhone UITextField - Change placeholder text color

Easy and pain-free, could be an easy alternative for some.

_placeholderLabel.textColor

Not suggested for production, Apple may reject your submission.

Add comma to numbers every three digits

Use function Number();

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  var price1 = 1000;_x000D_
  var price2 = 500000;_x000D_
  var price3 = 15245000;_x000D_
_x000D_
  $("span#s1").html(Number(price1).toLocaleString('en'));_x000D_
  $("span#s2").html(Number(price2).toLocaleString('en'));_x000D_
  $("span#s3").html(Number(price3).toLocaleString('en'));_x000D_
_x000D_
  console.log(Number(price).toLocaleString('en'));_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<span id="s1"></span><br />_x000D_
<span id="s2"></span><br />_x000D_
<span id="s3"></span><br />
_x000D_
_x000D_
_x000D_

What is two way binding?

McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.

It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.

Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).

I was gonna put this in a comment, but it was getting pretty long...

Android custom Row Item for ListView

Add this row.xml to your layout folder

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Header"/>

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/text"/>
    
    
</LinearLayout>

make your main xml layout as this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>

This is your adapter

class yourAdapter extends BaseAdapter {

    Context context;
    String[] data;
    private static LayoutInflater inflater = null;

    public yourAdapter(Context context, String[] data) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.row, null);
        TextView text = (TextView) vi.findViewById(R.id.text);
        text.setText(data[position]);
        return vi;
    }
}

Your java activity

public class StackActivity extends Activity {

    ListView listview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(new yourAdapter(this, new String[] { "data1",
                "data2" }));
    }
}

the results

enter image description here

How to make child process die after parent exits?

If you send a signal to the pid 0, using for instance

kill(0, 2); /* SIGINT */

that signal is sent to the entire process group, thus effectively killing the child.

You can test it easily with something like:

(cat && kill 0) | python

If you then press ^D, you'll see the text "Terminated" as an indication that the Python interpreter have indeed been killed, instead of just exited because of stdin being closed.

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

Read/Write 'Extended' file properties (C#)

I'm not sure what types of files you are trying to write the properties for but taglib-sharp is an excellent open source tagging library that wraps up all this functionality nicely. It has a lot of built in support for most of the popular media file types but also allows you to do more advanced tagging with pretty much any file.

EDIT: I've updated the link to taglib sharp. The old link no longer worked.

EDIT: Updated the link once again per kzu's comment.

How do I run Redis on Windows?

The MSOpenTech-Redis project is no longer being actively maintained. If you are looking for a Windows version of Redis, you may want to check out Memurai. Please note that Microsoft is not officially endorsing this product in any way. More details in https://github.com/microsoftarchive/redis

To install & setup Redis Server on Windows 10 https://redislabs.com/blog/redis-on-windows-10

To install & setup Redis Server on macOS & Linux https://redis.io/download

Also, you may install & setup Redis Server on Linux via the package manager

For quick Redis Server Installation & Setup Guide for macOS https://github.com/rahamath18/Redis-on-MacOS

to_string not declared in scope

you must compile the file with c++11 support

g++ -std=c++0x  -o test example.cpp

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

You're getting into looping most likely due to these rules:

RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

Just comment it out and try again in a new browser.

Embed website into my site

**What's the best way to avoid a fixed size, i.e., to have the embedded website scale responsively to the browser's window size? I'd like to avoid scroll bars within my website. – CGFoX Feb 2 '19 at 15:52

**Is it possible to set width and height to percentages instead of absolute pixels? – CGFoX Mar 16 at 11:53

ANSWER: <embed src="https://YOURDOMAIN.com/PAGE.HTM" style="width:100%; height: 50vw;">

Equal height rows in CSS Grid Layout

Short Answer

If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:

  • Set the container to grid-auto-rows: 1fr

How it works

Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow property in flexbox.

If you set all rows in a grid container to 1fr, let's say like this:

grid-auto-rows: 1fr;

... then all rows will be equal height.

It doesn't really make sense off-the-bat because fr is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.

Except, buried deep in the grid spec is this little nugget:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.

The height of each row is determined by the tallest (max-content) grid item.

The maximum height of those rows becomes the length of 1fr.

That's how 1fr creates equal height rows in a grid container.


Why flexbox isn't an option

As noted in the question, equal height rows are not possible with flexbox.

Flex items can be equal height on the same row, but not across multiple rows.

This behavior is defined in the flexbox spec:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

how to open a page in new tab on button click in asp.net?

Why not just call window.open straight from OnClick?

<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="window.open('New.aspx')" />

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

This can also happen if you are attempting to connect over HTTPS and the server is not configured to handle SSL connections correctly.

I would check your application servers SSL settings and make sure that the certification is configured correctly.

Could not create work tree dir 'example.com'.: Permission denied

I was facing the same issue but it was not a permission issue.

When you are doing git clone it will create try to create replica of the respository structure.

When its trying to create the folder/directory with same name and path in your local os process is not allowing to do so and hence the error. There was "background" java process running in Task-manager which was accessing the resource of the directory(folder) and hence it was showing as permission denied for git operations. I have killed those process and that solved my problem. Cheers!!

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

How to get the URL of the current page in C#

Just sharing as this was my solution thanks to Canavar's post.

If you have something like this:

"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"

or like this:

"https://www.something.com/index.html?a=123&b=4567"

and you only want the part that a user would type in then this will work:

String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");

which would result in these:

"http://localhost:1234/"
"https://www.something.com/"

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

Create a custom event in Java

There are 3 different ways you may wish to set this up:

  1. Thrower inside of Catcher
  2. Catcher inside of Thrower
  3. Thrower and Catcher inside of another class in this example Test

THE WORKING GITHUB EXAMPLE I AM CITING Defaults to Option 3, to try the others simply uncomment the "Optional" code block of the class you want to be main, and set that class as the ${Main-Class} variable in the build.xml file:

4 Things needed on throwing side code:

import java.util.*;//import of java.util.event

//Declaration of the event's interface type, OR import of the interface,
//OR declared somewhere else in the package
interface ThrowListener {
    public void Catch();
}
/*_____________________________________________________________*/class Thrower {
//list of catchers & corresponding function to add/remove them in the list
    List<ThrowListener> listeners = new ArrayList<ThrowListener>();
    public void addThrowListener(ThrowListener toAdd){ listeners.add(toAdd); }
    //Set of functions that Throw Events.
        public void Throw(){ for (ThrowListener hl : listeners) hl.Catch();
            System.out.println("Something thrown");
        }
////Optional: 2 things to send events to a class that is a member of the current class
. . . go to github link to see this code . . .
}

2 Things needed in a class file to receive events from a class

/*_______________________________________________________________*/class Catcher
implements ThrowListener {//implement added to class
//Set of @Override functions that Catch Events
    @Override public void Catch() {
        System.out.println("I caught something!!");
    }
////Optional: 2 things to receive events from a class that is a member of the current class
. . . go to github link to see this code . . .
}

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I was struggling with this as well. I used an interceptor, it captures the response headers, then clone the headers(since headers are immutable objects) and then sends the modified headers. https://angular.io/guide/http#intercepting-requests-and-responses

Cannot add a project to a Tomcat server in Eclipse

  1. Right click on the project name in the Package Explorer view.
  2. Select Properties
  3. Select Project Facets
  4. Click on the Runtimes tab
  5. Check Server
  6. Click on OK

And now:

  1. Right click on the server name in the Servers view
  2. Click on Add and Remove...
  3. Move resources to the right column

Format output string, right alignment

You can align it like that:

print('{:>8} {:>8} {:>8}'.format(*words))

where > means "align to right" and 8 is the width for specific value.

And here is a proof:

>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
    print('{:>8} {:>8} {:>8}'.format(*line))


       1      128  1298039
  123388        0        2

Ps. *line means the line list will be unpacked, so .format(*line) works similarly to .format(line[0], line[1], line[2]) (assuming line is a list with only three elements).

<code> vs <pre> vs <samp> for inline and block code snippets

Use <code> for inline code that can wrap and <pre><code> for block code that must not wrap. <samp> is for sample output, so I would avoid using it to represent sample code (which the reader is to input). This is what Stack Overflow does.

(Better yet, if you want easy to maintain, let the users edit the articles as Markdown, then they don’t have to remember to use <pre><code>.)

HTML5 agrees with this in “the pre element”:

The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements.

Some examples of cases where the pre element could be used:

  • Including fragments of computer code, with structure indicated according to the conventions of that language.

[…]

To represent a block of computer code, the pre element can be used with a code element; to represent a block of computer output the pre element can be used with a samp element. Similarly, the kbd element can be used within a pre element to indicate text that the user is to enter.

In the following snippet, a sample of computer code is presented.

_x000D_
_x000D_
<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
      this.element = element;
      this.canClose = canClose;
      this.closeHandler = function () { if (closeHandler) closeHandler() };
    }</code></pre>
_x000D_
_x000D_
_x000D_

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

Get a Div Value in JQuery

You could use

jQuery('#gregsButton').click(function() { 
    var mb = jQuery('#myDiv').text(); 
    alert("Value of div is: " + mb); 
});

Looks like there may be a conflict with using the $. Remember that the variable 'mb' will not be accessible outside of the event handler. Also, the text() function returns a string, no need to get mb.value.

Printing an array in C++?

C++ can print whatever you want if you program it to do so. You'll have to go through the array yourself printing each element.

SQLite Reset Primary Key Field

You can reset by update sequence after deleted rows in your-table

UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';

How to enable C# 6.0 feature in Visual Studio 2013?

It seems there's some misunderstanding. So, instead of trying to patch VS2013 here's and answer from a Microsoft guy: https://social.msdn.microsoft.com/Forums/vstudio/en-US/49ba9a67-d26a-4b21-80ef-caeb081b878e/will-c-60-ever-be-supported-by-vs-2013?forum=roslyn

So, please, read it and install VS2015.

How do you get a directory listing sorted by creation date in python?

Alex Coventry's answer will produce an exception if the file is a symlink to an unexistent file, the following code corrects that answer:

import time
import datetime
sorted(filter(os.path.isfile, os.listdir('.')), 
    key=lambda p: os.path.exists(p) and os.stat(p).st_mtime or time.mktime(datetime.now().timetuple())

When the file doesn't exist, now() is used, and the symlink will go at the very end of the list.

How can I easily add storage to a VirtualBox machine with XP installed?

Adding a second drive is probably easiest. That would only take a few minutes, and it wouldn't require any configuration, really.

Alternatively, you could create the second, bigger drive, then run a disk imaging utility to copy all data on disk1 to disk2. That certainly shouldn't take a few hours, but it would take longer than just living with two drives.

onchange file input change img src and change image color

in your HTML : <input type="file" id="yourFile"> don't forget to reference your js file or put the following script between <script></script> in your script :

var fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener("change", function(event) {
    var files = fileToRead.files;
    if (files.length) {
        console.log("Filename: " + files[0].name);
        console.log("Type: " + files[0].type);
        console.log("Size: " + files[0].size + " bytes");
    }

}, false);

HTML colspan in CSS

Try adding display: table-cell; width: 1%; to your table cell element.

_x000D_
_x000D_
.table-cell {_x000D_
  display: table-cell;_x000D_
  width: 1%;_x000D_
  padding: 4px;_x000D_
  border: 1px solid #efefef;_x000D_
}
_x000D_
<div class="table">_x000D_
  <div class="table-cell">one</div>_x000D_
  <div class="table-cell">two</div>_x000D_
  <div class="table-cell">three</div>_x000D_
  <div class="table-cell">four</div>_x000D_
</div>_x000D_
<div class="table">_x000D_
  <div class="table-cell">one</div>_x000D_
  <div class="table-cell">two</div>_x000D_
  <div class="table-cell">three</div>_x000D_
  <div class="table-cell">four</div>_x000D_
</div>_x000D_
<div class="table">_x000D_
  <div class="table-cell">one</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between array_map, array_walk and array_filter

  • Changing Values:
  • Array Keys Access:
  • Return Value:
    • array_map returns a new array, array_walk only returns true. Hence, if you don't want to create an array as a result of traversing one array, you should use array_walk.
  • Iterating Multiple Arrays:
    • array_map also can receive an arbitrary number of arrays and it can iterate over them in parallel, while array_walk operates only on one.
  • Passing Arbitrary Data to Callback:
    • array_walk can receive an extra arbitrary parameter to pass to the callback. This mostly irrelevant since PHP 5.3 (when anonymous functions were introduced).
  • Length of Returned Array:
    • The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function. It does preserve the keys.

Example:

<pre>
<?php

$origarray1 = array(2.4, 2.6, 3.5);
$origarray2 = array(2.4, 2.6, 3.5);

print_r(array_map('floor', $origarray1)); // $origarray1 stays the same

// changes $origarray2
array_walk($origarray2, function (&$v, $k) { $v = floor($v); }); 
print_r($origarray2);

// this is a more proper use of array_walk
array_walk($origarray1, function ($v, $k) { echo "$k => $v", "\n"; });

// array_map accepts several arrays
print_r(
    array_map(function ($a, $b) { return $a * $b; }, $origarray1, $origarray2)
);

// select only elements that are > 2.5
print_r(
    array_filter($origarray1, function ($a) { return $a > 2.5; })
);

?>
</pre>

Result:

Array
(
    [0] => 2
    [1] => 2
    [2] => 3
)
Array
(
    [0] => 2
    [1] => 2
    [2] => 3
)
0 => 2.4
1 => 2.6
2 => 3.5
Array
(
    [0] => 4.8
    [1] => 5.2
    [2] => 10.5
)
Array
(
    [1] => 2.6
    [2] => 3.5
)

Increasing the Command Timeout for SQL command

Since it takes 2 mins to respond, you can increase the timeout to 3 mins by adding the below code

scGetruntotals.CommandTimeout = 180;

Note : the parameter value is in seconds.

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

How to use JavaScript with Selenium WebDriver Java

Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver. Please correct me if I'm wrong.

The WebDriverJs is actually "just" another WebDriver language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.

If you want to run JavaScript code in Java WebDriver, do this instead:

WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
    ((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
    throw new IllegalStateException("This driver does not support JavaScript!");
}

I like to do this, also:

WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
    js = (JavascriptExecutor)driver;
} // else throw...

// later on...
js.executeScript("return document.getElementById('someId');");

You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor.

The executeScript() takes function calls and raw JS, too. You can return a value from it and you can pass lots of complicated arguments to it, some random examples:

  1. // returns the right WebElement
    // it's the same as driver.findElement(By.id("someId"))
    js.executeScript("return document.getElementById('someId');");
    
  2. // draws a border around WebElement
    WebElement element = driver.findElement(By.anything("tada"));
    js.executeScript("arguments[0].style.border='3px solid red'", element);
    
  3. // changes all input elements on the page to radio buttons
    js.executeScript(
            "var inputs = document.getElementsByTagName('input');" +
            "for(var i = 0; i < inputs.length; i++) { " +
            "    inputs[i].type = 'radio';" +
            "}" );
    

MySQL Fire Trigger for both Insert and Update

unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

How to set cookie in node js using express framework?

Not exactly answering your question, but I came across your question, while looking for an answer to an issue that I had. Maybe it will help somebody else.

My issue was that cookies were set in server response, but were not saved by the browser.

The server response came back with cookies set:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 

This is how I solved it.

I used fetch in the client-side code. If you do not specify credentials: 'include' in the fetch options, cookies are neither sent to server nor saved by the browser, even though the server response sets cookies.

Example:

var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');

return fetch('/your/server_endpoint', {
    method: 'POST',
    mode: 'same-origin',
    redirect: 'follow',
    credentials: 'include', // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({
        first_name: 'John',
        last_name: 'Doe'
    })
})

I hope this helps somebody.

What is the use of a private static variable in Java?

I'm new to Java, but one way I use static variables, as I'm assuming many people do, is to count the number of instances of the class. e.g.:

public Class Company {
    private static int numCompanies;

    public static int getNumCompanies(){
        return numCompanies;
    }
}

Then you can sysout:

Company.getNumCompanies();

You can also get access to numCompanies from each instance of the class (which I don't completely understand), but it won't be in a "static way". I have no idea if this is best practice or not, but it makes sense to me.

How to get phpmyadmin username and password

Try changing the following lines with new values

$cfg['Servers'][$i]['user'] = 'NEW_USERNAME';
$cfg['Servers'][$i]['password'] = 'NEW_PASSWORD';

Updated due to the absence of the above lines in the config file

Stop the MySQL server

sudo service mysql stop

Start mysqld

sudo mysqld --skip-grant-tables &

Login to MySQL as root

mysql -u root mysql

Change MYSECRET with your new root password

UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;

Kill mysqld

sudo pkill mysqld

Start mysql

sudo service mysql start

Login to phpmyadmin as root with your new password

Time part of a DateTime Field in SQL

select cast(getdate() as time(0))

returns for example :- 15:19:43

replace getdate() with the date time you want to extract just time from!

align 3 images in same row with equal spaces?

HTML:

<div class="container">
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
    <span>
        <img ... >
    </span>
</div>

CSS:

.container{ width:50%; margin:0 auto; text-align:center}
.container span{ width:30%; margin:0 1%;  }

I haven't tested this, but hope this will work.

You can add 'display:inline-block' to .container span to make the span to have fixed 30% width

How to remove CocoaPods from a project?

enter image description here

pictorial representation detailed

How do I pass along variables with XMLHTTPRequest

Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

You could write a simple utility function that handles building the query formatting for you.

function formatParams( params ){
  return "?" + Object
        .keys(params)
        .map(function(key){
          return key+"="+encodeURIComponent(params[key])
        })
        .join("&")
}

And you would use it this way to build a request.

var endpoint = "https://api.example.com/endpoint"
var params = {
  a: 1, 
  b: 2,
  c: 3
}

var url = endpoint + formatParams(params)
//=> "https://api.example.com/endpoint?a=1&b=2&c=3"

There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.

It is similar to the above example function, but handles recursively serializing nested objects and arrays.

Argparse: Required arguments listed under "optional arguments"?

Building off of @Karl Rosaen

parser = argparse.ArgumentParser()
optional = parser._action_groups.pop() # Edited this line
required = parser.add_argument_group('required arguments')
# remove this line: optional = parser...
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
parser._action_groups.append(optional) # added this line
return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
           [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  -h, --help                    show this help message and exit
  --optional_arg OPTIONAL_ARG

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

For UWP, I tried a different approach. I extended the ComboBox class, and processed the SelectionChanged and OnKeyUp events on the ComboBox as well as the Tapped event on the ComboBoxItems. In cases where I get a Tapped event or an Enter or Space key without first getting a SelectionChanged then I know the current item has been re-selected and I respond accordingly.

class ExtendedComboBox : ComboBox
{
    public ExtendedComboBox()
    {
        SelectionChanged += OnSelectionChanged;
    }

    protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
    {
        ComboBoxItem cItem = element as ComboBoxItem;
        if (cItem != null)
        {
            cItem.Tapped += OnItemTapped;
        }

        base.PrepareContainerForItemOverride(element, item);
    }

    protected override void OnKeyUp(KeyRoutedEventArgs e)
    {
        // if the user hits the Enter or Space to select an item, then consider this a "reselect" operation
        if ((e.Key == Windows.System.VirtualKey.Space || e.Key == Windows.System.VirtualKey.Enter) && !isSelectionChanged)
        {
            // handle re-select logic here
        }

        isSelectionChanged = false;

        base.OnKeyUp(e);
    }

    // track whether or not the ComboBox has received a SelectionChanged notification
    // in cases where it has not yet we get a Tapped or KeyUp notification we will want to consider that a "re-select"
    bool isSelectionChanged = false;
    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        isSelectionChanged = true;
    }

    private void OnItemTapped(object sender, TappedRoutedEventArgs e)
    {
        if (!isSelectionChanged)
        {
            // indicates that an item was re-selected  - handle logic here
        }

        isSelectionChanged = false;
    }
}

ContractFilter mismatch at the EndpointDispatcher exception

Your client was not updated.So Update your services from Web service and then rebuild your project

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

Go to

Tools->Options->Text Editor->C# (or All Languages)->General

and enable Auto List Members and Parameter Information in right hand side pane.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

Foreign Key to non-primary key

If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.

From Books Online:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

So in your case if you make AnotherID unique, it will be allowed. If you can't apply a unique constraint you're out of luck, but this really does make sense if you think about it.

Although, as has been mentioned, if you have a perfectly good primary key as a candidate key, why not use that?

Redirecting output to $null in PowerShell, but ensuring the variable remains set

If it's errors you want to hide you can do it like this

$ErrorActionPreference = "SilentlyContinue"; #This will hide errors
$someObject.SomeFunction();
$ErrorActionPreference = "Continue"; #Turning errors back on

Remove .php extension with .htaccess

Here is the code that I used to hide the .php extension from the filename:

## hide .php extension
# To redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L,NC]

Note: R=301 is for permanent redirect and is recommended to use for SEO purpose. However if one wants just a temporary redirect replace it with just R

Freeze screen in chrome debugger / DevTools panel for popover inspection?

Got it working. Here was my procedure:

  1. Browse to the desired page
  2. Open the dev console - F12 on Windows/Linux or option + ? + J on macOS
  3. Select the Sources tab in chrome inspector
  4. In the web browser window, hover over the desired element to initiate the popover
  5. Hit F8 on Windows/Linux (or fn + F8 on macOS) while the popover is showing. If you have clicked anywhere on the actual page F8 will do nothing. Your last click needs to be somewhere in the inspector, like the sources tab
  6. Go to the Elements tab in inspector
  7. Find your popover (it will be nested in the trigger element's HTML)
  8. Have fun modifying the CSS

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

Generic htaccess redirect www to non-www

RewriteEngine on
# if host value starts with "www."
RewriteCond %{HTTP_HOST} ^www\.
# redirect the request to "non-www"
RewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]

If you want to remove www on both http and https , use the following :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]

This redirects Non ssl

to

And SSL

to

on apache 2.4.* you can accomplish this using a Redirect with if directive,

<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>

How to get Locale from its String representation in Java?

There doesn't seem to be a static valueOf method for this, which is a bit surprising.

One rather ugly, but simple, way, would be to iterate over Locale.getAvailableLocales(), comparing their toString values with your value.

Not very nice, but no string parsing required. You could pre-populate a Map of Strings to Locales, and look up your database string in that Map.

Performance differences between ArrayList and LinkedList

Ignore this answer for now. The other answers, particularly that of aix, are mostly correct. Over the long term they're the way to bet. And if you have enough data (on one benchmark on one machine, it seemed to be about one million entries) ArrayList and LinkedList do currently work as advertized. However, there are some fine points that apply in the early 21st century.

Modern computer technology seems, by my testing, to give an enormous edge to arrays. Elements of an array can be shifted and copied at insane speeds. As a result arrays and ArrayList will, in most practical situations, outperform LinkedList on inserts and deletes, often dramatically. In other words, ArrayList will beat LinkedList at its own game.

The downside of ArrayList is it tends to hang onto memory space after deletions, where LinkedList gives up space as it gives up entries.

The bigger downside of arrays and ArrayList is they fragment free memory and overwork the garbage collector. As an ArrayList expands, it creates new, bigger arrays, copies the old array to the new one, and frees the old one. Memory fills with big contiguous chunks of free memory that are not big enough for the next allocation. Eventually there's no suitable space for that allocation. Even though 90% of memory is free, no individual piece is big enough to do the job. The GC will work frantically to move things around, but if it takes too long to rearrange the space, it will throw an OutOfMemoryException. If it doesn't give up, it can still slow your program way down.

The worst of it is this problem can be hard to predict. Your program will run fine one time. Then, with a bit less memory available, with no warning, it slows or stops.

LinkedList uses small, dainty bits of memory and GC's love it. It still runs fine when you're using 99% of your available memory.

So in general, use ArrayList for smaller sets of data that are not likely to have most of their contents deleted, or when you have tight control over creation and growth. (For instance, creating one ArrayList that uses 90% of memory and using it without filling it for the duration of the program is fine. Continually creating and freeing ArrayList instances that use 10% of memory will kill you.) Otherwise, go with LinkedList (or a Map of some sort if you need random access). If you have very large collections (say over 100,000 elements), no concerns about the GC, and plan lots of inserts and deletes and no random access, run a few benchmarks to see what's fastest.

How can a Javascript object refer to values in itself?

One alternative would be to use a getter/setter methods.

For instance, if you only care about reading the calculated value:

var book  = {}

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true },
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + " works!";
        }
    }
});

console.log(book.key2); //prints "it works!"

The above code, though, won't let you define another value for key2.

So, the things become a bit more complicated if you would like to also redefine the value of key2. It will always be a calculated value. Most likely that's what you want.

However, if you would like to be able to redefine the value of key2, then you will need a place to cache its value independently of the calculation.

Somewhat like this:

var book  = { _key2: " works!" }

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true},
    _key2: { enumerable: false},
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + this._key2;
        },
        set: function(newValue){
            this._key2 = newValue;
        }
    }
});

console.log(book.key2); //it works!

book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!

for(var key in book){
    //prints both key1 and key2, but not _key2
    console.log(key + ":" + book[key]); 
}

Another interesting alternative is to use a self-initializing object:

var obj = ({
  x: "it",
  init: function(){
    this.y = this.x + " works!";
    return this;
  }
}).init();

console.log(obj.y); //it works!

Hibernate Criteria for Dates

By using this way you can get the list of selected records.

GregorianCalendar gregorianCalendar = new GregorianCalendar();
Criteria cri = session.createCriteria(ProjectActivities.class);
cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime()));
List list = cri.list();

All the Records will be generated into list which are greater than or equal to '08-Oct-2012' or else pass the date of user acceptance date at 2nd parameter of Restrictions (gregorianCalendar.getTime()) of criteria to get the records.

How to make a vertical SeekBar in Android?

In my case, I used an ordinary seekBar and just flipped out the layout.

seekbark_layout.xml - my layout that containts seekbar which we need to make vertical.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"/>

</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vgfit.seekbarexample.MainActivity">

<View
    android:id="@+id/headerView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@color/colorAccent"/>

<View
    android:id="@+id/bottomView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:background="@color/colorAccent"/>

<include
    layout="@layout/seekbar_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottomView"
    android:layout_below="@id/headerView"/>

 </RelativeLayout>

And in MainActivity I rotate seekbar_layout:

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.RelativeLayout
import kotlinx.android.synthetic.main.seekbar_layout.*


class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    rootView.post {
        val w = rootView.width
        val h = rootView.height

        rootView.rotation = 270.0f
        rootView.translationX = ((w - h) / 2).toFloat()
        rootView.translationY = ((h - w) / 2).toFloat()

        val lp = rootView.layoutParams as RelativeLayout.LayoutParams
        lp.height = w
        lp.width = h
        rootView.requestLayout()
    }
}
}

As a result we have necessary vertical seekbar: enter image description here

Oracle sqlldr TRAILING NULLCOLS required, but why?

You have defined 5 fields in your control file. Your fields are terminated by a comma, so you need 5 commas in each record for the 5 fields unless TRAILING NULLCOLS is specified, even though you are loading the ID field with a sequence value via the SQL String.

RE: Comment by OP

That's not my experience with a brief test. With the following control file:

load data
infile *
into table T_new
fields terminated by "," optionally enclosed by '"'
( A,
  B,
  C,
  D,
  ID "ID_SEQ.NEXTVAL"
)
BEGINDATA
1,1,,,
2,2,2,,
3,3,3,3,
4,4,4,4,,
,,,,,

Produced the following output:

Table T_NEW, loaded from every logical record.
Insert option in effect for this table: INSERT

   Column Name                  Position   Len  Term Encl Datatype
------------------------------ ---------- ----- ---- ---- ---------------------
A                                   FIRST     *   ,  O(") CHARACTER            
B                                    NEXT     *   ,  O(") CHARACTER            
C                                    NEXT     *   ,  O(") CHARACTER            
D                                    NEXT     *   ,  O(") CHARACTER            
ID                                   NEXT     *   ,  O(") CHARACTER            
    SQL string for column : "ID_SEQ.NEXTVAL"

Record 1: Rejected - Error on table T_NEW, column ID.
Column not found before end of logical record (use TRAILING NULLCOLS)
Record 2: Rejected - Error on table T_NEW, column ID.
Column not found before end of logical record (use TRAILING NULLCOLS)
Record 3: Rejected - Error on table T_NEW, column ID.
Column not found before end of logical record (use TRAILING NULLCOLS)
Record 5: Discarded - all columns null.

Table T_NEW:
  1 Row successfully loaded.
  3 Rows not loaded due to data errors.
  0 Rows not loaded because all WHEN clauses were failed.
  1 Row not loaded because all fields were null.

Note that the only row that loaded correctly had 5 commas. Even the 3rd row, with all data values present except ID, the data does not load. Unless I'm missing something...

I'm using 10gR2.