Programs & Examples On #Netbeans6.7

It is the version 6.7 of Netbeans IDE for java application development.

How to handle invalid SSL certificates with Apache HttpClient?

The Apache HttpClient 4.5 way:

org.apache.http.ssl.SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
sslContextBuilder.loadTrustMaterial(new org.apache.http.conn.ssl.TrustSelfSignedStrategy());
SSLContext sslContext = sslContextBuilder.build();
org.apache.http.conn.ssl.SSLConnectionSocketFactory sslSocketFactory =
        new SSLConnectionSocketFactory(sslContext, new org.apache.http.conn.ssl.DefaultHostnameVerifier());

HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(sslSocketFactory);
httpClient = httpClientBuilder.build();

NOTE: org.apache.http.conn.ssl.SSLContextBuilder is deprecated and org.apache.http.ssl.SSLContextBuilder is the new one (notice conn missing from the latter's package name).

Get first day of week in PHP?

<?php
/* PHP 5.3.0 */

date_default_timezone_set('America/Denver'); //Set apprpriate timezone
$start_date = strtotime('2009-12-15'); //Set start date

//Today's date if $start_date is a Sunday, otherwise date of previous Sunday
$today_or_previous_sunday = mktime(0, 0, 0, date('m', $start_date), date('d', $start_date), date('Y', $start_date)) - ((date("w", $start_date) ==0) ? 0 : (86400 * date("w", $start_date)));

//prints 12-13-2009 (month-day-year)
echo date('m-d-Y', $today_or_previous_sunday);

?>

(Note: MM, dd and yyyy in the Question are not standard php date format syntax - I can't be sure what is meant, so I set the $start_date with ISO year-month-day)

How to sort an array of objects in Java?

Update for Java 8 constructs

Assuming a Book class with a name field getter, you can use Arrays.sort method by passing an additional Comparator specified using Java 8 constructs - Comparator default method & method references.

Arrays.sort(bookArray, Comparator.comparing(Book::getName));

Also, it's possible to compare on multiple fields using thenComparing methods.

Arrays.sort(bookArray, Comparator.comparing(Book::getName)
      .thenComparing(Book::getAuthor))
      .thenComparingInt(Book::getId));

How to check whether a variable is a class or not?

Benjamin Peterson is correct about the use of inspect.isclass() for this job. But note that you can test if a Class object is a specific Class, and therefore implicitly a Class, using the built-in function issubclass. Depending on your use-case this can be more pythonic.

from typing import Type, Any
def isclass(cl: Type[Any]):
    try:
        return issubclass(cl, cl)
    except TypeError:
        return False

Can then be used like this:

>>> class X():
...     pass
... 
>>> isclass(X)
True
>>> isclass(X())
False

How to include a class in PHP

Your code should be something like

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

How to use OpenFileDialog to select a folder?

As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.

This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)

Install-Package Microsoft.WindowsAPICodePack-Shell

For the include line:

using Microsoft.WindowsAPICodePack.Dialogs;

Usage:

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    MessageBox.Show("You selected: " + dialog.FileName);
}

How to create friendly URL in php?

I try to explain this problem step by step in following example.

0) Question

I try to ask you like this :

i want to open page like facebook profile www.facebook.com/kaila.piyush

it get id from url and parse it to profile.php file and return featch data from database and show user to his profile

normally when we develope any website its link look like www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678

now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink

http://example.com/profile/userid (get a profile by the ID) 
http://example.com/profile/username (get a profile by the username) 
http://example.com/myprofile (get the profile of the currently logged-in user)

1) .htaccess

Create a .htaccess file in the root folder or update the existing one :

Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php

What does that do ?

If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.

2) index.php

Now, we want to know what action to trigger, so we need to read the URL :

In index.php :

// index.php    

// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);

for ($i= 0; $i < sizeof($scriptName); $i++)
{
    if ($requestURI[$i] == $scriptName[$i])
    {
        unset($requestURI[$i]);
    }
}

$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :

// index.php

require_once("profile.php"); // We need this file
switch($command[0])
{
    case ‘profile’ :
        // We run the profile function from the profile.php file.
        profile($command([1]);
        break;
    case ‘myprofile’ :
        // We run the myProfile function from the profile.php file.
        myProfile();
        break;
    default:
        // Wrong page ! You could also redirect to your custom 404 page.
        echo "404 Error : wrong page.";
        break;
}

2) profile.php

Now in the profile.php file, we should have something like this :

// profile.php

function profile($chars)
{
    // We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)

    if (is_int($chars)) {
        $id = $chars;
        // Do the SQL to get the $user from his ID
        // ........
    } else {
        $username = mysqli_real_escape_string($char);
        // Do the SQL to get the $user from his username
        // ...........
    }

    // Render your view with the $user variable
    // .........
}

function myProfile()
{
    // Get the currently logged-in user ID from the session :
    $id = ....

    // Run the above function :
    profile($id);
}

Does React Native styles support gradients?

Here is a good choice for gradients for both platforms iOS and Android:

https://github.com/react-native-community/react-native-linear-gradient

There are others approaches like expo, however react-native-linear-gradient have worked better for me.

<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style={styles.linearGradient}>
  <Text style={styles.buttonText}>
    Sign in with Facebook
  </Text>
</LinearGradient>

// Later on in your styles..
var styles = StyleSheet.create({
  linearGradient: {
    flex: 1,
    paddingLeft: 15,
    paddingRight: 15,
    borderRadius: 5
  },
  buttonText: {
    fontSize: 18,
    fontFamily: 'Gill Sans',
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
});

Changing the width of Bootstrap popover

In bootstrap 4 you can simply override default value of bootstrap variable $popover-max-width in your styles.scss file like so:

$popover-max-width: 300px;

@import "node_modules/bootstrap/scss/functions";
@import "node_modules/bootstrap/scss/variables";
@import "node_modules/bootstrap/scss/mixins";
@import "node_modules/bootstrap/scss/popover";

More on overriding bootstrap 4 defaults https://getbootstrap.com/docs/4.0/getting-started/theming/#variable-defaults

Detect if an element is visible with jQuery

You're looking for:

.is(':visible')

Although you should probably change your selector to use jQuery considering you're using it in other places anyway:

if($('#testElement').is(':visible')) {
    // Code
}

It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible') on the child will return false (which makes sense).

jQuery 3

:visible has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible):

Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!

Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.


Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle():

function toggleTestElement() {
    $('#testElement').fadeToggle('fast');
}

Find Oracle JDBC driver in Maven repository

I ship opensource under LGPLv2 and even after several email conversations with Oracle they were unclear whether I was allowed to ship their binary JDBC driver with my distribution. The issue related to whether my license was compatible with their OTN terms so they suggested I was not permitted to ship the driver. Presumably related to this part

(b) to distribute the programs with applications you have developed to your customers provided that each such licensee agrees to license terms consistent with the terms of this Agreement

So even if you manage to publish the driver legally in your exclusive/local maven repository there is still the restriction on what you are permitted to do with that artifact. Seems absurd that even if I ship their driver in binary form along with the full OTN license file I still can't use it and must force my users to manually download the Oracle driver and drop into my library path before they can use my software.

How to get Bitmap from an Uri?

. . IMPORTANT: See answer from @Mark Ingram below and @pjv for at better solution. . .

You could try this:

public Bitmap loadBitmap(String url)
{
    Bitmap bm = null;
    InputStream is = null;
    BufferedInputStream bis = null;
    try 
    {
        URLConnection conn = new URL(url).openConnection();
        conn.connect();
        is = conn.getInputStream();
        bis = new BufferedInputStream(is, 8192);
        bm = BitmapFactory.decodeStream(bis);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
    finally {
        if (bis != null) 
        {
            try 
            {
                bis.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
        if (is != null) 
        {
            try 
            {
                is.close();
            }
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
    return bm;
}

But remember, this method should only be called from within a thread (not GUI -thread). I a AsyncTask.

java.lang.IllegalArgumentException: contains a path separator

String all = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String strLine;
            while ((strLine = br.readLine()) != null){
                all = all + strLine;
            }
        } catch (IOException e) {
            Log.e("notes_err", e.getLocalizedMessage());
        }

What is the Simplest Way to Reverse an ArrayList?

Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

 public ArrayList<Object> reverse(ArrayList<Object> list) {

   for (int i = 0; i < list.size() / 2; i++) {
     Object temp = list.get(i);
     list.set(i, list.get(list.size() - i - 1));
     list.set(list.size() - i - 1, temp);
   }

   return list;
 }

Regular Expression: Any character that is NOT a letter or number

Have you tried str = str.replace(/\W|_/g,''); it will return a string without any character and you can specify if any especial character after the pipe bar | to catch them as well.

var str = "1324567890abc§$)% John Doe #$@'.replace(/\W|_/g, ''); it will return str = 1324567890abcJohnDoe

or look for digits and letters and replace them for empty string (""):

var str = "1324567890abc§$)% John Doe #$@".replace(/\w|_/g, ''); it will return str = '§$)% #$@';

Set an empty DateTime variable

You may want to use a nullable datetime. Datetime? someDate = null;

You may find instances of people using DateTime.Max or DateTime.Min in such instances, but I highly doubt you want to do that. It leads to bugs with edge cases, code that's harder to read, etc.

java.io.FileNotFoundException: the system cannot find the file specified

Make sure when you create a txt file you don't type in the name "name.txt", just type in "name". If you type "name.txt" Eclipse will see it as "name.txt.txt". This solved it for me. Also save the file in the src folder, not the folder were the .java resides, one folder up.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

Excel Encodings

I found the WINDOWS-1252 encoding to be the least frustrating when dealing with Excel. Since its basically Microsofts own proprietary character set, one can assume it will work on both the Mac and the Windows version of MS-Excel. Both versions at least include a corresponding "File origin" or "File encoding" selector which correctly reads the data.

Depending on your system and the tools you use, this encoding could also be named CP1252, ANSI, Windows (ANSI), MS-ANSI or just Windows, among other variations.

This encoding is a superset of ISO-8859-1 (aka LATIN1 and others), so you can fallback to ISO-8859-1 if you cannot use WINDOWS-1252 for some reason. Be advised that ISO-8859-1 is missing some characters from WINDOWS-1252 as shown here:

| Char | ANSI | Unicode | ANSI Hex | Unicode Hex | HTML entity | Unicode Name                               | Unicode Range            |
| €    | 128  | 8364    | 0x80     | U+20AC      | &euro;      | euro sign                                  | Currency Symbols         |
| ‚    | 130  | 8218    | 0x82     | U+201A      | &sbquo;     | single low-9 quotation mark                | General Punctuation      |
| ƒ    | 131  | 402     | 0x83     | U+0192      | &fnof;      | Latin small letter f with hook             | Latin Extended-B         |
| „    | 132  | 8222    | 0x84     | U+201E      | &bdquo;     | double low-9 quotation mark                | General Punctuation      |
| …    | 133  | 8230    | 0x85     | U+2026      | &hellip;    | horizontal ellipsis                        | General Punctuation      |
| †    | 134  | 8224    | 0x86     | U+2020      | &dagger;    | dagger                                     | General Punctuation      |
| ‡    | 135  | 8225    | 0x87     | U+2021      | &Dagger;    | double dagger                              | General Punctuation      |
| ˆ    | 136  | 710     | 0x88     | U+02C6      | &circ;      | modifier letter circumflex accent          | Spacing Modifier Letters |
| ‰    | 137  | 8240    | 0x89     | U+2030      | &permil;    | per mille sign                             | General Punctuation      |
| Š    | 138  | 352     | 0x8A     | U+0160      | &Scaron;    | Latin capital letter S with caron          | Latin Extended-A         |
| ‹    | 139  | 8249    | 0x8B     | U+2039      | &lsaquo;    | single left-pointing angle quotation mark  | General Punctuation      |
| Π   | 140  | 338     | 0x8C     | U+0152      | &OElig;     | Latin capital ligature OE                  | Latin Extended-A         |
| Ž    | 142  | 381     | 0x8E     | U+017D      |             | Latin capital letter Z with caron          | Latin Extended-A         |
| ‘    | 145  | 8216    | 0x91     | U+2018      | &lsquo;     | left single quotation mark                 | General Punctuation      |
| ’    | 146  | 8217    | 0x92     | U+2019      | &rsquo;     | right single quotation mark                | General Punctuation      |
| “    | 147  | 8220    | 0x93     | U+201C      | &ldquo;     | left double quotation mark                 | General Punctuation      |
| ”    | 148  | 8221    | 0x94     | U+201D      | &rdquo;     | right double quotation mark                | General Punctuation      |
| •    | 149  | 8226    | 0x95     | U+2022      | &bull;      | bullet                                     | General Punctuation      |
| –    | 150  | 8211    | 0x96     | U+2013      | &ndash;     | en dash                                    | General Punctuation      |
| —    | 151  | 8212    | 0x97     | U+2014      | &mdash;     | em dash                                    | General Punctuation      |
| ˜    | 152  | 732     | 0x98     | U+02DC      | &tilde;     | small tilde                                | Spacing Modifier Letters |
| ™    | 153  | 8482    | 0x99     | U+2122      | &trade;     | trade mark sign                            | Letterlike Symbols       |
| š    | 154  | 353     | 0x9A     | U+0161      | &scaron;    | Latin small letter s with caron            | Latin Extended-A         |
| ›    | 155  | 8250    | 0x9B     | U+203A      | &rsaquo;    | single right-pointing angle quotation mark | General Punctuation      |
| œ    | 156  | 339     | 0x9C     | U+0153      | &oelig;     | Latin small ligature oe                    | Latin Extended-A         |
| ž    | 158  | 382     | 0x9E     | U+017E      |             | Latin small letter z with caron            | Latin Extended-A         |
| Ÿ    | 159  | 376     | 0x9F     | U+0178      | &Yuml;      | Latin capital letter Y with diaeresis      | Latin Extended-A         |

Note that the euro sign is missing. This table can be found at Alan Wood.

Conversion

Conversion is done differently in every tool and language. However, suppose you have a file query_result.csv which you know is UTF-8 encoded. Convert it to WINDOWS-1252 using iconv:

iconv -f UTF-8 -t WINDOWS-1252 query_result.csv > query_result-win.csv

Get list of passed arguments in Windows batch script (.bat)

If you have parameters in quotes that containing spaces, %* will not work correctly. The best solution I found is to have a loop that joins all arguments: https://serverfault.com/a/22541

set args=%1
shift
:start
if [%1] == [] goto done
set args=%args% %1
shift
goto start

:done
(use %args% here)

Converting an OpenCV Image to Black and White

Pay attention, if you use cv.CV_THRESH_BINARY means every pixel greater than threshold becomes the maxValue (in your case 255), otherwise the value is 0. Obviously if your threshold is 0 everything becomes white (maxValue = 255) and if the value is 255 everything becomes black (i.e. 0).

If you don't want to work out a threshold, you can use the Otsu's method. But this algorithm only works with 8bit images in the implementation of OpenCV. If your image is 8bit use the algorithm like this:

cv.Threshold(im_gray_mat, im_bw_mat, threshold, 255, cv.CV_THRESH_BINARY | cv.CV_THRESH_OTSU);

No matter the value of threshold if you have a 8bit image.

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

flash message after redirect will available in controller not in view. to show in view get in controller's action and pass it view

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

How to move a file?

  import os,shutil

  current_path = "" ## source path

  new_path = "" ## destination path

  os.chdir(current_path)

  for files in os.listdir():

        os.rename(files, new_path+'{}'.format(f))
        shutil.move(files, new_path+'{}'.format(f)) ## to move files from 

different disk ex. C: --> D:

How to import and export components using React + ES6 + webpack?

Try defaulting the exports in your components:

import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class MyNavbar extends React.Component {
    render(){
      return (
        <Navbar className="navbar-dark" fluid>
        ...
        </Navbar>
      );
    }
}

by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

Understanding ibeacon distancing

The iBeacon output power is measured (calibrated) at a distance of 1 meter. Let's suppose that this is -59 dBm (just an example). The iBeacon will include this number as part of its LE advertisment.

The listening device (iPhone, etc), will measure the RSSI of the device. Let's suppose, for example, that this is, say, -72 dBm.

Since these numbers are in dBm, the ratio of the power is actually the difference in dB. So:

ratio_dB = txCalibratedPower - RSSI

To convert that into a linear ratio, we use the standard formula for dB:

ratio_linear = 10 ^ (ratio_dB / 10)

If we assume conservation of energy, then the signal strength must fall off as 1/r^2. So:

power = power_at_1_meter / r^2. Solving for r, we get:

r = sqrt(ratio_linear)

In Javascript, the code would look like this:

function getRange(txCalibratedPower, rssi) {
    var ratio_db = txCalibratedPower - rssi;
    var ratio_linear = Math.pow(10, ratio_db / 10);

    var r = Math.sqrt(ratio_linear);
    return r;
}

Note, that, if you're inside a steel building, then perhaps there will be internal reflections that make the signal decay slower than 1/r^2. If the signal passes through a human body (water) then the signal will be attenuated. It's very likely that the antenna doesn't have equal gain in all directions. Metal objects in the room may create strange interference patterns. Etc, etc... YMMV.

Is there any boolean type in Oracle databases?

If you are using Java with Hibernate then using NUMBER(1,0) is the best approach. As you can see in here, this value is automatically translated to Boolean by Hibernate.

Multiline string literal in C#

If you don't want spaces/newlines, string addition seems to work:

var myString = String.Format(
  "hello " + 
  "world" +
  " i am {0}" +
  " and I like {1}.",
  animalType,
  animalPreferenceType
);
// hello world i am a pony and I like other ponies.

You can run the above here if you like.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

I agree with what seems to be the consensus here (return null if "not found" is a normal possible outcome, or throw an exception if the semantics of the situation require that the object always be found).

There is, however, a third possibility that might make sense depending on your particular situation. Your method could return a default object of some sort in the "not found" condition, allowing calling code to be assured that it will always receive a valid object without the need for null checking or exception catching.

How to style icon color, size, and shadow of Font Awesome Icons

I would not advice you to use built in font-awesome styling like the fa-5x etc; for fear they may change it and you would have to keep chainging your application code to meet up with the latest standard. You simply avoid this by giving each font-awesome class you want to style uniformly the same class say:

<i class="fa fa-facebook-square fa-sabi-social-icons" aria-hidden="true"></i>
<i class="fa fa-twitter-square fa-sabi-social-icons" aria-hidden="true"></i>
<i class="fa fa-google-plus-square fa-sabi-social-icons" aria-hidden="true"></i>

Here the class is fa-sabi-social-icons

Then in your css you can the style the fonts using the same css rules you would style a normal font with. e.g

.fa-sabi-social-icons {
     color: //your color;
     font-size: // your font-size in px, em or %;
     text-shadow: 2px 2px #FF0000;
}

That should get your font-awesome fonts styled

How to save a BufferedImage as a File

As a one liner:

ImageIO.write(Scalr.resize(ImageIO.read(...), 150));

Regex to match alphanumeric and spaces

This:

string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);

\x20 is ascii hex for 'space' character

you can add more individual characters that you want to be allowed. If you want for example "?" to be ok in the return string add \x3f.

How to use wget in php?

Shellwrap is great tool for using the command-line in PHP!

Your example can be done quite easy and readable:

use MrRio\ShellWrap as sh;

$xml = (string)sh::curl(['u' => 'user:pass'], 'http://example.com/file.xml');

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

Where is Android Studio layout preview?

File>>setting>>Compiler>>JavaCompiler At "Project bytecode version(leave blank for jdk default):" choose your jdk.

enter image description here

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

Getting the name / key of a JToken with JSON.net

JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)

Putting it all together we have:

JArray array = JArray.Parse(json);

foreach (JObject content in array.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        Console.WriteLine(prop.Name);
    }
}

Output:

MobileSiteContent
PageContent

Effective way to find any file's Encoding

Providing the implementation details for the steps proposed by @CodesInChaos:

1) Check if there is a Byte Order Mark

2) Check if the file is valid UTF8

3) Use the local "ANSI" codepage (ANSI as Microsoft defines it)

Step 2 works because most non ASCII sequences in codepages other that UTF8 are not valid UTF8. https://stackoverflow.com/a/4522251/867248 explains the tactic in more details.

using System; using System.IO; using System.Text;

// Using encoding from BOM or UTF8 if no BOM found,
// check if the file is valid, by reading all lines
// If decoding fails, use the local "ANSI" codepage

public string DetectFileEncoding(Stream fileStream)
{
    var Utf8EncodingVerifier = Encoding.GetEncoding("utf-8", new EncoderExceptionFallback(), new DecoderExceptionFallback());
    using (var reader = new StreamReader(fileStream, Utf8EncodingVerifier,
           detectEncodingFromByteOrderMarks: true, leaveOpen: true, bufferSize: 1024))
    {
        string detectedEncoding;
        try
        {
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
            }
            detectedEncoding = reader.CurrentEncoding.BodyName;
        }
        catch (Exception e)
        {
            // Failed to decode the file using the BOM/UT8. 
            // Assume it's local ANSI
            detectedEncoding = "ISO-8859-1";
        }
        // Rewind the stream
        fileStream.Seek(0, SeekOrigin.Begin);
        return detectedEncoding;
   }
}


[Test]
public void Test1()
{
    Stream fs = File.OpenRead(@".\TestData\TextFile_ansi.csv");
    var detectedEncoding = DetectFileEncoding(fs);

    using (var reader = new StreamReader(fs, Encoding.GetEncoding(detectedEncoding)))
    {
       // Consume your file
        var line = reader.ReadLine();
        ...

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

Generate Json schema from XML schema (XSD)

Copy your XML schema here & get the JSON schema code to the online tools which are available to generate JSON schema from XML schema.

How to convert an image to base64 encoding?

Here is the code for upload to encode and save it to the MySQL

if (!isset($_GET["getfile"])) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "<br>";
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);

        $bin_string = file_get_contents($_FILES["file"]["name"]);
        $hex_string = base64_encode($bin_string);
        $mysqli = mysqli_init();

        if (!$mysqli->real_connect('localhost', 'root', '', 'arihant')) {
            die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
        }

        $mysqli->query("INSERT INTO upload(image) VALUES ('" . $hex_string . "')");
    }
}

For showing the image use this

echo "<img src='data:image/jpeg;base64, $image' width=300>";

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

If you are using AS 3.1 the new build graphical console isn't very helpful for finding out the source of the problem.

you need to click on toggle view and see the logs in text format to see the error and if needed to Run with --stacktrace

enter image description here

Converting a generic list to a CSV string

For whatever reason, @AliUmair reverted the edit to his answer that fixes his code that doesn't run as is, so here is the working version that doesn't have the file access error and properly handles null object property values:

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
    if (list == null || list.Count == 0) return;

    //get type from 0th member
    Type t = list[0].GetType();
    string newLine = Environment.NewLine;

    if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));

    using (var sw = new StreamWriter(csvCompletePath))
    {
        //make a new instance of the class name we figured out to get its props
        object o = Activator.CreateInstance(t);
        //gets all properties
        PropertyInfo[] props = o.GetType().GetProperties();

        //foreach of the properties in class above, write out properties
        //this is the header row
        sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);

        //this acts as datarow
        foreach (T item in list)
        {
            //this acts as datacolumn
            var row = string.Join(",", props.Select(d => $"\"{item.GetType().GetProperty(d.Name).GetValue(item, null)?.ToString()}\"")
                                                    .ToArray());
            sw.Write(row + newLine);

        }
    }
}

how do you view macro code in access?

You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText

Option Compare Database

Option Explicit

Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects

    Dim db As Database
    Dim d As Document
    Dim c As Container
    Dim sExportLocation As String

    Set db = CurrentDb()

    sExportLocation = "C:\SomeFolder\"
    Set c = db.Containers("Scripts")
    For Each d In c.Documents
        Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
    Next d

An alternative object to use is as follows:

  For Each obj In Access.Application.CurrentProject.AllMacros
    Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"
  Next

Calculating how many minutes there are between two times

double minutes = varTime.TotalMinutes;
int minutesRounded = (int)Math.Round(varTime.TotalMinutes);

TimeSpan.TotalMinutes: The total number of minutes represented by this instance.

HTML CSS How to stop a table cell from expanding

Simply set the max-width attribute to 280px like this:

<td align="left" valign="top" style="overflow:hidden;" nowrap="nowrap" max-width="280px" width="280px">

This will solve your problem.

php error: Class 'Imagick' not found

Install Imagic in PHP7:

sudo apt-get install php-imagick

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

@denver_citizen and @Peter Szanto's answers didn't quite work for me, but I modified them to account for:

  1. Composite Keys
  2. On Delete and On Update actions
  3. Checking the index when re-adding
  4. Schemas other than dbo
  5. Multiple tables at once
DECLARE @Debug bit = 0;

-- List of tables to truncate
select
    SchemaName, Name
into #tables
from (values 
    ('schema', 'table')
    ,('schema2', 'table2')
) as X(SchemaName, Name)


BEGIN TRANSACTION TruncateTrans;

with foreignKeys AS (
     SELECT 
        SCHEMA_NAME(fk.schema_id) as SchemaName
        ,fk.Name as ConstraintName
        ,OBJECT_NAME(fk.parent_object_id) as TableName
        ,SCHEMA_NAME(t.SCHEMA_ID) as ReferencedSchemaName
        ,OBJECT_NAME(fk.referenced_object_id) as ReferencedTableName
        ,fc.constraint_column_id
        ,COL_NAME(fk.parent_object_id, fc.parent_column_id) AS ColumnName
        ,COL_NAME(fk.referenced_object_id, fc.referenced_column_id) as ReferencedColumnName
        ,fk.delete_referential_action_desc
        ,fk.update_referential_action_desc
    FROM sys.foreign_keys AS fk
        JOIN sys.foreign_key_columns AS fc
            ON fk.object_id = fc.constraint_object_id
        JOIN #tables tbl 
            ON OBJECT_NAME(fc.referenced_object_id) = tbl.Name
        JOIN sys.tables t on OBJECT_NAME(t.object_id) = tbl.Name 
            and SCHEMA_NAME(t.schema_id) = tbl.SchemaName
            and t.OBJECT_ID = fc.referenced_object_id
)



select
    quotename(fk.ConstraintName) AS ConstraintName
    ,quotename(fk.SchemaName) + '.' + quotename(fk.TableName) AS TableName
    ,quotename(fk.ReferencedSchemaName) + '.' + quotename(fk.ReferencedTableName) AS ReferencedTableName
    ,replace(fk.delete_referential_action_desc, '_', ' ') AS DeleteAction
    ,replace(fk.update_referential_action_desc, '_', ' ') AS UpdateAction
    ,STUFF((
        SELECT ',' + quotename(fk2.ColumnName)
        FROM foreignKeys fk2 
        WHERE fk2.ConstraintName = fk.ConstraintName and fk2.SchemaName = fk.SchemaName
        ORDER BY fk2.constraint_column_id
        FOR XML PATH('')
    ),1,1,'') AS ColumnNames
    ,STUFF((
        SELECT ',' + quotename(fk2.ReferencedColumnName)
        FROM foreignKeys fk2 
        WHERE fk2.ConstraintName = fk.ConstraintName and fk2.SchemaName = fk.SchemaName
        ORDER BY fk2.constraint_column_id
        FOR XML PATH('')
    ),1,1,'') AS ReferencedColumnNames
into #FKs
from foreignKeys fk
GROUP BY fk.SchemaName, fk.ConstraintName, fk.TableName, fk.ReferencedSchemaName, fk.ReferencedTableName, fk.delete_referential_action_desc, fk.update_referential_action_desc



-- Drop FKs
select 
    identity(int,1,1) as ID,
    'ALTER TABLE ' + fk.TableName + ' DROP CONSTRAINT ' + fk.ConstraintName AS script
into #scripts
from #FKs fk

-- Truncate 
insert into #scripts
select distinct 
    'TRUNCATE TABLE ' + quotename(tbl.SchemaName) + '.' + quotename(tbl.Name) AS script
from #tables tbl

-- Recreate
insert into #scripts
select 
    'ALTER TABLE ' + fk.TableName + 
    ' WITH CHECK ADD CONSTRAINT ' + fk.ConstraintName + 
    ' FOREIGN KEY ('+ fk.ColumnNames +')' + 
    ' REFERENCES ' + fk.ReferencedTableName +' ('+ fk.ReferencedColumnNames +')' +
    ' ON DELETE ' + fk.DeleteAction COLLATE Latin1_General_CI_AS_KS_WS + ' ON UPDATE ' + fk.UpdateAction COLLATE Latin1_General_CI_AS_KS_WS AS script
from #FKs fk


DECLARE @script nvarchar(MAX);

DECLARE curScripts CURSOR FOR 
    select script
    from #scripts
    order by ID

OPEN curScripts

WHILE 1=1 BEGIN
    FETCH NEXT FROM curScripts INTO @script
    IF @@FETCH_STATUS != 0 BREAK;

    print @script;
    IF @Debug = 0
        EXEC (@script);
END
CLOSE curScripts
DEALLOCATE curScripts


drop table #scripts
drop table #FKs
drop table #tables


COMMIT TRANSACTION TruncateTrans;

How to fill Dataset with multiple tables?

Filling a DataSet with multiple tables can be done by sending multiple requests to the database, or in a faster way: Multiple SELECT statements can be sent to the database server in a single request. The problem here is that the tables generated from the queries have automatic names Table and Table1. However, the generated table names can be mapped to names that should be used in the DataSet.

SqlDataAdapter adapter = new SqlDataAdapter(
      "SELECT * FROM Customers; SELECT * FROM Orders", connection);
adapter.TableMappings.Add("Table", "Customer");
adapter.TableMappings.Add("Table1", "Order");

adapter.Fill(ds);

Clone() vs Copy constructor- which is recommended in java

Have in mind that clone() doesn't work out of the box. You will have to implement Cloneable and override the clone() method making in public.

There are a few alternatives, which are preferable (since the clone() method has lots of design issues, as stated in other answers), and the copy-constructor would require manual work:

How to NodeJS require inside TypeScript file?

Use typings to access node functions from TypeScript:

typings install env~node --global

If you don't have typings install it:

npm install typings --global

How to create cross-domain request?

Many long (and correct) answers here. But usually you won't do these things manually - at least not when you set up your first projects for development (this is where you usually stumble upon these things). If you use koa for the backend: use koa-cors. Install via npm...

npm install --save koa-cors

...and use it in the code:

const cors = require('koa-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors());

problem solved.

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

For an alternative cryptography library, have a look at Bouncy Castle. It has AES and a lot of added functionality. It's a liberal open source library. You will have to use the lightweight, proprietary Bouncy Castle API for this to work though.

ssh-copy-id no identities found error

The ssh-copy-id is not able to locate the id_rsa.pub file that is generated by ssh-keygen in your system, Use the following command to complete:

  1. find the path of the .pub file: locate *.pub
  2. copy the path (ex: /home/user_name/.ssh/id_rsa.pub) and run the following command: ssh-copy-id -i /home/user_name/.ssh/id_rsa.pub hostname

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

How to reset the bootstrap modal when it gets closed and open it fresh again?

you can try this

$('body').on('hidden.bs.modal', '.modal', function () {
     $(this).removeData('bs.modal');
});

It will remove all the data from the model and reset it.

How do I check that multiple keys are in a dict in a single pass?

>>> if 'foo' in foo and 'bar' in foo:
...     print 'yes'
... 
yes

Jason, () aren't necessary in Python.

Fatal error: Call to undefined function mysql_connect()

I had this same problem on RHEL6. It turns out that the mysql.ini file in /etc/php.d only had a module name but needed a full path name. On my RHEL6 system the entry that works is:

; Enable mysql extension module

extension=/usr/lib64/php/modules/mysql.so

After modifying the file, I restarted apache and everything worked.

LINQ Inner-Join vs Left-Join

If you actually have a database, this is the most-simple way:

var lsPetOwners = ( from person in context.People
                    from pets in context.Pets
                        .Where(mypet => mypet.Owner == person.ID) 
                        .DefaultIfEmpty()
                     select new { OwnerName = person.Name, Pet = pets.Name }
                   ).ToList();

What is the best way to measure execution time of a function?

Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.

How to do constructor chaining in C#

What is usage of "Constructor Chain"?
You use it for calling one constructor from another constructor.

How can implement "Constructor Chain"?
Use ": this (yourProperties)" keyword after definition of constructor. for example:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        /// ===== This method is "Chained Method" ===== ///
        this.requestCount= inputCount;
    }
}

Why is it useful?
Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property Suppose some property in class must be initialized with specific value (In our sample, requestDate). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.

How it work? (Or, What is execution sequence in "Constructor Chain")?
in above example, method "a" will be executed first, and then instruction sequence will return to method "b". In other word, above code is equal with below:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        // ===== This method is "Chained Method" ===== ///

        /// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
        this.requestCount= inputCount;
    }
}

How much faster is C++ than C#?

As usual, it depends on the application. There are cases where C# is probably negligibly slower, and other cases where C++ is 5 or 10 times faster, especially in cases where operations can be easily SIMD'd.

How to find server name of SQL Server Management Studio

As mentioned by @Khaneddy2013, the cmd SQLCMD -L returns no server name when I run. Bcz I only have installed the SSMS (local db and server were not installed). After tried installing SqlLocaLDB and SQLEXPR32_x86_ENU(32 bit OS) I was able to connect. And now the cmd window shows the server names too. enter image description here

Get column index from column name in python pandas

In case you want the column name from the column location (the other way around to the OP question), you can use:

>>> df.columns.get_values()[location]

Using @DSM Example:

>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

>>> df.columns

Index(['apple', 'orange', 'pear'], dtype='object')

>>> df.columns.get_values()[1]

'orange'

Other ways:

df.iloc[:,1].name

df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.) 

IE6/IE7 css border on select element

It solves to me, for my purposes:

.select-container {
  position:relative;
  width:200px;
  height:18px;
  overflow:hidden;
  border:1px solid white !important
}
.select-container select {
  position:relative;
  left:-2px;
  top:-2px
}

To put more style will be necessary to use nested divs .

In WPF, what are the differences between the x:Name and Name attributes?

X:Name can cause memory issues if you have custom controls. It will keep a memory location for the NameScope entry.

I say never use x:Name unless you have to.

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

If I could, I would vote for the answer by Paulo. I tested it and understood the concept. I can confirm it works. The find command can output many parameters. For example, add the following to the --printf clause:

%a for attributes in the octal format
%n for the file name including a complete path

Example:

find Desktop/ -exec stat \{} --printf="%y %n\n" \; | sort -n -r | head -1
2011-02-14 22:57:39.000000000 +0100 Desktop/new file

Let me raise this question as well: Does the author of this question want to solve his problem using Bash or PHP? That should be specified.

Delete an element from a dictionary

The del statement is what you're looking for. If you have a dictionary named foo with a key called 'bar', you can delete 'bar' from foo like this:

del foo['bar']

Note that this permanently modifies the dictionary being operated on. If you want to keep the original dictionary, you'll have to create a copy beforehand:

>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}

The dict call makes a shallow copy. If you want a deep copy, use copy.deepcopy.

Here's a method you can copy & paste, for your convenience:

def minus_key(key, dictionary):
    shallow_copy = dict(dictionary)
    del shallow_copy[key]
    return shallow_copy

How can I avoid Java code in JSP files, using JSP 2?

No matter how much you try to avoid, when you work with other developers, some of them will still prefer scriptlet and then insert the evil code into the project. Therefore, setting up the project at the first sign is very important if you really want to reduce the scriptlet code. There are several techniques to get over this (including several frameworks that other mentioned). However, if you prefer the pure JSP way, then use the JSTL tag file. The nice thing about this is you can also set up master pages for your project, so the other pages can inherit the master pages

Create a master page called base.tag under your WEB-INF/tags with the following content

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>

<%@attribute name="title" fragment="true" %>

<html>
  <head>
    <title>  
       <jsp:invoke fragment="title"></jsp:invoke>
    </title>

  </head>
  <body>
    <div id="page-header">
       ....
    </div>
    <div id="page-body">
      <jsp:doBody/>
    </div>
    <div id="page-footer">
      .....
    </div>
  </body>
</html>

On this mater page, I created a fragment called "title", so that in the child page, I could insert more codes into this place of the master page. Also, the tag <jsp:doBody/> will be replaced by the content of the child page

Create child page (child.jsp) in your WebContent folder:

<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:base>
    <jsp:attribute name="title"> 
        <bean:message key="hello.world" />
    </jsp:attribute>

    <jsp:body>
    [Put your content of the child here]
    </jsp:body>   
</t:base>

<t:base> is used to specify the master page you want to use (which is base.tag at this moment). All the content inside the tag <jsp:body> here will replace the <jsp:doBody/> on your master page. Your child page can also include any tag lib and you can use it normally like the other mentioned. However, if you use any scriptlet code here (<%= request.getParameter("name") %> ...) and try to run this page, you will get a JasperException because Scripting elements ( &lt;%!, &lt;jsp:declaration, &lt;%=, &lt;jsp:expression, &lt;%, &lt;jsp:scriptlet ) are disallowed here. Therefore, there is no way other people can include the evil code into the jsp file

Calling this page from your controller:

You can easily call the child.jsp file from your controller. This also works nice with the struts framework

How can I do time/hours arithmetic in Google Spreadsheet?

Example of calculating time:

work-start   work-stop   lunchbreak    effective time

  07:30:00    17:00:00          1.5                 8  [=((A2-A1)*24)-A3]

If you subtract one time value from another the result you get will represent the fraction of 24 hours, so if you multiply the result with 24 you get the value represented in hours.

In other words: the operation is mutiply, but the meaning is to change the format of the number (from days to hours).

run program in Python shell

If you want to avoid writing all of this everytime, you can define a function :

def run(filename):
    exec(open(filename).read())

and then call it

run('filename.py')

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

Docker CE on RHEL - Requires: container-selinux >= 2.9

Docker CE is not supported on RHEL. Any way you are trying to get around that is not a supported way. You can see the supported platforms in the Docker Documentation. I suggest you either use a supported OS, or switch to Enterprise Edition.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

What is the meaning of CTOR?

It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor for the various constructors.

Multiple commands in an alias for bash

Try:

alias lock='gnome-screensaver; gnome-screensaver-command --lock'

or

lock() {
    gnome-screensaver
    gnome-screensaver-command --lock
}

in your .bashrc

The second solution allows you to use arguments.

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

Possible Duplicate Question

<@include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.

  • Only one servlet is executed at run time.
  • Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
  • The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
  • One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
  • A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.

<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.

  • Each included page is executed as a separate servlet at run time.
  • Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
  • The values of scriptlet variables need to be explicitly passed to the include page.
  • The included page must be able to be run on its own.
  • You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.

Depending on your needs, you may either use <@include> or <jsp:include>

How to check if a textbox is empty using javascript

Whatever method you choose is not freeing you from performing the same validation on at the back end.

How to test if a double is zero?

Numeric primitives in class scope are initialized to zero when not explicitly initialized.

Numeric primitives in local scope (variables in methods) must be explicitly initialized.

If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

if(value != 0)
    //divide by value is safe when value is not exactly zero.

Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

public boolean isZero(double value, double threshold){
    return value >= -threshold && value <= threshold;
}

How to pass a parameter to routerLink that is somewhere inside the URL?

app-routing.module.ts

const routes: Routes = [
  { path: 'products', component: ProductsComponent },
  { path: 'product/:id', component: ProductDetailsComponent },
  { path: '', redirectTo: '/products', pathMatch: 'full' },
];

In controller you can navigate like this,

this.router.navigate(['/products', productId]);

It will land you to path like this: http://localhost:4200/products/product-id

Ref

Show git diff on file in staging area

You can also use git diff HEAD file to show the diff for a specific file.

See the EXAMPLE section under git-diff(1)

How to disassemble a binary executable in Linux to get the assembly code?

You can come pretty damn close (but no cigar) to generating assembly that will reassemble, if that's what you are intending to do, using this rather crude and tediously long pipeline trick (replace /bin/bash with the file you intend to disassemble and bash.S with what you intend to send the output to):

objdump --no-show-raw-insn -Matt,att-mnemonic -Dz /bin/bash | grep -v "file format" | grep -v "(bad)" | sed '1,4d' | cut -d' ' -f2- | cut -d '<' -f2 | tr -d '>' | cut -f2- | sed -e "s/of\ section/#Disassembly\ of\ section/" | grep -v "\.\.\." > bash.S

Note how long this is, however. I really wish there was a better way (or, for that matter, a disassembler capable of outputting code that an assembler will recognize), but unfortunately there isn't.

html table span entire width?

<table border="1"; width=100%>

works for me.

How can I create a "Please Wait, Loading..." animation using jQuery?

It is very simple.

HTML

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<body>

  <div id="cover"> <span class="glyphicon glyphicon-refresh w3-spin preloader-Icon"></span>Please Wait, Loading…</div>

  <h1>Dom Loaded</h1>
</body>

CSS

#cover {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background: #141526;
  z-index: 9999;
  font-size: 65px;
  text-align: center;
  padding-top: 200px;
  color: #fff;
  font-family:tahoma;
}

JS - JQuery

$(window).on('load', function () {
  $("#cover").fadeOut(1750);
});

Where can I download english dictionary database in a text format?

user1247808 has a good link with: wget -c

http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip

If that isn't enough words for you:

http://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-all-titles-in-ns0.gz (updated url from Michael Kropat's suggestion)

Although that file name changes, you'll want to find the latest ... that turns out just to be a big (very big) text file.

http://dumps.wikimedia.org/enwiktionary/

How do I change Bootstrap 3 column order on mobile layout?

The answers here work for just 2 cells, but as soon as those columns have more in them it can lead to a bit more complexity. I think I've found a generalized solution for any number of cells in multiple columns.

#Goals Get a vertical sequence of tags on mobile to arrange themselves in whatever order the design calls for on tablet/desktop. In this concrete example, one tag must enter flow earlier than it normally would, and another later than it normally would.

##Mobile

[1 headline]
[2 image]
[3 qty]
[4 caption]
[5 desc]

##Tablet+

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][5 desc    ]
[4 caption][          ]
[         ][          ]

So headline needs to shuffle right on tablet+, and technically, so does desc - it sits above the caption tag that precedes it on mobile. You'll see in a moment 4 caption is in trouble too.

Let's assume every cell could vary in height, and needs to be flush top-to-bottom with its next cell (ruling out weak tricks like a table).

As with all Bootstrap Grid problems step 1 is to realize the HTML has to be in mobile-order, 1 2 3 4 5, on the page. Then, determine how to get tablet/desktop to reorder itself in this way - ideally without Javascript.

The solution to get 1 headline and 3 qty to sit to the right not the left is to simply set them both pull-right. This applies CSS float: right, meaning they find the first open space they'll fit to the right. You can think of the browser's CSS processor working in the following order: 1 fits in to the right top corner. 2 is next and is regular (float: left), so it goes to top-left corner. Then 3, which is float: right so it leaps over underneath 1.

But this solution wasn't enough for 4 caption; because the right 2 cells are so short 2 image on the left tends to be longer than the both of them combined. Bootstrap Grid is a glorified float hack, meaning 4 caption is float: left. With 2 image occupying so much room on the left, 4 caption attempts to fit in the next available space - often the right column, not the left where we wanted it.

The solution here (and more generally for any issue like this) was to add a hack tag, hidden on mobile, that exists on tablet+ to push caption out, that then gets covered up by a negative margin - like this:

[2 image  ][1 headline]
[         ][3 qty     ]
[         ][4 hack    ]
[5 caption][6 desc ^^^]
[         ][          ]

http://jsfiddle.net/b9chris/52VtD/16633/

HTML:

<div id=headline class="col-xs-12 col-sm-6 pull-right">Product Headline</div>
<div id=image class="col-xs-12 col-sm-6">Product Image</div>
<div id=qty class="col-xs-12 col-sm-6 pull-right">Qty, Add to cart</div>
<div id=hack class="hidden-xs col-sm-6">Hack</div>
<div id=caption class="col-xs-12 col-sm-6">Product image caption</div>
<div id=desc class="col-xs-12 col-sm-6 pull-right">Product description</div>

CSS:

#hack { height: 50px; }

@media (min-width: @screen-sm) {
    #desc { margin-top: -50px; }
}

So, the generalized solution here is to add hack tags that can disappear on mobile. On tablet+ the hack tags allow displayed tags to appear earlier or later in the flow, then get pulled up or down to cover up those hack tags.

Note: I've used fixed heights for the sake of the simple example in the linked jsfiddle, but the actual site content I was working on varies in height in all 5 tags. It renders properly with relatively large variance in tag heights, especially image and desc.

Note 2: Depending on your layout, you may have a consistent enough column order on tablet+ (or larger resolutions), that you can avoid use of hack tags, using margin-bottom instead, like so:

Note 3: This uses Bootstrap 3. Bootstrap 4 uses a different grid set, and won't work with these examples.

http://jsfiddle.net/b9chris/52VtD/16632/

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

You can also change the index name in column definitions within a create_table block (such as you get from the migration generator).

create_table :studies do |t|
  t.references :user, index: {:name => "index_my_shorter_name"}
end

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

gmdate() is doing exactly what you asked for.

Look at formats here: http://php.net/manual/en/function.gmdate.php

Get first date of current month in java

In Java 8 you can use:

LocalDate date = LocalDate.now(); //2020-01-12
date.withDayOfMonth(1); //2020-01-01

How to sort a Collection<T>?

A Collection does not have an ordering, so wanting to sort it does not make sense. You can sort List instances and arrays, and the methods to do that are Collections.sort() and Arrays.sort()

How to navigate to a section of a page

Use HTML's anchors:

Main Page:

<a href="sample.html#sushi">Sushi</a>
<a href="sample.html#bbq">BBQ</a>

Sample Page:

<div id='sushi'><a name='sushi'></a></div>
<div id='bbq'><a name='bbq'></a></div>

Splitting a continuous variable into equal sized groups

You can also use the bin function with method = "content" from the OneR package for that:

library(OneR)
das$wt_2 <- as.numeric(bin(das$wt, nbins = 3, method = "content"))
das
##    anim    wt wt_2
## 1     1 181.0    1
## 2     2 179.0    1
## 3     3 180.5    1
## 4     4 201.0    2
## 5     5 201.5    2
## 6     6 245.0    2
## 7     7 246.4    3
## 8     8 189.3    1
## 9     9 301.0    3
## 10   10 354.0    3
## 11   11 369.0    3
## 12   12 205.0    2
## 13   13 199.0    1
## 14   14 394.0    3
## 15   15 231.3    2

ASP.NET MVC controller actions that return JSON or partial html

To answer the other half of the question, you can call:

return PartialView("viewname");

when you want to return partial HTML. You'll just have to find some way to decide whether the request wants JSON or HTML, perhaps based on a URL part/parameter.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Adding items to an object through the .push() method

stuff is an object and push is a method of an array. So you cannot use stuff.push(..).

Lets say you define stuff as an array stuff = []; then you can call push method on it.

This works because the object[key/value] is well formed.

stuff.push( {'name':$(this).attr('checked')} );

Whereas this will not work because the object is not well formed.

stuff.push( {$(this).attr('value'):$(this).attr('checked')} );

This works because we are treating stuff as an associative array and added values to it

stuff[$(this).attr('value')] = $(this).attr('checked');

How to disable submit button once it has been clicked?

I think easy way to disable button is :data => { disable_with: "Saving.." } This will submit a form and then make a button disable, Also it won't disable button if you have any validations like required = 'required'.

Java Delegates?

Yes & No, but delegate pattern in Java could be thought of this way. This video tutorial is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces.

Java Interface

Spring MVC: How to return image in @ResponseBody?

In addition to registering a ByteArrayHttpMessageConverter, you may want to use a ResponseEntity instead of @ResponseBody. The following code works for me :

@RequestMapping("/photo2")
public ResponseEntity<byte[]> testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}

How do I get the value of a registry key and ONLY the value using powershell

Following code will enumerate all values for a certain Registry key, will sort them and will return value name : value pairs separated by colon (:):

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework';

Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
    $command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_);
    $value = Invoke-Expression -Command $command;
    $_ + ' : ' + $value; };

Like this:

DbgJITDebugLaunchSetting : 16

DbgManagedDebugger : "C:\Windows\system32\vsjitdebugger.exe" PID %d APPDOM %d EXTEXT "%s" EVTHDL %d

InstallRoot : C:\Windows\Microsoft.NET\Framework\

npm ERR cb() never called

Check if you have multiple versions of the npm command in your system path variable.

In my case, I had a version in the Node install directory and an older one in the npm globals install directory (called prefix in the npm config file). So I checked npm config get prefix for the location and deleted the link and the npm folder from node_modules. (Deleting the other one might also work, depending on the order in your PATH variable.)

How to use greater than operator with date?

In your statement, you are comparing a string called start_date with the time.
If start_date is a column, it should either be

 
  SELECT * FROM `la_schedule` WHERE start_date >'2012-11-18';
 

(no apostrophe) or


SELECT * FROM `la_schedule` WHERE `start_date` >'2012-11-18';

(with backticks).

Hope this helps.

Convert an integer to an array of digits

The immediate problem is due to you using <= temp.length() instead of < temp.length(). However, you can achieve this a lot more simply. Even if you use the string approach, you can use:

String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
    newGuess[i] = temp.charAt(i) - '0';
}

You need to make the same change to use < newGuess.length() when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]. The vast majority of for loops I write use < in the condition, rather than <=.

How to remove focus border (outline) around text/input boxes? (Chrome)

The current answer didn't work for me with Bootstrap 3.1.1. Here's what I had to override:

.form-control:focus {
  border-color: inherit;
  -webkit-box-shadow: none;
  box-shadow: none;
}

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

For what it's worth - I had a similar issue, assuming it's related to a Chrome update.

I had to add font-src, and then specify the url because I was using a CDN

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; font-src 'self' data: fonts.gstatic.com;">

How to put space character into a string name in XML?

to use white space in xml as string use &#160;. XML won't take white space as it is. it will trim the white space before setting it. So use &#160; instead of single white space

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

The OutputPath property is not set for this project

You can see this error in VS 2008 if you have a project in your solution that references an assembly that cannot be found. This could happen if the assembly comes from another project that is not part of your solution but should be. In this case simply adding the correct project to the solution will solve it.

Check the References section of each project in your solution. If any of them has a reference with an red x next to it, then it you have found your problem. That assembly reference cannot be found by the solution.

The error message is a bit confusing but I've seen this many times.

How to get pip to work behind a proxy server

at least pip3 also works without "=", however, instead of "http" you might need "https"

Final command, which worked for me:

sudo pip3 install --proxy https://{proxy}:{port} {BINARY}

compilation error: identifier expected

You also will have to catch or throw the IOException. See below. Not always the best way, but it will get you a result:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

ImportError: No module named _ssl

Unrelated to the original question, but because this is the first Google result... I hit this on Google AppEngine and had to add:

libraries:
- name: ssl
  version: latest

to app.yaml per: https://cloud.google.com/appengine/docs/python/sockets/ssl_support

Please NOTE: This seems to work upto Python version 2.7.9 but not for 2.7.10 or 2.7.11.

How to set Default Controller in asp.net MVC 4 & MVC 5

Set below code in RouteConfig.cs in App_Start folder

public static void RegisterRoutes(RouteCollection routes)
{
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 routes.MapRoute(
 name: "Default",
 url: "{controller}/{action}/{id}",
 defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}

IF still not working then do below steps

Second Way : You simple follow below steps,

1) Right click on your Project

2) Select Properties

3) Select Web option and then Select Specific Page (Controller/View) and then set your login page

Here, Account is my controller and Login is my action method (saved in Account Controller)

Please take a look attachedenter image description here screenshot.

Best way to resolve file path too long exception

If you are having an issue with your bin files due to a long path, In Visual Studio 2015 you can go to the offending project's property page and change the relative Output Directory to a shorter one.

E.g. bin\debug\ becomes C:\_bins\MyProject\

How do I get the base URL with PHP?

You can do it like this, but sorry my english is not good enough.

First, get home base url with this simple code..

I've tested this code on my local server and public and the result is good.

<?php

function home_base_url(){   

// first get http protocol if http or https

$base_url = (isset($_SERVER['HTTPS']) &&

$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';

// get default website root directory

$tmpURL = dirname(__FILE__);

// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",

//convert value to http url use string replace, 

// replace any backslashes to slash in this case use chr value "92"

$tmpURL = str_replace(chr(92),'/',$tmpURL);

// now replace any same string in $tmpURL value to null or ''

// and will return value like /localhost/my_website/ or just /my_website/

$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);

// delete any slash character in first and last of value

$tmpURL = ltrim($tmpURL,'/');

$tmpURL = rtrim($tmpURL, '/');


// check again if we find any slash string in value then we can assume its local machine

    if (strpos($tmpURL,'/')){

// explode that value and take only first value

       $tmpURL = explode('/',$tmpURL);

       $tmpURL = $tmpURL[0];

      }

// now last steps

// assign protocol in first value

   if ($tmpURL !== $_SERVER['HTTP_HOST'])

// if protocol its http then like this

      $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';

    else

// else if protocol is https

      $base_url .= $tmpURL.'/';

// give return value

return $base_url; 

}

?>

// and test it

echo home_base_url();

output will like this :

local machine : http://localhost/my_website/ or https://myhost/my_website 

public : http://www.my_website.com/ or https://www.my_website.com/

use home_base_url function at index.php of your website and define it

and then you can use this function to load scripts, css and content via url like

<?php

echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";

?>

will create output like this :

<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>

and if this script works fine,,!

Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

Radio Buttons ng-checked with ng-model

I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

The code from the example should not be difficult to adapt to your specific situation:

<script>
   function Ctrl($scope) {
      $scope.color = 'blue';
      $scope.specialValue = {
         "id": "12345",
         "value": "green"
      };
   }
</script>
<form name="myForm" ng-controller="Ctrl">
   <input type="radio" ng-model="color" value="red">  Red <br/>
   <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
   <input type="radio" ng-model="color" value="blue"> Blue <br/>
   <tt>color = {{color | json}}</tt><br/>
</form>

How to resize an image to fit in the browser window?

I know there's already a few answers here, but here is what I used:

max-width: 100%;
max-height: 100vh;
width: auto;
margin: auto;

How to get the Power of some Integer in Swift language?

Combining the answers into an overloaded set of functions (and using "**" instead of "^^" as some other languages use - clearer to me):

// http://stackoverflow.com/questions/24196689/how-to-get-the-power-of-some-integer-in-swift-language
// Put this at file level anywhere in your project
infix operator ** { associativity left precedence 160 }
func ** (radix: Double, power: Double) -> Double { return pow(radix, power) }
func ** (radix: Int,    power: Int   ) -> Double { return pow(Double(radix), Double(power)) }
func ** (radix: Float,  power: Float ) -> Double { return pow(Double(radix), Double(power)) }

When using Float, you may lose precision. If using numeric literals and a mix of integers and non-integers, you will end up with Double by default. I personally like the ability to use a mathematical expression instead of a function like pow(a, b) for stylistic/readability reasons, but that's just me.

Any operators that would cause pow() to throw an error will also cause these functions to throw an error, so the burden of error checking still lies with the code using the power function anyway. KISS, IMHO.

Using the native pow() function allows to eg take square roots (2 ** 0.5) or inverse (2 ** -3 = 1/8). Because of the possibility to use inverse or fractional exponents, I wrote all my code to return the default Double type of the pow() function, which should return the most precision (if I remember the documentation correctly). If needed, this can be type-casted down to Int or Float or whatever, possibly with the loss of precision.

2 ** -3  = 0.125
2 ** 0.5 = 1.4142135623731
2 ** 3   = 8

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

If any one is interested here is what query is executed by psql on postgres 9.1:

SELECT n.nspname as "Schema",
  p.proname as "Name",
  pg_catalog.pg_get_function_result(p.oid) as "Result data type",
  pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
 CASE
  WHEN p.proisagg THEN 'agg'
  WHEN p.proiswindow THEN 'window'
  WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
  ELSE 'normal'
 END as "Type"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;

You can get what psql runs for a backslash command by running psql with the -E flag.

How to parse the AndroidManifest.xml file inside an .apk package

If your into Python or use Androguard, the Androguard Androaxml feature will do this conversion for you. The feature is detailed in this blog post, with additional documentation here and source here.

Usage:

$ ./androaxml.py -h
Usage: androaxml.py [options]

Options:
-h, --help            show this help message and exit
-i INPUT, --input=INPUT
                      filename input (APK or android's binary xml)
-o OUTPUT, --output=OUTPUT
                      filename output of the xml
-v, --version         version of the API

$ ./androaxml.py -i yourfile.apk -o output.xml
$ ./androaxml.py -i AndroidManifest.xml -o output.xml

What's a standard way to do a no-op in python?

Use pass for no-op:

if x == 0:
  pass
else:
  print "x not equal 0"

And here's another example:

def f():
  pass

Or:

class c:
  pass

how to modify the size of a column

Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter statement exactly the way you originally had it works perfectly:

ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);

You only need to add parenthesis if you need to alter more than one column at once, such as:

ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));

Location of my.cnf file on macOS

I'm running MacOS Catalina(10.15.3) and find my.cnf in /usr/local/etc.

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch.

    http://github.com/user/repository/

-to-

http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

How to use ConcurrentLinkedQueue?

This is largely a duplicate of another question.

Here's the section of that answer that is relevant to this question:

Do I need to do my own synchronization if I use java.util.ConcurrentLinkedQueue?

Atomic operations on the concurrent collections are synchronized for you. In other words, each individual call to the queue is guaranteed thread-safe without any action on your part. What is not guaranteed thread-safe are any operations you perform on the collection that are non-atomic.

For example, this is threadsafe without any action on your part:

queue.add(obj);

or

queue.poll(obj);

However; non-atomic calls to the queue are not automatically thread-safe. For example, the following operations are not automatically threadsafe:

if(!queue.isEmpty()) {
   queue.poll(obj);
}

That last one is not threadsafe, as it is very possible that between the time isEmpty is called and the time poll is called, other threads will have added or removed items from the queue. The threadsafe way to perform this is like this:

synchronized(queue) {
    if(!queue.isEmpty()) {
       queue.poll(obj);
    }
}

Again...atomic calls to the queue are automatically thread-safe. Non-atomic calls are not.

Move_uploaded_file() function is not working

Try using copy() function instead of move_uploaded_file(). It worked for me.

copy($_FILES['file']['tmp_name'], $path);

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

Drawing circles with System.Drawing

     private void DrawEllipseRectangle(PaintEventArgs e)
        {
            Pen p = new Pen(Color.Black, 3);
            Rectangle r = new Rectangle(100, 100, 100, 100);
            e.Graphics.DrawEllipse(p, r);
        }
     private void Form1_Paint(object sender, PaintEventArgs e)
        {
            DrawEllipseRectangle(e);
        }

What is the difference between dynamic and static polymorphism in Java?

Compile time polymorphism(Static Binding/Early Binding): In static polymorphism, if we call a method in our code then which definition of that method is to be called actually is resolved at compile time only.

(or)

At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile-time polymorphism or static binding.

Dynamic Polymorphism(Late Binding/ Runtime Polymorphism): At run time, Java waits until runtime to determine which object is actually being pointed to by the reference. Method resolution was taken at runtime, due to that we call as run time polymorphism.

Add left/right horizontal padding to UILabel

Sometimes it's convenient to use UNICODE partial spaces to achieve alignment while prototyping. This can be handy in prototyping, proof-of-concept, or just to defer implementation of graphics algorithms.

If you use UNICODE spaces for convenience, be aware that at least one of the UNICODE spaces has a size based on the font it is displayed from, specifically the actual space character itself (U+0020, ASCII 32)

If you're using the default iOS system font in a UILabel, the default System font characteristics could change in a subsequent iOS release and suddenly introduce an unwanted misalignment by changing your app's precise spacing. This can and does happen, for example the "San Francisco" font replaced a previous iOS system font in an iOS release.

UNICODE easy to specify in Swift, for example:

let six_per_em_space = "\u{2006}"

Alternatively, cut/paste the space from an HTML page directly into the UILabel's text field in Interface Builder.

Note: Attached pic is a screenshot, not HTML, so visit the linked page if you want to cut/paste the space.

UNICODE spaces

How to get Device Information in Android

You may want to take a look at those pages : http://developer.android.com/reference/android/os/Build.html and http://developer.android.com/reference/java/lang/System.html (the getProperty() method might do the job).

For instance :

System.getProperty("os.version"); // OS version
android.os.Build.VERSION.SDK      // API Level
android.os.Build.DEVICE           // Device
android.os.Build.MODEL            // Model 
android.os.Build.PRODUCT          // Product

Etc...

Quickest way to convert XML to JSON in Java

I found this the quick and easy way: Used: org.json.XML class from java-json.jar

if (statusCode == 200 && inputStream != null) {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = bufferedReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}

How to send a header using a HTTP request through a curl call?

man curl:

   -H/--header <header>
          (HTTP)  Extra header to use when getting a web page. You may specify
          any number of extra headers. Note that if you should  add  a  custom
          header that has the same name as one of the internal ones curl would
          use, your externally set header will be used instead of the internal
          one.  This  allows  you  to make even trickier stuff than curl would
          normally do. You should not replace internally set  headers  without
          knowing  perfectly well what you're doing. Remove an internal header
          by giving a replacement without content on the  right  side  of  the
          colon, as in: -H "Host:".

          curl  will  make sure that each header you add/replace get sent with
          the proper end of line marker, you should thus not  add  that  as  a
          part  of the header content: do not add newlines or carriage returns
          they will only mess things up for you.

          See also the -A/--user-agent and -e/--referer options.

          This option can be used multiple times to add/replace/remove  multi-
          ple headers.

Example:

curl --header "X-MyHeader: 123" www.google.com

You can see the request that curl sent by adding the -v option.

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

The size of array must be greater than zero. ?therwise you will have unexpected results.

function zoomeExtends(){
  var bounds = new google.maps.LatLngBounds();
  if (markers.length>0) { 
      for (var i = 0; i < markers.length; i++) {
         bounds.extend(markers[i].getPosition());
        }    
        myMap.fitBounds(bounds);
    }
}

Invisible characters - ASCII

I just went through the character map to get these. They are all in Calibri.

Number    Name                   HTML Code    Appearance
------    --------------------   ---------    ----------
U+2000    En Quad                &#8192;      " "
U+2001    Em Quad                &#8193;      " "
U+2002    En Space               &#8194;      " "
U+2003    Em Space               &#8195;      " "
U+2004    Three-Per-Em Space     &#8196;      " "
U+2005    Four-Per-Em Space      &#8197;      " "
U+2006    Six-Per-Em Space       &#8198;      " "
U+2007    Figure Space           &#8199;      " "
U+2008    Punctuation Space      &#8200;      " "
U+2009    Thin Space             &#8201;      " "
U+200A    Hair Space             &#8202;      " "
U+200B    Zero-Width Space       &#8203;      "​"
U+200C    Zero Width Non-Joiner  &#8204;      "‌"
U+200D    Zero Width Joiner      &#8205;      "‍"
U+200E    Left-To-Right Mark     &#8206;      "‎"
U+200F    Right-To-Left Mark     &#8207;      "‏"
U+202F    Narrow No-Break Space  &#8239;      " "

Export to CSV using jQuery and html

From what I understand, you have your data on a table and you want to create the CSV from that data. However, you have problem creating the CSV.

My thoughts would be to iterate and parse the contents of the table and generate a string from the parsed data. You can check How to convert JSON to CSV format and store in a variable for an example. You are using jQuery in your example so that would not count as an external plugin. Then, you just have to serve the resulting string using window.open and use application/octetstream as suggested.

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

How to use this boolean in an if statement?

Try this:-

private String getWhoozitYs(){
    StringBuffer sb = new StringBuffer();
    boolean stop = generator.nextBoolean();
    if(stop)
    {
        sb.append("y");
        getWhoozitYs();
    }
    return sb.toString();
}

Determining the size of an Android view at runtime

Are you calling getWidth() before the view is actually laid out on the screen?

A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the onSizeChanged() method to be notified of the values when they are known, or you can use the getWidth() and getHeight() methods later, such as in the onDraw() method.

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

This part of code worked fine for me:

        WebRequest request = WebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Get;
        NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username"
        CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}};
        request.PreAuthenticate = true;
        request.Credentials = myCredentialCache;
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine(responseFromServer);
                }
            }
        }

event.preventDefault() vs. return false

Basically, this way you combine things because jQuery is a framework which mostly focuses on HTML elements, you basically preventing the default, but at the same time, you stop propagation to bubble up.

So we can simply say, return false in jQuery is equal to:

return false is e.preventDefault AND e.stopPropagation

But also don't forget it's all in jQuery or DOM related functions, when you run it on the element, basically, it prevents everything from firing including the default behaviour and propagation of the event.

Basically before starting using return false;, first understand what e.preventDefault(); and e.stopPropagation(); do, then if you think you need both at the same time, then simply use it.

So basically this code below:

$('div').click(function () {
  return false;
});

is equal to this code:

$('div').click(function (event) {
  event.preventDefault();
  event.stopPropagation();
});

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

Difference between java.lang.RuntimeException and java.lang.Exception

In simple words, if your client/user can recover from the Exception then make it a Checked Exception, if your client can't do anything to recover from the Exception then make it Unchecked RuntimeException. E.g, a RuntimeException would be a programmatic error, like division by zero, no user can do anything about it but the programmer himself, then it is a RuntimeException.

Getting last month's date in php

This question is quite old but here goes anyway. If you're trying to get just the previous month and the day does not matter you can use this:

$date = '2014-01-03';

$dateTime = new DateTime($date);

$lastMonth = $dateTime->modify('-' . $dateTime->format('d') . ' days')->format('F Y');

echo $lastMonth; // 'December 2013'

How to INNER JOIN 3 tables using CodeIgniter

it should be like that,

$this->db->select('*');    
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id');
$this->db->join('table3', 'table1.id = table3.id');
$query = $this->db->get();

as per CodeIgniters active record framework

Use of "global" keyword in Python

This is explained well in the Python FAQ

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

How to display div after click the button in Javascript?

<div  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">

SQL QUERY replace NULL value in a row with a value from the previous known value

This will work on Snowflake (credit to Darren Gardner):

create temp table ss (id int, val int);
insert into ss (id,val) select 1, 3;
insert into ss (id,val) select 2, null;
insert into ss (id,val) select 3, 5;
insert into ss (id,val) select 4, null;
insert into ss (id,val) select 5, null;
insert into ss (id,val) select 6, 2;

select *
      ,last_value(val ignore nulls) over 
       (order by id rows between unbounded preceding and current row) as val2
  from ss;

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

How Stuff and 'For Xml Path' work in SQL Server?

Declare @Temp As Table (Id Int,Name Varchar(100))
Insert Into @Temp values(1,'A'),(1,'B'),(1,'C'),(2,'D'),(2,'E'),(3,'F'),(3,'G'),(3,'H'),(4,'I'),(5,'J'),(5,'K')
Select X.ID,
stuff((Select ','+ Z.Name from @Temp Z Where X.Id =Z.Id For XML Path('')),1,1,'')
from @Temp X
Group by X.ID

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to hide the cursor in the entire webpage, using body will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:

document.documentElement.style.cursor = 'none';

To reenable it:

document.documentElement.style.cursor = 'auto';

The analogue with static CSS notation is in the answer by Pavel Salaquarda (in essence: html * {cursor:none})

Replacing some characters in a string with another character

read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter

^use as many of these as you need, and you can make your own BASIC encryption

Excel formula to get week number in month (having Monday)

Finding of week number for each date of a month (considering Monday as beginning of the week)

Keep the first date of month contant $B$13

=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1

WEEKNUM(B18,2) - returns the week number of the date mentioned in cell B18

WEEKNUM($B$13,2) - returns the week number of the 1st date of month in cell B13

Uncaught ReferenceError: React is not defined

Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.

P.S

Possible solutions.

  1. If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
  2. Make sure you have the line import React from 'react';

How to check the version of GitLab?

If using the Gitlab Docker image:

sudo cat /srv/gitlab/data/gitlab-rails/VERSION

Example output:

12.1.3

Detecting which UIButton was pressed in a UITableView

you can use the tag pattern:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSString *identifier = @"identifier";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
     if (cell == nil) {
         cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
         [cell autorelelase];

         UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
         [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
         [button setTag:[indexPath row]]; //use the row as the current tag
         [cell.contentView addSubview:button];

         [button release];
     }

     UIButton *button = (UIButton *)[cell viewWithTag:[indexPath row]]; //use [indexPath row]
     [button setTitle:@"Edit" forState:UIControlStateNormal];

     return cell;
}

- (void)buttonPressedAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    //button.tag has the row number (you can convert it to indexPath)
}

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

How to fade changing background image

This was the only reasonable thing I found to fade a background image.

<div id="foo">
  <!-- some content here -->
</div>

Your CSS; now enhanced with CSS3 transition.

#foo {
  background-image: url(a.jpg);
  transition: background 1s linear;
}

Now swap out the background

document.getElementById("foo").style.backgroundImage = "url(b.jpg)";

Voilà, it fades!


Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work. In which case, the image will change without a transition. Given <1% of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.

How to uninstall Anaconda completely from macOS

The official instructions seem to be here: https://docs.anaconda.com/anaconda/install/uninstall/

but if you like me that didn't work for some reason and for some reason your conda was installed somewhere else with telling you do this:

rm -rf ~/opt

I have no idea why it was saved there but that's what did it for me.


This was useful to me in fixing my conda installation (if that is the reason you are uninstalling it in the first place like me): https://stackoverflow.com/a/60902863/1601580 that ended up fixing it for me. Not sure why conda was acting weird in the first place or installing things wrongly in the first place though...

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

I've recently stumbled upon the following solution to this problem:

Source: Multiple versions of Chrome

...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):

  1. Install Chrome 2, you'll find it Application Data folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:

    C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
    

    and run Chrome

  2. Open registry and save

    [HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    

    keys, put them into one chrome2.reg file and copy this file next to chrome.exe (ChromeDir\Application)

  3. Rename Chrome folder to something else (e.g. Chrome2)

  4. Install Chrome 3, it will install to Chrome folder again and run Chrome

  5. Save the same keys (there are changes due to different version) and save it to the chrome3.reg file next to chrome.exe file of this new version again
  6. Rename the folder again (e.g. Chrome3)

    the result would be that there is no Chrome dir (only Chrome2 and Chrome3)

  7. Go to the Application folder of Chrome2, create chrome.bat file with this content:

    @echo off
    regedit /S chrome2.reg
    START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data"
    rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
    

    the first line is generic batch command, the second line will update registry with the content of chrome2.reg file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.

    Notice short name format passed as -user-data-dir parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)

  8. Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3

Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.

Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.

Bronislav Klucka

MySQL date formats - difficulty Inserting a date

The date format for mysql insert query is YYYY-MM-DD

example:

INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');

How to rename uploaded file before saving it into a directory?

You guess correctly. Read the manual page for move_uploaded_file. Set the second parameter to whereever your want to save the file.

If it doesn't work, there is something wrong with your $fileName. Please post your most recent code.

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

You would have to use the JavascriptExecutor class:

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");

Action Bar's onClick listener for the Home button

answers in half part of what is happening. if onOptionsItemSelected not control homeAsUp button when parent activity sets in manifest.xml system goes to parent activity. use like this in activity tag:

<activity ... >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.activities.MainActivity" /> 
</activity>

Python display text with font & color?

I have some code in my game that displays live score. It is in a function for quick access.

def texts(score):
   font=pygame.font.Font(None,30)
   scoretext=font.render("Score:"+str(score), 1,(255,255,255))
   screen.blit(scoretext, (500, 457))

and I call it using this in my while loop:

texts(score)

How to set an button align-right with Bootstrap?

UPDATE: For Bootstrap 5

The class name is now "float-end" instead of "pull-right"

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg float-end">
      Large button
    </button>
</div>

For Bootstrap 4 and under

Just add a simple pull-right class to the button, and make sure the container div is clearfixed:

<div class="alert alert-info clearfix">
    <a href="#" class="alert-link">
      Summary:Its some description.......testtesttest
    </a> 
    <button type="button" class="btn btn-primary btn-lg pull-right">
      Large button
    </button>
</div>

Wait for a void async method

do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.

You can also wait on a Task that returns from your void async

Comparing two NumPy arrays for equality, element-wise

If you want to check if two arrays have the same shape AND elements you should use np.array_equal as it is the method recommended in the documentation.

Performance-wise don't expect that any equality check will beat another, as there is not much room to optimize comparing two elements. Just for the sake, i still did some tests.

import numpy as np
import timeit

A = np.zeros((300, 300, 3))
B = np.zeros((300, 300, 3))
C = np.ones((300, 300, 3))

timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)
timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)
timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)
> 51.5094
> 52.555
> 52.761

So pretty much equal, no need to talk about the speed.

The (A==B).all() behaves pretty much as the following code snippet:

x = [1,2,3]
y = [1,2,3]
print all([x[i]==y[i] for i in range(len(x))])
> True

How to set xampp open localhost:8080 instead of just localhost

I believe the admin button will open the default configuration always. It simply contains a link to localhost/xampp and it doesn't read the server configuration.

If you change the default settings, you know what you changed and you can enter the URL directly in the browser.

Get Application Directory

Just use this in your code

 context.getApplicationInfo().dataDir

How can I tell if a DOM element is visible in the current viewport?

The simplest solution as the support of Element.getBoundingClientRect() has become perfect:

function isInView(el) {
  let box = el.getBoundingClientRect();
  return box.top < window.innerHeight && box.bottom >= 0;
}

how to sort an ArrayList in ascending order using Collections and Comparator

Two ways to get this done:

Collections.sort(myArray)

given elements inside myArray implements Comparable

Second

Collections.sort(myArray, new MyArrayElementComparator());

where MyArrayElementComparator is Comparator for elements inside myArray

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to calculate the difference between two dates using PHP?

Use this for legacy code (PHP < 5.3). For up to date solution see jurka's answer below

You can use strtotime() to convert two dates to unix time and then calculate the number of seconds between them. From this it's rather easy to calculate different time periods.

$date1 = "2007-03-24";
$date2 = "2009-06-26";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

Edit: Obviously the preferred way of doing this is like described by jurka below. My code is generally only recommended if you don't have PHP 5.3 or better.

Several people in the comments have pointed out that the code above is only an approximation. I still believe that for most purposes that's fine, since the usage of a range is more to provide a sense of how much time has passed or remains rather than to provide precision - if you want to do that, just output the date.

Despite all that, I've decided to address the complaints. If you truly need an exact range but haven't got access to PHP 5.3, use the code below (it should work in PHP 4 as well). This is a direct port of the code that PHP uses internally to calculate ranges, with the exception that it doesn't take daylight savings time into account. That means that it's off by an hour at most, but except for that it should be correct.

<?php

/**
 * Calculate differences between two dates with precise semantics. Based on PHPs DateTime::diff()
 * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved.
 * 
 * See here for original code:
 * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup
 * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup
 */

function _date_range_limit($start, $end, $adj, $a, $b, $result)
{
    if ($result[$a] < $start) {
        $result[$b] -= intval(($start - $result[$a] - 1) / $adj) + 1;
        $result[$a] += $adj * intval(($start - $result[$a] - 1) / $adj + 1);
    }

    if ($result[$a] >= $end) {
        $result[$b] += intval($result[$a] / $adj);
        $result[$a] -= $adj * intval($result[$a] / $adj);
    }

    return $result;
}

function _date_range_limit_days($base, $result)
{
    $days_in_month_leap = array(31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    $days_in_month = array(31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    _date_range_limit(1, 13, 12, "m", "y", &$base);

    $year = $base["y"];
    $month = $base["m"];

    if (!$result["invert"]) {
        while ($result["d"] < 0) {
            $month--;
            if ($month < 1) {
                $month += 12;
                $year--;
            }

            $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
            $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];

            $result["d"] += $days;
            $result["m"]--;
        }
    } else {
        while ($result["d"] < 0) {
            $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
            $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];

            $result["d"] += $days;
            $result["m"]--;

            $month++;
            if ($month > 12) {
                $month -= 12;
                $year++;
            }
        }
    }

    return $result;
}

function _date_normalize($base, $result)
{
    $result = _date_range_limit(0, 60, 60, "s", "i", $result);
    $result = _date_range_limit(0, 60, 60, "i", "h", $result);
    $result = _date_range_limit(0, 24, 24, "h", "d", $result);
    $result = _date_range_limit(0, 12, 12, "m", "y", $result);

    $result = _date_range_limit_days(&$base, &$result);

    $result = _date_range_limit(0, 12, 12, "m", "y", $result);

    return $result;
}

/**
 * Accepts two unix timestamps.
 */
function _date_diff($one, $two)
{
    $invert = false;
    if ($one > $two) {
        list($one, $two) = array($two, $one);
        $invert = true;
    }

    $key = array("y", "m", "d", "h", "i", "s");
    $a = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $one))));
    $b = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $two))));

    $result = array();
    $result["y"] = $b["y"] - $a["y"];
    $result["m"] = $b["m"] - $a["m"];
    $result["d"] = $b["d"] - $a["d"];
    $result["h"] = $b["h"] - $a["h"];
    $result["i"] = $b["i"] - $a["i"];
    $result["s"] = $b["s"] - $a["s"];
    $result["invert"] = $invert ? 1 : 0;
    $result["days"] = intval(abs(($one - $two)/86400));

    if ($invert) {
        _date_normalize(&$a, &$result);
    } else {
        _date_normalize(&$b, &$result);
    }

    return $result;
}

$date = "1986-11-10 19:37:22";

print_r(_date_diff(strtotime($date), time()));
print_r(_date_diff(time(), strtotime($date)));

MongoError: connect ECONNREFUSED 127.0.0.1:27017

I've forgot to start MongoDB at all. Go to separate tab in terminal and type:

sudo service mongod start

When to use StringBuilder in Java

For two strings concat is faster, in other cases StringBuilder is a better choice, see my explanation in concatenation operator (+) vs concat()

Java Thread Example?

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

This uses the above ideas but makes it a derived 'more sensitive' collection:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections;

namespace somethingelse
{
    public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged
    {
        // this collection also reacts to changes in its components' properties

        public ObservableCollectionEx() : base()
        {
            this.CollectionChanged +=new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ObservableCollectionEx_CollectionChanged);
        }

        void ObservableCollectionEx_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach(T item in e.OldItems)
                {
                    //Removed items
                    item.PropertyChanged -= EntityViewModelPropertyChanged;
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach(T item in e.NewItems)
                {
                    //Added items
                    item.PropertyChanged += EntityViewModelPropertyChanged;
                }     
            }       
        }

        public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //This will get called when the property of an object inside the collection changes - note you must make it a 'reset' - I don't know, why
            NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
            OnCollectionChanged(args);
        }
    }
}

Pretty print in MongoDB shell as default

Check this out:

db.collection.find().pretty()

Git: which is the default configured remote for branch?

the command to get the effective push remote for the branch, e.g., master, is:

git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote

Here's why (from the "man git config" output):

branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]

For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

You can solve the problem by checking if your date matches a REGEX pattern. If not, then NULL (or something else you prefer).

In my particular case it was necessary because I have >20 DATE columns saved as CHAR, so I don't know from which column the error is coming from.

Returning to your query:

1. Declare a REGEX pattern.
It is usually a very long string which will certainly pollute your code (you may want to reuse it as well).

define REGEX_DATE = "'your regex pattern goes here'"

Don't forget a single quote inside a double quote around your Regex :-)

A comprehensive thread about Regex date validation you'll find here.

2. Use it as the first CASE condition:

To use Regex validation in the SELECT statement, you cannot use REGEXP_LIKE (it's only valid in WHERE. It took me a long time to understand why my code was not working. So it's certainly worth a note.

Instead, use REGEXP_INSTR
For entries not found in the pattern (your case) use REGEXP_INSTR (variable, pattern) = 0 .

    DEFINE REGEX_DATE = "'your regex pattern goes here'"

    SELECT   c.contract_num,
         CASE
            WHEN REGEXP_INSTR(c.event_dt, &REGEX_DATE) = 0 THEN NULL
            WHEN   (  MAX (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                    - MIN (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                 / COUNT (c.event_occurrence) < 32
            THEN
              'Monthly'
            WHEN       (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) >= 32
                 AND   (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) < 91
            THEN
              'Quarterley'
            ELSE
              'Yearly'
         END
FROM     ps_ca_bp_events c
GROUP BY c.contract_num;

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

This is a fix for a pretty niche use case but it gets me each time. If you are using the Eclipse Jaxb generator it creates a file called package-info.

@javax.xml.bind.annotation.XmlSchema(namespace = "blah.xxx.com/em/feed/v2/CommonFeed")
package xxx.blah.mh.domain.pl3xx.startstop;

If you delete this file it will allow a more generic xml to be parsed. Give it a try!

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Partly JSON unmarshal into a map in Go

This can be accomplished by Unmarshaling into a map[string]json.RawMessage.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

To further parse sendMsg, you could then do something like:

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

For say, you can do the same thing and unmarshal into a string:

var str string
err = json.Unmarshal(objmap["say"], &str)

EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:

type sendMsg struct {
    User string
    Msg  string
}

Example: https://play.golang.org/p/OrIjvqIsi4-

How does "FOR" work in cmd batch file?

It works for me, try it.

for /f "tokens=* delims=;" %g in ('echo %PATH%') do echo %g%

IF/ELSE Stored Procedure

It isn't giving any errors? Try
SET @tmpType = 'premium'
and
SET @tmpType = 'basic'

Spark dataframe: collect () vs select ()

Short answer in bolds:

  • collect is mainly to serialize
    (loss of parallelism preserving all other data characteristics of the dataframe)
    For example with a PrintWriter pw you can't do direct df.foreach( r => pw.write(r) ), must to use collect before foreach, df.collect.foreach(etc).
    PS: the "loss of parallelism" is not a "total loss" because after serialization it can be distributed again to executors.

  • select is mainly to select columns, similar to projection in relational algebra
    (only similar in framework's context because Spark select not deduplicate data).
    So, it is also a complement of filter in the framework's context.


Commenting explanations of other answers: I like the Jeff's classification of Spark operations in transformations (as select) and actions (as collect). It is also good remember that transforms (including select) are lazily evaluated.

How to disable the back button in the browser using JavaScript

One cannot disable the browser back button functionality. The only thing that can be done is prevent them.

The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:

<script>
    function preventBack() {
        window.history.forward();
    }

    setTimeout("preventBack()", 0);
    window.onunload = function() {
        null
    };
</script>

Suppose there are two pages Page1.php and Page2.php and Page1.php redirects to Page2.php.

Hence to prevent user from visiting Page1.php using the back button you will need to place the above script in the head section of Page1.php.

For more information: Reference

How does Java resolve a relative path in new File()?

The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.

Relative paths are ones that start without a drive specifier. So in linux they don't start with a /, in windows they don't start with a C:\, etc. These always start from your working directory.

Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.

C++ Remove new line from multiline string

 std::string some_str = SOME_VAL;
 if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
  some_str.resize( some_str.length()-1 );

or (removes several newlines at the end)

some_str.resize( some_str.find_last_not_of(L"\n")+1 );

Android : Capturing HTTP Requests with non-rooted android device

You can use fiddler as webdebugger http://www.telerik.com/fiddler/web-debugging

Fiddler is a debugging tool from telerik software, which helps you to intercept every request that is initiated from your machine.

How to draw polygons on an HTML5 canvas?

For the people looking for regular polygons:

function regPolyPath(r,p,ctx){ //Radius, #points, context
  //Azurethi was here!
  ctx.moveTo(r,0);
  for(i=0; i<p+1; i++){
    ctx.rotate(2*Math.PI/p);
    ctx.lineTo(r,0);
  }
  ctx.rotate(-2*Math.PI/p);
}

Use:

//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.translate(60,60);    //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation);  //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx);   //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();

Getting value of HTML Checkbox from onclick/onchange events

For React.js, you can do this with more readable code. Hope it helps.

handleCheckboxChange(e) {
  console.log('value of checkbox : ', e.target.checked);
}
render() {
  return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}