Programs & Examples On #Countries

Of Countries and their Cities

Go through this link http://www.maxmind.com/en/worldcities

It Includes the following fields:

  1. Country Code
  2. ASCII City Name
  3. City Name
  4. Region
  5. Population
  6. Latitude (The latitude and longitude are near the center of the most granular location value returned: postal code, city, region, or country)
  7. Longitude

How do I print to the debug output window in a Win32 app?

I was looking for a way to do this myself and figured out a simple solution.

I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:

Project -> Properties -> Linker -> System -> Subsystem

And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.

Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.

So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.

The starting part of your program should now look something like this:

#include <iostream>

using namespace std;

// Main function for the console
int main(){

    // Calling the wWinMain function to start the GUI program
    // Parameters:
    // GetModuleHandle(NULL) - To get a handle to the current instance
    // NULL - Previous instance is not needed
    // NULL - Command line parameters are not needed
    // 1 - To show the window normally
    wWinMain(GetModuleHandle(NULL), NULL,NULL, 1); 

    system("pause");
    return 0;
}

// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    // This will display "Hello World" in the console as soon as the GUI begins.
    cout << "Hello World" << endl;
.
.
.

Result of my implementation

Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.

setup android on eclipse but don't know SDK directory

The path to the SDK is:

C:\Users\USERNAME\AppData\Local\Android\sdk

This can be used in Eclipse after you replace USERNAME with your Windows user name.

Escaping double quotes in JavaScript onClick event handler

I think that the best approach is to assign the onclick handler unobtrusively.

Something like this:

window.onload = function(){
    var myLink = document.getElementsById('myLinkId');
    myLink.onclick = function(){ 
        parse('#', false, '<a href="xyz');
        return false;
    }
}

//...


<a href="#" id="myLink">Test</a>

jQuery’s .bind() vs. .on()

From the jQuery documentation:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

http://api.jquery.com/bind/

What is a None value?

Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.

Example:

def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

Now try to guess output of above list. Well, the answer is surprisingly as below:

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

But Why?

Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.

However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.

list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).


'None' the savior: (Modify example above to produce desired behavior)

def extendList(val, list=None):
    if list is None:
       list = []
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

With this revised implementation, the output would be:

list1 = [10]
list2 = [123]
list3 = ['a']

Note - Example credit to toptal.com

Using wget to recursively fetch a directory with arbitrary files in it

The following option seems to be the perfect combination when dealing with recursive download:

wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2

Relevant snippets from man pages for convenience:

   -nd
   --no-directories
       Do not create a hierarchy of directories when retrieving recursively.  With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
       filenames will get extensions .n).


   -np
   --no-parent
       Do not ever ascend to the parent directory when retrieving recursively.  This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.

Using a global variable with a thread

Thanks so much Jason Pan for suggesting that method. The thread1 if statement is not atomic, so that while that statement executes, it's possible for thread2 to intrude on thread1, allowing non-reachable code to be reached. I've organized ideas from the prior posts into a complete demonstration program (below) that I ran with Python 2.7.

With some thoughtful analysis I'm sure we could gain further insight, but for now I think it's important to demonstrate what happens when non-atomic behavior meets threading.

# ThreadTest01.py - Demonstrates that if non-atomic actions on
# global variables are protected, task can intrude on each other.
from threading import Thread
import time

# global variable
a = 0; NN = 100

def thread1(threadname):
    while True:
      if a % 2 and not a % 2:
          print("unreachable.")
    # end of thread1

def thread2(threadname):
    global a
    for _ in range(NN):
        a += 1
        time.sleep(0.1)
    # end of thread2

thread1 = Thread(target=thread1, args=("Thread1",))
thread2 = Thread(target=thread2, args=("Thread2",))

thread1.start()
thread2.start()

thread2.join()
# end of ThreadTest01.py

As predicted, in running the example, the "unreachable" code sometimes is actually reached, producing output.

Just to add, when I inserted a lock acquire/release pair into thread1 I found that the probability of having the "unreachable" message print was greatly reduced. To see the message I reduced the sleep time to 0.01 sec and increased NN to 1000.

With a lock acquire/release pair in thread1 I didn't expect to see the message at all, but it's there. After I inserted a lock acquire/release pair also into thread2, the message no longer appeared. In hind signt, the increment statement in thread2 probably also is non-atomic.

AttributeError: 'module' object has no attribute

SoLvEd

Python is looking for the a object within your a.py module.

Either RENAME that file to something else or use

from __future__ import absolute_import 

at the top of your a.py module.

Laravel whereIn OR whereIn

$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery)  use ($stakeholderId){
            $subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
            $subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
    });

 $result = $query->get();

return $result;

// OUTPUT @input $stakeholderId = 1

//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss.rights from dms_stakeholder_permissions where dms_stakeholder_permissions.stakeholder_id = 4 or (dms_stakeholder_permissions.stakeholder_id = 1 and dms_stakeholder_permissions.rights in (1, 2, 3))

How to format JSON in notepad++

Here are the steps to install JSToolNPP plugin on your Notepad++.

  1. Download 64bit version from Sourceforge or the 32bit version if you are on a 32-bit OS.

    64bit - JSToolNPP.1.21.0.uni.64.zip: Download from SourceForget.net
    
  2. Notepad++ before installation

does not show JSTool in the Plugins menu.

  1. Unzip the downloaded JSToolNPP.1.21.0.uni.64 and copy the JSMinNPP.dll and place it under C:\Program Files\Notepad++\plugins.

  2. Close Notepad++ and reopen it. If you have downloaded an incompatible dll, then it will complain, else it will open successfully. If it complains about incompatibility, go back to STEP 1 and download the correct bit version as per your OS. Check Plugins in Notepad++.

JSTool is now located in the Plugins menu.

  1. Paste a sample unformatted but valid JSON data in Notepad++.

  2. Select all text in Notepad++ (CTRL+A) and format using Plugins -> JSTool -> JSFormat.

NOTE: On side note, if you do not want to install any plugins like this, I would recommend using the following 2 best online formatters.

Can regular JavaScript be mixed with jQuery?

Or no JavaScript load function at all...

<html>
<head></head>
<body>
    <canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="text/javascript">
    var draw = function() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (10, 10, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (30, 30, 55, 50);
        }
    }
    draw();

    //or self executing...

    (function(){
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (50, 50, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (70, 70, 55, 50);
        }
    })();
</script>
</html>

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Here is the complete solution for PostgreSQL 9+, updated recently.

CREATE USER readonly  WITH ENCRYPTED PASSWORD 'readonly';
GRANT USAGE ON SCHEMA public to readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

-- repeat code below for each database:

GRANT CONNECT ON DATABASE foo to readonly;
\c foo
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; --- this grants privileges on new tables generated in new database "foo"
GRANT USAGE ON SCHEMA public to readonly; 
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Thanks to https://jamie.curle.io/creating-a-read-only-user-in-postgres/ for several important aspects

If anyone find shorter code, and preferably one that is able to perform this for all existing databases, extra kudos.

How to use Angular4 to set focus by element id

Here is a directive that you can use in any component:

import { NgZone, Directive, ElementRef, AfterContentInit, Renderer2 } from '@angular/core';

@Directive({
    selector: '[appFocus]'
})
export class FocusDirective implements AfterContentInit {
    constructor(private el: ElementRef, private zone: NgZone, private renderer: Renderer2) {}

    ngAfterContentInit() {
        this.zone.runOutsideAngular(() => setTimeout(() => {
            this.renderer.selectRootElement(this.el.nativeElement).focus();
        }, 0));
    }
}

Use:

<input type="text" appFocus>

Get mouse wheel events in jQuery?

Binding to both mousewheel and DOMMouseScroll ended up working really well for me:

$(window).bind('mousewheel DOMMouseScroll', function(event){
    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
        // scroll up
    }
    else {
        // scroll down
    }
});

This method is working in IE9+, Chrome 33, and Firefox 27.


Edit - Mar 2016

I decided to revisit this issue since it's been a while. The MDN page for the scroll event has a great way of retrieving the scroll position that makes use of requestAnimationFrame, which is highly preferable to my previous detection method. I modified their code to provide better compatibility in addition to scroll direction and position:

_x000D_
_x000D_
(function() {_x000D_
  var supportOffset = window.pageYOffset !== undefined,_x000D_
    lastKnownPos = 0,_x000D_
    ticking = false,_x000D_
    scrollDir,_x000D_
    currYPos;_x000D_
_x000D_
  function doSomething(scrollPos, scrollDir) {_x000D_
    // Your code goes here..._x000D_
    console.log('scroll pos: ' + scrollPos + ' | scroll dir: ' + scrollDir);_x000D_
  }_x000D_
_x000D_
  window.addEventListener('wheel', function(e) {_x000D_
    currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;_x000D_
    scrollDir = lastKnownPos > currYPos ? 'up' : 'down';_x000D_
    lastKnownPos = currYPos;_x000D_
_x000D_
    if (!ticking) {_x000D_
      window.requestAnimationFrame(function() {_x000D_
        doSomething(lastKnownPos, scrollDir);_x000D_
        ticking = false;_x000D_
      });_x000D_
    }_x000D_
    ticking = true;_x000D_
  });_x000D_
})();
_x000D_
_x000D_
_x000D_

See the Pen Vanilla JS Scroll Tracking by Jesse Dupuy (@blindside85) on CodePen.

This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+

References:

What does "make oldconfig" do exactly in the Linux kernel makefile?

Updates an old config with new/changed/removed options.

Programmatically set left drawable in a TextView

A Kotlin extension + some padding around the drawable

fun TextView.addDrawable(drawable: Int) {
val imgDrawable = ContextCompat.getDrawable(context, drawable)
compoundDrawablePadding = 32
setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

What is a deadlock?

A deadlock happens when a thread is waiting for something that never occurs.

Typically, it happens when a thread is waiting on a mutex or semaphore that was never released by the previous owner.

It also frequently happens when you have a situation involving two threads and two locks like this:

Thread 1               Thread 2

Lock1->Lock();         Lock2->Lock();
WaitForLock2();        WaitForLock1();   <-- Oops!

You generally detect them because things that you expect to happen never do, or the application hangs entirely.

Get a list of all the files in a directory (recursive)

This code works for me:

import groovy.io.FileType

def list = []

def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
  list << file
}

Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:

list.each {
  println it.path
}

Populating VBA dynamic arrays

Yes, you're looking for the ReDim statement, which dynamically allocates the required amount of space in the array.

The following statement

Dim MyArray()

declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.

But you can use the ReDim statement to resize the array:

ReDim MyArray(0 To 3)

And if you need to resize the array while preserving its contents, you can use the Preserve keyword along with the ReDim statement:

ReDim Preserve MyArray(0 To 3)

But do note that both ReDim and particularly ReDim Preserve have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.


However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim at all. Just declare the array with explicit dimensions:

Dim MyArray(0 To 3)

How can I query for null values in entity framework?

var result = from entry in table
             where entry.something.Equals(null)
             select entry;

MSDN Reference: LINQ to SQL: .NET Language-Integrated Query for Relational Data

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

static function in C

The static keyword in C is used in a compiled file (.c as opposed to .h) so that the function exists only in that file.

Normally, when you create a function, the compiler generates cruft the linker can use to, well, link a function call to that function. If you use the static keyword, other functions within the same file can call this function (because it can be done without resorting to the linker), while the linker has no information letting other files access the function.

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

To check if this extensions are enabled or not, you can create a php file i.e. info.php and write the following code there:

<?php 
echo "GD: ", extension_loaded('gd') ? 'OK' : 'MISSING', '<br>';
echo "XML: ", extension_loaded('xml') ? 'OK' : 'MISSING', '<br>';
echo "zip: ", extension_loaded('zip') ? 'OK' : 'MISSING', '<br>';
?>

That's it.

How to test enum types?

If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.

But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.

How to return value from an asynchronous callback function?

If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/

It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.

No Exception while type casting with a null in java

This is very handy when using a method that would otherwise be ambiguous. For example: JDialog has constructors with the following signatures:

JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Dialog, String, boolean, GraphicsConfiguration)

I need to use this constructor, because I want to set the GraphicsConfiguration, but I have no parent for this dialog, so the first argument should be null. Using

JDialog(null, String, boolean, Graphicsconfiguration) 

is ambiguous, so in this case I can narrow the call by casting null to one of the supported types:

JDialog((Frame) null, String, boolean, GraphicsConfiguration)

Access POST values in Symfony2 request object

Symfony doc to get request data

Finally, the raw data sent with the request body can be accessed using getContent():

$content = $request->getContent();

How to change the color of progressbar in C# .NET 3.5?

I found this can be done by drawing a rectangle inside the progress bar, and to set its width according to the progress's current value. I also added support for right to left progress. This way you don't need to use the Image, and since Rectnalge.Inflate isn't called the drawn rectangle is smaller.

public partial class CFProgressBar : ProgressBar
{
    public CFProgressBar()
    {
        InitializeComponent();
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaintBackground(PaintEventArgs pevent) { }

    protected override void OnPaint(PaintEventArgs e)
    {
        double scaleFactor = (((double)Value - (double)Minimum) / ((double)Maximum - (double)Minimum));
        int currentWidth = (int)((double)Width * scaleFactor);
        Rectangle rect;
        if (this.RightToLeftLayout)
        {
            int currentX = Width - currentWidth;
            rect = new Rectangle(currentX, 0, this.Width, this.Height);
        }
        else
            rect = new Rectangle(0, 0, currentWidth, this.Height);

        if (rect.Width != 0)
        {
            SolidBrush sBrush = new SolidBrush(ForeColor);
            e.Graphics.FillRectangle(sBrush, rect);
        }
    }
}

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

If you don't have to support IE, you can use selectionStart and selectionEnd attributes of textarea.

To get caret position just use selectionStart:

function getCaretPosition(textarea) {
  return textarea.selectionStart
}

To get the strings surrounding the selection, use following code:

function getSurroundingSelection(textarea) {
  return [textarea.value.substring(0, textarea.selectionStart)
         ,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
         ,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}

Demo on JSFiddle.

See also HTMLTextAreaElement docs.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

On the client side you can enable cors requests in AngularJS via

app.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

However if this still returns an error, this would imply that the server that you are making the request has to allow CORS request and has to be configured for that.

How to request Location Permission at runtime

You need to actually request the Location permission at runtime (notice the comments in your code stating this).

Here is tested and working code to request the Location permission.

Be sure to import android.Manifest:

import android.Manifest;

Then put this code in the Activity:

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            new AlertDialog.Builder(this)
                    .setTitle(R.string.title_location_permission)
                    .setMessage(R.string.text_location_permission)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION);
                        }
                    })
                    .create()
                    .show();


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // location-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    //Request location updates:
                    locationManager.requestLocationUpdates(provider, 400, 1, this);
                }

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.

            }
            return;
        }

    }
}

Then call the checkLocationPermission() method in onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //.........

    checkLocationPermission();
}

You can then use onResume() and onPause() exactly as it is in the question.

Here is a condensed version that is a bit more clean:

@Override
protected void onResume() {
    super.onResume();
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {

        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {

        locationManager.removeUpdates(this);
    }
}

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

How can I suppress all output from a command using Bash?

In your script you can add the following to the lines that you know are going to give an output:

some_code 2>>/dev/null

Or else you can also try

some_code >>/dev/null

Ansible: filter a list by its attributes

I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:

- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"

would return:

ok: [localhost] => {
    "msg": [
        "172.16.1.100"
    ]
}

Java SSLException: hostname in certificate didn't match

In httpclient-4.3.3.jar, there is another HttpClient to use:

public static void main (String[] args) throws Exception {
    // org.apache.http.client.HttpClient client = new DefaultHttpClient();
    org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
    System.out.println("HttpClient = " + client.getClass().toString());
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

This HttpClientBuilder.create().build() will return org.apache.http.impl.client.InternalHttpClient. It can handle the this hostname in certificate didn't match issue.

javascript : sending custom parameters with window.open() but its not working

if you want to pass POST variables, you have to use a HTML Form:

<form action="http://localhost:8080/login" method="POST" target="_blank">
    <input type="text" name="cid" />
    <input type="password" name="pwd" />
    <input type="submit" value="open" />
</form>

or:

if you want to pass GET variables in an URL, write them without single-quotes:

http://yourdomain.com/login?cid=username&pwd=password

here's how to create the string above with javascrpt variables:

myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");

in the document with that url, you have to read the GET parameters. if it's in php, use:

$_GET['username']

be aware: to transmit passwords that way is a big security leak!

error: RPC failed; curl transfer closed with outstanding read data remaining

After few days, today I just resolved this problem. Generate ssh key, follow this article:

https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

Declare it to

  1. Git provider (GitLab what I am using, GitHub).
  2. Add this to local identity.

Then clone by command:

git clone [email protected]:my_group/my_repository.git

And no error happen.

The above problem

error: RPC failed; curl 18 transfer closed with outstanding read data remaining

because have error when clone by HTTP protocol (curl command).

And, you should increment buffer size:

git config --global http.postBuffer 524288000

How would I extract a single file (or changes to a file) from a git stash?

Short answer

To see the whole file: git show stash@{0}:<filename>

To see the diff: git diff stash@{0}^1 stash@{0} -- <filename>

Select Row number in postgres

SELECT tab.*,
    row_number() OVER () as rnum
  FROM tab;

Here's the relevant section in the docs.

P.S. This, in fact, fully matches the answer in the referenced question.

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

Can a shell script set environment variables of the calling shell?

This works — it isn't what I'd use, but it 'works'. Let's create a script teredo to set the environment variable TEREDO_WORMS:

#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL -i

It will be interpreted by the Korn shell, exports the environment variable, and then replaces itself with a new interactive shell.

Before running this script, we have SHELL set in the environment to the C shell, and the environment variable TEREDO_WORMS is not set:

% env | grep SHELL
SHELL=/bin/csh
% env | grep TEREDO
%

When the script is run, you are in a new shell, another interactive C shell, but the environment variable is set:

% teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%

When you exit from this shell, the original shell takes over:

% exit
% env | grep TEREDO
%

The environment variable is not set in the original shell's environment. If you use exec teredo to run the command, then the original interactive shell is replaced by the Korn shell that sets the environment, and then that in turn is replaced by a new interactive C shell:

% exec teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%

If you type exit (or Control-D), then your shell exits, probably logging you out of that window, or taking you back to the previous level of shell from where the experiments started.

The same mechanism works for Bash or Korn shell. You may find that the prompt after the exit commands appears in funny places.


Note the discussion in the comments. This is not a solution I would recommend, but it does achieve the stated purpose of a single script to set the environment that works with all shells (that accept the -i option to make an interactive shell). You could also add "$@" after the option to relay any other arguments, which might then make the shell usable as a general 'set environment and execute command' tool. You might want to omit the -i if there are other arguments, leading to:

#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL "${@-'-i'}"

The "${@-'-i'}" bit means 'if the argument list contains at least one argument, use the original argument list; otherwise, substitute -i for the non-existent arguments'.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

you have to add fulltext index on specific fields you want to search.

ALTER TABLE news ADD FULLTEXT(headline, story);

where "news" is your table and "headline, story" fields you wont to enable for fulltext search

Can you remove elements from a std::list while iterating through it?

do while loop, it's flexable and fast and easy to read and write.

auto textRegion = m_pdfTextRegions.begin();
    while(textRegion != m_pdfTextRegions.end())
    {
        if ((*textRegion)->glyphs.empty())
        {
            m_pdfTextRegions.erase(textRegion);
            textRegion = m_pdfTextRegions.begin();
        }
        else
            textRegion++;
    } 

Sum of values in an array using jQuery

You can do it in this way.

var somearray = ["20","40","80","400"];

somearray = somearray.map(Number);

var total = somearray.reduce(function(a,b){  return a+b },0)

console.log(total);

Jackson: how to prevent field serialization

Jackson has a class named SimpleBeanPropertyFilter that helps to filter fields during serialization and deserialization; not globally. I think that's what you wanted.

@JsonFilter("custom_serializer")
class User {
    private String password;

    //setter, getter..
}

Then in your code:

String[] fieldsToSkip = new String[] { "password" };

ObjectMapper mapper = new ObjectMapper();

final SimpleFilterProvider filter = new SimpleFilterProvider();
filter.addFilter("custom_serializer",
            SimpleBeanPropertyFilter.serializeAllExcept(fieldsToSkip));

mapper.setFilters(filter);

String jsonStr = mapper.writeValueAsString(currentUser);

This will prevent password field to get serialized. Also you will be able to deserialize password fields as it is. Just make sure no filters are applied on the ObjectMapper object.

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(yourJsonStr, User.class);    // user object does have non-null password field

Insert variable values in the middle of a string

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

How to filter an array/object by checking multiple values

You can use .filter() method of the Array object:

var filtered = workItems.filter(function(element) {
   // Create an array using `.split()` method
   var cats = element.category.split(' ');

   // Filter the returned array based on specified filters
   // If the length of the returned filtered array is equal to
   // length of the filters array the element should be returned  
   return cats.filter(function(cat) {
       return filtersArray.indexOf(cat) > -1;
   }).length === filtersArray.length;
});

http://jsfiddle.net/6RBnB/

Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

jQuery version:

var filtered = $(workItems).filter(function(i, element) {
   var cats = element.category.split(' ');

    return $(cats).filter(function(_, cat) {
       return $.inArray(cat, filtersArray) > -1;
    }).length === filtersArray.length;
});

Select method of Range class failed via VBA

This worked for me.

RowCounter = Sheets(3).UsedRange.Rows.Count + 1

Sheets(1).Rows(rowNum).EntireRow.Copy
Sheets(3).Activate
Sheets(3).Cells(RowCounter, 1).Select
Sheets(3).Paste
Sheets(1).Activate

CSS - center two images in css side by side

Try changing

#fblogo {
    display: block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}

to

.fblogo {
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}

#images{
    text-align:center;
}

HTML

<div id="images">
    <a href="mailto:[email protected]">
    <img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/07/email-icon-e1343123697991.jpg"/></a>
    <a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
    <img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>
</div>?

DEMO.

Laravel Redirect Back with() Message

In Laravel 5.5:

return back()->withErrors($arrayWithErrors);

In the view using Blade:

@if($errors->has())
    <ul>
    @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

Conversion of System.Array to List

in vb.net just do this

mylist.addrange(intsArray)

or

Dim mylist As New List(Of Integer)(intsArray)

Is there anything like .NET's NotImplementedException in Java?

No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.

Please refer to this discussion about why it's even in .NET.

I guess UnsupportedOperationException comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there? Interface segregation or Liskov substitution issues maybe?

If it's work in progress I'd go for ToBeImplementedException, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.

Can't bind to 'formGroup' since it isn't a known property of 'form'

The suggested answer did not work for me with Angular 4. Instead I had to use another way of attribute binding with the attr prefix:

<element [attr.attribute-to-bind]="someValue">

HTML5 best practices; section/header/aside/article elements

I dont think you should use the tag on the news item summary (lines 67, 80, 93). You could use section or just have the enclosing div.

An article needs to be able to stand on its own & still make sense or be complete. As its incomplete or just an extract it cannot be an article, its more a section.

When you click 'read more' the subsequent page can

Display animated GIF in iOS

You can use SwiftGif from this link

Usage:

imageView.loadGif(name: "jeremy")

How to configure slf4j-simple

This is a sample simplelogger.properties which you can place on the classpath (uncomment the properties you wish to use):

# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.

# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info

# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=

# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false

# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z

# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true

# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true

# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

Can't install any package with node npm

I also had problem in Ubuntu 15.10 while installing gulp-preetify.

The problem was:

  1. Registry returned 404 for GET on http://registry.npmjs.org/gulp-preetify

  2. I tried by using npm install gulp-preetify but it didn't worked.

  3. Again i tried using: npm i gulp-preetify and it just got installed.

I cannot guarantee that it will solve your problem but it won't harm with a single try.

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

String replacement in batch file

You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.

setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%

How to make layout with View fill the remaining space?

If you use RelativeLayout, you can do it something like this:

<RelativeLayout
    android:layout_width = "fill_parent"
    android:layout_height = "fill_parent">
    <ImageView
        android:id = "@+id/my_image"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_alignParentTop ="true" />
    <RelativeLayout
        android:id="@+id/layout_bottom"
        android:layout_width="fill_parent"
        android:layout_height = "50dp"
        android:layout_alignParentBottom = "true">
        <Button
            android:id = "@+id/but_left"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&lt;"
            android:layout_alignParentLeft = "true"/>
        <TextView
            android:layout_width = "fill_parent"
            android:layout_height = "wrap_content"
            android:layout_toLeftOf = "@+id/but_right"
            android:layout_toRightOf = "@id/but_left" />
        <Button
            android:id = "@id/but_right"
            android:layout_width = "80dp"
            android:layout_height = "wrap_content"
            android:text="&gt;"
            android:layout_alignParentRight = "true"/>
    </RelativeLayout>
</RelativeLayout>

How to update one file in a zip archive

I've found the Linux zip file to be cumbersome for replacing a single file in a zip. The jar utility from the Java Development Kit may be easier. Consider the common task of updating WEB/web.xml in a JAR file (which is just a zip file):

jar -uf path/to/myapp.jar -C path/to/dir WEB-INF/web.xml

Here, path/to/dir is the path to a directory containing the WEB-INF directory (which in turn contains web.xml).

Mockito - difference between doReturn() and when()

The latter alternative is used for methods on mocks that return void.

Please have a look, for example, here: How to make mock to void methods with mockito

How to set corner radius of imageView?

import UIKit

class BorderImage: UIImageView {

    override func awakeFromNib() {
        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 10.0
        layer.masksToBounds = true
    }
}

Based on @DCDC's answer

How to get folder path from file path with CMD

In case the accepted answer by Wadih didn't work for you, try echo %CD%

How can I color Python logging output?

Install the colorlog package, you can use colors in your log messages immediately:

  • Obtain a logger instance, exactly as you would normally do.
  • Set the logging level. You can also use the constants like DEBUG and INFO from the logging module directly.
  • Set the message formatter to be the ColoredFormatter provided by the colorlog library.
import colorlog

logger = colorlog.getLogger()
logger.setLevel(colorlog.colorlog.logging.DEBUG)

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter())
logger.addHandler(handler)

logger.debug("Debug message")
logger.info("Information message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")

output: enter image description here


UPDATE: extra info

Just update ColoredFormatter:

handler.setFormatter(colorlog.ColoredFormatter('%(log_color)s [%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S'))

output: enter image description here


Package:

pip install colorlog

output:

Collecting colorlog
  Downloading colorlog-4.6.2-py2.py3-none-any.whl (10.0 kB)
Installing collected packages: colorlog
Successfully installed colorlog-4.6.2

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

Here is the latest correct way that I know of how to check for IE and Edge:

if (/MSIE 10/i.test(navigator.userAgent)) {
   // This is internet explorer 10
   window.alert('isIE10');
}

if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
    // This is internet explorer 9 or 11
    window.location = 'pages/core/ie.htm';
}

if (/Edge\/\d./i.test(navigator.userAgent)){
   // This is Microsoft Edge
   window.alert('Microsoft Edge');
}

Note that you don't need the extra var isIE10 in your code because it does very specific checks now.

Also check out this page for the latest IE and Edge user agent strings because this answer may become outdated at some point: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx

How to find sum of multiple columns in a table in SQL Server 2005?

Try this:

select sum(num_tax_amount+num_total_amount) from table_name;

Display QImage with QtGui

One common way is to add the image to a QLabel widget using QLabel::setPixmap(), and then display the QLabel as you would any other widget. Example:

#include <QtGui>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  QPixmap pm("your-image.jpg");
  QLabel lbl;
  lbl.setPixmap(pm);
  lbl.show();
  return app.exec();
}

How do I rotate the Android emulator display?

Press Ctrl + F10 to rotate the emulator screen.

How can I directly view blobs in MySQL Workbench

select CONVERT((column_name) USING utf8) FROM table;

In my case, Workbench does not work. so i used the above solution to show blob data as text.

Make elasticsearch only return certain fields?

For example, you have a doc with three fields:

PUT movie/_doc/1
{
  "name":"The Lion King",
  "language":"English",
  "score":"9.3"
}

If you want to return name and score you can use the following command:

GET movie/_doc/1?_source_includes=name,score

If you want to get some fields which match a pattern:

GET movie/_doc/1?_source_includes=*re

Maybe exclude some fields:

GET movie/_doc/1?_source_excludes=score

Android: Bitmaps loaded from gallery are rotated in ImageView

This is a full solution (found in the Hackbook example from the Facebook SDK). It has the advantage of not needing access to the file itself. This is extremely useful if you are loading an image from the content resolver thingy (e.g. if your app is responding to a share-photo intent).

public static int getOrientation(Context context, Uri photoUri) {
    /* it's on the external media. */
    Cursor cursor = context.getContentResolver().query(photoUri,
            new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

    if (cursor.getCount() != 1) {
        return -1;
    }

    cursor.moveToFirst();
    return cursor.getInt(0);
}

And then you can get a rotated Bitmap as follows. This code also scales down the image (badly unfortunately) to MAX_IMAGE_DIMENSION. Otherwise you may run out of memory.

public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri) throws IOException {
    InputStream is = context.getContentResolver().openInputStream(photoUri);
    BitmapFactory.Options dbo = new BitmapFactory.Options();
    dbo.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, dbo);
    is.close();

    int rotatedWidth, rotatedHeight;
    int orientation = getOrientation(context, photoUri);

    if (orientation == 90 || orientation == 270) {
        rotatedWidth = dbo.outHeight;
        rotatedHeight = dbo.outWidth;
    } else {
        rotatedWidth = dbo.outWidth;
        rotatedHeight = dbo.outHeight;
    }

    Bitmap srcBitmap;
    is = context.getContentResolver().openInputStream(photoUri);
    if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
        float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
        float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
        float maxRatio = Math.max(widthRatio, heightRatio);

        // Create the bitmap from file
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = (int) maxRatio;
        srcBitmap = BitmapFactory.decodeStream(is, null, options);
    } else {
        srcBitmap = BitmapFactory.decodeStream(is);
    }
    is.close();

    /*
     * if the orientation is not 0 (or -1, which means we don't know), we
     * have to do a rotation.
     */
    if (orientation > 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(orientation);

        srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
                srcBitmap.getHeight(), matrix, true);
    }

    return srcBitmap;
}

How to get UTC value for SYSDATE on Oracle

Usually, I work with DATE columns, not the larger but more precise TIMESTAMP used by some answers.

The following will return the current UTC date as just that -- a DATE.

CAST(sys_extract_utc(SYSTIMESTAMP) AS DATE)

I often store dates like this, usually with the field name ending in _UTC to make it clear for the developer. This allows me to avoid the complexity of time zones until last-minute conversion by the user's client. Oracle can store time zone detail with some data types, but those types require more table space than DATE, and knowledge of the original time zone is not always required.

How to prevent ENTER keypress to submit a web form?

[revision 2012, no inline handler, preserve textarea enter handling]

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

Now you can define a keypress handler on the form:
<form [...] onkeypress="return checkEnter(event)">

document.querySelector('form').onkeypress = checkEnter;

HTML5 image icon to input placeholder

I don't know whether there's a better answer out there as time goes by but this is simple and it works;

input[type='email'] {
  background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
  background-image: none;
}

Style it up to suit.

Displaying splash screen for longer than default seconds

You can create your own view and display it when application starts and hide it with timer. Please avoid delaying app start as its bad idea

How to SELECT WHERE NOT EXIST using LINQ?

from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;

Hope this helps

Is there an equivalent of CSS max-width that works in HTML emails?

This is the solution that worked for me

https://gist.github.com/elidickinson/5525752#gistcomment-1649300, thanks to @philipp-klinz

<table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
    <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20">&nbsp;</td></tr>
     <tr>
        <td style="padding:0px;margin:0px;">&nbsp;</td>
        <td style="padding:0px;margin:0px;" width="560"><!-- max width goes here -->

             <!-- PLACE CONTENT HERE -->

        </td>
        <td style="padding:0px;margin:0px;">&nbsp;</td>
    </tr>
    <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20">&nbsp;</td></tr>
</table>

Android: Getting a file URI from a content URI?

Trying to handle the URI with content:// scheme by calling ContentResolver.query()is not a good solution. On HTC Desire running 4.2.2 you could get NULL as a query result.

Why not to use ContentResolver instead? https://stackoverflow.com/a/29141800/3205334

How to call two methods on button's onclick method in HTML or JavaScript?

  1. Try this:

    <input type="button" onclick="function1();function2();" value="Call2Functions" />
    
  2. Or, call second function at the end of first function:

       function func1(){
         //--- some logic
         func2();
       }
    
       function func2(){
        //--- some logic
       }
    

    ...and call func1() onclick of button:

    <input type="button" onclick="func1();" value="Call2Functions" />
    

Gets byte array from a ByteBuffer in java

This is a simple way to get a byte[], but part of the point of using a ByteBuffer is avoiding having to create a byte[]. Perhaps you can get whatever you wanted to get from the byte[] directly from the ByteBuffer.

Java error: Comparison method violates its general contract

I had the same symptom. For me it turned out that another thread was modifying the compared objects while the sorting was happening in a Stream. To resolve the issue, I mapped the objects to immutable temporary objects, collected the Stream to a temporary Collection and did the sorting on that.

Insert all data of a datagridview to database at once

Please see if below can help you

Class Post_Sales

Public Shared Sub Post_sales()

    Dim ITM_ID As Integer

    Dim SLS_QTY As Integer

    Dim SLS_PRC As Double

    Dim SLS_AMT As Double

    Dim DSPL_RCT As String

    Dim TAX_CODE As Integer


    'Format the current  date and send it to a textbox
    Form1.TextBox6.Text = System.DateTime.Now.ToString((" yyyy-MM-dd"))

    'Open Connection

    Dim con As New SqlConnection("Initial Catalog=Your Database here;Data source=.;Network Library=DBMSSOCN;User ID=sa;Password=")

    con.Open()

    'Insert Records into the database


    For Each rw As DataGridViewRow In Form1.DataGridView1.Rows

        ITM_ID = rw.Cells("Column1").Value
        DSPL_RCT = rw.Cells("Column2").Value
        SLS_QTY = rw.Cells("Column3").Value
        SLS_PRC = rw.Cells("Column4").Value
        SLS_AMT = rw.Cells("Column5").Value
        TAX_CODE = rw.Cells("Column6").Value

        Dim cmd As New SqlCommand("INSERT INTO DAY_PLUSALES (DT,ITM_ID,DSPL_RCT,SLS_QTY,SLS_PRC,SLS_AMT,TAX_CODE) values ('" & Form1.TextBox6.Text & "','" & ITM_ID & "','" & DSPL_RCT & "','" & SLS_QTY & "','" & SLS_PRC & "','" & SLS_AMT & "','" & TAX_CODE & "')", con)

        cmd.ExecuteNonQuery()

    Next

    con.Close()

    MessageBox.Show("Records Added to the SQL Database successfully!", "Records Updated ")

End Sub

End Class

What is the purpose of a self executing function in javascript?

I can't believe none of the answers mention implied globals.

The (function(){})() construct does not protect against implied globals, which to me is the bigger concern, see http://yuiblog.com/blog/2006/06/01/global-domination/

Basically the function block makes sure all the dependent "global vars" you defined are confined to your program, it does not protect you against defining implicit globals. JSHint or the like can provide recommendations on how to defend against this behavior.

The more concise var App = {} syntax provides a similar level of protection, and may be wrapped in the function block when on 'public' pages. (see Ember.js or SproutCore for real world examples of libraries that use this construct)

As far as private properties go, they are kind of overrated unless you are creating a public framework or library, but if you need to implement them, Douglas Crockford has some good ideas.

Using a custom typeface in Android

I did this in a more "brute force" way that doesn't require changes to the layout xml or Activities.

Tested on Android version 2.1 through 4.4. Run this at app startup, in your Application class:

private void setDefaultFont() {

    try {
        final Typeface bold = Typeface.createFromAsset(getAssets(), DEFAULT_BOLD_FONT_FILENAME);
        final Typeface italic = Typeface.createFromAsset(getAssets(), DEFAULT_ITALIC_FONT_FILENAME);
        final Typeface boldItalic = Typeface.createFromAsset(getAssets(), DEFAULT_BOLD_ITALIC_FONT_FILENAME);
        final Typeface regular = Typeface.createFromAsset(getAssets(),DEFAULT_NORMAL_FONT_FILENAME);

        Field DEFAULT = Typeface.class.getDeclaredField("DEFAULT");
        DEFAULT.setAccessible(true);
        DEFAULT.set(null, regular);

        Field DEFAULT_BOLD = Typeface.class.getDeclaredField("DEFAULT_BOLD");
        DEFAULT_BOLD.setAccessible(true);
        DEFAULT_BOLD.set(null, bold);

        Field sDefaults = Typeface.class.getDeclaredField("sDefaults");
        sDefaults.setAccessible(true);
        sDefaults.set(null, new Typeface[]{
                regular, bold, italic, boldItalic
        });

    } catch (NoSuchFieldException e) {
        logFontError(e);
    } catch (IllegalAccessException e) {
        logFontError(e);
    } catch (Throwable e) {
        //cannot crash app if there is a failure with overriding the default font!
        logFontError(e);
    }
}

For a more complete example, see http://github.com/perchrh/FontOverrideExample

SQL Order By Count

SELECT group, COUNT(*) FROM table GROUP BY group ORDER BY group

or to order by the count

SELECT group, COUNT(*) AS count FROM table GROUP BY group ORDER BY count DESC

Align image in center and middle within div

This can also be done using the Flexbox layout:

STATIC SIZE

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    height: 300px; /* Or whatever */_x000D_
    background-color: #000;_x000D_
}_x000D_
_x000D_
.child {_x000D_
    width: 100px;  /* Or whatever */_x000D_
    height: 100px; /* Or whatever */_x000D_
    margin: auto;  /* Magic! */_x000D_
}
_x000D_
<div class="parent">_x000D_
    <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

DYNAMIC SIZE

_x000D_
_x000D_
html, body {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  background-color: #999;_x000D_
}_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  margin: auto;_x000D_
  background-color: #000;_x000D_
  display: flex;_x000D_
  height: 80%;_x000D_
  width: 80%;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  margin: auto;  /* Magic! */_x000D_
  max-width: 100%;_x000D_
  max-height: 100%;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I found the example in this article, which does a great job explaining the how to use layout.

Generate Java class from JSON?

I had the same problem so i decided to start writing a small tool to help me with this. Im gonna share andopen source it.

https://github.com/BrunoAlexandreMendesMartins/CleverModels

It supports, JAVA, C# & Objective-c from JSON .

Feel free to contribute!

CentOS 64 bit bad ELF interpreter

You can also install OpenJDK 32-bit (.i686) instead. According to my test, it will be installed and works without problems.

sudo yum install java-1.8.0-openjdk.i686

Note:

The java-1.8.0-openjdk package contains just the Java Runtime Environment. If you want to develop Java programs then install the java-1.8.0-openjdk-devel package.

See here for more details.

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

Make sure that you have valid cacerts in the JRE/security, otherwise you will not bypass the invalid empty trustAnchors error.

In my Amazon EC2 Opensuse12 installation, the problem was that the file pointed by the cacerts in the JRE security directory was invalid:

$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)

$ ls -l /var/lib/ca-certificates/
-rw-r--r-- 1 root    363 Feb 28 14:17 ca-bundle.pem

$ ls -l /usr/lib64/jvm/jre/lib/security/
lrwxrwxrwx 1 root    37 Mar 21 00:16 cacerts -> /var/lib/ca-certificates/java-cacerts
-rw-r--r-- 1 root  2254 Jan 18 16:50 java.policy
-rw-r--r-- 1 root 15374 Jan 18 16:50 java.security
-rw-r--r-- 1 root    88 Jan 18 17:34 nss.cfg

So I solved installing an old Opensuse 11 valid certificates. (sorry about that!!)

$ ll
total 616
-rw-r--r-- 1 root 220065 Jan 31 15:48 ca-bundle.pem
-rw-r--r-- 1 root    363 Feb 28 14:17 ca-bundle.pem.old
-rw-r--r-- 1 root 161555 Jan 31 15:48 java-cacerts

I understood that you could use the keytool to generate a new one (http://mail.openjdk.java.net/pipermail/distro-pkg-dev/2010-April/008961.html). I'll probably have to that soon.

regards lellis

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

What’s the best way to load a JSONObject from a json text file?

With java 8 you can try this:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}

Python exit commands - why so many and when should each be used?

Different Means of Exiting

os._exit():

  • Exit the process without calling the cleanup handlers.

exit(0):

  • a clean exit without any errors / problems.

exit(1):

  • There was some issue / error / problem and that is why the program is exiting.

sys.exit():

  • When the system and python shuts down; it means less memory is being used after the program is run.

quit():

  • Closes the python file.

Summary

Basically they all do the same thing, however, it also depends on what you are doing it for.

I don't think you left anything out and I would recommend getting used to quit() or exit().

You would use sys.exit() and os._exit() mainly if you are using big files or are using python to control terminal.

Otherwise mainly use exit() or quit().

pop/remove items out of a python tuple

As DSM mentions, tuple's are immutable, but even for lists, a more elegant solution is to use filter:

tupleX = filter(str.isdigit, tupleX)

or, if condition is not a function, use a comprehension:

tupleX = [x for x in tupleX if x > 5]

if you really need tupleX to be a tuple, use a generator expression and pass that to tuple:

tupleX = tuple(x for x in tupleX if condition)

PowerShell The term is not recognized as cmdlet function script file or operable program

You first have to 'dot' source the script, so for you :

. .\Get-NetworkStatistics.ps1

The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted or set-ExecutionPolicy AllSigned see(the Execution Policy instructions).

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

What is python's site-packages directory?

When you use --user option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.

The location of user's packages folder can be found using:

python -m site --user-site

This will print something like:

C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages

When you don't use --user option with pip, the package gets installed in global folder given by:

python -c "import site; print(site.getsitepackages())"

This will print something like:

['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'

Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.

How to scroll to top of a div using jQuery?

This is my solution to scroll to the top on a button click.

$(".btn").click(function () {
if ($(this).text() == "Show options") {
$(".tabs").animate(
  {
    scrollTop: $(window).scrollTop(0)
  },
  "slow"
 );
 }
});

How to print SQL statement in codeigniter model

I'm using xdebug for watch this values in VSCode with the respective extension and CI v2.x. I add the expresion $this->db->last_query() in the watch section, and I add xdebugSettings node like these lines for get non truncate value in the launch.json.

{
  "name": "Launch currently open script",
  "type": "php",
  "request": "launch",
  "program": "${file}",
  "cwd": "${fileDirname}",
  "port": 9000,
  "xdebugSettings": {
    "max_data": -1,
    "max_children": -1
  }
},

And run my debuger with the breakpoint and finally just select my expresion and do click right > copy value.

How do I return clean JSON from a WCF Service?

This is accomplished in web.config for your webservice. Set the bindingBehavior to <webHttp> and you will see the clean JSON. The extra "[d]" is set by the default behavior which you need to overwrite.

See in addition this blogpost: http://blog.clauskonrad.net/2010/11/how-to-expose-json-endpoint-from-wcf.html

Rails.env vs RAILS_ENV

Update: in Rails 3.0.9: env method defined in railties/lib/rails.rb

How to do if-else in Thymeleaf?

<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

enter image description here

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

When calling a function that is declared with throws in Swift, you must annotate the function call site with try or try!. For example, given a throwing function:

func willOnlyThrowIfTrue(value: Bool) throws {
  if value { throw someError }
}

this function can be called like:

func foo(value: Bool) throws {
  try willOnlyThrowIfTrue(value)
}

Here we annotate the call with try, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws, because this function could throw an exception (i.e., when willOnlyThrowIfTrue() throws, then foo will automatically rethrow the exception upwards.

If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!.

func bar() {
  try! willOnlyThrowIfTrue(false)
}

This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.

try! is enforced at runtime: if you use try! and the function does end up throwing, then your program's execution will be terminated with a runtime error.

Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()), or sometimes via defered code.

func baz(value: Bool) throws {

  var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
  var data = NSData(contentsOfFile:filePath)

  try willOnlyThrowIfTrue(value)

  // data and filePath automatically cleaned up, even when an exception occurs.
}

If for whatever reason you have clean up code that needs to run but isn't in a deinit() function, you can use defer.

func qux(value: Bool) throws {
  defer {
    print("this code runs when the function exits, even when it exits by an exception")
  }

  try willOnlyThrowIfTrue(value)
}

Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit() or defer. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.

Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.

Handling exceptions is done via catch statements.

func quux(value: Bool) {
  do {
    try willOnlyThrowIfTrue(value)
  } catch {
    // handle error
  }
}

You can have multiple catch statements, each catching a different kind of exception.

  do {
    try someFunctionThatThowsDifferentExceptions()
  } catch MyErrorType.errorA {
    // handle errorA
  } catch MyErrorType.errorB {
    // handle errorB
  } catch {
    // handle other errors
  }

For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.

For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).

How can I convince IE to simply display application/json rather than offer to download it?

I found the answer.

You can configure IE8 to display application/json in the browser window by updating the registry. There's no need for an external tool. I haven't tested this broadly, but it works with IE8 on Vista.

To use this, remember, all the usual caveats about updating the registry apply. Stop IE. Then, cut and paste the following into a file, by the name of json-ie.reg.

Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.  
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;  

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

Then double-click the .reg file. Restart IE. The new behavior you get when tickling a URL that returns a doc with Content-Type: application/json or Content-Type: text/json is like this:

alt text

What it does, why it works:

The 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" action. Basically this registry entry is telling IE that for docs that have a mime type of application/json, just view it in place. This won't affect any application/json documents downloaded via <script> tags, or via XHR, and so on.

The CLSID and Encoding keys get the same values used for image/gif, image/jpeg, and text/html.

This hint came from this site, and from Microsoft's article Handling MIME Types in Internet Explorer .


In FF, you don't need an external add-on either. You can just use the view-source: pseudo-protocol. Enter a URL like this into the address bar:

view-source:http://myserver/MyUrl/That/emits/Application/json

This pseudo-protocol used to be supported in IE, also, until WinXP-sp2, when Microsoft disabled it for security reasons.

How to write Unicode characters to the console?

I found some elegant solution on MSDN

System.Console.Write('\uXXXX') //XXXX is hex Unicode for character

This simple program writes ? right on the screen.

using System;

public class Test
{
    public static void Main()
    {
        Console.Write('\u2103'); //? character code
    }
}

How to read first N lines of a file?

Starting at Python 2.6, you can take advantage of more sophisticated functions in the IO base clase. So the top rated answer above can be rewritten as:

    with open("datafile") as myfile:
       head = myfile.readlines(N)
    print head

(You don't have to worry about your file having less than N lines since no StopIteration exception is thrown.)

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

Determining the current foreground application from a background task or service

This worked for me. But it gives only the main menu name. That is if user has opened Settings --> Bluetooth --> Device Name screen, RunningAppProcessInfo calls it as just Settings. Not able to drill down furthur

ActivityManager activityManager = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
                PackageManager pm = context.getPackageManager();
                List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
                for(RunningAppProcessInfo appProcess : appProcesses) {              
                    if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(appProcess.processName, PackageManager.GET_META_DATA));
                        Log.i("Foreground App", "package: " + appProcess.processName + " App: " + c.toString());
                    }               
                }

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

How to remove underline from a name on hover

Remove the text decoration for the anchor tag

<a name="Section 1" style="text-decoration : none">Section</a>

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

  1. PM>Uninstall-Package EntityFramework -Force
  2. PM>Iinstall-Package EntityFramework -Pre -Version 6.0.0

I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.

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

Using a temp directory is fine, but this will work if you want to avoid that step. From the root of your working directory:

$ rm -fr .git
$ git init
$ git remote add origin your-git-url
$ git fetch
$ git reset --mixed origin/master

PHPMailer character encoding issues

To avoid problems of character encoding in sending emails using the class PHPMailer we can configure it to send it with UTF-8 character encoding using the "CharSet" parameter, as we can see in the following Php code:

$mail = new PHPMailer();
$mail->From = '[email protected]';
$mail->FromName = 'Mi nombre';
$mail->AddAddress('[email protected]');
$mail->Subject = 'Prueba';
$mail->Body = '';
$mail->IsHTML(true);


// Active condition utf-8
$mail->CharSet = 'UTF-8';


// Send mail
$mail->Send();

pthread function from a class

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

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

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

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

Try this only if you are ok with uninstalling python.

I uninstalled python using

brew uninstall python

then later installed using

brew install python

then it worked!

Error message "No exports were found that match the constraint contract name"

I had the same problem upon launching Visual Studio 2013 Ultimate, and the solutions here didn't work for me. I tried deleting the mentioned folders and starting Visual Studio again, but it didn't work.

However I had other problems too, like Microsoft.visual studio package did not load correctly and also Page '312e8a59-2712-48a1-863e-0ef4e67961fc' not found VS 2012. The latter refers to a message in the Team Explorer window saying "Page 'somenumber' cannot be found".

So I run devenv /setup on the Visual Studio command prompt with administrative rights. It did the job, and everything is fine now.

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

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

struct arg_struct
{
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
{
   struct arg_struct *args = arguments;
   printf("Thread\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   pthread_exit(NULL);
   return NULL;
}

int main()
{
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("Before\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   printf("\n");


   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
   {
      printf("Uh-oh!\n");
      return -1;
   }

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

Project Links do not work on Wamp Server

How To Fix The Broken Icon Links (blank.gif, text.gif, etc.)

Unfortunately as previously mentioned, simply adding a virtual host to your project doesn't fix the broken icon links.

The Problem:

WAMP/Apache does not change the directory reference for the icons to your respective installation directory. It is statically set to "c:/Apache24/icons" and 99.9% of users Apache installation does not reside here. Especially with WAMP.

The Fix:

  1. Find your Apache icons directory! Typically it will be located here: "c:/wamp/bin/apache/apache2.4.9/icons". However your mileage may vary depending on your installation and if your Apache version is different, then your path will be different as well.\

  2. Open up httpd-autoindex.conf in your favorite editor. This file can usually be found here: "C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-autoindex.conf". Again, if your Apache version is different, then so will this path.

  3. Find this definition (usually located near the top of the file):

    Alias /icons/ "c:/Apache24/icons/"
    
    <Directory "c:/Apache24/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
    </Directory>
    
  4. Replace the "c:/Apache24/icons/" directories with your own. IMPORTANT You MUST have a trailing forward slash in the first directory reference. The second directory reference must have no trailing slash. Your results should look similar to this. Again, your directory may differ:

    Alias /icons/ "c:/wamp/bin/apache/apache2.4.9/icons/"
    
    <Directory "c:/wamp/bin/apache/apache2.4.9/icons">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
    </Directory>
    
  5. Restart your Apache server and enjoy your cool icons!

Convert timedelta to total seconds

More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):

from datetime import datetime
        
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
    
time2 = datetime.strftime('19 01 2021', '%d %m %Y')

difference = time2 - time1

difference_in_seconds = difference.total_seconds()

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

Try this

<html>
    <head>
        <script type="text/javascript">
        function runProgram()
        {
            var shell = new ActiveXObject("WScript.Shell");                 
            var appWinMerge = "\"C:\\Program Files\\WinMerge\\WinMergeU.exe\" /e /s /u /wl /wr /maximize";
            var fileLeft = "\"D:\\Path\\to\\your\\file\"";
            var fileRight= "\"D:\\Path\\to\\your\\file2\"";
            shell.Run(appWinMerge + " " + fileLeft + " " + fileRight);
        }
        </script>
    </head>

    <body>
        <a href="javascript:runProgram()">Run program</a>
    </body>
</html>

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

How to get the directory of the currently running file?

Gustavo Niemeyer's answer is great. But in Windows, runtime proc is mostly in another dir, like this:

"C:\Users\XXX\AppData\Local\Temp"

If you use relative file path, like "/config/api.yaml", this will use your project path where your code exists.

Best practice for using assert?

The four purposes of assert

Assume you work on 200,000 lines of code with four colleagues Alice, Bernd, Carl, and Daphne. They call your code, you call their code.

Then assert has four roles:

  1. Inform Alice, Bernd, Carl, and Daphne what your code expects.
    Assume you have a method that processes a list of tuples and the program logic can break if those tuples are not immutable:

    def mymethod(listOfTuples):
        assert(all(type(tp)==tuple for tp in listOfTuples))
    

    This is more trustworthy than equivalent information in the documentation and much easier to maintain.

  2. Inform the computer what your code expects.
    assert enforces proper behavior from the callers of your code. If your code calls Alices's and Bernd's code calls yours, then without the assert, if the program crashes in Alices code, Bernd might assume it was Alice's fault, Alice investigates and might assume it was your fault, you investigate and tell Bernd it was in fact his. Lots of work lost.
    With asserts, whoever gets a call wrong, they will quickly be able to see it was their fault, not yours. Alice, Bernd, and you all benefit. Saves immense amounts of time.

  3. Inform the readers of your code (including yourself) what your code has achieved at some point.
    Assume you have a list of entries and each of them can be clean (which is good) or it can be smorsh, trale, gullup, or twinkled (which are all not acceptable). If it's smorsh it must be unsmorshed; if it's trale it must be baludoed; if it's gullup it must be trotted (and then possibly paced, too); if it's twinkled it must be twinkled again except on Thursdays. You get the idea: It's complicated stuff. But the end result is (or ought to be) that all entries are clean. The Right Thing(TM) to do is to summarize the effect of your cleaning loop as

    assert(all(entry.isClean() for entry in mylist))
    

    This statements saves a headache for everybody trying to understand what exactly it is that the wonderful loop is achieving. And the most frequent of these people will likely be yourself.

  4. Inform the computer what your code has achieved at some point.
    Should you ever forget to pace an entry needing it after trotting, the assert will save your day and avoid that your code breaks dear Daphne's much later.

In my mind, assert's two purposes of documentation (1 and 3) and safeguard (2 and 4) are equally valuable.
Informing the people may even be more valuable than informing the computer because it can prevent the very mistakes the assert aims to catch (in case 1) and plenty of subsequent mistakes in any case.

Return Bit Value as 1/0 and NOT True/False in SQL Server

Modify your query to generate the output that you want.

Try casting them to int:

select cast(bitFlag as int)

Or, if you like, use case:

select (case when bitFlag = 0 then 0 else 1 end)

Connecting to TCP Socket from browser using javascript

In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):

  1. Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.

  2. Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.

It should work like this

  1. The Bridge will open a WS connection to the web app (because a server can't connect to a client).
  2. The Web app will ask the client to identify itself
  3. The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
    1. The browser-viewable page connects to the WS server using JS.
    2. Repeat step 3, but for the JS-based page
    3. The JS-based page sends a command to the server, including to which bridge it must go.
    4. The server forwards the command to the bridge.
    5. The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
    6. The Bridge sends a response to the server through the WS
    7. The WS forwards the response to the browser-viewable page
    8. The JS processes the response and reacts accordingly
    9. Repeat until either client disconnects/unloads

Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.

Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.

See full command of running/stopped container in Docker

Use runlike from git repository https://github.com/lavie/runlike

To install runlike

pip install runlike

As it accept container id as an argument so to extract container id use following command

docker ps -a -q

You are good to use runlike to extract complete docker run command with following command

runlike <docker container ID>

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

mysql count group by having

What about:

SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a

PHP strtotime +1 month adding an extra month

It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.

This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.

If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.

For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.

JS. How to replace html element with another element/text, represented in string?

Because you are talking about your replacement being anything, and also replacing in the middle of an element's children, it becomes more tricky than just inserting a singular element, or directly removing and appending:

function replaceTargetWith( targetID, html ){
  /// find our target
  var i, tmp, elm, last, target = document.getElementById(targetID);
  /// create a temporary div or tr (to support tds)
  tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'));
  /// fill that div with our html, this generates our children
  tmp.innerHTML = html;
  /// step through the temporary div's children and insertBefore our target
  i = tmp.childNodes.length;
  /// the insertBefore method was more complicated than I first thought so I 
  /// have improved it. Have to be careful when dealing with child lists as  
  /// they are counted as live lists and so will update as and when you make
  /// changes. This is why it is best to work backwards when moving children 
  /// around, and why I'm assigning the elements I'm working with to `elm` 
  /// and `last`
  last = target;
  while(i--){
    target.parentNode.insertBefore((elm = tmp.childNodes[i]), last);
    last = elm;
  }
  /// remove the target.
  target.parentNode.removeChild(target);
}

example usage:

replaceTargetWith( 'idTABLE', 'I <b>can</b> be <div>anything</div>' );

demo:

By using the .innerHTML of our temporary div this will generate the TextNodes and Elements we need to insert without any hard work. But rather than insert the temporary div itself -- this would give us mark up that we don't want -- we can just scan and insert it's children.

...either that or look to using jQuery and it's replaceWith method.

jQuery('#idTABLE').replaceWith('<blink>Why this tag??</blink>');


update 2012/11/15

As a response to EL 2002's comment above:

It not always possible. For example, when createElement('div') and set its innerHTML as <td>123</td>, this div becomes <div>123</div> (js throws away inappropriate td tag)

The above problem obviously negates my solution as well - I have updated my code above accordingly (at least for the td issue). However for certain HTML this will occur no matter what you do. All user agents interpret HTML via their own parsing rules, but nearly all of them will attempt to auto-correct bad HTML. The only way to achieve exactly what you are talking about (in some of your examples) is to take the HTML out of the DOM entirely, and manipulate it as a string. This will be the only way to achieve a markup string with the following (jQuery will not get around this issue either):

<table><tr>123 text<td>END</td></tr></table>

If you then take this string an inject it into the DOM, depending on the browser you will get the following:

123 text<table><tr><td>END</td></tr></table>

<table><tr><td>END</td></tr></table>

The only question that remains is why you would want to achieve broken HTML in the first place? :)

Using import fs from 'fs'

If we are using TypeScript, we can update the type definition file by running the command npm install @types/node from the terminal or command prompt.

System has not been booted with systemd as init system (PID 1). Can't operate

I had this problem running WSL 2

the solution was the command

 $ sudo dockerd

if after that you still have a problem with permission, run the command:

 $ sudo usermod -aG docker your-user

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

How to use WinForms progress bar?

I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.

Look at BackgroundWorker.ReportProgress() to see how to report progress back to the UI thread.

For example:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var backgroundWorker = sender as BackgroundWorker;
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);
        backgroundWorker.ReportProgress((j * 100) / 100000);
    }
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // TODO: do something with final calculation.
}

md-table - How to update the column width

When Material creates the table it automagically applies two class-names for you which you can use to style each column. In the the example below the styles is named mat-column-userId and cdk-column-userId.

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

Now you can use those names in css:

.mat-column-userId {
  flex: 0 0 100px;
}

Similar to Rahul Patil's answer, but you don't need to add another class to your column definitions.

map function for objects (instead of arrays)

You can convert an object to array simply by using the following:

You can convert the object values to an array:

_x000D_
_x000D_
myObject = { 'a': 1, 'b': 2, 'c': 3 };

let valuesArray = Object.values(myObject);

console.log(valuesArray);
_x000D_
_x000D_
_x000D_

You can convert the object keys to an array:

_x000D_
_x000D_
myObject = { 'a': 1, 'b': 2, 'c': 3 };

let keysArray = Object.keys(myObject);

console.log(keysArray);
_x000D_
_x000D_
_x000D_

Now you can perform normal array operations, including the 'map' function

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

_x000D_
_x000D_
<h1 style="display:inline-block;text-align: center;background : red;">The Last Will and Testament of Eric Jones</h1>
_x000D_
_x000D_
_x000D_

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

JQUERY: Uncaught Error: Syntax error, unrecognized expression

If you're using jQuery 2.1.4 or above, try this:

$("#" + this.d);

Or, you can define var before using it. It makes your code simpler.

var d = this.d
$("#" + d);

Laravel 5 route not defined, while it is?

when you execute the command

php artisan route:list

You will see all your registered routes in there in table format . Well there you see many columns like Method , URI , Name , Action .. etc.

So basically if you are using route() method that means it will accept only name column values and if you want to use URI column values you should go with url() method of laravel.

Cloning specific branch

To clone a particular branch in a git repository

- Command: git clone "repository_url" -b "branch_name"
- Example: git clone https://gitlab.com/amm.kazi/yusufoverseas.git -b routes

How to enter a multi-line command

I assume you're talking about on the command-line - if it's in a script, then a new-line acts as a command delimiter.

On the command line, use a semi-colon ';'

How do I access Configuration in any class in ASP.NET Core?

I know there may be several ways to do this, I'm using Core 3.1 and was looking for the optimal/cleaner option and I ended up doing this:

  1. My startup class is as default
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
}
  1. My appsettings.json is like this
{
  "CompanySettings": {
    "name": "Fake Co"
  }
}

  1. My class is an API Controller, so first I added the using reference and then injected the IConfiguration interface
using Microsoft.Extensions.Configuration;

public class EmployeeController 
{
    private IConfiguration _configuration;
    public EmployeeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}
  1. Finally I used the GetValue method
public async Task<IActionResult> Post([FromBody] EmployeeModel form)
{
    var companyName = configuration.GetValue<string>("CompanySettings:name");
    // companyName = "Fake Co"
}

Protect image download

As some people already said that it is not possible to prevent people to download your pictures, a trick could be something like this:

$(document).ready(function()
{
    $('img').bind('contextmenu', function(e){
        return false;
    }); 
});

This trick prevents from the right click on all img. Obviously people can open the source code and download the images using links in your source code.

How to append contents of multiple files into one file

You need the cat (short for concatenate) command, with shell redirection (>) into your output file

cat 1.txt 2.txt 3.txt > 0.txt

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

Could not load file or assembly ... The parameter is incorrect

I Had the similar issue while opening Nuget Packet manager, I removed all the temp files and build the project, it worked fine.

How to set <iframe src="..."> without causing `unsafe value` exception?

Congratulation ! ¨^^ I have an easy & efficient solution for you, yes!

<iframe width="100%" height="300" [attr.src]="video.url"></iframe

[attr.src] instead of src "video.url" and not {{video.url}}

Great ;)

Maximum call stack size exceeded error

I was facing same issue I have resolved it by removing a field name which was used twice on ajax e.g

    jQuery.ajax({
    url : '/search-result',
    data : {
      searchField : searchField,
      searchFieldValue : searchField,
      nid    :  nid,
      indexName : indexName,
      indexType : indexType
    },
.....

Spring - applicationContext.xml cannot be opened because it does not exist

enter image description here

I was struggling since a couple of hours for this issue because i was putting that file under resources folder but it didn't help me, finally i realized my mistake. Put it directly under src/main/java.

How comment a JSP expression?

Pure JSP comments look like this:

<%-- Comment --%>

So if you want to retain the "=".you could do something like:

<%--= map.size() --%>

The key thing is that <%= defines the beginning of an expression, in which you can't leave the body empty, but you could do something like this instead if the pure JSP comment doesn't appeal to you:

<% /*= map.size()*/ %>

Code Conventions for the JavaServer Pages Technology Version 1.x Language has details about the different commenting options available to you (but has a complete lack of link targets, so I can't link you directly to the relevant section - boo!)

Trust Anchor not found for Android SSL Connection

The Trust anchor error can happen for a lot of reasons. For me it was simply that I was trying to access https://example.com/ instead of https://www.example.com/.

So you might want to double-check your URLs before starting to build your own Trust Manager (like I did).

React Hooks useState() with Object

If anyone is searching for useState() hooks update for object

- Through Input

        const [state, setState] = useState({ fName: "", lName: "" });
        const handleChange = e => {
            const { name, value } = e.target;
            setState(prevState => ({
                ...prevState,
                [name]: value
            }));
        };

        <input
            value={state.fName}
            type="text"
            onChange={handleChange}
            name="fName"
        />
        <input
            value={state.lName}
            type="text"
            onChange={handleChange}
            name="lName"
        />
   ***************************

 - Through onSubmit or button click
    
        setState(prevState => ({
            ...prevState,
            fName: 'your updated value here'
         }));

Display HTML snippets in HTML

Deprecated, but works in FF3 and IE8.

<xmp>
   <b>bold</b><ul><li>list item</li></ul>
</xmp>

Recommended:

<pre><code>
    code here, escape it yourself.
</code></pre>

How to serialize a JObject without the formatting?

you can use JsonConvert.SerializeObject()

JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method

JsonConvert.SerializeObject()

JObject.Parse()

How to submit a form using PhantomJS

Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS

// Example using HTTP POST operation

var page = require('webpage').create(),
    server = 'http://posttestserver.com/post.php?dump',
    data = 'universe=expanding&answer=42';

page.open(server, 'post', data, function (status) {
    if (status !== 'success') {
        console.log('Unable to post!');
    } else {
        console.log(page.content);
    }
    phantom.exit();
});

Finding an element in an array in Java

With Java 8, you can do this:

int[] haystack = {1, 2, 3};
int needle = 3;

boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);

You'd need to do

boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));

if you're working with objects.

In python, what is the difference between random.uniform() and random.random()?

Apart from what is being mentioned above, .uniform() can also be used for generating multiple random numbers that too with the desired shape which is not possible with .random()

np.random.seed(99)
np.random.random()

#generates 0.6722785586307918

while the following code

np.random.seed(99)
np.random.uniform(0.0, 1.0, size = (5,2))

#generates this 
array([[0.67227856, 0.4880784 ],
       [0.82549517, 0.03144639],
       [0.80804996, 0.56561742],
       [0.2976225 , 0.04669572],
       [0.9906274 , 0.00682573]])

This can't be done with random(...), and if you're generating the random(...) numbers for ML related things, most of the time, you'll end up using .uniform(...)

Update a dataframe in pandas while iterating row by row

It's better to use lambda functions using df.apply() -

df["ifor"] = df.apply(lambda x: {value} if {condition} else x["ifor"], axis=1)

html button to send email

As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject and body attributes of the mailto: URI when supplied as a <form>'s action.

But here's a working example:

HTML (with Bootstrap styles):

<p><input id="subject" type="text" placeholder="type your subject here" 
    class="form-control"></p>
<p><input id="message" type="text" placeholder="type your message here" 
    class="form-control"></p>
<p><a id="mail-link" class="btn btn-primary">Create email</a></p>

JavaScript (with jQuery):

<script type="text/javascript">
    function loadEvents() {
        var mailString;
        function updateMailString() {
            mailString = '?subject=' + encodeURIComponent($('#subject').val())
                + '&body=' + encodeURIComponent($('#message').val());
            $('#mail-link').attr('href',  'mailto:[email protected]' + mailString);
        }
        $( "#subject" ).focusout(function() { updateMailString(); });
        $( "#message" ).focusout(function() { updateMailString(); });
        updateMailString();
    }
</script>

Notes:

  • The <form> element with associated action attribute is not used.
  • The <input> element of type button is also not used.
    • <a> styled as a button (here using Bootstrap) replaces <input type="button">
    • focusout() with updateMailString() is necessary because the <a> tag's href attribute does not automatically update when the input fields' values change.
    • updateMailString() is also called when document is loaded in case the input fields are prepopulated.
  • Also encodeURIComponent() is used to get characters such as the quotation mark (") across to Outlook.

In this approach, the mailto: URI is supplied (with subject and body attributes) in an a element's href tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:

  • Browsers: Firefox/Win&OSX, Chrome/Win&OSX, IE/Win, Safari/OSX&iOS, Opera/OSX
  • E-mail clients: Outlook/Win, Mail.app/OSX&iOS, Sparrow/OSX

Bonus tip: In my use cases, I add some contextual text to the e-mail body. More often than not, I want that text to contain line breaks. %0D%0A (carriage return and linefeed) works in my tests.

Return different type of data from a method in java?

The class you're looking for already exists. Map.Entry:

public static Entry<Integer,String> myMethod(){
    return new SimpleEntry<>(12, "value");
}

And later:

Entry<Integer,String> valueAndIndex = myMethod();
int index = valueAndIndex.getKey();
String value = valueAndIndex.getValue();

It's just a simple two-field data structure that stores a key and value. If you need to do any special processing, store more than two fields, or have any other fringe case, you should make your own class, but otherwise, Map.Entry is one of the more underutilized Java classes and is perfect for situations like these.

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

I want to use CASE statement to update some records in sql server 2005

If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN in the UPDATE:

declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
 ('AAA','BBB'),
 ('CCC','DDD'),
 ('EEE','FFF')

update ts set LastName = ToName
from dbo.TestStudents ts
       inner join
     @ToDo t
       on
         ts.LastName = t.FromName

How to open adb and use it to send commands


In Windows 10 while installing Android SDK, by default latest SDK gets installed.
Platform List is part of Android SDK and the best way to find the location is to open SDK manager and get the path.
It will be available at:
Android SDK Location: C:\Users\<User Name>\AppData\Local\Android\sdk\platform-tools\
In SDK Manager, SDK path can be found by following the below
Appearance & Behaviour --> System Settings --> Android SDK You can get the path where SDK is installed and can edit the location as well.

How to create a new instance from a class object in Python

Just call the "type" built in using three parameters, like this:

ClassName = type("ClassName", (Base1, Base2,...), classdictionary)

update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.

To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:

instance = ClassObject()

The mechanism for instantiation is thus:

Python does not use the new keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:

Its class' __call__ method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root.

So calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)

class type:
    ...
    def __call__(cls, *args, **kw):
          constructor = getattr(cls, "__new__")
          instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
          instance.__init__(cls, *args, **kw)
          return instance

(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happen "in real life" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally)

What's the difference between commit() and apply() in SharedPreferences

From javadoc:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself

How to create helper file full of functions in react native?

To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

Example:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

Let's create another file which has functions to help you with tables:

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

Now the trick is to have a index.js inside the helpers folder:

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

Now you can import then separately to use each function:

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

Hope it can help to organise your files in a better way.

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

How to replace innerHTML of a div using jQuery?

Here is your answer:

//This is the setter of the innerHTML property in jQuery
$('#regTitle').html('Hello World');

//This is the getter of the innerHTML property in jQuery
var helloWorld = $('#regTitle').html();

How to force garbage collection in Java?

On OracleJDK 10 with G1 GC, a single call to System.gc() will cause GC to clean up the Old Collection. I am not sure if GC runs immediately. However, GC will not clean up the Young Collection even if System.gc() is called many times in a loop. To get GC to clean up the Young Collection, you must allocate in a loop (e.g. new byte[1024]) without calling System.gc(). Calling System.gc() for some reason prevents GC from cleaning up the Young Collection.

A process crashed in windows .. Crash dump location

The location is in the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps

Source: http://msdn.microsoft.com/en-us/library/windows/desktop/bb787181%28v=vs.85%29.aspx

Work with a time span in Javascript

a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat

some formatting examples

/** delta: 1234567890, @locale: 'en-US', @style: 'long' */

/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds

/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890

/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms

/* D,h:m:s.f */
14,06:56:07.890

/* D~, h:m:s.f */
14 days, 06:56:07.890

/* h~ m~ s~ */
342 hours 56 minutes 7 seconds

/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days

/* up D~, h:m */
up 14 days, 06:56

the code & test

_x000D_
_x000D_
/**
    Init locale formatter:
    
        timespan.locale(@locale, @style)
    
    Example:

        timespan.locale('en-US', 'long');
        timespan.locale('es', 'narrow');

    Format time delta:
    
        timespan.format(@pattern, @milliseconds)

        @pattern tokens:
            D: days, h: hours, m: minutes, s: seconds, f: millis

        @pattern token extension:
            h  => '0'-padded value, 
            h# => raw value,
            h~ => locale formatted value

    Example:

        timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
        
        output: 14 days 6 hours 56 minutes 7 seconds 890 millis

    NOTES:

    * milliseconds unit have no locale translation
    * may encounter declension issues for some locales
    * use quoted text for raw inserts
            
*/

const timespan = (() => {
    let rtf, tokensRtf;
    const
    tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
    map = [
        {t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
        {t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
        {t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
        {t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
        {t: [['f', 3], ['f#'], ['f~']], u: 1}
    ],
    locale = (value, style = 'long') => {
        try {
            rtf = new Intl.RelativeTimeFormat(value, {style});
        } catch (e) {
            if (rtf) throw e;
            return;
        }
        const h = rtf.format(1, 'hour').split(' ');
        tokensRtf = new Set(rtf.format(1, 'day').split(' ')
            .filter(t => t != 1 && h.indexOf(t) > -1));
        return true;
    },
    fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
    mapper = {
        number: (t, u) => (u + '').padStart(t.fmt, '0'),
        string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
            .filter(t => !tokensRtf.has(t)).join(' ')
            .trim().replace(/[+-]/g, '') : fallback(t, u),
    },
    replace = (out, t) => out[t] || t.slice(1, t.length - 1),
    format = (pattern, value) => {
        if (typeof pattern !== 'string')
            throw Error('invalid pattern');
        if (!Number.isFinite(value))
            throw Error('invalid value');
        if (!pattern)
            return '';
        const out = {};
        value = Math.abs(value);
        pattern.match(tokens)?.forEach(t => out[t] = null);
        map.forEach(m => {
            let u = null;
            m.t.forEach(t => {
                if (out[t.token] !== null)
                    return;
                if (u === null) {
                    u = Math.floor(value / m.u);
                    value %= m.u;
                }
                out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
            })
        });
        return pattern.replace(tokens, replace.bind(null, out));
    };
    map.forEach(m => m.t = m.t.map(t => ({
        token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
    })));
    locale('en');
    return {format, locale};
})();


/************************** test below *************************/

const
cfg = {
  locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
  style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
  try {
      const tv = new Date(td.value);
      if (isNaN(tv)) throw Error('invalid "datetime2" value');
      timespan.locale(loc.value || locale.value, style.value);
      const delta = fd.getTime() - tv.getTime();
      out.innerHTML = timespan.format(fmt.value, delta);
  } catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
  const elm = el(id);
  value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
_x000D_
_x000D_

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE but you can use UPDATE.

The syntax is as follows:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

how to start stop tomcat server using CMD?

Create a .bat file and write two commands:

cd C:\ Path to your tomcat directory \ bin

startup.bat

Now on double-click, Tomcat server will start.

What is a "slug" in Django?

A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

An example:

<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>

Now let's pretend that we have a Django model such as:

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(max_length=1000)
    slug = models.SlugField(max_length=40)

How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

www.example.com/article/23

Or, you might want to reference the title like this:

www.example.com/article/The 46 Year Old Virgin

Since spaces aren't valid in URLs, they must be replaced by %20, which results in:

www.example.com/article/The%2046%20Year%20Old%20Virgin

Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

www.example.com/article/the-46-year-old-virgin

In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

Also see the URL of this very web page for another example.

How to get the unique ID of an object which overrides hashCode()?

I came up with this solution which works in my case where I have objects created on multiple threads and are serializable:

public abstract class ObjBase implements Serializable
    private static final long serialVersionUID = 1L;
    private static final AtomicLong atomicRefId = new AtomicLong();

    // transient field is not serialized
    private transient long refId;

    // default constructor will be called on base class even during deserialization
    public ObjBase() {
       refId = atomicRefId.incrementAndGet()
    }

    public long getRefId() {
        return refId;
    }
}

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

SecurityError: The operation is insecure - window.history.pushState()

I had this problem on ReactJS history push, turned out i was trying to open //link (with double slashes)

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

I highly recommend CSharpJExcel for reading Excel 97-2003 files (xls) and ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, xlsx).

They both work perfectly. They have absolutely no dependency on anything.

Sample using CSharpJExcel:

Workbook workbook = Workbook.getWorkbook(new System.IO.FileInfo(fileName));
var sheet = workbook.getSheet(0);
...
var content = sheet.getCell(colIndex, rowIndex).getContents();
...
workbook.close();

Sample using ExcelPackage:

using (ExcelPackage xlPackage = new ExcelPackage(existingFile))
{
  // get the first worksheet in the workbook
  ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
  int iCol = 2;  // the column to read

  // output the data in column 2
  for (int iRow = 1; iRow < 6; iRow++)
    Console.WriteLine("Cell({0},{1}).Value={2}", iRow, iCol, 
      worksheet.Cell(iRow, iCol).Value);

  // output the formula in row 6
  Console.WriteLine("Cell({0},{1}).Formula={2}", 6, iCol, 
    worksheet.Cell(6, iCol).Formula);

} // the using statement calls Dispose() which closes the package.

EDIT:

There is another project, ExcelDataReader, that seems to have the ability to handle both formats. It is also easy like the other ones I've mentioned.

There are also other libraries:

iOS 7 - Status bar overlaps the view

To hide status bar in ios7 follow these simple steps :

In Xcode goto "Resources" folder and open "(app name)-Info.plist file".

  • check for "View controller based status bar appearance" key and set its value "NO"
  • check for "Status bar is initially hidden" key and set its value "YES"

If the keys are not there then you can add it by selecting "information property list" at top and click + icon

SQL time difference between two dates result in hh:mm:ss

I came across this post today as I was trying to gather the time difference between fields located in separate tables joined together on a key field. This is the working code for such an endeavor. (tested in sql 2010) Bare in mind that my original query co-joined 6 tables on a common keyfield, in the code below I have removed the other tables as to not cause any confusion for the reader.

The purpose of the query is to calculate the difference between the variables CreatedUTC & BackupUTC, where difference is expressed in days and the field is called 'DaysActive.'

declare @CreatedUTC datetime
declare @BackupUtc datetime


SELECT TOP 500

table02.Column_CreatedUTC AS DeviceCreated,
CAST(DATEDIFF(day, table02.Column_CreatedUTC, table03.Column_EndDateUTC) AS nvarchar(5))+ ' Days' As DaysActive,
table03.Column_EndDateUTC AS LastCompleteBackup

FROM

Operations.table01 AS table01

LEFT OUTER JOIN

    dbo.table02 AS table02
ON
    table02.Column_KeyField = table01.Column_KeyField

LEFT OUTER JOIN 

    dbo.table03 AS table03
ON
    table01.Column_KeyField = table03.Column_KeyField

Where table03.Column_EndDateUTC > dateadd(hour, -24, getutcdate()) --Gathers records with an end date in the last 24 hours
AND table02.[Column_CreatedUTC] = COALESCE(@CreatedUTC, table02.[Column_CreatedUTC])
AND table03.[Column_EndDateUTC] = COALESCE(@BackupUTC, table03.[Column_EndDateUTC])

GROUP BY table03.Column_EndDateUTC, table02.Column_CreatedUTC
ORDER BY table02.Column_CreatedUTC ASC, DaysActive, table03.Column_EndDateUTC DESC

The Output will be as follows:

[DeviceCreated]..[DaysActive]..[LastCompleteBackup]
---------------------------------------------------------
[2/13/12 16:04]..[463 Days]....[5/21/13 12:14]
[2/12/13 22:37]..[97 Days].....[5/20/13 22:10]

MongoDB what are the default user and password?

For MongoDB earlier than 2.6, the command to add a root user is addUser (e.g.)

db.addUser({user:'admin',pwd:'<password>',roles:["root"]})

Parsing JSON giving "unexpected token o" error

Response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o". if you need to get it as string, you could use JSON.stringify()

Remove everything after a certain character

It works for me very nicely:

var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result =  x.substring(0, remove_after);
alert(result);

Python: How exactly can you take a string, split it, reverse it and join it back together again?

>>> tmp = "a,b,cde"
>>> tmp2 = tmp.split(',')
>>> tmp2.reverse()
>>> "".join(tmp2)
'cdeba'

or simpler:

>>> tmp = "a,b,cde"
>>> ''.join(tmp.split(',')[::-1])
'cdeba'

The important parts here are the split function and the join function. To reverse the list you can use reverse(), which reverses the list in place or the slicing syntax [::-1] which returns a new, reversed list.

Launch an app from within another (iPhone)

In Swift

Just in case someone was looking for a quick Swift copy and paste.

if let url = NSURL(string: "app://") where UIApplication.sharedApplication().canOpenURL(url) {
            UIApplication.sharedApplication().openURL(url)
} else if let itunesUrl = NSURL(string: "https://itunes.apple.com/itunes-link-to-app") where UIApplication.sharedApplication().canOpenURL(itunesUrl) {
            UIApplication.sharedApplication().openURL(itunesUrl)      
}

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

numpy get index where value is true

You can use nonzero function. it returns the nonzero indices of the given input.

Easy Way

>>> (e > 15).nonzero()

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

to see the indices more cleaner, use transpose method:

>>> numpy.transpose((e>15).nonzero())

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

Not Bad Way

>>> numpy.nonzero(e > 15)

(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

or the clean way:

>>> numpy.transpose(numpy.nonzero(e > 15))

[[1 6]
 [1 7]
 [1 8]
 [1 9]
 [2 0]
 ...

Database Structure for Tree Data Structure

If you have to use Relational DataBase to organize tree data structure then Postgresql has cool ltree module that provides data type for representing labels of data stored in a hierarchical tree-like structure. You can get the idea from there.(For more information see: http://www.postgresql.org/docs/9.0/static/ltree.html)

In common LDAP is used to organize records in hierarchical structure.

How would I get a cron job to run every 30 minutes?

If your cron job is running on Mac OS X only, you may want to use launchd instead.

From Scheduling Timed Jobs (official Apple docs):

Note: Although it is still supported, cron is not a recommended solution. It has been deprecated in favor of launchd.

You can find additional information (such as the launchd Wikipedia page) with a simple web search.

var functionName = function() {} vs function functionName() {}

I prefer defining function as variable:

let first = function(x){
   return x[0];
}

Instead of:

function first(){
    ....
}

Because i can use expressions and decorators when defining the function. For example:

let safe = function(f){
  try {f()...}
}
let last = safe(function(x){return x[0]}).

Also with ES6 its much shorter:

 let last = x => x[0]
 ...........
 function last(x){
     return x[0];
 }
......

let last = safe(x => x[0]);