Programs & Examples On #Slidingdrawer

SlidingDrawer is an Android View Widget that hides content out of the screen and allows the user to drag a handle to bring the content on screen.

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Whenever such an error occurs. Try to check Following Things

  1. Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.

  2. Check if your activity type which is extended falls under the compat category

example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based

if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()

  1. Check the theme applied to the activity in question in the manifest file

example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work

but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()

Slide a layout up from bottom of screen

Use these animations:

bottom_up.xml

<?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android">
   <translate android:fromYDelta="75%p" android:toYDelta="0%p" 
    android:fillAfter="true"
 android:duration="500"/>
</set>

bottom_down.xml

 <?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android">

<translate android:fromYDelta="0%p" android:toYDelta="100%p" android:fillAfter="true"
            android:interpolator="@android:anim/linear_interpolator"
    android:duration="500" />

</set>

Use this code in your activity for hiding/animating your view:

Animation bottomUp = AnimationUtils.loadAnimation(getContext(),
            R.anim.bottom_up);
ViewGroup hiddenPanel = (ViewGroup)findViewById(R.id.hidden_panel);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);

if else condition in blade file (laravel 5.3)

No curly braces required you can directly write

@if($user->status =='waiting')         
      <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>         
@else
      <td>{{ $user->status }}</td>        
@endif

How to add border around linear layout except at the bottom?

Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.

Here is a quick sample code for you to see how easy it is, but you will find more information on the link.

<com.khandelwal.library.view.BorderFrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:leftBorderColor="#00F0F0"
            app:leftBorderWidth="10dp"
            app:topBorderColor="#F0F000"
            app:topBorderWidth="15dp"
            app:rightBorderColor="#F000F0"
            app:rightBorderWidth="20dp"
            app:bottomBorderColor="#000000"
            app:bottomBorderWidth="25dp" >
    </com.khandelwal.library.view.BorderFrameLayout>

So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.

And no, I'm neither the author of this library nor one of his friend ;-)

How to make a radio button look like a toggle button

_x000D_
_x000D_
$(document).ready(function () {
    $('#divType button').click(function () {
        $(this).addClass('active').siblings().removeClass('active');
        $('#<%= hidType.ClientID%>').val($(this).data('value'));
        //alert($(this).data('value'));             
    });
});
_x000D_
<div class="col-xs-12">
    <div class="form-group">
        <asp:HiddenField ID="hidType" runat="server" />
        <div class="btn-group" role="group" aria-label="Selection type" id="divType">
            <button type="button" class="btn btn-default BtnType" data-value="1">Food</button>                        
            <button type="button" class="btn btn-default BtnType" data-value="2">Drink</button>
        </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How do I apply a diff patch on Windows?

Eclipse should be able to do it, go to TeamSynchronize perspective and then into Project->Apply patch

Send POST data using XMLHttpRequest

Here is a complete solution with application-json:

// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">

// return stops normal action and runs login()
<button onclick="return login()">Submit</button>

<script>
    function login() {
        // Form fields, see IDs above
        const params = {
            email: document.querySelector('#loginEmail').value,
            password: document.querySelector('#loginPassword').value
        }

        const http = new XMLHttpRequest()
        http.open('POST', '/login')
        http.setRequestHeader('Content-type', 'application/json')
        http.send(JSON.stringify(params)) // Make sure to stringify
        http.onload = function() {
            // Do whatever with response
            alert(http.responseText)
        }
    }
</script>

Ensure that your Backend API can parse JSON.

For example, in Express JS:

import bodyParser from 'body-parser'
app.use(bodyParser.json())

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

on command line type journalctl -xe and the results will be

SELinux is preventing /usr/sbin/httpd from name_bind access on the tcp_socket port 83 or 80

This means that the SELinux is running on your machine and you need to disable it. then edit the configuration file by type the following

nano /etc/selinux/config

Then find the line SELINUX=enforce and change to SELINUX=disabled

Then type the following and run the command to start httpd

setenforce 0

Lastly start a server

systemctl start httpd

How do I use Maven through a proxy?

I run cntlm localy, configured with NTLMv2 password hashes to authenticate with the corporate proxy, and use

export MAVEN_OPTS="-DproxyHost=127.0.0.1 -DproxyPort=3128"

to use that proxy from maven. Of course the proxy you use should support cntlm/NTLMv2.

How do I change the background color with JavaScript?

<!DOCTYPE html>
<html>
<body>
<select name="" id="select" onClick="hello();">
    <option>Select</option>
    <option style="background-color: #CD5C5C;">#CD5C5C</option>
    <option style="background-color: #F08080;">#F08080</option>
    <option style="background-color: #FA8072;">#FA8072</option>
    <option style="background-color: #E9967A;">#E9967A</option>
    <option style="background-color: #FFA07A;">#FFA07A</option>
</select>
<script>
function hello(){
let d = document.getElementById("select");
let text = d.options[d.selectedIndex].value;
document.body.style.backgroundColor=text;
}
</script>
</body>
</html>

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

Comparing the contents of two files in Sublime Text

UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation...)

  1. In the Menu bar click on File->Open Folder...
  2. Select a folder (the actual folder does not really matter, this step is just to make the FOLDERS sidebar available)
  3. If there is no Side Bar shown yet, make it appear via View -> Side Bar -> Show Side Bar
  4. Use this FOLDERS-titled Side Bar to navigate to the first file you want to compare.
  5. Select it (click on it), hold down ctrl and select the second file.
  6. Having two files selected, right click on one of the two and select Diff Files...

There should be a new Tab now showing the comparison.


Original short answer:
Note that:

The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

Looks like Users that are added in your Country object, are not already present in the DB. You need to use cascade to make sure that when Country is persisted, all User which are not there in data but are associated with Country also get persisted.

Below code should help:

@ManyToOne (cascade = CascadeType.ALL)
   @JoinColumn (name = "countryId")
   private Country country;

Install Visual Studio 2013 on Windows 7

Visual Studio Express for Windows needs Windows 8.1. Having a look at the requirements page you might want to try the Web or Windows Desktop version which are able to run under Windows 7.

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

Bootstrap >= v4.0 dropped glyphicon support

Dropped the Glyphicons icon font. If you need icons, some options are:

the upstream version of Glyphicons

Octicons

Font Awesome

Source: https://v4-alpha.getbootstrap.com/migration/#components

If you are using Bootstrap >= v4.0 or newer, you can use existing style classes of bootstrap such as text-success,text-warning etc.

For example, if you are using fontawesome:

<i class="fa fa-tag text-danger" aria-hidden="true"></i>

Java swing application, close one window and open another when button is clicked

You can call dispose() on the current window and setVisible(true) on the one you want to display.

CSS to select/style first word

Use the strong element, that is it's purpose:

<div id="content">
    <p><strong>First Word</strong> rest of paragraph.</p>
</div>

Then create a style for it in your style sheet.

#content p strong
{
    font-size: 14pt;
}

Trim leading and trailing spaces from a string in awk

just use a regex as a separator:

', *' - for leading spaces

' *,' - for trailing spaces

for both leading and trailing:

awk -F' *,? *' '{print $1","$2}' input.txt

Importing a function from a class in another file?

You can use the below syntax -

from FolderName.FileName import Classname

How do you migrate an IIS 7 site to another server?

I'd say export your server config in IIS manager:

  1. In IIS manager, click the Server node
  2. Go to Shared Configuration under "Management"
  3. Click “Export Configuration”. (You can use a password if you are sending them across the internet, if you are just gonna move them via a USB key then don't sweat it.)
  4. Move these files to your new server

    administration.config
    applicationHost.config
    configEncKey.key 
    
  5. On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.

  6. It should prompt for the encryption password(if you set it) and reset IIS.

BAM! Go have a beer!

Decorators with parameters?

Great answers above. This one also illustrates @wraps, which takes the doc string and function name from the original function and applies it to the new wrapped version:

from functools import wraps

def decorator_func_with_args(arg1, arg2):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            print("Before orginal function with decorator args:", arg1, arg2)
            result = f(*args, **kwargs)
            print("Ran after the orginal function")
            return result
        return wrapper
    return decorator

@decorator_func_with_args("foo", "bar")
def hello(name):
    """A function which prints a greeting to the name provided.
    """
    print('hello ', name)
    return 42

print("Starting script..")
x = hello('Bob')
print("The value of x is:", x)
print("The wrapped functions docstring is:", hello.__doc__)
print("The wrapped functions name is:", hello.__name__)

Prints:

Starting script..
Before orginal function with decorator args: foo bar
hello  Bob
Ran after the orginal function
The value of x is: 42
The wrapped functions docstring is: A function which prints a greeting to the name provided.
The wrapped functions name is: hello

how to open an URL in Swift3

If you want to open inside the app itself instead of leaving the app you can import SafariServices and work it out.

import UIKit
import SafariServices

let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)

I get conflicting provisioning settings error when I try to archive to submit an iOS app

In my case I had to login to Apple Developer Website and reset the list of devices.

It appears they now require you to do it every year when the subscription is renewed, before being able to add new devices and generate certificates.

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

Process list on Linux via Python

IMO looking at the /proc filesystem is less nasty than hacking the text output of ps.

import os
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]

for pid in pids:
    try:
        print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read().split('\0')
    except IOError: # proc has already terminated
        continue

How to run a single test with Mocha?

Just use .only before 'describe', 'it' or 'context'. I run using "$npm run test:unit", and it executes only units with .only.

describe.only('get success', function() {
 // ...
});

it.only('should return 1', function() {
  // ...
});

How to use mongoose findOne

Use obj[0].nick and you will get desired result,

Get Filename Without Extension in Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

Removing empty lines in Notepad++

  1. Edit >> Blank Operations >> Trim Leading and Trailing Spaces (to remove black tabs and spaces in empty lines)
  2. Ctrl + H to get replace window and replace pattern: ^\r\n with nothing (select regular expression)

Note: step 1 will remove your code intendation done via tabs and blank spaces

Return only string message from Spring MVC 3 Controller

What about:

PrintWriter out = response.getWriter();
out.println("THE_STRING_TO_SEND_AS_RESPONSE");
return null;

This woks for me.

Using a scanner to accept String input and storing in a String Array

Would this work better?

import java.util.Scanner;

public class Work {

public static void main(String[] args){

    System.out.println("Please enter the following information");

    String name = "0";
    String num = "0";
    String address = "0";

    int i = 0;

    Scanner input = new Scanner(System.in);

    //The Arrays
    String [] contactName = new String [7];
    String [] contactNum = new String [7];
    String [] contactAdd = new String [7];

    //I set these as the Array titles
    contactName[0] = "Name";
    contactNum[0] = "Phone Number";
    contactAdd[0] = "Address";

    //This asks for the information and builds an Array for each
    //i -= i resets i back to 0 so the arrays are not 7,14,21+
    while (i < 6){

        i++;
        System.out.println("Enter contact name." + i);
        name = input.nextLine();
        contactName[i] = name;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact number." + i);
        num = input.nextLine();
        contactNum[i] = num;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact address." + i);
        num = input.nextLine();
        contactAdd[i] = num;
    }


    //Now lets print out the Arrays
    i -= i;
    while(i < 6){
    i++;
    System.out.print( i + " " + contactName[i] + " / " );
    }

    //These are set to print the array on one line so println will skip a line
    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
    i++;

    System.out.print( i + " " + contactNum[i] + " / " );
    }

    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
        i++;

    System.out.print( i + " " + contactAdd[i] + " / " );
    }

    System.out.println();

    System.out.println("End of program");

}

}

How to convert CLOB to VARCHAR2 inside oracle pl/sql

This is my aproximation:

  Declare 
  Variableclob Clob;
  Temp_Save Varchar2(32767); //whether it is greater than 4000

  Begin
  Select reportClob Into Temp_Save From Reporte Where Id=...;
  Variableclob:=To_Clob(Temp_Save);
  Dbms_Output.Put_Line(Variableclob);


  End;

Lost connection to MySQL server during query?

This happened to me when I tried to update a table whose size on disk was bigger than the available disk space. The solution for me was simply to increase the available disk space.

Allowed characters in filename

For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.

$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);

Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.

Entity Framework vs LINQ to SQL

I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.

This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.

How to use sudo inside a docker container?

The other answers didn't work for me. I kept searching and found a blog post that covered how a team was running non-root inside of a docker container.

Here's the TL;DR version:

RUN apt-get update \
 && apt-get install -y sudo

RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

USER docker

# this is where I was running into problems with the other approaches
RUN sudo apt-get update 

I was using FROM node:9.3 for this, but I suspect that other similar container bases would work as well.

Set Session variable using javascript in PHP

One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.

Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.

Code is like this:

session_start();
if(!isset($_SESSION['v']))
{   
    $_SESSION['v']=0;
}
else
{
    header("Location:connect.php");
}

Now in count.html I want to set this session variable to 1.

Content in count.html

function doneHandler(result) {
   window.location="setSession.php";
}

In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.

So in setSession.php will write

session_start(); 
$_SESSION['v']=1;
header('Location:index.php');

Passing parameters to JavaScript files

Although this question has been asked a while ago, it is still relevant as of today. This is not a trivial approach using script file params, but I already had some extreme use-cases that this way was most suited.

I came across this post to find out a better solution than I wrote a while ago, with hope to find maybe a native feature or something similar.
I will share my solution, up until a better one will be implemented. This works on most modern browsers, maybe even on older ones, didn't try.

All the solutions above, are based on the fact that it has to be injected with predefined and well marked SCRIPT tag and rely completely on the HTML implementation. But, what if the script is injected dynamically, or even worse, what if you are write a library, that will be used in a variety of websites?
In these and some other cases, all the above answers are not sufficient and even becoming too complicated.

First, let's try to understand what do we need to achieve here. All we need to do is to get the URL of the script itself, from there it's a piece of cake.

There is actually a nice trick to get the script URL from the script itself. One of the functionalities of the native Error class, is the ability to provide a stack trace of the "problematic location", including the exact file trace to the last call. In order to achieve this, I will use the stack property of the Error instance, that once created, will give the full stack trace.

Here is how the magic works:

// The pattern to split each row in the stack trace string
const STACK_TRACE_SPLIT_PATTERN = /(?:Error)?\n(?:\s*at\s+)?/;
// For browsers, like Chrome, IE, Edge and more.
const STACK_TRACE_ROW_PATTERN1 = /^.+?\s\((.+?):\d+:\d+\)$/;
// For browsers, like Firefox, Safari, some variants of Chrome and maybe other browsers.
const STACK_TRACE_ROW_PATTERN2 = /^(?:.*?@)?(.*?):\d+(?::\d+)?$/;

const getFileParams = () => {
    const stack = new Error().stack;
    const row = stack.split(STACK_TRACE_SPLIT_PATTERN, 2)[1];
    const [, url] = row.match(STACK_TRACE_ROW_PATTERN1) || row.match(STACK_TRACE_ROW_PATTERN2) || [];
    if (!url) {
        console.warn("Something went wrong. You should debug it and find out why.");
        return;
    }
    try {
        const urlObj = new URL(url);
        return urlObj.searchParams; // This feature doesn't exists in IE, in this case you should use urlObj.search and handle the query parsing by yourself.
    } catch (e) {
        console.warn(`The URL '${url}' is not valid.`);
    }
}

Now, in any case of script call, like in the OP case:

<script type="text/javascript" src="file.js?obj1=somevalue&obj2=someothervalue"></script>

In the file.js script, you can now do:

const params = getFileParams();
console.log(params.get('obj2'));
// Prints: someothervalue

This will also work with RequireJS and other dynamically injected file scripts.

Rails: update_attribute vs update_attributes

To answer your question, update_attribute skips pre save "validations" but it still runs any other callbacks like after_save etc. So if you really want to "just update the column and skip any AR cruft" then you need to use (apparently)

Model.update_all(...) see https://stackoverflow.com/a/7243777/32453

How to check file MIME type with javascript before upload?

You can easily determine the file MIME type with JavaScript's FileReader before uploading it to a server. I agree that we should prefer server-side checking over client-side, but client-side checking is still possible. I'll show you how and provide a working demo at the bottom.


Check that your browser supports both File and Blob. All major ones should.

if (window.FileReader && window.Blob) {
    // All the File APIs are supported.
} else {
    // File and Blob are not supported
}

Step 1:

You can retrieve the File information from an <input> element like this (ref):

<input type="file" id="your-files" multiple>
<script>
var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {
    // When the control has changed, there are new files
    var files = control.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }
}, false);
</script>

Here is a drag-and-drop version of the above (ref):

<div id="your-files"></div>
<script>
var target = document.getElementById("your-files");
target.addEventListener("dragover", function(event) {
    event.preventDefault();
}, false);

target.addEventListener("drop", function(event) {
    // Cancel default actions
    event.preventDefault();
    var files = event.dataTransfer.files,
    for (var i = 0; i < files.length; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }
}, false);
</script>

Step 2:

We can now inspect the files and tease out headers and MIME types.

✘ Quick method

You can naïvely ask Blob for the MIME type of whatever file it represents using this pattern:

var blob = files[i]; // See step 1 above
console.log(blob.type);

For images, MIME types come back like the following:

image/jpeg
image/png
...

Caveat: The MIME type is detected from the file extension and can be fooled or spoofed. One can rename a .jpg to a .png and the MIME type will be be reported as image/png.


✓ Proper header-inspecting method

To get the bonafide MIME type of a client-side file we can go a step further and inspect the first few bytes of the given file to compare against so-called magic numbers. Be warned that it's not entirely straightforward because, for instance, JPEG has a few "magic numbers". This is because the format has evolved since 1991. You might get away with checking only the first two bytes, but I prefer checking at least 4 bytes to reduce false positives.

Example file signatures of JPEG (first 4 bytes):

FF D8 FF E0 (SOI + ADD0)
FF D8 FF E1 (SOI + ADD1)
FF D8 FF E2 (SOI + ADD2)

Here is the essential code to retrieve the file header:

var blob = files[i]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
  var header = "";
  for(var i = 0; i < arr.length; i++) {
     header += arr[i].toString(16);
  }
  console.log(header);

  // Check the file signature against known types

};
fileReader.readAsArrayBuffer(blob);

You can then determine the real MIME type like so (more file signatures here and here):

switch (header) {
    case "89504e47":
        type = "image/png";
        break;
    case "47494638":
        type = "image/gif";
        break;
    case "ffd8ffe0":
    case "ffd8ffe1":
    case "ffd8ffe2":
    case "ffd8ffe3":
    case "ffd8ffe8":
        type = "image/jpeg";
        break;
    default:
        type = "unknown"; // Or you can use the blob.type as fallback
        break;
}

Accept or reject file uploads as you like based on the MIME types expected.


Demo

Here is a working demo for local files and remote files (I had to bypass CORS just for this demo). Open the snippet, run it, and you should see three remote images of different types displayed. At the top you can select a local image or data file, and the file signature and/or MIME type will be displayed.

Notice that even if an image is renamed, its true MIME type can be determined. See below.

Screenshot

Expected output of demo


_x000D_
_x000D_
// Return the first few bytes of the file as a hex string_x000D_
function getBLOBFileHeader(url, blob, callback) {_x000D_
  var fileReader = new FileReader();_x000D_
  fileReader.onloadend = function(e) {_x000D_
    var arr = (new Uint8Array(e.target.result)).subarray(0, 4);_x000D_
    var header = "";_x000D_
    for (var i = 0; i < arr.length; i++) {_x000D_
      header += arr[i].toString(16);_x000D_
    }_x000D_
    callback(url, header);_x000D_
  };_x000D_
  fileReader.readAsArrayBuffer(blob);_x000D_
}_x000D_
_x000D_
function getRemoteFileHeader(url, callback) {_x000D_
  var xhr = new XMLHttpRequest();_x000D_
  // Bypass CORS for this demo - naughty, Drakes_x000D_
  xhr.open('GET', '//cors-anywhere.herokuapp.com/' + url);_x000D_
  xhr.responseType = "blob";_x000D_
  xhr.onload = function() {_x000D_
    callback(url, xhr.response);_x000D_
  };_x000D_
  xhr.onerror = function() {_x000D_
    alert('A network error occurred!');_x000D_
  };_x000D_
  xhr.send();_x000D_
}_x000D_
_x000D_
function headerCallback(url, headerString) {_x000D_
  printHeaderInfo(url, headerString);_x000D_
}_x000D_
_x000D_
function remoteCallback(url, blob) {_x000D_
  printImage(blob);_x000D_
  getBLOBFileHeader(url, blob, headerCallback);_x000D_
}_x000D_
_x000D_
function printImage(blob) {_x000D_
  // Add this image to the document body for proof of GET success_x000D_
  var fr = new FileReader();_x000D_
  fr.onloadend = function() {_x000D_
    $("hr").after($("<img>").attr("src", fr.result))_x000D_
      .after($("<div>").text("Blob MIME type: " + blob.type));_x000D_
  };_x000D_
  fr.readAsDataURL(blob);_x000D_
}_x000D_
_x000D_
// Add more from http://en.wikipedia.org/wiki/List_of_file_signatures_x000D_
function mimeType(headerString) {_x000D_
  switch (headerString) {_x000D_
    case "89504e47":_x000D_
      type = "image/png";_x000D_
      break;_x000D_
    case "47494638":_x000D_
      type = "image/gif";_x000D_
      break;_x000D_
    case "ffd8ffe0":_x000D_
    case "ffd8ffe1":_x000D_
    case "ffd8ffe2":_x000D_
      type = "image/jpeg";_x000D_
      break;_x000D_
    default:_x000D_
      type = "unknown";_x000D_
      break;_x000D_
  }_x000D_
  return type;_x000D_
}_x000D_
_x000D_
function printHeaderInfo(url, headerString) {_x000D_
  $("hr").after($("<div>").text("Real MIME type: " + mimeType(headerString)))_x000D_
    .after($("<div>").text("File header: 0x" + headerString))_x000D_
    .after($("<div>").text(url));_x000D_
}_x000D_
_x000D_
/* Demo driver code */_x000D_
_x000D_
var imageURLsArray = ["http://media2.giphy.com/media/8KrhxtEsrdhD2/giphy.gif", "http://upload.wikimedia.org/wikipedia/commons/e/e9/Felis_silvestris_silvestris_small_gradual_decrease_of_quality.png", "http://static.giantbomb.com/uploads/scale_small/0/316/520157-apple_logo_dec07.jpg"];_x000D_
_x000D_
// Check for FileReader support_x000D_
if (window.FileReader && window.Blob) {_x000D_
  // Load all the remote images from the urls array_x000D_
  for (var i = 0; i < imageURLsArray.length; i++) {_x000D_
    getRemoteFileHeader(imageURLsArray[i], remoteCallback);_x000D_
  }_x000D_
_x000D_
  /* Handle local files */_x000D_
  $("input").on('change', function(event) {_x000D_
    var file = event.target.files[0];_x000D_
    if (file.size >= 2 * 1024 * 1024) {_x000D_
      alert("File size must be at most 2MB");_x000D_
      return;_x000D_
    }_x000D_
    remoteCallback(escape(file.name), file);_x000D_
  });_x000D_
_x000D_
} else {_x000D_
  // File and Blob are not supported_x000D_
  $("hr").after( $("<div>").text("It seems your browser doesn't support FileReader") );_x000D_
} /* Drakes, 2015 */
_x000D_
img {_x000D_
  max-height: 200px_x000D_
}_x000D_
div {_x000D_
  height: 26px;_x000D_
  font: Arial;_x000D_
  font-size: 12pt_x000D_
}_x000D_
form {_x000D_
  height: 40px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input type="file" />_x000D_
  <div>Choose an image to see its file signature.</div>_x000D_
</form>_x000D_
<hr/>
_x000D_
_x000D_
_x000D_

Export a list into a CSV or TXT file in R

Check out in here, worked well for me, with no limits in the output size, no omitted elements, even beyond 1000

Exporting large lists in R as .txt or .csv

What is the difference between bottom-up and top-down?

Following is the DP based solution for Edit Distance problem which is top down. I hope it will also help in understanding the world of Dynamic Programming:

public int minDistance(String word1, String word2) {//Standard dynamic programming puzzle.
         int m = word2.length();
            int n = word1.length();


     if(m == 0) // Cannot miss the corner cases !
                return n;
        if(n == 0)
            return m;
        int[][] DP = new int[n + 1][m + 1];

        for(int j =1 ; j <= m; j++) {
            DP[0][j] = j;
        }
        for(int i =1 ; i <= n; i++) {
            DP[i][0] = i;
        }

        for(int i =1 ; i <= n; i++) {
            for(int j =1 ; j <= m; j++) {
                if(word1.charAt(i - 1) == word2.charAt(j - 1))
                    DP[i][j] = DP[i-1][j-1];
                else
                DP[i][j] = Math.min(Math.min(DP[i-1][j], DP[i][j-1]), DP[i-1][j-1]) + 1; // Main idea is this.
            }
        }

        return DP[n][m];
}

You can think of its recursive implementation at your home. It's quite good and challenging if you haven't solved something like this before.

if (select count(column) from table) > 0 then

not so elegant but you dont need to declare any variable:

for k in (select max(1) from table where 1 = 1) loop
    update x where column = value;
end loop;

jQuery vs document.querySelectorAll

If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.

If you care for performance, you can have incredible performance benefits (2-10 faster) using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2

I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.

                    Number of lines       Execution Time                       
Jquery version :        340                    155ms
Native version :        370                    27ms

You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.

http://youmightnotneedjquery.com/


Appendix: Further speed comparisons how native methods compete to jquery

Is there a way to run Bash scripts on Windows?

If your looking for something a little more native, you can use getGnuWin32 to install all of the unix command line tools that have been ported. That plus winBash gives you most of a working unix environment. Add console2 for a better terminal emulator and you almost can't tell your on windows!

Cygwin is a better toolkit overall, but I have found myself running into suprise problems because of the divide between it and windows. None of these solutions are as good as a native linux system though.

You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.

Why use String.Format?

String.Format adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.

For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format (as well as xxx.WriteLine and other methods that support composite formatting) over normal concatenation operators.

Posting parameters to a url using the POST method without using a form

You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check this link out. Keep in mind that you will need JavaScript enabled in your browser though.

Android Bitmap to Base64 String

use following method to convert bitmap to byte array:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();

to encode base64 from byte array use following method

String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

If you want to avoid inline script, you can simply listen for a click event on the radio. This can be achieved with plain Javascript by listening to a click event on

for (var radioCounter = 0 ; radioCounter < document.getElementsByName('myRadios').length; radioCounter++) {
      document.getElementsByName('myRadios')[radioCounter].onclick = function() {
        //VALUE OF THE CLICKED RADIO ELEMENT
        console.log('this : ',this.value);
      }
}

how do you filter pandas dataframes by multiple columns

You can filter by multiple columns (more than two) by using the np.logical_and operator to replace & (or np.logical_or to replace |)

Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:

def filter_df(df, filter_values):
    """Filter df by matching targets for multiple columns.

    Args:
        df (pd.DataFrame): dataframe
        filter_values (None or dict): Dictionary of the form:
                `{<field>: <target_values_list>}`
            used to filter columns data.
    """
    import numpy as np
    if filter_values is None or not filter_values:
        return df
    return df[
        np.logical_and.reduce([
            df[column].isin(target_values) 
            for column, target_values in filter_values.items()
        ])
    ]

Usage:

df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]})

filter_df(df, {
    'a': [1, 2, 3],
    'b': [1, 2, 4]
})

Bootstrap close responsive menu "on click"

You don't have to add any extra javascript to what's already included with bootstraps collapse option. Instead simply include data-toggle and data-target selectors on your menu list items just as you do with your navbar-toggle button. So for your Products menu item it would look like this

<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>

Then you would need to repeat the data-toggle and data-target selectors for each menu item

EDIT!!! In order to fix overflow issues and flickering on this fix I'm adding some more code that will fix this and still not have any extra javascript. Here is the new code:

<li><a href="#products" class="hidden-xs">Products</a></li>
<li><a href="#products" class="visible-xs" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>

Here it is at work http://jsfiddle.net/jaketaylor/84mqazgq/

This will make your toggle and target selectors specific to screen size and eliminate glitches on the larger menu. If anyone is still having issues with glitches please let me know and I'll find a fix. Thanks

EDIT: In the bootstrap v4.1.3 I couldnt use visible/hidden classes. Instead of hidden-xs use d-none d-sm-block and instead of visible-xs use d-block d-sm-none.

How to set Oracle's Java as the default Java in Ubuntu?

If you want this environment variable available to all users and on system start then you can add the following to /etc/profile.d/java.sh (create it if necessary):

export JDK_HOME=/usr/lib/jvm/java-7-oracle
export JAVA_HOME=/usr/lib/jvm/java-7-oracle

Then in a terminal run:

sudo chmod +x /etc/profile.d/java.sh
source /etc/profile.d/java.sh

My second question is - should it point to java-6-sun or java-6-sun-1.6.0.24 ?

It should always point to java-7-oracle as that symlinks to the latest installed one (assuming you installed Java from the Ubuntu repositories and now from the download available at oracle.com).

Jquery find nearest matching element

You could try:

$(this).closest(".column").prev().find(".inputQty").val();

is python capable of running on multiple cores?

CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.

Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.

The usual recommendation is to use many processes rather than many threads.

Converting a string to a date in JavaScript

ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.

This is a great resource to figure out which datestring format you should use:

http://dygraphs.com/date-formats.html

Yes, that means that your datestring could be as simple as as opposed to

"2014/10/13 23:57:52" instead of "2014-10-13 23:57:52"

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString when you need to display the name to the user.

Use name when you need the name for your program itself, e.g. to identify and differentiate between different enum values.

Auto start node.js server on boot

Use pm2 to start and run your nodejs processes on windows.

Be sure to read this github discussion of how to set up task scheduler to start pm2: https://github.com/Unitech/pm2/issues/1079

Use bash to find first folder name that contains a string

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

Default behavior of "git push" without a branch specified

You can change that default behavior in your .gitconfig, for example:

[push]
  default = current

To check the current settings, run:

git config --global --get push.default

Calculate correlation for more than two variables?

You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:

http://www.statmethods.net/stats/correlations.html

How to find out if a Python object is a string?

In order to check if your variable is something you could go like:

s='Hello World'
if isinstance(s,str):
#do something here,

The output of isistance will give you a boolean True or False value so you can adjust accordingly. You can check the expected acronym of your value by initially using: type(s) This will return you type 'str' so you can use it in the isistance function.

How do I print my Java object without getting "SomeType@2f92e0f4"?

By default, every Object in Java has the toString() method which outputs the ObjectType@HashCode.

If you want more meaningfull information then you need to override the toString() method in your class.

public class Person {
  private String name;

  // constructor and getter/setter omitted

  // overridding toString() to print name
  public String toString(){
     return name;  
  }
}

Now when you print the person object using System.out.prtinln(personObj); it will print the name of the person instead of the classname and hashcode.

In your second case when you are trying to print the array, it prints [Lcom.foo.Person;@28a418fc the Array type and it's hashcode.


If you want to print the person names, there are many ways.

You could write your own function that iterates each person and prints

void printPersonArray(Person[] persons){
    for(Person person: persons){
        System.out.println(person);
    }
}

You could print it using Arrays.toString(). This seems the simplest to me.

 System.out.println(Arrays.toString(persons));
 System.out.println(Arrays.deepToString(persons));  // for nested arrays  

You could print it the java 8 way (using streams and method reference).

 Arrays.stream(persons).forEach(System.out::println);

There might be other ways as well. Hope this helps. :)

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

Build Step Progress Bar (css and jquery)

I have searched for a solution that will visualize process steps in my web application. I have found the following excellent write-up by Stephen A Thomas:

Tracking Progress in Pure CSS (Original Link now dead)

In his approach Thomas even gets away with just using CSS - no Javascript! In an essence the following CSS code from his article does the trick for me:

    <style>

    <!-- Progress with steps -->

    ol.progtrckr {
        margin: 0;
        padding: 0;
        list-style-type: none;
    }

    ol.progtrckr li {
        display: inline-block;
        text-align: center;
        line-height: 3em;
    }

    ol.progtrckr[data-progtrckr-steps="2"] li { width: 49%; }
    ol.progtrckr[data-progtrckr-steps="3"] li { width: 33%; }
    ol.progtrckr[data-progtrckr-steps="4"] li { width: 24%; }
    ol.progtrckr[data-progtrckr-steps="5"] li { width: 19%; }
    ol.progtrckr[data-progtrckr-steps="6"] li { width: 16%; }
    ol.progtrckr[data-progtrckr-steps="7"] li { width: 14%; }
    ol.progtrckr[data-progtrckr-steps="8"] li { width: 12%; }
    ol.progtrckr[data-progtrckr-steps="9"] li { width: 11%; }

    ol.progtrckr li.progtrckr-done {
        color: black;
        border-bottom: 4px solid yellowgreen;
    }
    ol.progtrckr li.progtrckr-todo {
        color: silver; 
        border-bottom: 4px solid silver;
    }

    ol.progtrckr li:after {
        content: "\00a0\00a0";
    }
    ol.progtrckr li:before {
        position: relative;
        bottom: -2.5em;
        float: left;
        left: 50%;
        line-height: 1em;
    }
    ol.progtrckr li.progtrckr-done:before {
        content: "\2713";
        color: white;
        background-color: yellowgreen;
        height: 1.2em;
        width: 1.2em;
        line-height: 1.2em;
        border: none;
        border-radius: 1.2em;
    }
    ol.progtrckr li.progtrckr-todo:before {
        content: "\039F";
        color: silver;
        background-color: white;
        font-size: 1.5em;
        bottom: -1.6em;
    }

</style>

As well as HTML tags from his example (I use Grails GSP pages to generate tags and 'done/todo' class dynamically):

<ol class="progtrckr" data-progtrckr-steps="5">
    <li class="progtrckr-done">Order Processing</li>
    <li class="progtrckr-done">Pre-Production</li>
    <li class="progtrckr-done">In Production</li>
    <li class="progtrckr-done">Shipped</li>
    <li class="progtrckr-todo">Delivered</li>
</ol>

Hope it helps. Works pretty well for me.


UPDATE: The following (shortened) version also works well.

    ol.progtrckr {
        display: table;
        list-style-type: none;
        margin: 0;
        padding: 0;
        table-layout: fixed;
        width: 100%;
    }
    ol.progtrckr li {
        display: table-cell;
        text-align: center;
        line-height: 3em;
    }
    ... and the rest of the CSS ...

    <ol class="progtrckr">
        ...
    </ol>

display: table; table-layout: fixed; width: 100% ensure that the list items are automatically sized equally as long as the content does not overflow. There is no need to use data-progtrckr-steps and its associated CSS.

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

In c# is there a method to find the max of 3 numbers?

You could try this code:

private float GetBrightestColor(float r, float g, float b) { 
    if (r > g && r > b) {
        return r;
    } else if (g > r && g > b) { 
        return g;
    } else if (b > r && b > g) { 
        return b;
    }
}

How to create a jQuery function (a new jQuery method or plugin)?

You can always do this:

jQuery.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);

What is difference between INNER join and OUTER join

Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. check this

INSERT SELECT statement in Oracle 11G

You don't need the 'values' clause when using a 'select' as your source.

insert into table1 (col1, col2) 
select t1.col1, t2.col2 from oldtable1 t1, oldtable2 t2;

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

Remove multiple whitespaces

this will replace multiple tabs with a single tab

preg_replace("/\s{2,}/", "\t", $string);

Lock down Microsoft Excel macro

Just like you can password protect workbooks and worksheets, you can password protect a macro in Excel from being viewed (and executed).

Place a command button on your worksheet and add the following code lines:

  1. First, create a simple macro that you want to protect.

    Range("A1").Value = "This is secret code"

  2. Next, click Tools, Then VBAProject Properties...

enter image description here

Click Tools, VBAProject Properties...

  1. On the Protection tab, check "Lock project for viewing" and enter a password twice.

enter image description here

Enter a Password Twice

  1. Click OK.

  2. Save, close and reopen the Excel file. Try to view the code.

enter image description here

The following dialog box will appear:

Password Protected from being Viewed

You can still execute the code by clicking on the command button but you cannot view or edit the code anymore (unless you know the password). The password for the downloadable Excel file is "easy".

  1. If you want to password protect the macro from being executed, add the following code lines:
Dim password As Variant
password = Application.InputBox("Enter Password", "Password Protected")

Select Case password
    Case Is = False
        'do nothing
    Case Is = "easy"
        Range("A1").Value = "This is secret code"
    Case Else
        MsgBox "Incorrect Password"
End Select

Result when you click the command button on the sheet:

enter image description here

Password Protected from being Executed

Explanation: The macro uses the InputBox method of the Application object. If the users clicks Cancel, this method returns False and nothing happens (InputBox disappears). Only when the user knows the password ("easy" again), the secret code will be executed. If the entered password is incorrect, a MsgBox is displayed. Note that the user cannot take a look at the password in the Visual Basic Editor because the project is protected from being viewed

How can I change the font-size of a select option?

select[value="value"]{
   background-color: red;
   padding: 3px;
   font-weight:bold;
}

Download and open PDF file using Ajax

You don't necessarily need Ajax for this. Just an <a> link is enough if you set the content-disposition to attachment in the server side code. This way the parent page will just stay open, if that was your major concern (why would you unnecessarily have chosen Ajax for this otherwise?). Besides, there is no way to handle this nicely acynchronously. PDF is not character data. It's binary data. You can't do stuff like $(element).load(). You want to use completely new request for this. For that <a href="pdfservlet/filename.pdf">pdf</a> is perfectly suitable.

To assist you more with the server side code, you'll need to tell more about the language used and post an excerpt of the code attempts.

how to play video from url

pDialog = new ProgressDialog(this);

    // Set progressbar message
    pDialog.setMessage("Buffering...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    // Show progressbar
    pDialog.show();

    try {
        // Start the MediaController
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoView);      

        Uri videoUri = Uri.parse(videoUrl);
        mVideoView.setMediaController(mediacontroller);
        mVideoView.setVideoURI(videoUri);

    } catch (Exception e) {

        e.printStackTrace();
    }

    mVideoView.requestFocus();
    mVideoView.setOnPreparedListener(new OnPreparedListener() {
        // Close the progress bar and play the video
        public void onPrepared(MediaPlayer mp) {
            pDialog.dismiss();
            mVideoView.start();
        }
    });
    mVideoView.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            finish();               
        }
    });

Is it possible to select the last n items with nth-child?

If you are using jQuery in your project, or are willing to include it you can call nth-last-child through its selector API (this is this simulated it will cross browser). Here is a link to an nth-last-child plugin. If you took this method of targeting the elements you were interested in:

$('ul li:nth-last-child(1)').addClass('last');

And then style again the last class instead of the nth-child or nth-last-child pseudo selectors, you will have a much more consistent cross browser experience.

Format Date/Time in XAML in Silverlight

You can use StringFormat in Silverlight 4 to provide a custom formatting of the value you bind to.

Dates

The date formatting has a huge range of options.

For the DateTime of “April 17, 2004, 1:52:45 PM”

You can either use a set of standard formats (standard formats)…

StringFormat=f : “Saturday, April 17, 2004 1:52 PM”
StringFormat=g : “4/17/2004 1:52 PM”
StringFormat=m : “April 17”
StringFormat=y : “April, 2004”
StringFormat=t : “1:52 PM”
StringFormat=u : “2004-04-17 13:52:45Z”
StringFormat=o : “2004-04-17T13:52:45.0000000”

… or you can create your own date formatting using letters (custom formats)

StringFormat=’MM/dd/yy’ : “04/17/04”
StringFormat=’MMMM dd, yyyy g’ : “April 17, 2004 A.D.”
StringFormat=’hh:mm:ss.fff tt’ : “01:52:45.000 PM”

Download image from the site in .NET/C#

There is no need to involve any image classes, you can simply call WebClient.DownloadFile:

string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}

Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:

private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.

Update OpenSSL on OS X with Homebrew

On mac OS X Yosemite, after installing it with brew it put it into

/usr/local/opt/openssl/bin/openssl

But kept getting an error "Linking keg-only openssl means you may end up linking against the insecure" when trying to link it

So I just linked it by supplying the full path like so

ln -s /usr/local/opt/openssl/bin/openssl /usr/local/bin/openssl

Now it's showing version OpenSSL 1.0.2o when I do "openssl version -a", I'm assuming it worked

Preventing console window from closing on Visual Studio C/C++ Console application

A somewhat better solution:

atexit([] { system("PAUSE"); });

at the beginning of your program.

Pros:

  • can use std::exit()
  • can have multiple returns from main
  • you can run your program under the debugger
  • IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)

Cons:

  • have to modify code
  • won't pause on std::terminate()
  • will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:

extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
    if (IsDebuggerPresent())
        atexit([] {system("PAUSE"); });
    ...
}

Remove all html tags from php string

Remove all HTML tags from PHP string with content!

Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.

$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

echo strip_tags_content($srting);

function strip_tags_content($text) {

    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
    
 }

Output:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Simple CSS Animation Loop – Fading In & Out "Loading" Text

As King King said, you must add the browser specific prefix. This should cover most browsers:

_x000D_
_x000D_
@keyframes flickerAnimation {_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
  0%   { opacity:1; }_x000D_
  50%  { opacity:0; }_x000D_
  100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
   -webkit-animation: flickerAnimation 1s infinite;_x000D_
   -moz-animation: flickerAnimation 1s infinite;_x000D_
   -o-animation: flickerAnimation 1s infinite;_x000D_
    animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
_x000D_
_x000D_

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Creating a static class with no instances

Seems that you need classmethod:

class World(object):

    allAirports = []

    @classmethod
    def initialize(cls):

        if not cls.allAirports:
            f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
            file_reader = csv.reader(f)

            for col in file_reader:
                cls.allAirports.append(Airport(col[0],col[2],col[3]))

        return cls.allAirports

How to extract the substring between two markers?

Using PyParsing

import pyparsing as pp

word = pp.Word(pp.alphanums)

s = 'gfgfdAAA1234ZZZuijjk'
rule = pp.nestedExpr('AAA', 'ZZZ')
for match in rule.searchString(s):
    print(match)

which yields:

[['1234']]

I'm trying to use python in powershell

This works for me permanently:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27","User")

Angular 2: How to access an HTTP response body?

Can't you just refer to the _body object directly? Apparently it doesn't return any errors if used this way.

this.http.get('https://thecatapi.com/api/images/get?format=html&results_per_page=10')
            .map(res => res)
            .subscribe(res => {
                this.data = res._body;
            });

Working plunker

Java - Convert int to Byte Array of 4 Bytes?

You can convert yourInt to bytes by using a ByteBuffer like this:

return ByteBuffer.allocate(4).putInt(yourInt).array();

Beware that you might have to think about the byte order when doing so.

Vue 'export default' vs 'new Vue'

The first case (export default {...}) is ES2015 syntax for making some object definition available for use.

The second case (new Vue (...)) is standard syntax for instantiating an object that has been defined.

The first will be used in JS to bootstrap Vue, while either can be used to build up components and templates.

See https://vuejs.org/v2/guide/components-registration.html for more details.

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

Why can't I do <img src="C:/localfile.jpg">?

Honestly the easiest way was to add file hosting to the server.

  • Open IIS

  • Add a Virtual Directory under Default Web Site

    • virtual path will be what you want to browse to in the browser. So if you choose "serverName/images you will be able to browse to it by going to http://serverName/images
    • Then add the physical path on the C: drive
  • Add the appropriate permissions to the folder on the C: drive for "NETWORK SERVICE" and "IIS AppPool\DefaultAppPool"

  • Refresh Default Web Site

  • And you're done. You can now browse to any image in that folder by navigating to http://yourServerName/whateverYourFolderNameIs/yourImage.jpg and use that url in your img src

Hope this helps someone

Escape dot in a regex range

Because the dot is inside character class (square brackets []).

Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):

Any character except ^-]\ add that character to the possible matches for the character class.

How do I use .woff fonts for my website?

After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts subdirectory.

In CSS code:

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font.woff") format('woff');
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-bold.woff") format('woff');
    font-weight: bold;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-boldoblique.woff") format('woff');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "myfont";
    src: url("fonts/awesome-font-oblique.woff") format('woff');
    font-style: italic;
}

After having that definitions, you can just write, for example,

In HTML code:

<div class="mydiv">
    <b>this will be written with awesome-font-bold.woff</b>
    <br/>
    <b><i>this will be written with awesome-font-boldoblique.woff</i></b>
    <br/>
    <i>this will be written with awesome-font-oblique.woff</i>
    <br/>
    this will be written with awesome-font.woff
</div>

In CSS code:

.mydiv {
    font-family: myfont
}

The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.

return SQL table as JSON in python

After 10 years :) . Without list comprehension

Return a single row of values from a select query like below.

"select name,userid, address from table1 where userid = 1"

json output

{ name : "name1", userid : 1, address : "adress1, street1" }

Code

cur.execute(f"select name,userid, address from table1 where userid = 1 ")
row = cur.fetchone()
desc = list(zip(*cur.description))[0]  #To get column names
rowdict = dict(zip(desc,row))
jsondict = jsonify(rowdict)  #Flask jsonify

cur.description is a tuple of tuples as below. unzip and zip to combine column name with values

(('name', None, None, None, None, None, None), ('userid', None, None, None, None, None, None), ('address', None, None, None, None, None, None))

What is setContentView(R.layout.main)?

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

  • Activity is basically a empty window
  • SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R.layout.somae_file).
  • Here layoutfile is inflated to view and added to the Activity context(Window).

nodeJS - How to create and read session with express

It is cumbersome to interoperate socket.io and connect sessions support. The problem is not because socket.io "hijacks" request somehow, but because certain socket.io transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:

  1. Implement a separate session store for socket.io that stores data in the same format as connect-redis
  2. Make connect session cookie not http-only so it's accessible from client JS
  3. Upon a socket.io connection, send session cookie over socket.io from browser to server
  4. Store the session id in a socket.io connection, and use it to access session data from redis.

All combinations of a list of lists

One can use base python for this. The code needs a function to flatten lists of lists:

def flatten(B):    # function needed for code below;
    A = []
    for i in B:
        if type(i) == list: A.extend(i)
        else: A.append(i)
    return A

Then one can run:

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

outlist =[]; templist =[[]]
for sublist in L:
    outlist = templist; templist = [[]]
    for sitem in sublist:
        for oitem in outlist:
            newitem = [oitem]
            if newitem == [[]]: newitem = [sitem]
            else: newitem = [newitem[0], sitem]
            templist.append(flatten(newitem))

outlist = list(filter(lambda x: len(x)==len(L), templist))  # remove some partial lists that also creep in;
print(outlist)

Output:

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

How to compare two List<String> to each other?

You can check in all the below ways for a List

List<string> FilteredList = new List<string>();
//Comparing the two lists and gettings common elements.
FilteredList = a1.Intersect(a2, StringComparer.OrdinalIgnoreCase);

How to check if a user is logged in (how to properly use user.is_authenticated)?

In your view:

{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}

In you controller functions add decorator:

from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):

Node.js global variables

The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.

Use a JavaScript file and then use module exports.

Example:

File globals.js

var Globals = {
    'domain':'www.MrGlobal.com';
}

module.exports = Globals;

Then if you want to use these, use require.

var globals = require('globals'); // << globals.js path
globals.domain // << Domain.

Access to the path is denied

I encountered this problem while developing on my local workstation.

After several unsuccessful iisreset invocations, I remedied this situation by rebooting my machine.

In retrospect, an open file handle may have been causing issues.

How to convert string to IP address and vice versa

Use inet_ntop() and inet_pton() if you need it other way around. Do not use inet_ntoa(), inet_aton() and similar as they are deprecated and don't support ipv6.

Here is a nice guide with quite a few examples.

// IPv4 demo of inet_ntop() and inet_pton()

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));

// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);

printf("%s\n", str); // prints "192.0.2.33"

How to print a certain line of a file with PowerShell?

Here's a function that uses .NET's System.IO classes directly:

function GetLineAt([String] $path, [Int32] $index)
{
    [System.IO.FileMode] $mode = [System.IO.FileMode]::Open;
    [System.IO.FileAccess] $access = [System.IO.FileAccess]::Read;
    [System.IO.FileShare] $share = [System.IO.FileShare]::Read;
    [Int32] $bufferSize = 16 * 1024;
    [System.IO.FileOptions] $options = [System.IO.FileOptions]::SequentialScan;
    [System.Text.Encoding] $defaultEncoding = [System.Text.Encoding]::UTF8;
    # FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) constructor
    # http://msdn.microsoft.com/library/d0y914c5.aspx
    [System.IO.FileStream] $input = New-Object `
        -TypeName 'System.IO.FileStream' `
        -ArgumentList ($path, $mode, $access, $share, $bufferSize, $options);
    # StreamReader(Stream, Encoding, Boolean, Int32) constructor
    # http://msdn.microsoft.com/library/ms143458.aspx
    [System.IO.StreamReader] $reader = New-Object `
        -TypeName 'System.IO.StreamReader' `
        -ArgumentList ($input, $defaultEncoding, $true, $bufferSize);
    [String] $line = $null;
    [Int32] $currentIndex = 0;

    try
    {
        while (($line = $reader.ReadLine()) -ne $null)
        {
            if ($currentIndex++ -eq $index)
            {
                return $line;
            }
        }
    }
    finally
    {
        # Close $reader and $input
        $reader.Close();
    }

    # There are less than ($index + 1) lines in the file
    return $null;
}

GetLineAt 'file.txt' 9;

Tweaking the $bufferSize variable might affect performance. A more concise version that uses default buffer sizes and doesn't provide optimization hints could look like this:

function GetLineAt([String] $path, [Int32] $index)
{
    # StreamReader(String, Boolean) constructor
    # http://msdn.microsoft.com/library/9y86s1a9.aspx
    [System.IO.StreamReader] $reader = New-Object `
        -TypeName 'System.IO.StreamReader' `
        -ArgumentList ($path, $true);
    [String] $line = $null;
    [Int32] $currentIndex = 0;

    try
    {
        while (($line = $reader.ReadLine()) -ne $null)
        {
            if ($currentIndex++ -eq $index)
            {
                return $line;
            }
        }
    }
    finally
    {
        $reader.Close();
    }

    # There are less than ($index + 1) lines in the file
    return $null;
}

GetLineAt 'file.txt' 9;

Splitting a string into chunks of a certain size

This can be done in this way too

        string actualString = "1111222233334444";
        var listResult = new List<string>();
        int groupingLength = actualString.Length % 4;
        if (groupingLength > 0)
            listResult.Add(actualString.Substring(0, groupingLength));
        for (int i = groupingLength; i < actualString.Length; i += 4)
        {
            listResult.Add(actualString.Substring(i, 4));
        }

        foreach(var res in listResult)
        {
            Console.WriteLine(res);
        }
        Console.Read();

Converting an int to std::string

If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:

std::string to_string( int value ) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.

Implementation

#include <cstdio>
#include <string>
#include <cassert>

std::string to_string( int x ) {
  int length = snprintf( NULL, 0, "%d", x );
  assert( length >= 0 );
  char* buf = new char[length + 1];
  snprintf( buf, length + 1, "%d", x );
  std::string str( buf );
  delete[] buf;
  return str;
}

You can do more with it. Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.

Named capturing groups in JavaScript regex?

There is a node.js library called named-regexp that you could use in your node.js projects (on in the browser by packaging the library with browserify or other packaging scripts). However, the library cannot be used with regular expressions that contain non-named capturing groups.

If you count the opening capturing braces in your regular expression you can create a mapping between named capturing groups and the numbered capturing groups in your regex and can mix and match freely. You just have to remove the group names before using the regex. I've written three functions that demonstrate that. See this gist: https://gist.github.com/gbirke/2cc2370135b665eee3ef

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

What kind of document library information do you want in the view? How do you want the user to filter the view?

In general the most powerful way of creating views in sharepoint is with the data view web part. http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx

You will need Microsoft Office SharePoint Designer.

You can present different views of you folders using the data view filter and sorting controls.

You can use web part connections to filter a dataview. You can use any datasource linked to say a drop down to filter a dataview. How to tie a dropdown list to a gridview in Sharepoint 2007?

..The underlying connection was closed: An unexpected error occurred on a receive

To expand on Bartho Bernsmann's answer, I should like to add that one can have a universal, future-proof implementation at the expense of a little reflection:

static void AllowAllSecurityPrototols()
{   int                  i, n;
    Array                types;
    SecurityProtocolType combined;

    types = Enum.GetValues( typeof( SecurityProtocolType ) ); 
    combined = ( SecurityProtocolType )types.GetValue( 0 );

    n = types.Length;
    for( i = 1; i < n; i += 1 )
    {   combined |= ( SecurityProtocolType )types.GetValue( i );  }

    ServicePointManager.SecurityProtocol = combined;
}

I invoke this method in the static constructor of the class that accesses the internet.

Vuejs and Vue.set(), update array

One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.

So you this should work as well:

var tempArray[];

tempArray = this.items;

tempArray[targetPosition]  = value;

this.items = tempArray;

This then should also update your DOM.

Using ORDER BY and GROUP BY together

Just you need to desc with asc. Write the query like below. It will return the values in ascending order.

SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

How do you overcome the svn 'out of date' error?

Just do svn up into command line or if you are in windows select the svn update option.

  • Once this will done, this allow you to make further action like committing and others.

Adding a directory to the PATH environment variable in Windows

Option 1

After you change PATH with the GUI, close and re-open the console window.

This works because only programs started after the change will see the new PATH.

Option 2

Execute this command in the command window you have open:

set PATH=%PATH%;C:\your\path\here\

This command appends C:\your\path\here\ to the current PATH.

Breaking it down:

  • set – A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.
  • PATH= – Signifies that PATH is the environment variable to be temporarily changed.
  • %PATH%;C:\your\path\here\ – The %PATH% part expands to the current value of PATH, and ;C:\your\path\here\ is then concatenated to it. This becomes the new PATH.

How do I calculate the date six months from the current date using the datetime Python module?

With Python 3.x you can do it like this:

from datetime import datetime, timedelta
from dateutil.relativedelta import *

date = datetime.now()
print(date)
# 2018-09-24 13:24:04.007620

date = date + relativedelta(months=+6)
print(date)
# 2019-03-24 13:24:04.007620

but you will need to install python-dateutil module:

pip install python-dateutil

How to get the current working directory in Java?

Use CodeSource#getLocation().

This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

Consistency of hashCode() on a Java string

If you're worried about changes and possibly incompatibly VMs, just copy the existing hashcode implementation into your own utility class, and use that to generate your hashcodes .

How to convert SQL Server's timestamp column to datetime format

The simplest way of doing this is:

SELECT id,name,FROM_UNIXTIME(registration_date) FROM `tbl_registration`;

This gives the date column atleast in a readable format. Further if you want to change te format click here.

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

// In jest.setup.js
jest.setTimeout(30000)

If on Jest <= 23:

// In jest.config.js
module.exports = {
  setupTestFrameworkScriptFile: './jest.setup.js'
}

If on Jest > 23:

// In jest.config.js
module.exports = {
  setupFilesAfterEnv: ['./jest.setup.js']
}

Bash command to sum a column of numbers

I like the chosen answer. However, it tends to be slower than awk since 2 tools are needed to do the job.

$ wc -l file
49999998 file

$ time paste -sd+ file | bc
1448700364

real    1m36.960s
user    1m24.515s
sys     0m1.772s

$ time awk '{s+=$1}END{print s}' file
1448700364

real    0m45.476s
user    0m40.756s
sys     0m0.287s

Alternative to mysql_real_escape_string without connecting to DB

It is impossible to safely escape a string without a DB connection. mysql_real_escape_string() and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.

If you are only testing, then you may as well use mysql_escape_string(), it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.

How do I install pip on macOS or OS X?

You should install Brew first:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then brew install Python

brew install python

Then pip will work

PHP: Split string

explode('.', $string)

If you know your string has a fixed number of components you could use something like

list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;

Prints:

object
attribute

How to get image height and width using java?

You could use the Toolkit, no need for ImageIO

Image image = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());
int width = image.getWidth(null);
int height = image.getHeight(null);

If you don't want to handle the loading of the image do

ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());
int height = imageIcon.getIconHeight();
int width = imageIcon.getIconWidth();

Docker Error bind: address already in use

On my machine a PID was not being shown from this command netstat -tulpn for the in-use port (8080), so i could not kill it, killing the containers and restarting the computer did not work. So service docker restart command restarted docker for me (ubuntu) and the port was no longer in use and i am a happy chap and off to lunch.

Touch move getting stuck Ignored attempt to cancel a touchmove

Calling preventDefault on touchmove while you're actively scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.

Try to call preventDefault() from touchstart and everything should be ok.

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

Horizontal list items

You could also use inline blocks to avoid floating elements

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
   </li>
</ul>

and then style as:

li{
    /* with fix for IE */
    display:inline;
    display:inline-block;
    zoom:1;
    /*
    additional styles to make it look nice
    */
 }

that way you wont need to float anything, eliminating the need for clearfixes

Ripple effect on Android Lollipop CardView

If the app minSdkVersion which you are working is level 9, you can use:

android:foreground="?selectableItemBackground"
android:clickable="true"

Instead, starting from level 11, you use:

android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"

From documentation:

clickable - Defines whether this view reacts to click events. Must be a boolean value, either "true" or "false".

foreground - Defines the drawable to draw over the content. This can be used as an overlay. The foreground drawable participates in the padding of the content if the gravity is set to fill.

upgade python version using pip

Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

How about this:

$ seq 1 100000 | tail -n +10000 | head -n 10
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009

It uses tail to output from the 10,000th line and onwards and then head to only keep 10 lines.

The same (almost) result with sed:

$ seq 1 100000 | sed -n '10000,10010p'
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010

This one has the advantage of allowing you to input the line range directly.

ps1 cannot be loaded because running scripts is disabled on this system

Another solution is Remove ng.ps1 from the directory C:\Users%username%\AppData\Roaming\npm\ and clearing the npm cache

Adding elements to a C# array

What's abaut this one:

List<int> tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

SQL Server: How to check if CLR is enabled?

This is @Jason's answer but with simplified output

SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'

The above returns the following:

| name        | Enabled |
-------------------------
| clr enabled | YES     |

Tested on SQL Server 2017

Twitter Bootstrap Modal Form Submit

This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:

$(function () {
    $('body').on('click', '.odom-submit', function (e) {
        $(this.form).submit();
        $('#myModal').modal('hide');
    });
});

To make this work I did this in the modal footer

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary odom-submit">Save changes</button>
</div>

Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.

'module' object is not callable - calling method in another file

  • from a directory_of_modules, you can import a specific_module.py
  • this specific_module.py, can contain a Class with some_methods() or just functions()
  • from a specific_module.py, you can instantiate a Class or call functions()
  • from this Class, you can execute some_method()

Example:

#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()

Excerpts from PEP 8 - Style Guide for Python Code:

Modules should have short and all-lowercase names.

Notice: Underscores can be used in the module name if it improves readability.

A Python module is simply a source file(*.py), which can expose:

  • Class: names using the "CapWords" convention.

  • Function: names in lowercase, words separated by underscores.

  • Global Variables: the conventions are about the same as those for Functions.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

Cannot change column used in a foreign key constraint

You can turn off foreign key checks:

SET FOREIGN_KEY_CHECKS = 0;

/* DO WHAT YOU NEED HERE */

SET FOREIGN_KEY_CHECKS = 1;

Please make sure to NOT use this on production and have a backup.

Command to list all files in a folder as well as sub-folders in windows

An addition to the answer: when you do not want to list the folders, only the files in the subfolders, use /A-D switch like this:

dir ..\myfolder /b /s /A-D /o:gn>list.txt

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

How do I use a Boolean in Python?

Boolean types are defined in documentation:
http://docs.python.org/library/stdtypes.html#boolean-values

Quoted from doc:

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).

They are written as False and True, respectively.

So in java code remove braces, change true to True and you will be ok :)

Aggregate multiple columns at once

You could try:

agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)

How can I find whitespace in a String?

public static void main(String[] args) {
    System.out.println("test word".contains(" "));
}

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

Use a content script to access the page context variables and functions

in Content script , i add script tag to the head which binds a 'onmessage' handler, inside the handler i use , eval to execute code. In booth content script i use onmessage handler as well , so i get two way communication. Chrome Docs

//Content Script

var pmsgUrl = chrome.extension.getURL('pmListener.js');
$("head").first().append("<script src='"+pmsgUrl+"' type='text/javascript'></script>");


//Listening to messages from DOM
window.addEventListener("message", function(event) {
  console.log('CS :: message in from DOM', event);
  if(event.data.hasOwnProperty('cmdClient')) {
    var obj = JSON.parse(event.data.cmdClient);
    DoSomthingInContentScript(obj);
 }
});

pmListener.js is a post message url listener

//pmListener.js

//Listen to messages from Content Script and Execute Them
window.addEventListener("message", function (msg) {
  console.log("im in REAL DOM");
  if (msg.data.cmnd) {
    eval(msg.data.cmnd);
  }
});

console.log("injected To Real Dom");

This way , I can have 2 way communication between CS to Real Dom. Its very usefull for example if you need to listen webscoket events , or to any in memory variables or events.

Better way to check if a Path is a File or a Directory?

As an alternative to Directory.Exists(), you can use the File.GetAttributes() method to get the attributes of a file or a directory, so you could create a helper method like this:

private static bool IsDirectory(string path)
{
    System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
    return (fa & FileAttributes.Directory) != 0;
}

You could also consider adding an object to the tag property of the TreeView control when populating the control that contains additional metadata for the item. For instance, you could add a FileInfo object for files and a DirectoryInfo object for directories and then test for the item type in the tag property to save making additional system calls to get that data when clicking on the item.

Passing variables in remote ssh command

(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)

You can feed data right through the standard input of the ssh command and read that from the remote location.

In the following example,

  1. an indexed array is filled (for convenience) with the names of the variables whose values you want to retrieve on the remote side.
  2. For each of those variables, we give to ssh a null-terminated line giving the name and value of the variable.
  3. In the shh command itself, we loop through these lines to initialise the required variables.
# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb

# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
    FOO
    BAR
)

for name in "${VAR_NAMES[@]}"
do
    printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
    while read -rd '"''"' name value
    do
        export "$name"="$value"
    done

    # Check
    printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'

Output:

FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]

If you don’t need to export those, you should be able to use declare instead of export.

A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:

$ ssh [email protected] 'read foo' <<< "$foo"

How do I make JavaScript beep?

Note:put this code in your javascript at the point you want the beep to occur. and remember to specify the directory or folder where the beep sound is stored(source).

<script>
//Appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio"><source src="sound/notify.ogg" type="audio/ogg"><source src="sound/notify.mp3" type="audio/mpeg"><source src="sound/notify.wav" type="audio/wav"></audio>').appendTo('body');

$('#chatAudio')[0].play();
</script>

Reference:http://www.9lessons.info/2013/04/play-notification-sound-using-jquery.html.

I implemented this in a social media i am developing and it works find, a notification like that of facebook when chatting, notifying you that you have a new chat message

Why can't I reference my class library?

I had this problem. It took me ages to figure out. I had people over my shoulder to help. We rebuilt, cleaned and restarted Visual studio and this didn't fix it. We removed and re-added the references...

All to no avail.... Until!

The solution to my problem was that my class declaration was spelt incorrectly.

Before you start judging me harshly, allow me to explain why it wasn't stupid, and also why this mistake could be made by even the most intelligent of programmers.

Since the mistake was early on in the name, it wasn't appearing in the intellisense class listing when I began typing.

e.g.

Class name: Message.cs

Declaration:

public class Massage
{
    //code here

}

At a glance and in a small font, Massage looks identical to Message.

Typing M listed too many classes, so I typed e, which didn't appear in the mistyped version, which gave the impression that the class wasn't being picked up by the compiler.

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

How to write console output to a txt file

To write console output to a txt file

public static void main(String[] args) {
    int i;
    List<String> ls = new ArrayList<String>();
    for (i = 1; i <= 100; i++) {
        String str = null;
        str = +i + ":-  HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
        ls.add(str);
    }
    String listString = "";
    for (String s : ls) {
        listString += s + "\n";
    }
    FileWriter writer = null;
    try {
        writer = new FileWriter("final.txt");
        writer.write(listString);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

If you want to generate the PDF rather then the text file, you use the dependency given below:

<dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.0.6</version>
</dependency>

To generate a PDF, use this code:

public static void main(String[] args) {
    int i;
    List<String> ls = new ArrayList<String>();
    for (i = 1; i <= 100; i++) {
        String str = null;
        str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
        ls.add(str);
    }
    String listString = "";

    for (String s : ls) {
        listString += s + "\n";
    }
    Document document = new Document();
    try {
        PdfWriter writer1 = PdfWriter
                .getInstance(
                        document,
                        new FileOutputStream(
                                "final_pdf.pdf"));
        document.open();
        document.add(new Paragraph(listString));
        document.close();
        writer1.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

How do I turn off Oracle password expiration?

To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:

select profile from DBA_USERS where username = '<username>';

Then you can change the limit to never expire using:

alter profile <profile_name> limit password_life_time UNLIMITED;

If you want to previously check the limit you may use:

select resource_name,limit from dba_profiles where profile='<profile_name>';

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

I went to publish, application files, found the dll throwing the error changed it to 'Include' from 'Include (Auto)'. I can now publish.

Upgrading Node.js to latest version

For Windows

I had the same problem, I tried to reinstall and didn't worked for me.

Remove "C:\Program Files(x86)\nodejs" from your system enviorment PATH and thats it!

I can not find my.cnf on my windows computer

You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)

SHOW VARIABLES

Where does Vagrant download its .box files to?

On Mac/Linux System, the successfully downloaded boxes are located at:

~/.vagrant.d/boxes

and unsuccessful boxes are located at:

~/.vagrant.d/tmp

On Windows systems it is located under the Users folder:

C:\Users\%userprofile%\.vagrant.d\boxes

Hope this will help. Thanks

How to change Windows 10 interface language on Single Language version

Actually, it looks like you may be able to download language packs directly through Windows Update. Open the old Control Panel by pressing WinKey+X and clicking Control Panel. Then go to Clock, Language, and Region > Add a language. Add the desired language. Then under the language it should say "Windows display language: Available". Click "Options" and then "Download and install language pack."

I'm not sure why this functionality appears to be less accessible than it was in Windows 8.

How to set time zone of a java.util.Date?

If you must work with only standard JDK classes you can use this:

/**
 * Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
 * <code>toTimeZone</code>.  Since java.util.Date has does not really store time zome
 * information, this actually converts the date to the date that it would be in the
 * other time zone.
 * @param date
 * @param fromTimeZone
 * @param toTimeZone
 * @return
 */
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
    long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
    long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);

    return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}

/**
 * Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
 * additional offset due to the time zone being in daylight savings time as of
 * the given <code>date</code>.
 * @param date
 * @param timeZone
 * @return
 */
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
    long timeZoneDSTOffset = 0;
    if(timeZone.inDaylightTime(date))
    {
        timeZoneDSTOffset = timeZone.getDSTSavings();
    }

    return timeZone.getRawOffset() + timeZoneDSTOffset;
}

Credit goes to this post.

Regular expression matching a multiline block of text

The following is a regular expression matching a multiline block of text:

import re
result = re.findall('(startText)(.+)((?:\n.+)+)(endText)',input)

Program "make" not found in PATH

You may try altering toolchain in case if for some reason you can't use gcc. Open Properties for your project (by right clicking on your project name in the Project Explorer), then C/C++ Build > Tool Chain Editor. You can change the current builder there from GNU Make Builder to CDT Internal Builder or whatever compatible you have.

MySQL WHERE: how to write "!=" or "not equals"?

You may be using old version of Mysql but surely you can use

 DELETE FROM konta WHERE taken <> ''

But there are many other options available. You can try the following ones

DELETE * from konta WHERE strcmp(taken, '') <> 0;

DELETE * from konta where NOT (taken = '');

Programmatically get own phone number in iOS

No official API to do it. Using private API you can use following method:

-(NSString*) getMyNumber {
    NSLog(@"Open CoreTelephony");
    void *lib = dlopen("/Symbols/System/Library/Framework/CoreTelephony.framework/CoreTelephony",RTLD_LAZY);
    NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");
    NSString* (*pCTSettingCopyMyPhoneNumber)() = dlsym(lib, "CTSettingCopyMyPhoneNumber");
    NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");

    if (pCTSettingCopyMyPhoneNumber == nil) {
        NSLog(@"pCTSettingCopyMyPhoneNumber is nil");
        return nil;
    }
    NSString* ownPhoneNumber = pCTSettingCopyMyPhoneNumber();
    dlclose(lib);
    return ownPhoneNumber;
}

It works on iOS 6 without JB and special signing.

As mentioned creker on iOS 7 with JB you need to use entitlements to make it working.

How to do it with entitlements you can find here: iOS 7: How to get own number via private API?

How to merge remote master to local branch

I found out it was:

$ git fetch upstream
$ git merge upstream/master

How can I copy columns from one sheet to another with VBA in Excel?

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim rng As Range, r As Range
  Set rng = Intersect(Target, Range("a2:a" & Rows.Count))
  If rng Is Nothing Then Exit Sub
    For Each r In rng
      If Not IsEmpty(r.Value) Then
        r.Copy Destination:=Sheets("sheet2").Range("a2")
      End If
    Next
  Set rng = Nothing
End Sub

RuntimeWarning: DateTimeField received a naive datetime

Quick and dirty - Turn it off:

USE_TZ = False

in your settings.py

Node.js console.log() not logging anything

This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github

UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js

How can I copy network files using Robocopy?

You should be able to use Windows "UNC" paths with robocopy. For example:

robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder

Robocopy has the ability to recover from certain types of network hiccups automatically.

Read a HTML file into a string variable in memory

What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument(); followed by doc.Load(filename). Then the XML document can be parsed in memory.

Read here for more information on XmlDocument:

Resolve Git merge conflicts in favor of their changes during a pull

The git pull -X theirs answers may create an ugly merge commit, or issue an

error: Your local changes to the following files would be overwritten by merge:

If you want to simply ignore any local modifications to files from the repo, for example on a client that should always be a mirror of an origin, run this (replace master with the branch you want):

git fetch && git reset --hard origin/master

How does it work? git fetch does git pull but without merge. Then git reset --hard makes your working tree match the last commit. All of your local changes to files in the repo will be discarded, but new local files will be left alone.

How do I return clean JSON from a WCF Service?

In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare

 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]

    List<personClass> Getperson(string id);

How to find if an array contains a specific string in JavaScript/jQuery?

Here you go:

$.inArray('specialword', arr)

This function returns a positive integer (the array index of the given value), or -1 if the given value was not found in the array.

Live demo: http://jsfiddle.net/simevidas/5Gdfc/

You probably want to use this like so:

if ( $.inArray('specialword', arr) > -1 ) {
    // the value is in the array
}

Installing Python 3 on RHEL

Along with Python 2.7 and 3.3, Red Hat Software Collections now includes Python 3.4 - all work on both RHEL 6 and 7.

RHSCL 2.0 docs are at https://access.redhat.com/documentation/en-US/Red_Hat_Software_Collections/

Plus lot of articles at developerblog.redhat.com.

edit

Follow these instructions to install Python 3.4 on RHEL 6/7 or CentOS 6/7:

# 1. Install the Software Collections tools:
yum install scl-utils

# 2. Download a package with repository for your system.
#  (See the Yum Repositories on external link. For RHEL/CentOS 6:)
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-6-x86_64/download/rhscl-rh-python34-epel-6-x86_64.noarch.rpm
#  or for RHEL/CentOS 7
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-7-x86_64/download/rhscl-rh-python34-epel-7-x86_64.noarch.rpm

# 3. Install the repo package (on RHEL you will need to enable optional channel first):
yum install rhscl-rh-python34-*.noarch.rpm

# 4. Install the collection:
yum install rh-python34

# 5. Start using software collections:
scl enable rh-python34 bash

Android scale animation on view

try this code to create Scale animation without using xml

ScaleAnimation animation = new ScaleAnimation(fromXscale, toXscale, fromYscale, toYscale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

SQL LIKE condition to check for integer?

In PostreSQL you can use SIMILAR TO operator (more):

-- only digits
select * from books where title similar to '^[0-9]*$';
-- start with digit
select * from books where title similar to '^[0-9]%$';

How can I enable MySQL's slow query log without restarting MySQL?

This should work on mysql > 5.5

SHOW VARIABLES LIKE '%long%';

SET GLOBAL long_query_time = 1;

Encrypt and Decrypt text with RSA in PHP

Security warning: This code snippet is vulnerable to Bleichenbacher's 1998 padding oracle attack. See this answer for better security.

class MyEncryption
{

    public $pubkey = '...public key here...';
    public $privkey = '...private key here...';

    public function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
            $data = base64_encode($encrypted);
        else
            throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');

        return $data;
    }

    public function decrypt($data)
    {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
            $data = $decrypted;
        else
            $data = '';

        return $data;
    }
}

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I ran into this problem, and when I checked out the database directory, there were a number of exp files (the ibd and frm files had been removed). Listing the files to look at their attributes (since the owner already had rw privileges on the files)

lsattr *.exp
-------------e-- foo.exp
-------------e-- bar.exp

Man page says

       The  'e'  attribute  indicates that the file is using extents for mapping the blocks on disk.
       It may not be removed using chattr(1).

You actually can chattr -e these files, but mysql still won't let you drop the database. Removing the files with rm, however, allows the database to be dropped cleanly.

Disable browser cache for entire ASP.NET website

I implemented all the previous answers and still had one view that did not work correctly.

It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.

After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

$stateProvider
  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }
  })

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
}
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"
}

// param will be array []
params: {
  param1: { array: true }
}

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info

Here is an example of a state definition:

 $stateProvider
  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
      ...
  })
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
      ...
  })
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },
      ...
  })

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
  })">home</a>

<a ui-sref="parent({ 
    veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
  })">parent</a>

<a ui-sref="parent.child({
    veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',  
    veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
  })">parent.child</a>

Check the example here

Check if key exists and iterate the JSON array using Python

You can use a try-except

try:
   print(str.to.id)
except AttributeError: # Not a Retweet
   print('null')

SQL Server datetime LIKE select?

There's no direct support for LIKE operator against DATETIME variables, but you can always cast the DATETIME to a VARCHAR:

SELECT (list of fields) FROM YourTable
WHERE CONVERT(VARCHAR(25), register_date, 126) LIKE '2009-10-10%'

Check the MSDN docs for a complete list of available "styles" in the CONVERT function.

Marc

Print the address or pointer for value in C

char c = 'A';
printf("ptr: %p,\tvalue: %c,\tand also address: %zu", &c, c, &c);

Result:

ptr: 0x7ffc48e5105f,    value: A,    and also address: 140721531457631

scp copy directory to another server with private key auth

Putty doesn't use openssh key files - there is a utility in putty suite to convert them.

edit: it is called puttygen

How do I mock a static method that returns void with PowerMock?

You can stub a static void method like this:

PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());

Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed

More useful, you can capture the value passed to StaticResource.getResource() like this:

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
               StaticResource.class, "getResource", captor.capture());

Then you can evaluate the String that was passed to StaticResource.getResource like this:

String resourceName = captor.getValue();

Get just the filename from a path in a Bash script

basename and dirname solutions are more convenient. Those are alternative commands:

FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"

This returns test.old.img like basename.

This is salt filename without extension:

echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"

It returns test.old.

And following statement gives the full path like dirname command.

echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"

It returns /opt/datastores/sda2

MySQL: Insert record if not exists in table

I had a similar problem and I needed to insert multiple if not existing. So from the examples above I came to this combination... it's here just in case somebody would need it.

Notice: I had to define name everywhere as MSSQL required it... MySQL works with * too.

INSERT INTO names (name)
SELECT name
FROM
(
  SELECT name
  FROM
  (
     SELECT 'Test 4' as name
  ) AS tmp_single
  WHERE NOT EXISTS
  (
     SELECT name FROM names WHERE name = 'Test 4'
  )
  UNION ALL
  SELECT name
  FROM
  (
     SELECT 'Test 5' as name
  ) AS tmp_single
  WHERE NOT EXISTS
  (
     SELECT name FROM names WHERE name = 'Test 5'
  )
) tmp_all;

MySQL: CREATE TABLE names ( OID int(11) NOT NULL AUTO_INCREMENT, name varchar(32) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (OID), UNIQUE KEY name_UNIQUE (name) ) ENGINE=InnoDB AUTO_INCREMENT=1;

or

MSSQL: CREATE TABLE [names] ( [OID] INT IDENTITY (1, 1) NOT NULL, [name] NVARCHAR (32) NOT NULL, PRIMARY KEY CLUSTERED ([OID] ASC) ); CREATE UNIQUE NONCLUSTERED INDEX [Index_Names_Name] ON [names]([name] ASC);

Set padding for UITextField with UITextBorderStyleNone

^ these suggestions are great for those who are programmatically creating an interface.

But there are two LAZY EASY WAYS for those of us who use the Xcode interface builder:

  • easier: put a UIImageView behind a text field

  • easiest: change the border style on your to the simple black square (second from left option), then add your image as a background image. The image takes precedence over the square, so you still get the padding needed for a normal image background, without the square actually being drawn on.

EDIT: you can also use the black sphere (third from left option when selecting the UITextBox in IB), it does not work with the far right, "graphical sphere" style.

Most efficient way to find smallest of 3 numbers Java?

For those who find this topic much later:

If you have just three values to compare there is no significant difference. But if you have to find min of, say, thirty or sixty values, "min" could be easier for anyone to read in the code next year:

int smallest;

smallest = min(a1, a2);
smallest = min(smallest, a3);
smallest = min(smallest, a4);
...
smallest = min(smallest, a37);

But if you think of speed, maybe better way would be to put values into list, and then find min of that:

List<Integer> mySet = Arrays.asList(a1, a2, a3, ..., a37);

int smallest = Collections.min(mySet);

Would you agree?

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

.NET - How do I retrieve specific items out of a Dataset?

I prefer to use something like this:

int? var1 = ds.Tables[0].Rows[0].Field<int?>("ColumnName");

or

int? var1 = ds.Tables[0].Rows[0].Field<int?>(3);   //column index

How to get single value of List<object>

Define a class like this :

public class myclass {
       string id ;
       string title ;
       string content;
 }

 public class program {
        public void Main () {
               List<myclass> objlist = new List<myclass> () ;
               foreach (var value in objlist)  {
                       TextBox1.Text = value.id ;
                       TextBox2.Text= value.title;
                       TextBox3.Text= value.content ;
                }
         }
  }

I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

Assign command output to variable in batch file

This is work for me

@FOR /f "delims=" %i in ('reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion') DO set var=%i
echo %var%

How to upgrade rubygems

You can update gem to any specific version like this,

gem update --system 'version'

gem update --system '2.3.0'

Install php-mcrypt on CentOS 6

If you want to recompile PHP with mcrypt enable.

1. Insatll mcrypt. libmcrypt-devel is from Third Party Repositories EPEL, so you should:

yum --enablerepo=extras install epel-release
yum install libmcrypt-devel

2. Append --with-mcrypt to your ./configure arguments:

./configure --with-mcrypt

3. Build and install:

make & make install

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name