Programs & Examples On #Pyml

PyML is an interactive object oriented framework for machine learning written in Python. PyML focuses on SVMs and other kernel methods. It is supported on Linux and Mac OS X.

Nested ifelse statement

If the data set contains many rows it might be more efficient to join with a lookup table using data.table instead of nested ifelse().

Provided the lookup table below

lookup
     idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

and a sample data set

library(data.table)
n_row <- 10L
set.seed(1L)
DT <- data.table(idnat = "french",
                 idbp = sample(c("mainland", "colony", "overseas", "foreign"), n_row, replace = TRUE))
DT[idbp == "foreign", idnat := "foreign"][]
      idnat     idbp
 1:  french   colony
 2:  french   colony
 3:  french overseas
 4: foreign  foreign
 5:  french mainland
 6: foreign  foreign
 7: foreign  foreign
 8:  french overseas
 9:  french overseas
10:  french mainland

then we can do an update while joining:

DT[lookup, on = .(idnat, idbp), idnat2 := i.idnat2][]
      idnat     idbp   idnat2
 1:  french   colony overseas
 2:  french   colony overseas
 3:  french overseas overseas
 4: foreign  foreign  foreign
 5:  french mainland mainland
 6: foreign  foreign  foreign
 7: foreign  foreign  foreign
 8:  french overseas overseas
 9:  french overseas overseas
10:  french mainland mainland

How do you run a Python script as a service in Windows?

I started hosting as a service with pywin32.

Everything was well but I met the problem that service was not able to start within 30 seconds (default timeout for Windows) on system startup. It was critical for me because Windows startup took place simultaneous on several virtual machines hosted on one physical machine, and IO load was huge. Error messages were:

Error 1053: The service did not respond to the start or control request in a timely fashion.

Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.

I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.

Return value from nested function in Javascript

you have to call a function before it can return anything.

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction();
}

var test = mainFunction();
alert(test);

Or:

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction;
}

var test = mainFunction();
alert( test() );

for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations method and hence its return value is not recieved inside your main function.

function reverseGeocode(latitude,longitude){
    var address = "";
    var country = "";
    var countrycode = "";
    var locality = "";

    var geocoder = new GClientGeocoder();
    var latlng = new GLatLng(latitude, longitude);

    geocoder.getLocations(latlng, function(addresses) {
     address = addresses.Placemark[0].address;
     country = addresses.Placemark[0].AddressDetails.Country.CountryName;
     countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
     locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    });   
    return country
   }

How to get rid of blank pages in PDF exported from SSRS

If your report includes a subreport, the width of the subreport could push the boundaries of the body if subreport and hierarchy are allowed to grow. I had a similar problem arise with a subreport that could be placed in a cell (spanning 2 columns). It looked like the span could contain it in the designer and it rendered fine in a winform or a browser and, originally, it could generate printer output (or pdf file) without spilling over onto excess pages.
Then, after changing some other column widths (and without exceeding the body width plus margins), the winform and browser renderings looked still looked fine but when the output (printer or pdf) was generated, it grew past the margins and wrote the right side of each page as a 2nd (4th, etc.) page. I could eliminate my problem by increasing colspan where the subreport was placed.
Whether or not you're using subreports, if you have page spillover and your body design fits within the margins of the page, look for something allowed to grow that pushes the width of the body out.

cURL error 60: SSL certificate: unable to get local issuer certificate

If you're unable to change php.ini you could also point to the cacert.pem file from code like this:

$http = new GuzzleHttp\Client(['verify' => '/path/to/cacert.pem']);
$client = new Google_Client();
$client->setHttpClient($http);

How do I use arrays in C++?

5. Common pitfalls when using arrays.

5.1 Pitfall: Trusting type-unsafe linking.

OK, you’ve been told, or have found out yourself, that globals (namespace scope variables that can be accessed outside the translation unit) are Evil™. But did you know how truly Evil™ they are? Consider the program below, consisting of two files [main.cpp] and [numbers.cpp]:

// [main.cpp]
#include <iostream>

extern int* numbers;

int main()
{
    using namespace std;
    for( int i = 0;  i < 42;  ++i )
    {
        cout << (i > 0? ", " : "") << numbers[i];
    }
    cout << endl;
}

// [numbers.cpp]
int numbers[42] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

In Windows 7 this compiles and links fine with both MinGW g++ 4.4.1 and Visual C++ 10.0.

Since the types don't match, the program crashes when you run it.

The Windows 7 crash dialog

In-the-formal explanation: the program has Undefined Behavior (UB), and instead of crashing it can therefore just hang, or perhaps do nothing, or it can send threating e-mails to the presidents of the USA, Russia, India, China and Switzerland, and make Nasal Daemons fly out of your nose.

In-practice explanation: in main.cpp the array is treated as a pointer, placed at the same address as the array. For 32-bit executable this means that the first int value in the array, is treated as a pointer. I.e., in main.cpp the numbers variable contains, or appears to contain, (int*)1. This causes the program to access memory down at very bottom of the address space, which is conventionally reserved and trap-causing. Result: you get a crash.

The compilers are fully within their rights to not diagnose this error, because C++11 §3.5/10 says, about the requirement of compatible types for the declarations,

[N3290 §3.5/10]
A violation of this rule on type identity does not require a diagnostic.

The same paragraph details the variation that is allowed:

… declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4).

This allowed variation does not include declaring a name as an array in one translation unit, and as a pointer in another translation unit.

5.2 Pitfall: Doing premature optimization (memset & friends).

Not written yet

5.3 Pitfall: Using the C idiom to get number of elements.

With deep C experience it’s natural to write …

#define N_ITEMS( array )   (sizeof( array )/sizeof( array[0] ))

Since an array decays to pointer to first element where needed, the expression sizeof(a)/sizeof(a[0]) can also be written as sizeof(a)/sizeof(*a). It means the same, and no matter how it’s written it is the C idiom for finding the number elements of array.

Main pitfall: the C idiom is not typesafe. For example, the code …

#include <stdio.h>

#define N_ITEMS( array ) (sizeof( array )/sizeof( *array ))

void display( int const a[7] )
{
    int const   n = N_ITEMS( a );          // Oops.
    printf( "%d elements.\n", n );
}

int main()
{
    int const   moohaha[]   = {1, 2, 3, 4, 5, 6, 7};

    printf( "%d elements, calling display...\n", N_ITEMS( moohaha ) );
    display( moohaha );
}

passes a pointer to N_ITEMS, and therefore most likely produces a wrong result. Compiled as a 32-bit executable in Windows 7 it produces …

7 elements, calling display...
1 elements.

  1. The compiler rewrites int const a[7] to just int const a[].
  2. The compiler rewrites int const a[] to int const* a.
  3. N_ITEMS is therefore invoked with a pointer.
  4. For a 32-bit executable sizeof(array) (size of a pointer) is then 4.
  5. sizeof(*array) is equivalent to sizeof(int), which for a 32-bit executable is also 4.

In order to detect this error at run time you can do …

#include <assert.h>
#include <typeinfo>

#define N_ITEMS( array )       (                               \
    assert((                                                    \
        "N_ITEMS requires an actual array as argument",        \
        typeid( array ) != typeid( &*array )                    \
        )),                                                     \
    sizeof( array )/sizeof( *array )                            \
    )

7 elements, calling display...
Assertion failed: ( "N_ITEMS requires an actual array as argument", typeid( a ) != typeid( &*a ) ), file runtime_detect ion.cpp, line 16

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

The runtime error detection is better than no detection, but it wastes a little processor time, and perhaps much more programmer time. Better with detection at compile time! And if you're happy to not support arrays of local types with C++98, then you can do that:

#include <stddef.h>

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

#define N_ITEMS( array )       n_items( array )

Compiling this definition substituted into the first complete program, with g++, I got …

M:\count> g++ compile_time_detection.cpp
compile_time_detection.cpp: In function 'void display(const int*)':
compile_time_detection.cpp:14: error: no matching function for call to 'n_items(const int*&)'

M:\count> _

How it works: the array is passed by reference to n_items, and so it does not decay to pointer to first element, and the function can just return the number of elements specified by the type.

With C++11 you can use this also for arrays of local type, and it's the type safe C++ idiom for finding the number of elements of an array.

5.4 C++11 & C++14 pitfall: Using a constexpr array size function.

With C++11 and later it's natural, but as you'll see dangerous!, to replace the C++03 function

typedef ptrdiff_t   Size;

template< class Type, Size n >
Size n_items( Type (&)[n] ) { return n; }

with

using Size = ptrdiff_t;

template< class Type, Size n >
constexpr auto n_items( Type (&)[n] ) -> Size { return n; }

where the significant change is the use of constexpr, which allows this function to produce a compile time constant.

For example, in contrast to the C++03 function, such a compile time constant can be used to declare an array of the same size as another:

// Example 1
void foo()
{
    int const x[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
    constexpr Size n = n_items( x );
    int y[n] = {};
    // Using y here.
}

But consider this code using the constexpr version:

// Example 2
template< class Collection >
void foo( Collection const& c )
{
    constexpr int n = n_items( c );     // Not in C++14!
    // Use c here
}

auto main() -> int
{
    int x[42];
    foo( x );
}

The pitfall: as of July 2015 the above compiles with MinGW-64 5.1.0 with -pedantic-errors, and, testing with the online compilers at gcc.godbolt.org/, also with clang 3.0 and clang 3.2, but not with clang 3.3, 3.4.1, 3.5.0, 3.5.1, 3.6 (rc1) or 3.7 (experimental). And important for the Windows platform, it does not compile with Visual C++ 2015. The reason is a C++11/C++14 statement about use of references in constexpr expressions:

C++11 C++14 $5.19/2 nineth dash

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
        ?

  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either
    • it is initialized with a constant expression or
    • it is a non-static data member of an object whose lifetime began within the evaluation of e;

One can always write the more verbose

// Example 3  --  limited

using Size = ptrdiff_t;

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = std::extent< decltype( c ) >::value;
    // Use c here
}

… but this fails when Collection is not a raw array.

To deal with collections that can be non-arrays one needs the overloadability of an n_items function, but also, for compile time use one needs a compile time representation of the array size. And the classic C++03 solution, which works fine also in C++11 and C++14, is to let the function report its result not as a value but via its function result type. For example like this:

// Example 4 - OK (not ideal, but portable and safe)

#include <array>
#include <stddef.h>

using Size = ptrdiff_t;

template< Size n >
struct Size_carrier
{
    char sizer[n];
};

template< class Type, Size n >
auto static_n_items( Type (&)[n] )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

template< class Type, size_t n >        // size_t for g++
auto static_n_items( std::array<Type, n> const& )
    -> Size_carrier<n>;
// No implementation, is used only at compile time.

#define STATIC_N_ITEMS( c ) \
    static_cast<Size>( sizeof( static_n_items( c ).sizer ) )

template< class Collection >
void foo( Collection const& c )
{
    constexpr Size n = STATIC_N_ITEMS( c );
    // Use c here
    (void) c;
}

auto main() -> int
{
    int x[42];
    std::array<int, 43> y;
    foo( x );
    foo( y );
}

About the choice of return type for static_n_items: this code doesn't use std::integral_constant because with std::integral_constant the result is represented directly as a constexpr value, reintroducing the original problem. Instead of a Size_carrier class one can let the function directly return a reference to an array. However, not everybody is familiar with that syntax.

About the naming: part of this solution to the constexpr-invalid-due-to-reference problem is to make the choice of compile time constant explicit.

Hopefully the oops-there-was-a-reference-involved-in-your-constexpr issue will be fixed with C++17, but until then a macro like the STATIC_N_ITEMS above yields portability, e.g. to the clang and Visual C++ compilers, retaining type safety.

Related: macros do not respect scopes, so to avoid name collisions it can be a good idea to use a name prefix, e.g. MYLIB_STATIC_N_ITEMS.

PHP Session Destroy on Log Out Button

// logout

if(isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['username']);
    header('location:login.php');
}

?>

libaio.so.1: cannot open shared object file

I had the same problem, and it turned out I hadn't installed the library.

this link was super usefull.

http://help.directadmin.com/item.php?id=368

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Shorthand if/else statement Javascript

Other way is using short-circuit:

x = (typeof y !== 'undefined') && y || 1

Although I myself think that ternary is more readable.

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

how to stop Javascript forEach?

You can't break from a forEach. I can think of three ways to fake it, though.

1. The Ugly Way: pass a second argument to forEach to use as context, and store a boolean in there, then use an if. This looks awful.

2. The Controversial Way: surround the whole thing in a try-catch block and throw an exception when you want to break. This looks pretty bad and may affect performance, but can be encapsulated.

3. The Fun Way: use every().

['a', 'b', 'c'].every(function(element, index) {
  // Do your thing, then:
  if (you_want_to_break) return false
  else return true
})

You can use some() instead, if you'd rather return true to break.

CSS pseudo elements in React

Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):

https://stackoverflow.com/a/42000085

<span class="something" datacustomattribute="">
  Hello
</span>
.something::before {
  content: attr(datascustomattribute);
  position: absolute;
}

Note that the datacustomattribute must start with data and be all lowercase to satisfy React.

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

<VirtualHost *:80>
    ServerName www.YOURDOMAIN.COM
    ServerAlias YOURDOMAIN.COM
    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    ErrorLog /var/www/YOURDOMAIN.COM/error.log
    CustomLog /var/www/YOURDOMAIN.COM/requests.log combined

    DocumentRoot /var/www/YOURDOMAIN.COM/public_html
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/YOURDOMAIN.COM/public_html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

</VirtualHost>

comparing strings in vb

I think this String.Equals is what you need.

Dim aaa = "12/31"
            Dim a = String.Equals(aaa, "06/30")

a will return false.

How to "inverse match" with regex?

In perl you can do

process($line) if ($line =~ !/Andrea/);

How to run .APK file on emulator

Step-by-Step way to do this:

  1. Install Android SDK
  2. Start the emulator by going to $SDK_root/emulator.exe
  3. Go to command prompt and go to the directory $SDK_root/platform-tools (or else add the path to windows environment)
  4. Type in the command adb install
  5. Bingo. Your app should be up and running on the emulator

How to search multiple columns in MySQL?

Here is a query which you can use to search for anything in from your database as a search result ,

SELECT * FROM tbl_customer 
    WHERE CustomerName LIKE '%".$search."%'
    OR Address LIKE '%".$search."%' 
    OR City LIKE '%".$search."%' 
    OR PostalCode LIKE '%".$search."%' 
    OR Country LIKE '%".$search."%'

Using this code will help you search in for multiple columns easily

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Well, I'm late.


In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


Main steps:

  1. Read into BGR
  2. Convert the image from bgr to hsv space
  3. Threshold the S channel
  4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is my result:

enter image description here


The Python code(Python 3.5 + OpenCV 3.3):

#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

Related answers:

  1. How to detect colored patches in an image using OpenCV?
  2. Edge detection on colored background using OpenCV
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
  4. How to use `cv2.findContours` in different OpenCV versions?

Angular 2 - Redirect to an external URL and open in a new tab

I want to share with you one more solution if you have absolute part in the URL

SharePoint solution with ${_spPageContextInfo.webAbsoluteUrl}

HTML:

<button (click)="onNavigate()">Google</button>

TypeScript:

onNavigate()
{
    let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
    window.open(link, "_blank");
}

and url will be opened in new tab.

MySQL ORDER BY rand(), name ASC

SELECT  *
FROM    (
        SELECT  *
        FROM    users
        WHERE   1
        ORDER BY
                rand()
        LIMIT 20
        ) q
ORDER BY
        name

What is the best way to get the count/length/size of an iterator?

iterator object contains the same number of elements what your collection contained.

List<E> a =...;
Iterator<E> i = a.iterator();
int size = a.size();//Because iterators size is equal to list a's size.

But instead of getting the size of iterator and iterating through index 0 to that size, it is better to iterate through the method next() of the iterator.

Changing the CommandTimeout in SQL Management studio

Changing Command Execute Timeout in Management Studio:

Click on Tools -> Options

Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.

Changing Command Timeout in Server:

In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.

Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property

Remote query timeout (in seconds, 0 = no timeout):
[up/down control]

you can set the value in up/down control.

How to call a PHP function on the click of a button

You can simply do this. In php, you can determine button click by use of

if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}

Therefore you should modify you code as follows:


<?php

if(isset($_Post['select']){
 echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
 echo "insert button clicked and insert method should be executed";
}
           
        ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <body>
        <form action="functioncalling.php">
            <input type="text" name="txt" />
            <input type="submit" name="insert" value="insert" onclick="insert()" />
            <input type="submit" name="select" value="select" onclick="select()" />
        </form>

<script>
//This will be processed on the client side
function insert(){
  window.alert("You click insert button");
}

function select(){
  window.alert("You click insert button");
}
</script>
</body>
</html>


        

How to exit git log or git diff

I wanted to give some kudos to the comment that mentioned CTRL + Z as an option. At the end of the day, it's going to depend on what system that you have Git installed on and what program is configured to open text files (e.g. less vs. vim). CTRL + Z works for vim on Windows.

If you're using Git in a Windows environment, there are some quirks. Just helps to know what they are. (i.e. Notepad vs. Nano, etc.).

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

The following worked for me. Just add the following snippet:

android {
        compileSdkVersion 25
        buildToolsVersion '25.0.1'

defaultConfig {
        applicationId "yourpackage"
        minSdkVersion 10
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
dexOptions {
        javaMaxHeapSize "4g"
    }
}

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

    SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';

Hope This Might Help

Can you run GUI applications in a Docker container?

I'm late to the party, but for Mac users who don't want to go down the XQuartz path, here is a working example that builds a Fedora Image, with a Desktop Environment (xfce) using Xvfb and VNC. It's simple, and works:

On a Mac, you can just access it using the Screen Sharing (default) application, connecting to localhost:5901.

Dockerfile:

FROM fedora

USER root

# Set root password, so I know it for the future
RUN echo "root:password123" | chpasswd

# Install Java, Open SSL, etc.
RUN dnf update -y --setopt=deltarpm=false  \
 && dnf install -y --setopt=deltarpm=false \
                openssl.x86_64             \
                java-1.8.0-openjdk.x86_64  \
                xorg-x11-server-Xvfb       \
                x11vnc                     \
                firefox                    \
                @xfce-desktop-environment  \
 && dnf clean all

# Create developer user (password: password123, uid: 11111)
RUN useradd -u 11111 -g users -d /home/developer -s /bin/bash -p $(echo password123 | openssl passwd -1 -stdin) developer

# Copy startup script over to the developer home
COPY start-vnc.sh /home/developer/start-vnc.sh
RUN chmod 700 /home/developer/start-vnc.sh
RUN chown developer.users /home/developer/start-vnc.sh

# Expose VNC, SSH
EXPOSE 5901 22

# Set up VNC Password and DisplayEnvVar to point to Display1Screen0
USER developer
ENV  DISPLAY :1.0
RUN  mkdir ~/.x11vnc
RUN  x11vnc -storepasswd letmein ~/.x11vnc/passwd

WORKDIR /home/developer
CMD ["/home/developer/start-vnc.sh"]

start-vnc.sh

#!/bin/sh

Xvfb :1 -screen 0 1024x768x24 &
sleep 5
x11vnc -noxdamage -many -display :1 -rfbport 5901 -rfbauth ~/.x11vnc/passwd -bg
sleep 2
xfce4-session &

bash
# while true; do sleep 1000; done

Check the linked readme for build and run commands if you want/need.

How to disable horizontal scrolling of UIScrollView?

Disable horizontal scrolling by overriding contentOffset property in subclass.

override var contentOffset: CGPoint {
  get {
    return super.contentOffset
  }
  set {
    super.contentOffset = CGPoint(x: 0, y: newValue.y)
  }
}

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

Formatting text in a TextBlock

You can do this in XAML easily enough:

<TextBlock>
  Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic>
</TextBlock>

How do I compare two hashes?

I had the same problem and sent a pull request to rails

  • Works with deeply nested hash
  • Works with arrays of hashes

https://github.com/elfassy/rails/commit/5f3410e04fe8c4d4745397db866c9633b80ccec6

Beautiful way to remove GET-variables with PHP?

How about:

preg_replace('/\\?.*/', '', $str)

Sending emails with Javascript

You can use this free service: https://www.smtpjs.com

  1. Include the script:

<script src="https://smtpjs.com/v2/smtp.js"></script>

  1. Send an email using:
Email.send(
  "[email protected]",
  "[email protected]",
  "This is a subject",
  "this is the body",
  "smtp.yourisp.com",
  "username",
  "password"
);

How do I change the title of the "back" button on a Navigation Bar

I've found that it is best to change the title of the current view controller in the navigation stack to the desired text of the back button before pushing to the next view controller.

For instance

self.navigationItem.title = @"Desired back button text";
[self.navigationController pushViewController:QAVC animated:NO];

Then in the viewDidAppear set the title back to the desired title for the original VC. Voila!

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

You often see the check for definedness so you don't have to deal with the warning for using an undef value (and in Perl 5.10 it tells you the offending variable):

 Use of uninitialized value $name in ...

So, to get around this warning, people come up with all sorts of code, and that code starts to look like an important part of the solution rather than the bubble gum and duct tape that it is. Sometimes, it's better to show what you are doing by explicitly turning off the warning that you are trying to avoid:

 {
 no warnings 'uninitialized';

 if( length $name ) {
      ...
      }
 }

In other cases, use some sort of null value instead of the data. With Perl 5.10's defined-or operator, you can give length an explicit empty string (defined, and give back zero length) instead of the variable that will trigger the warning:

 use 5.010;

 if( length( $name // '' ) ) {
      ...
      }

In Perl 5.12, it's a bit easier because length on an undefined value also returns undefined. That might seem like a bit of silliness, but that pleases the mathematician I might have wanted to be. That doesn't issue a warning, which is the reason this question exists.

use 5.012;
use warnings;

my $name;

if( length $name ) { # no warning
    ...
    }

Call Class Method From Another Class

Just call it and supply self

class A:
    def m(self, x, y):
        print(x+y)

class B:
    def call_a(self):
        A.m(self, 1, 2)

b = B()
b.call_a()

output: 3

When to favor ng-if vs. ng-show/ng-hide?

Depends on your use case but to summarise the difference:

  1. ng-if will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and your click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
  2. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.
  3. ng-if creates a child scope while ng-show/ng-hide does not

Elements that are not in the DOM have less performance impact and your web app might appear to be faster when using ng-if compared to ng-show/ng-hide. In my experience, the difference is negligible. Animations are possible when using both ng-show/ng-hide and ng-if, with examples for both in the Angular documentation.

Ultimately, the question you need to answer is whether you can remove element from DOM or not?

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

Objective-C for Windows

Get GNUStep here

Get MINGW here

Install MINGW Install GNUStep Then Test

Making a mocked method return an argument that was passed to it

You can create an Answer in Mockito. Let's assume, we have an interface named Application with a method myFunction.

public interface Application {
  public String myFunction(String abc);
}

Here is the test method with a Mockito answer:

public void testMyFunction() throws Exception {
  Application mock = mock(Application.class);
  when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
      Object[] args = invocation.getArguments();
      return (String) args[0];
    }
  });

  assertEquals("someString",mock.myFunction("someString"));
  assertEquals("anotherString",mock.myFunction("anotherString"));
}

Since Mockito 1.9.5 and Java 8, you can also use a lambda expression:

when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

Working with huge files in VIM

I had the same problem, but it was a 300GB mysql dump and I wanted to get rid of the DROP and change CREATE TABLE to CREATE TABLE IF NOT EXISTS so didn't want to run two invocations of sed. I wrote this quick Ruby script to dupe the file with those changes:

#!/usr/bin/env ruby

matchers={
    %q/^CREATE TABLE `foo`/ => %q/CREATE TABLE IF NOT EXISTS `foo`/,
    %q/^DROP TABLE IF EXISTS `foo`;.*$/ => "-- DROP TABLE IF EXISTS `foo`;"
}

matchers.each_pair { |m,r|
    STDERR.puts "%s: %s" % [ m, r ]
}

STDIN.each { |line|
    #STDERR.puts "line=#{line}"
    line.chomp!
    unless matchers.length == 0
        matchers.each_pair { |m,r|
            re=/#{m}/
            next if line[re].nil?
            line.sub!(re,r)
            STDERR.puts "Matched: #{m} -> #{r}"
            matchers.delete(m)
            break
        }
    end
    puts line
}

Invoked like

./mreplace.rb < foo.sql > foo_two.sql

Quickest way to find missing number in an array of numbers

One thing you could do is sort the numbers using quick sort for instance. Then use a for loop to iterate through the sorted array from 1 to 100. In each iteration, you compare the number in the array with your for loop increment, if you find that the index increment is not the same as the array value, you have found your missing number as well as the missing index.

How can I get the max (or min) value in a vector?

Using c++11/c++0x compile flags, you can

auto it = max_element(std::begin(cloud), std::end(cloud)); // c++11

Otherwise, write your own:

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }    
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

See it live at http://ideone.com/aDkhW:

#include <iostream>
#include <algorithm>

template <typename T, size_t N> const T* mybegin(const T (&a)[N]) { return a; }    
template <typename T, size_t N> const T* myend  (const T (&a)[N]) { return a+N; }

int main()
{
    const int cloud[] = { 1,2,3,4,-7,999,5,6 };

    std::cout << *std::max_element(mybegin(cloud), myend(cloud)) << '\n';
    std::cout << *std::min_element(mybegin(cloud), myend(cloud)) << '\n';
}

Oh, and use std::minmax_element(...) if you need both at once :/

Setting environment variables on OS X

Much like the answer Matt Curtis gave, I set environment variables via launchctl, but I wrap it in a function called export, so that whenever I export a variable like normal in my .bash_profile, it is also set by launchctl. Here is what I do:

  1. My .bash_profile consists solely of one line, (This is just personal preference.)

    source .bashrc
    
  2. My .bashrc has this:

    function export()
    {
        builtin export "$@"
        if [[ ${#@} -eq 1 && "${@//[^=]/}" ]]
        then
            launchctl setenv "${@%%=*}" "${@#*=}"
        elif [[ ! "${@//[^ ]/}" ]]
        then
            launchctl setenv "${@}" "${!@}"
        fi
    }
    
    export -f export
    
  3. The above will overload the Bash builtin "export" and will export everything normally (you'll notice I export "export" with it!), then properly set them for OS X app environments via launchctl, whether you use any of the following:

    export LC_CTYPE=en_US.UTF-8
    # ~$ launchctl getenv LC_CTYPE
    # en_US.UTF-8
    PATH="/usr/local/bin:${PATH}"
    PATH="/usr/local/opt/coreutils/libexec/gnubin:${PATH}"
    export PATH
    # ~$ launchctl getenv PATH
    # /usr/local/opt/coreutils/libexec/gnubin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
    export CXX_FLAGS="-mmacosx-version-min=10.9"
    # ~$ launchctl getenv CXX_FLAGS
    # -mmacosx-version-min=10.9
    
  4. This way I don't have to send every variable to launchctl every time, and I can just have my .bash_profile / .bashrc set up the way I want. Open a terminal window, check out your environment variables you're interested in with launchctl getenv myVar, change something in your .bash_profile/.bashrc, close the terminal window and re-open it, check the variable again with launchctl, and voilá, it's changed.

  5. Again, like the other solutions for the post-Mountain Lion world, for any new environment variables to be available for apps, you need to launch or re-launch them after the change.

Asp.net MVC ModelState.Clear

I think is a bug in MVC. I struggled with this issue for hours today.

Given this:

public ViewResult SomeAction(SomeModel model) 
{
    model.SomeString = "some value";
    return View(model); 
}

The view renders with the original model, ignoring the changes. So I thought, maybe it does not like me using the same model, so I tried like this:

public ViewResult SomeAction(SomeModel model) 
{
    var newModel = new SomeModel { SomeString = "some value" };
    return View(newModel); 
}

And still the view renders with the original model. What's odd is, when I put a breakpoint in the view and examine the model, it has the changed value. But the response stream has the old values.

Eventually I discovered the same work around that you did:

public ViewResult SomeAction(SomeModel model) 
{
    var newModel = new SomeModel { SomeString = "some value" };
    ModelState.Clear();
    return View(newModel); 
}

Works as expected.

I don't think this is a "feature," is it?

Date in mmm yyyy format in postgresql

You can write your select query as,

select * from table_name where to_char(date_time_column, 'YYYY-MM')  = '2011-03';

Excel Formula: Count cells where value is date

This is difficult with worksheet functions because dates in excel are simply formatted numbers - only CELL function lets you investigate the format of a cell (and you can't apply that to a range, so a helper column would be required).......or, if you only have dates and blanks.....or dates and text then it would be sufficient to use COUNT function, i.e.

=COUNT(range)

That counts numbers so it won't be adequate if you want to distinguish dates from numbers. If you do then the number range could be utilised, e.g. if you have numbers in a range and dates but the numbers will all be lower than 10,000 and the dates will all be relatively recent then you could use this version to exclude the numbers

=COUNTIF(range,">10000")

HTML embed autoplay="false", but still plays automatically

Just change the mime type to: type="audio/mpeg", this way chrome will honor the autostart="false" parameter.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

For my Android Studio workout. I found that this happen when I change Compile SDK Version from API23 (Android 6) to be API17 (Android 4.2) manually in Project Structure setting, and trying to change some code in layout files.

I miss-understood that I have to change it manually, even on New Project I have selected the "Minimum SdK" to be 4.2 already.

Solve by just change it back to API23, and it still can run on Android 4.2. ^^

How to override !important?

In any case, you can override height with max-height.

Parse HTML table to Python list?

Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.

import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest

Only downside is that read_html() doesn't preserve hyperlinks.

Extract number from string with Oracle function

This works for me, I only need first numbers in string:

TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))

the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION".

result field: 43

How do I debug Windows services in Visual Studio?

I'm using the /Console parameter in the Visual Studio project Debug ? Start Options ? Command line arguments:

public static class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
         var runMode = args.Contains(@"/Console")
             ? WindowsService.RunMode.Console
             : WindowsService.RunMode.WindowsService;
         new WinodwsService().Run(runMode);
    }
}


public class WindowsService : ServiceBase
{
    public enum RunMode
    {
        Console,
        WindowsService
    }

    public void Run(RunMode runMode)
    {
        if (runMode.Equals(RunMode.Console))
        {
            this.StartService();
            Console.WriteLine("Press <ENTER> to stop service...");
            Console.ReadLine();

            this.StopService();
            Console.WriteLine("Press <ENTER> to exit.");
            Console.ReadLine();
        }
        else if (runMode.Equals(RunMode.WindowsService))
        {
            ServiceBase.Run(new[] { this });
        }
    }

    protected override void OnStart(string[] args)
    {
        StartService(args);
    }

    protected override void OnStop()
    {
        StopService();
    }

    /// <summary>
    /// Logic to Start Service
    /// Public accessibility for running as a console application in Visual Studio debugging experience
    /// </summary>
    public virtual void StartService(params string[] args){ ... }

    /// <summary>
    /// Logic to Stop Service
    /// Public accessibility for running as a console application in Visual Studio debugging experience
    /// </summary>
    public virtual void StopService() {....}
}

How to grep and replace

Other solutions mix regex syntaxes. To use perl/PCRE patterns for both search and replace, and only process matching files, this works quite well:

grep -rlIZPi 'match1' | xargs -0r perl -pi -e 's/match2/replace/gi;'

match1 and match2 are usually identical but match1 can be simplified to remove more advanced features that are only relevant to the substitution, e.g. capturing groups.

Translation: grep recursively and list matching filenames, each separated by nul to protect any special characters; pipe any filenames to xargs which is expecting a nul-separated list; if any filenames are received, pass them to perl to perform the actual substitutions.

For case-sensitive matching, drop the i flag from grep and the i pattern modifier from the s/// expression, but not the i flag from perl itself. Remove the I flag from grep to include binary files.

Simple way to find if two different lists contain exactly the same elements?

I posted a bunch of stuff in comments I think it warrants its own answer.

As everyone says here, using equals() depends on the order. If you don't care about order, you have 3 options.

Option 1

Use containsAll(). This option is not ideal, in my opinion, because it offers worst case performance, O(n^2).

Option 2

There are two variations to this:

2a) If you don't care about maintaining the order ofyour lists... use Collections.sort() on both list. Then use the equals(). This is O(nlogn), because you do two sorts, and then an O(n) comparison.

2b) If you need to maintain the lists' order, you can copy both lists first. THEN you can use solution 2a on both the copied lists. However this might be unattractive if copying is very expensive.

This leads to:

Option 3

If your requirements are the same as part 2b, but copying is too expensive. You can use a TreeSet to do the sorting for you. Dump each list into its own TreeSet. It will be sorted in the set, and the original lists will remain intact. Then perform an equals() comparison on both TreeSets. The TreeSetss can be built in O(nlogn) time, and the equals() is O(n).

Take your pick :-).

EDIT: I almost forgot the same caveat that Laurence Gonsalves points out. The TreeSet implementation will eliminate duplicates. If you care about duplicates, you will need some sort of sorted multiset.

Do I need to pass the full path of a file in another directory to open()?

Here's a snippet that will walk the file tree for you:

indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)
        log = open(indir + f, 'r')

jQuery Datepicker onchange event issue

if you are using wdcalendar this going to help you

 $("#PatientBirthday").datepicker({ 
        picker: "<button class='calpick'></button>",
        onReturn:function(d){
          var today = new Date();
          var birthDate = d;
          var age = today.getFullYear() - birthDate.getFullYear();
          var m = today.getMonth() - birthDate.getMonth();
          if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
          }

          $('#ageshow')[0].innerHTML="Age: "+age;
          $("#PatientBirthday").val((d.getMonth() + 1) + '/' + d.getDate() + '/' +  d.getFullYear());
        }
      }); 

the event onReturn works for me

hope this help

apache mod_rewrite is not working or not enabled

Please try

sudo a2enmod rewrite

or use correct apache restart command

sudo /etc/init.d/apache2 restart 

Is there a way to crack the password on an Excel VBA Project?

My tool, VbaDiff, reads VBA directly from the file, so you can use it to recover protected VBA code from most office documents without resorting to a hex editor.

Difference between "read commited" and "repeatable read"

I think this picture can also be useful, it helps me as a reference when I want to quickly remember the differences between isolation levels (thanks to kudvenkat on youtube)

enter image description here

Difference between Math.Floor() and Math.Truncate()

Truncate drops the decimal point.

missing private key in the distribution certificate on keychain

When I try to upload iOS build to test flight then error was appear.

"Missing privacy key".

enter image description here

Just 2 step for fix this error.

  1. Remove old certificate from developer.apple.com
  2. Create new certificate from Xcode or developer.apple.com

My problem has been solved (I am using Xcode 9.4.1).

Please check, Xcode created new certificate.

enter image description here

How can we run a test method with multiple parameters in MSTest?

It's very simple to implement - you should use TestContext property and TestPropertyAttribute.

Example

public TestContext TestContext { get; set; }
private List<string> GetProperties()
{
    return TestContext.Properties
        .Cast<KeyValuePair<string, object>>()
        .Where(_ => _.Key.StartsWith("par"))
        .Select(_ => _.Value as string)
        .ToList();
}

//usage
[TestMethod]
[TestProperty("par1", "http://getbootstrap.com/components/")]
[TestProperty("par2", "http://www.wsj.com/europe")]
public void SomeTest()
{
    var pars = GetProperties();
    //...
}

EDIT:

I prepared few extension methods to simplify access to the TestContext property and act like we have several test cases. See example with processing simple test properties here:

[TestMethod]
[TestProperty("fileName1", @".\test_file1")]
[TestProperty("fileName2", @".\test_file2")]
[TestProperty("fileName3", @".\test_file3")]
public void TestMethod3()
{
    TestContext.GetMany<string>("fileName").ForEach(fileName =>
    {
        //Arrange
        var f = new FileInfo(fileName);

        //Act
        var isExists = f.Exists;

        //Asssert
        Assert.IsFalse(isExists);
    });
}

and example with creating complex test objects:

[TestMethod]
//Case 1
[TestProperty(nameof(FileDescriptor.FileVersionId), "673C9C2D-A29E-4ACC-90D4-67C52FBA84E4")]
//...
public void TestMethod2()
{
    //Arrange
    TestContext.For<FileDescriptor>().Fill(fi => fi.FileVersionId).Fill(fi => fi.Extension).Fill(fi => fi.Name).Fill(fi => fi.CreatedOn, new CultureInfo("en-US", false)).Fill(fi => fi.AccessPolicy)
        .ForEach(fileInfo =>
        {
            //Act
            var fileInfoString = fileInfo.ToString();

            //Assert
            Assert.AreEqual($"Id: {fileInfo.FileVersionId}; Ext: {fileInfo.Extension}; Name: {fileInfo.Name}; Created: {fileInfo.CreatedOn}; AccessPolicy: {fileInfo.AccessPolicy};", fileInfoString);
        });
}

Take a look to the extension methods and set of samples for more details.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

EditText underline below text property

It's actually fairly easy to set the underline color of an EditText programmatically (just one line of code).

To set the color:

editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);

To remove the color:

editText.getBackground().clearColorFilter();

Note: when the EditText has focus on, the color you set won't take effect, instead, it has a focus color.

API Reference:

Drawable#setColorFilter

Drawable#clearColorFilter

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

Bootstrap number validation

It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min and max attributes (in your case only the first attribute). For example:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step attribute:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .

BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.

For a list of browsers that support it, you can look at caniuse.com.

Passing multiple values to a single PowerShell script parameter

One way to do it would be like this:

 param(
       [Parameter(Position=0)][String]$Vlan,
       [Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
    ) ...

This would allow multiple hosts to be entered with spaces.

PostgreSQL - fetch the row which has the Max value for a column

I like the style of Mike Woodhouse's answer on the other page you mentioned. It's especially concise when the thing being maximised over is just a single column, in which case the subquery can just use MAX(some_col) and GROUP BY the other columns, but in your case you have a 2-part quantity to be maximised, you can still do so by using ORDER BY plus LIMIT 1 instead (as done by Quassnoi):

SELECT * 
FROM lives outer
WHERE (usr_id, time_stamp, trans_id) IN (
    SELECT usr_id, time_stamp, trans_id
    FROM lives sq
    WHERE sq.usr_id = outer.usr_id
    ORDER BY trans_id, time_stamp
    LIMIT 1
)

I find using the row-constructor syntax WHERE (a, b, c) IN (subquery) nice because it cuts down on the amount of verbiage needed.

Hashing with SHA1 Algorithm in C#

This is what I went with. For those of you who want to optimize, check out https://stackoverflow.com/a/624379/991863.

    public static string Hash(string stringToHash)
    {
        using (var sha1 = new SHA1Managed())
        {
            return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(stringToHash)));
        }
    }

SELECTING with multiple WHERE conditions on same column

Sometimes you can't see the wood for the trees :)

Your original SQL ..

SELECT contactid 
 WHERE flag = 'Volunteer' 
   AND flag = 'Uploaded'...

Should be:

SELECT contactid 
 WHERE flag = 'Volunteer' 
   OR flag = 'Uploaded'...

How do I update a Tomcat webapp without restarting the entire service?

Have you tried to use Tomcat's Manager application? It allows you to undeploy / deploy war files with out shutting Tomcat down.

If you don't want to use the Manager application, you can also delete the war file from the webapps directory, Tomcat will undeploy the application after a short period of time. You can then copy a war file back into the directory, and Tomcat will deploy the war file.

If you are running Tomcat on Windows, you may need to configure your Context to not lock various files.

If you absolutely can't have any downtime, you may want to look at Tomcat 7's Parallel deployments You may deploy multiple versions of a web application with the same context path at the same time. The rules used to match requests to a context version are as follows:

  • If no session information is present in the request, use the latest version.
  • If session information is present in the request, check the session manager of each version for a matching session and if one is found, use that version.
  • If session information is present in the request but no matching session can be found, use the latest version.

Cannot start session without errors in phpMyAdmin

First: if not session dir (in my case it was)

sudo mkdir /var/lib/php/session

Second: set privilege for session dir

sudo chmod 777 /var/lib/php/session

Resolve absolute path from relative path and/or file name

In batch files, as in standard C programs, argument 0 contains the path to the currently executing script. You can use %~dp0 to get only the path portion of the 0th argument (which is the current script) - this path is always a fully qualified path.

You can also get the fully qualified path of your first argument by using %~f1, but this gives a path according to the current working directory, which is obviously not what you want.

Personally, I often use the %~dp0%~1 idiom in my batch file, which interpret the first argument relative to the path of the executing batch. It does have a shortcoming though: it miserably fails if the first argument is fully-qualified.

If you need to support both relative and absolute paths, you can make use of Frédéric Ménez's solution: temporarily change the current working directory.

Here's an example that'll demonstrate each of these techniques:

@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"

rem Temporarily change the current working directory, to retrieve a full path 
rem   to the first parameter
pushd .
cd %~dp0
echo batch-relative %%~f1 is "%~f1"
popd

If you save this as c:\temp\example.bat and the run it from c:\Users\Public as

c:\Users\Public>\temp\example.bat ..\windows

...you'll observe the following output:

%~dp0 is "C:\temp\"
%0 is "\temp\example.bat"
%~dpnx0 is "C:\temp\example.bat"
%~f1 is "C:\Users\windows"
%~dp0%~1 is "C:\temp\..\windows"
batch-relative %~f1 is "C:\Windows"

the documentation for the set of modifiers allowed on a batch argument can be found here: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call

Matplotlib-Animation "No MovieWriters Available"

Had the same problem under Linux. By default the animate.save method is using ffmpeg but it seems to be deprecated. https://askubuntu.com/questions/432542/is-ffmpeg-missing-from-the-official-repositories-in-14-04

Solution: Install some coder, like avconv or mencoder. Provide the alternative coder in the call:

ani.save('the_movie.mp4', writer = 'mencoder', fps=15)

Grant SELECT on multiple tables oracle

This worked for me on my Oracle database:

SELECT   'GRANT SELECT, insert, update, delete ON mySchema.' || TABLE_NAME || ' to myUser;'
FROM     user_tables
where table_name like 'myTblPrefix%'

Then, copy the results, paste them into your editor, then run them like a script.

You could also write a script and use "Execute Immediate" to run the generated SQL if you don't want the extra copy/paste steps.

Start / Stop a Windows Service from a non-Administrator user account

Windows Service runs using a local system account.It can start automatically as the user logs into the system or it can be started manually.However, a windows service say BST can be run using a particular user account on the machine.This can be done as follows:start services.msc and go to the properties of your windows service,BST.From there you can give the login parameters of the required user.Service then runs with that user account and no other user can run that service.

jQuery removing '-' character from string

If you want to remove all - you can use:

.replace(new RegExp('-', 'g'),"")

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I dont know what is the exact reason but I solved the problem running:

   app/console cache:clear --env=prod

checked = "checked" vs checked = true

The original checked attribute (HTML 4 and before) did not require a value on it - if it existed, the element was "checked", if not, it wasn't.

This, however is not valid for XHTML that followed HTML 4.

The standard proposed to use checked="checked" as a condition for true - so both ways you posted end up doing the same thing.

It really doesn't matter which one you use - use the one that makes most sense to you and stick to it (or agree with your team which way to go).

JQuery How to extract value from href tag?

The first thing that comes to my mind is a one-liner regex:

var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];

What is the purpose and use of **kwargs?

As an addition, you can also mix different ways of usage when calling kwargs functions:

def test(**kwargs):
    print kwargs['a']
    print kwargs['b']
    print kwargs['c']


args = { 'b': 2, 'c': 3}

test( a=1, **args )

gives this output:

1
2
3

Note that **kwargs has to be the last argument

SOAP vs REST (differences)

Although SOAP and REST share similarities over the HTTP protocol, SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are relevant because we can’t achieve any degree of standardization without them. REST needs no processing as an architecture style and is inherently more versatile. In the spirit of information exchange, both SOAP and REST depend on well-established laws that everybody has decided to abide by. The choice of SOAP vs. REST is dependent on the programming language you are using the environment you are using and the specifications.

Merge 2 arrays of objects

For those who are experimenting with modern things:

var odd = [
    { name : "1", arr: "in odd" },
    { name : "3", arr: "in odd" }
];

var even = [
    { name : "1", arr: "in even" },
    { name : "2", arr: "in even" },
    { name : "4", arr: "in even" }
];

// ----
// ES5 using Array.filter and Array.find
function merge(a, b, prop){
  var reduced = a.filter(function(aitem){
      return ! b.find(function(bitem){
          return aitem[prop] === bitem[prop];
      });
  });
  return reduced.concat(b);
}
console.log( "ES5", merge(odd, even, "name") );

// ----
// ES6 arrow functions
function merge(a, b, prop){
    var reduced =  a.filter( aitem => ! b.find ( bitem => aitem[prop] === bitem[prop]) )
  return reduced.concat(b);
}
console.log( "ES6", merge(odd, even, "name") );

// ----
// ES6 one-liner
var merge = (a, b, p) => a.filter( aa => ! b.find ( bb => aa[p] === bb[p]) ).concat(b);


console.log( "ES6 one-liner", merge(odd, even, "name") );

// Results
// ( stuff in the "b" array replaces things in the "a" array )
// [
//    {
//         "name": "3",
//         "arr": "in odd"
//     },
//     {
//         "name": "1",
//         "arr": "in even"
//     },
//     {
//         "name": "2",
//         "arr": "in even"
//     },
//     {
//         "name": "4",
//         "arr": "in even"
//     }
// ]

WPF global exception handler

You can handle the AppDomain.UnhandledException event

EDIT: actually, this event is probably more adequate: Application.DispatcherUnhandledException

Load CSV file with Spark

And yet another option which consist in reading the CSV file using Pandas and then importing the Pandas DataFrame into Spark.

For example:

from pyspark import SparkContext
from pyspark.sql import SQLContext
import pandas as pd

sc = SparkContext('local','example')  # if using locally
sql_sc = SQLContext(sc)

pandas_df = pd.read_csv('file.csv')  # assuming the file contains a header
# pandas_df = pd.read_csv('file.csv', names = ['column 1','column 2']) # if no header
s_df = sql_sc.createDataFrame(pandas_df)

Most common C# bitwise operations on enums

To test a bit you would do the following: (assuming flags is a 32 bit number)

Test Bit:

if((flags & 0x08) == 0x08)
(If bit 4 is set then its true) Toggle Back (1 - 0 or 0 - 1):
flags = flags ^ 0x08;
Reset Bit 4 to Zero:
flags = flags & 0xFFFFFF7F;

Good way of getting the user's location in Android

Looks like we're coding the same application ;-)
Here is my current implementation. I'm still in the beta testing phase of my GPS uploader app, so there might be many possible improvements. but it seems to work pretty well so far.

/**
 * try to get the 'best' location selected from all providers
 */
private Location getBestLocation() {
    Location gpslocation = getLocationByProvider(LocationManager.GPS_PROVIDER);
    Location networkLocation =
            getLocationByProvider(LocationManager.NETWORK_PROVIDER);
    // if we have only one location available, the choice is easy
    if (gpslocation == null) {
        Log.d(TAG, "No GPS Location available.");
        return networkLocation;
    }
    if (networkLocation == null) {
        Log.d(TAG, "No Network Location available");
        return gpslocation;
    }
    // a locationupdate is considered 'old' if its older than the configured
    // update interval. this means, we didn't get a
    // update from this provider since the last check
    long old = System.currentTimeMillis() - getGPSCheckMilliSecsFromPrefs();
    boolean gpsIsOld = (gpslocation.getTime() < old);
    boolean networkIsOld = (networkLocation.getTime() < old);
    // gps is current and available, gps is better than network
    if (!gpsIsOld) {
        Log.d(TAG, "Returning current GPS Location");
        return gpslocation;
    }
    // gps is old, we can't trust it. use network location
    if (!networkIsOld) {
        Log.d(TAG, "GPS is old, Network is current, returning network");
        return networkLocation;
    }
    // both are old return the newer of those two
    if (gpslocation.getTime() > networkLocation.getTime()) {
        Log.d(TAG, "Both are old, returning gps(newer)");
        return gpslocation;
    } else {
        Log.d(TAG, "Both are old, returning network(newer)");
        return networkLocation;
    }
}

/**
 * get the last known location from a specific provider (network/gps)
 */
private Location getLocationByProvider(String provider) {
    Location location = null;
    if (!isProviderSupported(provider)) {
        return null;
    }
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.d(TAG, "Cannot acces Provider " + provider);
    }
    return location;
}

Edit: here is the part that requests the periodic updates from the location providers:

public void startRecording() {
    gpsTimer.cancel();
    gpsTimer = new Timer();
    long checkInterval = getGPSCheckMilliSecsFromPrefs();
    long minDistance = getMinDistanceFromPrefs();
    // receive updates
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    for (String s : locationManager.getAllProviders()) {
        locationManager.requestLocationUpdates(s, checkInterval,
                minDistance, new LocationListener() {

                    @Override
                    public void onStatusChanged(String provider,
                            int status, Bundle extras) {}

                    @Override
                    public void onProviderEnabled(String provider) {}

                    @Override
                    public void onProviderDisabled(String provider) {}

                    @Override
                    public void onLocationChanged(Location location) {
                        // if this is a gps location, we can use it
                        if (location.getProvider().equals(
                                LocationManager.GPS_PROVIDER)) {
                            doLocationUpdate(location, true);
                        }
                    }
                });
        // //Toast.makeText(this, "GPS Service STARTED",
        // Toast.LENGTH_LONG).show();
        gps_recorder_running = true;
    }
    // start the gps receiver thread
    gpsTimer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            Location location = getBestLocation();
            doLocationUpdate(location, false);
        }
    }, 0, checkInterval);
}

public void doLocationUpdate(Location l, boolean force) {
    long minDistance = getMinDistanceFromPrefs();
    Log.d(TAG, "update received:" + l);
    if (l == null) {
        Log.d(TAG, "Empty location");
        if (force)
            Toast.makeText(this, "Current location not available",
                    Toast.LENGTH_SHORT).show();
        return;
    }
    if (lastLocation != null) {
        float distance = l.distanceTo(lastLocation);
        Log.d(TAG, "Distance to last: " + distance);
        if (l.distanceTo(lastLocation) < minDistance && !force) {
            Log.d(TAG, "Position didn't change");
            return;
        }
        if (l.getAccuracy() >= lastLocation.getAccuracy()
                && l.distanceTo(lastLocation) < l.getAccuracy() && !force) {
            Log.d(TAG,
                    "Accuracy got worse and we are still "
                      + "within the accuracy range.. Not updating");
            return;
        }
        if (l.getTime() <= lastprovidertimestamp && !force) {
            Log.d(TAG, "Timestamp not never than last");
            return;
        }
    }
    // upload/store your location here
}

Things to consider:

  • do not request GPS updates too often, it drains battery power. I currently use 30 min as default for my application.

  • add a 'minimum distance to last known location' check. without this, your points will "jump around" when GPS is not available and the location is being triangulated from the cell towers. or you can check if the new location is outside of the accuracy value from the last known location.

Change the maximum upload file size

You can also use ini_set function (only for PHP version below 5.3):

ini_set('post_max_size', '64M');
ini_set('upload_max_filesize', '64M');

Like @acme said, in php 5.3 and above this settings are PHP_INI_PERDIR directives so they can't be set using ini_set. You can use user.ini instead.

How to reduce the image size without losing quality in PHP

You can resize and then use imagejpeg()

Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.

imagejpeg($tn, $save, 75);

How to properly ignore exceptions

When you just want to do a try catch without handling the exception, how do you do it in Python?

It depends on what you mean by "handling."

If you mean to catch it without taking any action, the code you posted will work.

If you mean that you want to take action on an exception without stopping the exception from going up the stack, then you want something like this:

try:
    do_something()
except:
    handle_exception()
    raise  #re-raise the exact same exception that was thrown

jQuery - trapping tab select event

From what I can tell, per the documentation here: http://jqueryui.com/demos/tabs/#event-select, it seems as though you're not quite initializing it right. The demos state that you need a main wrapped <div> element, with a <ul> or possibly <ol> element representing the tabs, and then an element for each tab page (presumable a <div> or <p>, possibly a <section> if we're using HTML5). Then you call $().tabs() on the main <div>, not the <ul> element.

After that, you can bind to the tabsselect event no problem. Check out this fiddle for basic, basic example:

http://jsfiddle.net/KE96S/

Can someone explain the dollar sign in Javascript?

A '$' in a variable means nothing special to the interpreter, much like an underscore.

From what I've seen, many people using jQuery (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.

The dollar sign function $() in jQuery is a library function that is frequently used, so a short name is desirable.

Design Android EditText to show error message as described by google

There's no need to use a third-party library since Google introduced the TextInputLayout as part of the design-support-library.

Following a basic example:

Layout

<android.support.design.widget.TextInputLayout
    android:id="@+id/text_input_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:errorEnabled="true">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />

</android.support.design.widget.TextInputLayout>

Note: By setting app:errorEnabled="true" as an attribute of the TextInputLayout it won't change it's size once an error is displayed - so it basically blocks the space.

Code

In order to show the Error below the EditText you simply need to call #setError on the TextInputLayout (NOT on the child EditText):

TextInputLayout til = (TextInputLayout) findViewById(R.id.text_input_layout);
til.setError("You need to enter a name");

Result

picture showing the edit text with the error message

To hide the error and reset the tint simply call til.setError(null).


Note

In order to use the TextInputLayout you have to add the following to your build.gradle dependencies:

dependencies {
    compile 'com.android.support:design:25.1.0'
}

Setting a custom color

By default the line of the EditText will be red. If you need to display a different color you can use the following code as soon as you call setError.

editText.getBackground().setColorFilter(getResources().getColor(R.color.red_500_primary), PorterDuff.Mode.SRC_ATOP);

To clear it simply call the clearColorFilter function, like this:

editText.getBackground().clearColorFilter();

Should black box or white box testing be the emphasis for testers?

White Box Testing equals Software Unit Test. The developer or a development level tester (e.g. another developer) ensures that the code he has written is working properly according to the detailed level requirements before integrating it in the system.

Black Box Testing equals Integration Testing. The tester ensures that the system works according to the requirements on a functional level.

Both test approaches are equally important in my opinion.

A thorough unit test will catch defects in the development stage and not after the software has been integrated into the system. A system level black box test will ensure all software modules behave correctly when integrated together. A unit test in the development stage would not catch these defects since modules are usually developed independent from each other.

What is the 'open' keyword in Swift?

Read open as

open for inheritance in other modules

I repeat open for inheritance in other modules. So an open class is open for subclassing in other modules that include the defining module. Open vars and functions are open for overriding in other modules. Its the least restrictive access level. It is as good as public access except that something that is public is closed for inheritance in other modules.

From Apple Docs:

Open access applies only to classes and class members, and it differs from public access as follows:

  1. Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.

  2. Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.

  3. Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.

  4. Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.

The network path was not found

Same problem with me. I solved this by adding @ before connection string (C# has a thing called 'String Literals') like so:

SqlConnection sconnection = new SqlConnection(@"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");

sconnection.Open();

Video auto play is not working in Safari and Chrome desktop browser

I've just get now the same issue with my video

<video preload="none" autoplay="autoplay" loop="loop">
  <source src="Home_Teaser.mp4" type="video/mp4">
  <source src="Home_Teaser" type="video/webm">
  <source src="Home_Teaser.ogv" type="video/ogg">
</video>

After search, I've found a solution:

If I set "preload" attributes to "true" the video start normally

How to round down to nearest integer in MySQL?

Both Query is used for round down the nearest integer in MySQL

  1. SELECT FLOOR(445.6) ;
  2. SELECT NULL(222.456);

Hide keyboard in react-native

For hide keyboard use Keyboard.dismiss() inside TextInput.

How to wrap async function calls into a sync function in Node.js or Javascript?

You've got to use promises:

const asyncOperation = () => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{resolve("hi")}, 3000)
    })
}

const asyncFunction = async () => {
    return await asyncOperation();
}

const topDog = () => {
    asyncFunction().then((res) => {
        console.log(res);
    });
}

I like arrow function definitions more. But any string of the form "() => {...}" could also be written as "function () {...}"

So topDog is not async despite calling an async function.

enter image description here

EDIT: I realize a lot of the times you need to wrap an async function inside a sync function is inside a controller. For those situations, here's a party trick:

const getDemSweetDataz = (req, res) => {
    (async () => {
        try{
            res.status(200).json(
                await asyncOperation()
            );
        }
        catch(e){
            res.status(500).json(serviceResponse); //or whatever
        }
    })() //So we defined and immediately called this async function.
}

Utilizing this with callbacks, you can do a wrap that doesn't use promises:

const asyncOperation = () => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{resolve("hi")}, 3000)
    })
}

const asyncFunction = async (callback) => {
    let res = await asyncOperation();
    callback(res);
}

const topDog = () => {
    let callback = (res) => {
        console.log(res);
    };

    (async () => {
        await asyncFunction(callback)
    })()
}

By applying this trick to an EventEmitter, you can get the same results. Define the EventEmitter's listener where I've defined the callback, and emit the event where I called the callback.

Get list of all tables in Oracle?

Simple query to select the tables for the current user:

  SELECT table_name FROM user_tables;

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

Show / hide div on click with CSS

You could do this with the CSS3 :target selector.

menu:hover block {
    visibility: visible;
}

block:target {
    visibility:hidden;
}

Radio button validation in javascript

You could do something like this

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

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

Insert PHP code In WordPress Page and Post

When I was trying to accomplish something very similar, I ended up doing something along these lines:

wp-content/themes/resources/functions.php

add_action('init', 'my_php_function');
function my_php_function() {
    if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
        // add desired php code here
    }
}

Is optimisation level -O3 dangerous in g++?

In my somewhat checkered experience, applying -O3 to an entire program almost always makes it slower (relative to -O2), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2 relative to -Os!

The intended use pattern for -O3 is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3 optimizations to hot functions -- effectively automating this process.

set initial viewcontroller in appdelegate - swift

For Swift 5+


var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            let submodules = (
                home: HomeRouter.createModule(),
                search: SearchRouter.createModule(),
                exoplanets: ExoplanetsRouter.createModule()
            )
            
            let tabBarController = TabBarModuleBuilder.build(usingSubmodules: submodules)
            
            window.rootViewController = tabBarController
            self.window = window
            window.makeKeyAndVisible()
        }
    }

add string to String array

you would have to write down some method to create a temporary array and then copy it like

public String[] increaseArray(String[] theArray, int increaseBy)  
{  
    int i = theArray.length;  
    int n = ++i;  
    String[] newArray = new String[n];  
    for(int cnt=0;cnt<theArray.length;cnt++)
    {  
        newArray[cnt] = theArray[cnt];  
    }  
    return newArray;  
}  

or The ArrayList would be helpful to resolve your problem.

OnClickListener in Android Studio

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         int id = item.getItemId();
         if (id == R.id.standingsButton) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

Github: Can I see the number of downloads for a repo?

The Github API does not provide the needed information anymore. Take a look at the releases page, mentioned in Stan Towianski's answer. As we discussed in the comments to that answer, the Github API only reports the downloads of 1 of the three files he offers per release.

I have checked the solutions, provided in some other answers to this questions. Vonc's answer presents the essential part of Michele Milidoni's solution. I installed his gdc script with the following result

# ./gdc stant
mdcsvimporter.mxt: 37 downloads
mdcsvimporter.mxt: 80 downloads
How-to-use-mdcsvimporter-beta-16.zip: 12 downloads

As you can clearly see, gdc does not report the download count of the tar.gz and zip files.

If you want to check without installing anything, try the web page where Somsubhra has installed the solution, mentioned in his answer. Fill in 'stant' as Github username and 'mdcsvimporter2015' as Repository name and you will see things like:

Download Info:
mdcsvimporter.mxt(0.20MB) - Downloaded 37 times.
Last updated on 2015-03-26

Alas, once again only a report without the downloads of the tar.gz and zip files. I have carefully examined the information that Github's API returns, but it is not provided anywhere. The download_count that the API does return is far from complete nowadays.

How to get body of a POST in php?

To access the entity body of a POST or PUT request (or any other HTTP method):

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

Also, the STDIN constant is an already-open stream to php://input, so you can alternatively do:

$entityBody = stream_get_contents(STDIN);

From the PHP manual entry on I/O streamsdocs:

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Specifically you'll want to note that the php://input stream, regardless of how you access it in a web SAPI, is not seekable. This means that it can only be read once. If you're working in an environment where large HTTP entity bodies are routinely uploaded you may wish to maintain the input in its stream form (rather than buffering it like the first example above).

To maintain the stream resource something like this can be helpful:

<?php

function detectRequestBody() {
    $rawInput = fopen('php://input', 'r');
    $tempStream = fopen('php://temp', 'r+');
    stream_copy_to_stream($rawInput, $tempStream);
    rewind($tempStream);

    return $tempStream;
}

php://temp allows you to manage memory consumption because it will transparently switch to filesystem storage after a certain amount of data is stored (2M by default). This size can be manipulated in the php.ini file or by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.

Of course, unless you have a really good reason for seeking on the input stream, you shouldn't need this functionality in a web application. Reading the HTTP request entity body once is usually enough -- don't keep clients waiting all day while your app figures out what to do.

Note that php://input is not available for requests specifying a Content-Type: multipart/form-data header (enctype="multipart/form-data" in HTML forms). This results from PHP already having parsed the form data into the $_POST superglobal.

addEventListener for keydown on Canvas

Set the tabindex of the canvas element to 1 or something like this

<canvas tabindex='1'></canvas>

It's an old trick to make any element focusable

If statement in select (ORACLE)

SELECT (CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 1 ELSE 0 END) AS ISSUES
    --  <add any columns to outer select from inner query> 
  FROM
 (  -- your query here --
   select 'CARAT Issue Open' issue_comment, ...., ..., 
          substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else  instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
          case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
     from ....
    where UPPER(ISSUE_STATUS) like '%OPEN%'
 )
 WHERE... -- optional --

Undefined reference to pthread_create in Linux

Compile it like this : gcc demo.c -o demo -pthread

How to create full path with node's fs.mkdirSync?

This version works better on Windows than the top answer because it understands both / and path.sep so that forward slashes work on Windows as they should. Supports absolute and relative paths (relative to the process.cwd).

/**
 * Creates a folder and if necessary, parent folders also. Returns true
 * if any folders were created. Understands both '/' and path.sep as 
 * path separators. Doesn't try to create folders that already exist,
 * which could cause a permissions error. Gracefully handles the race 
 * condition if two processes are creating a folder. Throws on error.
 * @param targetDir Name of folder to create
 */
export function mkdirSyncRecursive(targetDir) {
  if (!fs.existsSync(targetDir)) {
    for (var i = targetDir.length-2; i >= 0; i--) {
      if (targetDir.charAt(i) == '/' || targetDir.charAt(i) == path.sep) {
        mkdirSyncRecursive(targetDir.slice(0, i));
        break;
      }
    }
    try {
      fs.mkdirSync(targetDir);
      return true;
    } catch (err) {
      if (err.code !== 'EEXIST') throw err;
    }
  }
  return false;
}

SQL Server 2008 R2 can't connect to local database in Management Studio

I also received this error when the service stopped. Here's another path to start your service...

  1. Search for "Services" in you start menu like so and click on it:

enter image description here

  1. Find the service for the instance you need started and select it (shown below)
  2. Click start (shown below)

enter image description here

Note: As Kenan stated, if your services Startup Type is not set to Automatic, then you probably want to double click on the service and set it to Automatic.

Unzip files (7-zip) via cmd command

Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:

set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z

You should see as output (or something similar - as this is on my laptop running Windows 7):

C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\

C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\

C:\Users\Phillip>7z

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18

Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
       [<@listfiles...>]

<Commands>
  a: Add files to archive
  b: Benchmark
  d: Delete files from archive
  e: Extract files from archive (without using directory names)
  l: List contents of archive
  t: Test integrity of archive
  u: Update files to archive
  x: eXtract files with full paths
<Switches>
  -ai[r[-|0]]{@listfile|!wildcard}: Include archives
  -ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
  -bd: Disable percentage indicator
  -i[r[-|0]]{@listfile|!wildcard}: Include filenames
  -m{Parameters}: set compression Method
  -o{Directory}: set Output directory
  -p{Password}: set Password
  -r[-|0]: Recurse subdirectories
  -scs{UTF-8 | WIN | DOS}: set charset for list files
  -sfx[{name}]: Create SFX archive
  -si[{name}]: read data from stdin
  -slt: show technical information for l (List) command
  -so: write data to stdout
  -ssc[-]: set sensitive case mode
  -ssw: compress shared files
  -t{Type}: Set type of archive
  -u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
  -v{Size}[b|k|m|g]: Create volumes
  -w[{path}]: assign Work directory. Empty path means a temporary directory
  -x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
  -y: assume Yes on all queries

Reading a binary file with python

You could use numpy.fromfile, which can read data from both text and binary files. You would first construct a data type, which represents your file format, using numpy.dtype, and then read this type from file using numpy.fromfile.

Android REST client, Sample?

EDIT 2 (October 2017):

It is 2017. Just use Retrofit. There is almost no reason to use anything else.

EDIT:

The original answer is more than a year and a half old at the time of this edit. Although the concepts presented in original answer still hold, as other answers point out, there are now libraries out there that make this task easier for you. More importantly, some of these libraries handle device configuration changes for you.

The original answer is retained below for reference. But please also take the time to examine some of the Rest client libraries for Android to see if they fit your use cases. The following is a list of some of the libraries I've evaluated. It is by no means intended to be an exhaustive list.


Original Answer:

Presenting my approach to having REST clients on Android. I do not claim it is the best though :) Also, note that this is what I came up with in response to my requirement. You might need to have more layers/add more complexity if your use case demands it. For example, I do not have local storage at all; because my app can tolerate loss of a few REST responses.

My approach uses just AsyncTasks under the covers. In my case, I "call" these Tasks from my Activity instance; but to fully account for cases like screen rotation, you might choose to call them from a Service or such.

I consciously chose my REST client itself to be an API. This means, that the app which uses my REST client need not even be aware of the actual REST URL's and the data format used.

The client would have 2 layers:

  1. Top layer: The purpose of this layer is to provide methods which mirror the functionality of the REST API. For example, you could have one Java method corresponding to every URL in your REST API (or even two - one for GETs and one for POSTs).
    This is the entry point into the REST client API. This is the layer the app would use normally. It could be a singleton, but not necessarily.
    The response of the REST call is parsed by this layer into a POJO and returned to the app.

  2. This is the lower level AsyncTask layer, which uses HTTP client methods to actually go out and make that REST call.

In addition, I chose to use a Callback mechanism to communicate the result of the AsyncTasks back to the app.

Enough of text. Let's see some code now. Lets take a hypothetical REST API URL - http://myhypotheticalapi.com/user/profile

The top layer might look like this:

   /**
 * Entry point into the API.
 */
public class HypotheticalApi{   
    public static HypotheticalApi getInstance(){
        //Choose an appropriate creation strategy.
    }
    
    /**
     * Request a User Profile from the REST server.
     * @param userName The user name for which the profile is to be requested.
     * @param callback Callback to execute when the profile is available.
     */
    public void getUserProfile(String userName, final GetResponseCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(userName);
        new GetTask(restUrl, new RestTaskCallback (){
            @Override
            public void onTaskComplete(String response){
                Profile profile = Utils.parseResponseAsProfile(response);
                callback.onDataReceived(profile);
            }
        }).execute();
    }
    
    /**
     * Submit a user profile to the server.
     * @param profile The profile to submit
     * @param callback The callback to execute when submission status is available.
     */
    public void postUserProfile(Profile profile, final PostCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(profile);
        String requestBody = Utils.serializeProfileAsString(profile);
        new PostTask(restUrl, requestBody, new RestTaskCallback(){
            public void onTaskComplete(String response){
                callback.onPostSuccess();
            }
        }).execute();
    }
}


/**
 * Class definition for a callback to be invoked when the response data for the
 * GET call is available.
 */
public abstract class GetResponseCallback{
    
    /**
     * Called when the response data for the REST call is ready. <br/>
     * This method is guaranteed to execute on the UI thread.
     * 
     * @param profile The {@code Profile} that was received from the server.
     */
    abstract void onDataReceived(Profile profile);
    
    /*
     * Additional methods like onPreGet() or onFailure() can be added with default implementations.
     * This is why this has been made and abstract class rather than Interface.
     */
}

/**
 * 
 * Class definition for a callback to be invoked when the response for the data 
 * submission is available.
 * 
 */
public abstract class PostCallback{
    /**
     * Called when a POST success response is received. <br/>
     * This method is guaranteed to execute on the UI thread.
     */
    public abstract void onPostSuccess();

}

Note that the app doesn't use the JSON or XML (or whatever other format) returned by the REST API directly. Instead, the app only sees the bean Profile.

Then, the lower layer (AsyncTask layer) might look like this:

/**
 * An AsyncTask implementation for performing GETs on the Hypothetical REST APIs.
 */
public class GetTask extends AsyncTask<String, String, String>{
    
    private String mRestUrl;
    private RestTaskCallback mCallback;
    
    /**
     * Creates a new instance of GetTask with the specified URL and callback.
     * 
     * @param restUrl The URL for the REST API.
     * @param callback The callback to be invoked when the HTTP request
     *            completes.
     * 
     */
    public GetTask(String restUrl, RestTaskCallback callback){
        this.mRestUrl = restUrl;
        this.mCallback = callback;
    }
    
    @Override
    protected String doInBackground(String... params) {
        String response = null;
        //Use HTTP Client APIs to make the call.
        //Return the HTTP Response body here.
        return response;
    }
    
    @Override
    protected void onPostExecute(String result) {
        mCallback.onTaskComplete(result);
        super.onPostExecute(result);
    }
}

    /**
     * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
     */
    public class PostTask extends AsyncTask<String, String, String>{
        private String mRestUrl;
        private RestTaskCallback mCallback;
        private String mRequestBody;
        
        /**
         * Creates a new instance of PostTask with the specified URL, callback, and
         * request body.
         * 
         * @param restUrl The URL for the REST API.
         * @param callback The callback to be invoked when the HTTP request
         *            completes.
         * @param requestBody The body of the POST request.
         * 
         */
        public PostTask(String restUrl, String requestBody, RestTaskCallback callback){
            this.mRestUrl = restUrl;
            this.mRequestBody = requestBody;
            this.mCallback = callback;
        }
        
        @Override
        protected String doInBackground(String... arg0) {
            //Use HTTP client API's to do the POST
            //Return response.
        }
        
        @Override
        protected void onPostExecute(String result) {
            mCallback.onTaskComplete(result);
            super.onPostExecute(result);
        }
    }
    
    /**
     * Class definition for a callback to be invoked when the HTTP request
     * representing the REST API Call completes.
     */
    public abstract class RestTaskCallback{
        /**
         * Called when the HTTP request completes.
         * 
         * @param result The result of the HTTP request.
         */
        public abstract void onTaskComplete(String result);
    }

Here's how an app might use the API (in an Activity or Service):

HypotheticalApi myApi = HypotheticalApi.getInstance();
        myApi.getUserProfile("techie.curious", new GetResponseCallback() {

            @Override
            void onDataReceived(Profile profile) {
                //Use the profile to display it on screen, etc.
            }
            
        });
        
        Profile newProfile = new Profile();
        myApi.postUserProfile(newProfile, new PostCallback() {
            
            @Override
            public void onPostSuccess() {
                //Display Success
            }
        });

I hope the comments are sufficient to explain the design; but I'd be glad to provide more info.

How to get a list of images on docker registry v2

you can search on

http://<ip/hostname>:<port>/v2/_catalog

How to automatically indent source code?

In 2010 it is Ctrl+k, Ctrl+d. See image below.

enter image description here

Create XML file using java

package com.server;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


import org.w3c.dom.*;

import com.gwtext.client.data.XmlReader;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;  

public class XmlServlet extends HttpServlet
{ 

  NodeList list;
  Connection con=null;
  Statement st=null;
  ResultSet rs = null;
  String xmlString ;
  BufferedWriter bw;
  String displayTo;
  String displayFrom;
  String addressto;
  String addressFrom;
  Date send;
  String Subject;
  String body;
  String category;
  Document doc1;
  public void doGet(HttpServletRequest request,HttpServletResponse response)
   throws ServletException,IOException{

    System.out.print("on server");  

  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  System.out.print("on server");
  try
  {


    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
    //creating a new instance of a DOM to build a DOM tree.
    doc1 = docBuilder.newDocument();
    new XmlServlet().createXmlTree(doc1);

    System.out.print("on server");

  }
  catch(Exception e)
  {
  System.out.println(e.toString());
  }

   }

  public void createXmlTree(Document doc) throws Exception {
  //This method creates an element node

    System.out.println("ruchipaliwal111");

    try
    {

      System.out.println("ruchi111");
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1");
      st = con.createStatement();

      rs = st.executeQuery("select * from data");


      Element root = doc.createElement("message");
      doc.appendChild(root);

        while(rs.next())
        {



       displayTo=rs.getString(1).toString();
       System.out.println(displayTo+"getdataname");

       displayFrom=rs.getString(2).toString();
       System.out.println(displayFrom +"getdataname");

         addressto=rs.getString(3).toString();
         System.out.println(addressto +"getdataname");

       addressFrom=rs.getString(4).toString();
       System.out.println(addressFrom +"getdataname");

       send=rs.getDate(5);
       System.out.println(send +"getdataname");

       Subject=rs.getString(6).toString();
       System.out.println(Subject +"getdataname");

       body=rs.getString(7).toString();
       System.out.println(body+"getdataname");

      category=rs.getString(8).toString();
       System.out.println(category +"getdataname");


       //adding a node after the last child node of ssthe specified node.


        Element element1 = doc.createElement("Header");
        root.appendChild(element1);


        Element child1 = doc.createElement("To");
        element1.appendChild(child1);

        child1.setAttribute("displayNameTo",displayTo);
        child1.setAttribute("addressTo",addressto);

        Element child2 = doc.createElement("From");
        element1.appendChild(child2);

        child2.setAttribute("displayNameFrom",displayFrom);
        child2.setAttribute("addressFrom",addressFrom);

        Element child3 = doc.createElement("Send");
        element1.appendChild(child3);

        Text text2 = doc.createTextNode(send.toString());
        child3.appendChild(text2);

        Element child4 = doc.createElement("Subject");
        element1.appendChild(child4);

        Text text3 = doc.createTextNode(Subject);
        child4.appendChild(text3);

        Element child5 = doc.createElement("category");
        element1.appendChild(child5);

        Text text44 = doc.createTextNode(category);
        child5.appendChild(text44);


        Element element2 = doc.createElement("Body");
        root.appendChild(element2);

        Text text1 = doc.createTextNode(body);
        element2.appendChild(text1);

       /*
        Element child1 = doc.createElement("name");
        root.appendChild(child1);
        Text text = doc.createTextNode(getdataname);
        child1.appendChild(text);
        Element element = doc.createElement("address");
        root.appendChild(element);
        Text text1 = doc.createTextNode( getdataaddress);
        element.appendChild(text1); 
     */
      } 






//TransformerFactory instance is used to create Transformer objects. 
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer();

  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty(OutputKeys.METHOD,"xml");
  // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");


  // create string from xml tree
  StringWriter sw = new StringWriter();
  StreamResult result = new StreamResult(sw);
  DOMSource source = new DOMSource(doc);
  transformer.transform(source, result);

  xmlString = sw.toString();


  File file = new File("./war/ds/newxml.xml");
  bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
  bw.write(xmlString);
   }

    catch(Exception e)
    {
      System.out.print("after while loop exception"+e.toString());
    }

  bw.flush();
  bw.close();
  System.out.println("successfully done.....");
  }
}

Set the Value of a Hidden field using JQuery

If you have a hidden field like this

  <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>

Now you can use your value like this

$(this).parent().find('input[type=hidden]').val()

Cell Style Alignment on a range

  ExcelApp.Sheets[1].Range[ExcelApp.Sheets[1].Cells[1, 1], ExcelApp.Sheets[1].Cells[70, 15]].Cells.HorizontalAlignment =
                 Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

This works fine for me.

JQuery .on() method with multiple event handlers to one selector

And you can combine same events/functions in this way:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    'click blur paste' : function() {
        // Handle click...
    }
}, "input");

Sending an Intent to browser to open specific URL

Use following snippet in your code

Intent newIntent = new Intent(Intent.ACTION_VIEW, 
Uri.parse("https://www.google.co.in/?gws_rd=cr"));
startActivity(newIntent);

Use This link

http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW

iOS: How to store username/password within an app?

The following should work just fine:

KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
[keychainItem setObject:@"password you are saving" forKey:kSecValueData]; 
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];

count (non-blank) lines-of-code in bash

grep -v '^\W*$' `find -type f` | grep -c '.' > /path/to/lineCountFile.txt

gives an aggregate count for all files in the current directory and its subdirectories.

HTH!

What is the easiest way to ignore a JPA field during persistence?

Sometimes you want to:

  1. Serialize a column
  2. Ignore column from being persisted:

Use @Column(name = "columnName", insertable = false, updatable = false)

A good scenario is when a certain column is automatically calculated by using other column values

How to declare variable and use it in the same Oracle SQL script?

In PL/SQL v.10

keyword declare is used to declare variable

DECLARE stupidvar varchar(20);

to assign a value you can set it when you declare

DECLARE stupidvar varchar(20) := '12345678';

or to select something into that variable you use INTO statement, however you need to wrap statement in BEGIN and END, also you need to make sure that only single value is returned, and don't forget semicolons.

so the full statement would come out following:

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;
END;

Your variable is only usable within BEGIN and END so if you want to use more than one you will have to do multiple BEGIN END wrappings

DECLARE stupidvar varchar(20);
BEGIN
    SELECT stupid into stupidvar FROM stupiddata CC 
    WHERE stupidid = 2;

    DECLARE evenmorestupidvar varchar(20);
    BEGIN
        SELECT evenmorestupid into evenmorestupidvar FROM evenmorestupiddata CCC 
        WHERE evenmorestupidid = 42;

        INSERT INTO newstupiddata (newstupidcolumn, newevenmorestupidstupidcolumn)
        SELECT stupidvar, evenmorestupidvar 
        FROM dual

    END;
END;

Hope this saves you some time

How to find difference between two columns data?

Yes, you can select the data, calculate the difference, and insert all values in the other table:

insert into #temp2 (Difference)
select previous - Present
from #TEMP1

Use Excel pivot table as data source for another Pivot Table

In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.

What's the fastest way to loop through an array in JavaScript?

It's just 2018 so an update could be nice...

And I really have to disagree with the accepted answer. It defers on different browsers. some do forEach faster, some for-loop, and some while here is a benchmark on all method http://jsben.ch/mW36e

arr.forEach( a => {
  // ...
}

and since you can see alot of for-loop like for(a = 0; ... ) then worth to mention that without 'var' variables will be define globally and this can dramatically affects on speed so it'll get slow.

Duff's device run faster on opera but not in firefox

_x000D_
_x000D_
var arr = arr = new Array(11111111).fill(255);_x000D_
var benches =     _x000D_
[ [ "empty", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++);_x000D_
}]_x000D_
, ["for-loop", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; ++a)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop++", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop - arr.length", () => {_x000D_
  for(var a = 0; a < arr.length; ++a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["reverse for-loop", () => {_x000D_
  for(var a = arr.length - 1; a >= 0; --a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
,["while-loop", () => {_x000D_
  var a = 0, l = arr.length;_x000D_
  while( a < l ) {_x000D_
    var b = arr[a] + 1;_x000D_
    ++a;_x000D_
  }_x000D_
}]_x000D_
, ["reverse-do-while-loop", () => {_x000D_
  var a = arr.length - 1; // CAREFUL_x000D_
  do {_x000D_
    var b = arr[a] + 1;_x000D_
  } while(a--);   _x000D_
}]_x000D_
, ["forEach", () => {_x000D_
  arr.forEach( a => {_x000D_
    var b = a + 1;_x000D_
  });_x000D_
}]_x000D_
, ["for const..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( const a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for let..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( let a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for var..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( var a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["Duff's device", () => {_x000D_
  var len = arr.length;_x000D_
  var i, n = len % 8 - 1;_x000D_
_x000D_
  if (n > 0) {_x000D_
    do {_x000D_
      var b = arr[len-n] + 1;_x000D_
    } while (--n); // n must be greater than 0 here_x000D_
  }_x000D_
  n = (len * 0.125) ^ 0;_x000D_
  if (n > 0) { _x000D_
    do {_x000D_
      i = --n <<3;_x000D_
      var b = arr[i] + 1;_x000D_
      var c = arr[i+1] + 1;_x000D_
      var d = arr[i+2] + 1;_x000D_
      var e = arr[i+3] + 1;_x000D_
      var f = arr[i+4] + 1;_x000D_
      var g = arr[i+5] + 1;_x000D_
      var h = arr[i+6] + 1;_x000D_
      var k = arr[i+7] + 1;_x000D_
    }_x000D_
    while (n); // n must be greater than 0 here also_x000D_
  }_x000D_
}]];_x000D_
function bench(title, f) {_x000D_
  var t0 = performance.now();_x000D_
  var res = f();_x000D_
  return performance.now() - t0; // console.log(`${title} took ${t1-t0} msec`);_x000D_
}_x000D_
var globalVarTime = bench( "for-loop without 'var'", () => {_x000D_
  // Here if you forget to put 'var' so variables'll be global_x000D_
  for(a = 0, l = arr.length; a < l; ++a)_x000D_
     var b = arr[a] + 1;_x000D_
});_x000D_
var times = benches.map( function(a) {_x000D_
                      arr = new Array(11111111).fill(255);_x000D_
                      return [a[0], bench(...a)]_x000D_
                     }).sort( (a,b) => a[1]-b[1] );_x000D_
var max = times[times.length-1][1];_x000D_
times = times.map( a => {a[2] = (a[1]/max)*100; return a; } );_x000D_
var template = (title, time, n) =>_x000D_
  `<div>` +_x000D_
    `<span>${title} &nbsp;</span>` +_x000D_
    `<span style="width:${3+n/2}%">&nbsp;${Number(time.toFixed(3))}msec</span>` +_x000D_
  `</div>`;_x000D_
_x000D_
var strRes = times.map( t => template(...t) ).join("\n") + _x000D_
            `<br><br>for-loop without 'var' ${globalVarTime} msec.`;_x000D_
var $container = document.getElementById("container");_x000D_
$container.innerHTML = strRes;
_x000D_
body { color:#fff; background:#333; font-family:helvetica; }_x000D_
body > div > div {  clear:both   }_x000D_
body > div > div > span {_x000D_
  float:left;_x000D_
  width:43%;_x000D_
  margin:3px 0;_x000D_
  text-align:right;_x000D_
}_x000D_
body > div > div > span:nth-child(2) {_x000D_
  text-align:left;_x000D_
  background:darkorange;_x000D_
  animation:showup .37s .111s;_x000D_
  -webkit-animation:showup .37s .111s;_x000D_
}_x000D_
@keyframes showup { from { width:0; } }_x000D_
@-webkit-keyframes showup { from { width:0; } }
_x000D_
<div id="container"> </div>
_x000D_
_x000D_
_x000D_

How do I pass data to Angular routed components?

Some super smart person (tmburnell) that is not me suggests re-writing the route data:

let route = this.router.config.find(r => r.path === '/path');
route.data = { entity: 'entity' };
this.router.navigateByUrl('/path');

As seen here in the comments.

I hope someone will find this useful

Python code to remove HTML tags from a string

Python has several XML modules built in. The simplest one for the case that you already have a string with the full HTML is xml.etree, which works (somewhat) similarly to the lxml example you mention:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

Don't reload application when orientation changes

It's my experience that it's actually better to just deal with the orientation changes properly instead of trying to shoehorn a non-default behavior.

You should save the image that's currently being displayed in onSaveInstanceState() and restore it properly when your application runs through onCreate() again.

Incrementing a variable inside a Bash loop

I had the same $count variable in a while loop getting lost issue.

@fedorqui's answer (and a few others) are accurate answers to the actual question: the sub-shell is indeed the problem.

But it lead me to another issue: I wasn't piping a file content... but the output of a series of pipes & greps...

my erroring sample code:

count=0
cat /etc/hosts | head | while read line; do
  ((count++))
  echo $count $line
done
echo $count

and my fix thanks to the help of this thread and the process substitution:

count=0
while IFS= read -r line; do
  ((count++))
  echo "$count $line"
done < <(cat /etc/hosts | head)
echo "$count"

How do I pass parameters into a PHP script through a webpage?

$argv[0]; // the script name
$argv[1]; // the first parameter
$argv[2]; // the second parameter

If you want to all the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

<?php
if ($_GET) {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
} else {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
?>

To call from command line chmod 755 /var/www/webroot/index.php and use

/usr/bin/php /var/www/webroot/index.php arg1 arg2

To call from the browser, use

http://www.mydomain.com/index.php?argument1=arg1&argument2=arg2

Passing vector by reference

If you define your function to take argument of std::vector<int>& arr and integer value, then you can use push_back inside that function:

void do_something(int el, std::vector<int>& arr)
{
    arr.push_back(el);
    //....
}

usage:

std::vector<int> arr;
do_something(1, arr); 

Swift - Split string over multiple lines

Swift 4 has addressed this issue by giving Multi line string literal support.To begin string literal add three double quotes marks (”””) and press return key, After pressing return key start writing strings with any variables , line breaks and double quotes just like you would write in notepad or any text editor. To end multi line string literal again write (”””) in new line.

See Below Example

     let multiLineStringLiteral = """
    This is one of the best feature add in Swift 4
    It let’s you write “Double Quotes” without any escaping
    and new lines without need of “\n”
    """

print(multiLineStringLiteral)

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

I experienced the same problem on my repository. I'm the master of the repository, but I had such an error.

I've unprotected my project and then re-protected again, and the error is gone.

We had upgraded the gitlab version between my previous push and the problematic one. I suppose that this upgrade has created the bug.

Turning off eslint rule for a specific line

Or for multiple ignores on the next line, string the rules using commas

// eslint-disable-next-line class-methods-use-this, no-unused-vars

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Asked and answered before...

Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )"

"1" is a non-null expression so it's the same as COUNT(*). The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK) = COUNT(*)

This is a similar myth to EXISTS (SELECT * ... or EXISTS (SELECT 1 ...

And see the ANSI 92 spec, section 6.5, General Rules, case 1

        a) If COUNT(*) is specified, then the result is the cardinality
          of T.

        b) Otherwise, let TX be the single-column table that is the
          result of applying the <value expression> to each row of T
          and eliminating null values. If one or more null values are
          eliminated, then a completion condition is raised: warning-
          null value eliminated in set function.

Find records from one table which don't exist in another

SELECT name, phone_number FROM Call a
WHERE a.phone_number NOT IN (SELECT b.phone_number FROM Phone_book b)

Meaning of "487 Request Terminated"

It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).

Here is a nice CANCEL SIP Call Flow illustration.

PHP: convert spaces in string into %20?

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

Second line in li starts under the bullet after CSS-reset

Here is a good example -

ul li{
    list-style-type: disc;
    list-style-position: inside;
    padding: 10px 0 10px 20px;
    text-indent: -1em;
}

Working Demo: http://jsfiddle.net/d9VNk/

Check if key exists and iterate the JSON array using Python

import json

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    if 'to' not in data:
        raise ValueError("No target in given data")
    if 'data' not in data['to']:
        raise ValueError("No data for target")

    for dest in data['to']['data']:
        if 'id' not in dest:
            continue
        targetId = dest['id']
        print("to_id:", targetId)

Output:

In [9]: getTargetIds(s)
to_id: 1543

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

select to_char(sysdate, 'DD-fmMONTH-YYYY') "Date" from Dual;

The above query result will be as given below.

Date

01-APRIL-2019

How do I programmatically set device orientation in iOS 7?

If you want to lock the main view of your app to portrait, but want to open popup views in landscape, and you are using tabBarController as rootViewController as I am, you can use this code on your AppDelegate.

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UITabBarController *tabBarController;

@end

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Create a tab bar and set it as root view for the application
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.delegate = self;
    self.window.rootViewController = self.tabBarController;

    ...
}

- (NSUInteger)tabBarControllerSupportedInterfaceOrientations:(UITabBarController *)tabBarController
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)tabBarControllerPreferredInterfaceOrientationForPresentation:(UITabBarController *)tabBarController
{
    return UIInterfaceOrientationPortrait;
}

It works very well.

In your viewController you want to be presented in landscape, you simply use the following:

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL)shouldAutorotate {
    return YES;
}

How to jump to a particular line in a huge text file?

Can use this function to return line n:

def skipton(infile, n):
    with open(infile,'r') as fi:
        for i in range(n-1):
            fi.next()
        return fi.next()

How to Reload ReCaptcha using JavaScript?

grecaptcha.reset(opt_widget_id)

Resets the reCAPTCHA widget. An optional widget id can be passed, otherwise the function resets the first widget created. (from Google's web page)

How to get the position of a character in Python?

>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

"Long winded" way

>>> for i,c in enumerate(s):
...   if "r"==c: print i
...
4

to get substring,

>>> s="mystring"
>>> s[4:10]
'ring'

Disabling the long-running-script message in Internet Explorer

This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.

Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.

The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.

Breaking up a loop with timers is relatively straightforward:

var i=0;
(function () {
    for (; i < 6000000; i++) {
        /*
            Normal processing here
        */

        // Every 100,000 iterations, take a break
        if ( i > 0 && i % 100000 == 0) {
            // Manually increment `i` because we break
            i++;
            // Set a timer for the next iteration 
            window.setTimeout(arguments.callee);
            break;
        }
    }
})();

How can I check file size in Python?

You can check a file size by using

import sys
print(sys.getsizeof(your_file))

For example,

nums = range(10000)
squares = [i**2 for i in nums]
print(sys.getsizeof(squares))

What does the return keyword do in a void method in Java?

The Java language specification says you can have return with no expression if your method returns void.

How do I clone a range of array elements to a new array?

As an alternative to copying the data you can make a wrapper that gives you access to a part of the original array as if it was a copy of the part of the array. The advantage is that you don't get another copy of the data in memory, and the drawback is a slight overhead when accessing the data.

public class SubArray<T> : IEnumerable<T> {

   private T[] _original;
   private int _start;

   public SubArray(T[] original, int start, int len) {
      _original = original;
      _start = start;
      Length = len;
   }

   public T this[int index] {
      get {
         if (index < 0 || index >= Length) throw new IndexOutOfRangeException();
         return _original[_start + index];
      }
   }

   public int Length { get; private set; }

   public IEnumerator<T> GetEnumerator() {
      for (int i = 0; i < Length; i++) {
        yield return _original[_start + i];
      }
   }

   IEnumerator IEnumerable.GetEnumerator() {
      return GetEnumerator();
   }

}

Usage:

int[] original = { 1, 2, 3, 4, 5 };
SubArray<int> copy = new SubArray<int>(original, 2, 2);

Console.WriteLine(copy.Length); // shows: 2
Console.WriteLine(copy[0]); // shows: 3
foreach (int i in copy) Console.WriteLine(i); // shows 3 and 4

IntelliJ - Convert a Java project/module into a Maven project/module

A visual for those that benefit from it.

enter image description here

After right-clicking the project name ("test" in this example), select "Add framework support" and check the "Maven" option.

Passing arrays as parameters in bash

Just to add to the accepted answer, as I found it doesn't work well if the array contents are someting like:

RUN_COMMANDS=(
  "command1 param1... paramN"
  "command2 param1... paramN"
)

In this case, each member of the array gets split, so the array the function sees is equivalent to:

RUN_COMMANDS=(
    "command1"
    "param1"
     ...
    "command2"
    ...
)

To get this case to work, the way I found is to pass the variable name to the function, then use eval:

function () {
    eval 'COMMANDS=( "${'"$1"'[@]}" )'
    for COMMAND in "${COMMANDS[@]}"; do
        echo $COMMAND
    done
}

function RUN_COMMANDS

Just my 2©

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

remove double quotes from Json return data using Jquery

Use replace:

var test = "\"House\"";
console.log(test);
console.log(test.replace(/\"/g, ""));  

// "House"
// House

Note the g on the end means "global" (replace all).

How do I sort an observable collection?

To improve a little bit the extension method on xr280xr answer I added an optional bool parameter to determine whether the sorting is descending or not. I also included the suggestion made by Carlos P in the comment to that answer. Please see below.

public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector, bool desc = false)
    {
        if (source == null) return;

        Comparer<TKey> comparer = Comparer<TKey>.Default;

        for (int i = source.Count - 1; i >= 0; i--)
        {
            for (int j = 1; j <= i; j++)
            {
                TSource o1 = source[j - 1];
                TSource o2 = source[j];
                int comparison = comparer.Compare(keySelector(o1), keySelector(o2));
                if (desc && comparison < 0)
                    source.Move(j, j - 1);
                else if (!desc && comparison > 0)
                    source.Move(j - 1, j);
            }
        }
    }

Recommended method for escaping HTML in Java

On android (API 16 or greater) you can:

Html.escapeHtml(textToScape);

or for lower API:

TextUtils.htmlEncode(textToScape);

How to get a reversed list view on a list in Java?

If i have understood correct then it is one line of code .It worked for me .

 Collections.reverse(yourList);

pull/push from multiple remote locations

add an alias to global gitconfig(/home/user/.gitconfig) with below command.

git config --global alias.pushall '!f(){ for var in $(git remote show); do echo "pushing to $var"; git push $var; done; }; f'

Once you commit code, we say

git push

to push to origin by default. After above alias, we can say

git pushall

and code will be updated to all remotes including origin remote.

Query an XDocument for elements by name at any depth

We know the above is true. Jon is never wrong; real life wishes can go a little further.

<ota:OTA_AirAvailRQ
    xmlns:ota="http://www.opentravel.org/OTA/2003/05" EchoToken="740" Target=" Test" TimeStamp="2012-07-19T14:42:55.198Z" Version="1.1">
    <ota:OriginDestinationInformation>
        <ota:DepartureDateTime>2012-07-20T00:00:00Z</ota:DepartureDateTime>
    </ota:OriginDestinationInformation>
</ota:OTA_AirAvailRQ>

For example, usually the problem is, how can we get EchoToken in the above XML document? Or how to blur the element with the name attribute.

  1. You can find them by accessing with the namespace and the name like below

     doc.Descendants().Where(p => p.Name.LocalName == "OTA_AirAvailRQ").Attributes("EchoToken").FirstOrDefault().Value
    
  2. You can find it by the attribute content value, like this one.

Laravel Eloquent limit and offset

skip = OFFSET
$products = $art->products->skip(0)->take(10)->get(); //get first 10 rows
$products = $art->products->skip(10)->take(10)->get(); //get next 10 rows

From laravel doc 5.2 https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

skip / take

To limit the number of results returned from the query, or to skip a given number of results in the query (OFFSET), you may use the skip and take methods:

$users = DB::table('users')->skip(10)->take(5)->get();

In laravel 5.3 you can write (https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset)

$products = $art->products->offset(0)->limit(10)->get(); 

Angular 2 Dropdown Options Default Value

works great as seen below:

<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
          [class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
           (this.docForm.controls['tipoDocumento'].touched ||  this.docForm.controls['tipoDocumento'].dirty)"
          [class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
           (this.docForm.controls['tipoDocumento'].touched ||  this.docForm.controls['tipoDocumento'].dirty)">
            <option value="">Selecione um tipo</option>
            <option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
          </select>

How to send 100,000 emails weekly?

People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

Here's a summary of what we found...

AuthSMTP

  • Cheapest around
  • No analysis/reporting
  • No tracking for opens/clicks
  • Had slight hesitation on some sends

Postmark

  • Very cheap, but not as cheap as AuthSMTP
  • Beautiful cpanel but no tracking on opens/clicks
  • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
  • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
  • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
  • Requires a set list of from names/addresses.

JangoSMTP

  • Expensive in relation to the others – more than 10 times in some cases
  • Ugly cpanel but great tracking on opens/clicks with email-level detail
  • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
  • Requires a set list of from name/addresses.

SendGrid

  • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
  • Decent cpanel but no in-depth detail on open/click tracking
  • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
  • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
  • Can send from any from name/address.

Conclusion

SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

How Can I Remove “public/index.php” in the URL Generated Laravel?

Laravel ships with a pretty URL .htaccess already... you should be good to go out of the box... http://laravel.com/docs/installation#pretty-urls

Make sure mod_rewrite is enabled and that your home path is set to the public directory of your application.

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Most updated solution

If you are using Javascript, the best solution that I came up with is using match instead of exec method. Then, iterate matches and remove the delimiters with the result of the first group using $1

const text = "This is a test string [more or less], [more] and [less]";
const regex = /\[(.*?)\]/gi;
const resultMatchGroup = text.match(regex); // [ '[more or less]', '[more]', '[less]' ]
const desiredRes = resultMatchGroup.map(match => match.replace(regex, "$1"))
console.log("desiredRes", desiredRes); // [ 'more or less', 'more', 'less' ]

As you can see, this is useful for multiple delimiters in the text as well

How do I test for an empty JavaScript object?

Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.

Tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:

  • (for...in...) is the fastest option to use!
  • Object.keys(obj).length is 10 times slower for empty objects
  • JSON.stringify(obj).length is always the slowest (not suprising)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.

Bottom line performance wise, use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

function isEmpty(obj) {
   for (var x in obj) { if (obj.hasOwnProperty(x))  return false; }
   return true;
}

See detailed testing results and test code at Is object empty?

How to get the clicked link's href with jquery?

Suppose we have three anchor tags like ,

<a  href="ID=1" class="testClick">Test1.</a>
<br />
<a  href="ID=2" class="testClick">Test2.</a>
<br />
<a  href="ID=3" class="testClick">Test3.</a>

now in script

$(".testClick").click(function () {
        var anchorValue= $(this).attr("href");
        alert(anchorValue);
});

use this keyword instead of className (testClick)

"401 Unauthorized" on a directory

  1. Open IIS and select site that is causing 401
  2. Select Authentication property in IIS Header
  3. Select Anonymous Authentication
  4. Right click on it, select Edit and choose Application pool identity
  5. Restart site and it should work

Scanner is skipping nextLine() after using next() or nextFoo()?

The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.

Try it like that:

System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();

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

Writing MemoryStream to Response Object

Try with this

Response.Clear();
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));
Response.Flush();                
Response.BinaryWrite(masterPresentation.ToArray());
Response.End();

Show hide divs on click in HTML and CSS without jQuery

Using display:none is not SEO-friendly. The following way allows the hidden content to be searchable. Adding the transition-delay ensures any links included in the hidden content is clickable.

.collapse > p{
cursor: pointer;
display: block;
}

.collapse:focus{
outline: none;
}

.collapse > div {
height: 0;
width: 0;
overflow: hidden;
transition-delay: 0.3s;
}

.collapse:focus div{
display: block; 
height: 100%;
width: 100%;
overflow: auto;
}

<div class="collapse" tabindex="1">
<p>Question 1</p>
<div>
  <p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
<div class="collapse" tabindex="2">
<p>Question 2</p>
<div>
  <p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div> 

How to catch a unique constraint error in a PL/SQL block?

As an alternative to explicitly catching and handling the exception you could tell Oracle to catch and automatically ignore the exception by including a /*+ hint */ in the insert statement. This is a little faster than explicitly catching the exception and then articulating how it should be handled. It is also easier to setup. The downside is that you do not get any feedback from Oracle that an exception was caught.

Here is an example where we would be selecting from another table, or perhaps an inner query, and inserting the results into a table called TABLE_NAME which has a unique constraint on a column called IDX_COL_NAME.

INSERT /*+ ignore_row_on_dupkey_index(TABLE_NAME(IDX_COL_NAME)) */ 
INTO TABLE_NAME(
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n)
SELECT 
    INDEX_COL_NAME
  , col_1
  , col_2
  , col_3
  , ...
  , col_n);

This is not a great solution if your goal it to catch and handle (i.e. print out or update the row that is violating the constraint). But if you just wanted to catch it and ignore the violating row then then this should do the job.

Not able to access adb in OS X through Terminal, "command not found"

For some reason when installed Android Studio 3.6.1 the adb file was actually in $ANDROID_HOME/platform-tools/platform-tools. not sure if this is a bug with my installation or what but this fixed it for me.

Remove a JSON attribute

The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.

For example:

var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}

//that will not work.
delete myObj.test.keyToDelete 

instead you would need to use:

delete myObj.test[keyToDelete];

Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.

What is apache's maximum url length?

Allowed default size of URI is 8177 characters in GET request. Simple code in python for such testing.

#!/usr/bin/env python2

import sys
import socket

if __name__ == "__main__":
    string = sys.argv[1]
    buf_get = "x" * int(string)
    buf_size = 1024
    request = "HEAD %s HTTP/1.1\nHost:localhost\n\n" % buf_get
    print "===>", request

    sock_http = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_http.connect(("localhost", 80))
    sock_http.send(request)
    while True:
       print "==>", sock_http.recv(buf_size)
       if not sock_http.recv(buf_size):
           break
    sock_http.close()

On 8178 characters you will get such message: HTTP/1.1 414 Request-URI Too Large

Difference between string and char[] types in C++

Strings have helper functions and manage char arrays automatically. You can concatenate strings, for a char array you would need to copy it to a new array, strings can change their length at runtime. A char array is harder to manage than a string and certain functions may only accept a string as input, requiring you to convert the array to a string. It's better to use strings, they were made so that you don't have to use arrays. If arrays were objectively better we wouldn't have strings.

Get first and last day of month using threeten, LocalDate

Just use withDayOfMonth, and lengthOfMonth():

LocalDate initial = LocalDate.of(2014, 2, 13);
LocalDate start = initial.withDayOfMonth(1);
LocalDate end = initial.withDayOfMonth(initial.lengthOfMonth());

React : difference between <Route exact path="/" /> and <Route path="/" />

In this example, nothing really. The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

<Switch>
  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

Now the problem here, when we go to http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

<Switch>
  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

The docs explain exact in detail and give other examples.

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

I've been looking for the same thing ... some good ideas here, but I ran a few micro benchmarks. I found the following to be the fastest (modified from Ayman's above and about 2x as fast, and about 50% faster than Steve's just above this one):

public static String hash(String text, String algorithm)
        throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
    return new BigInteger(1, hash).toString(16);
}

Edit: Oops - missed that this is essentially the same as kgiannakakis's and so may strip off a leading 0. Still, modifying this to the following, it's still the fastest:

public static String hash(String text, String algorithm)
        throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
    BigInteger bi = new BigInteger(1, hash);
    String result = bi.toString(16);
    if (result.length() % 2 != 0) {
        return "0" + result;
    }
    return result;
}

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

How to use the onClick event for Hyperlink using C# code?

this may help you.

In .cs page,

//Declare a string
   public string usertypeurl = "";
  //check who is the user
       //place your code to check who is the user
       //if it is admin
       usertypeurl = "help/AdminTutorial.html";
       //if it is other 
        usertypeurl = "help/UserTutorial.html";

In .aspx age pass this variabe

  <a href='<%=usertypeurl%>'>Tutorial</a>

How to add an extra language input to Android?

I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.

C# Debug - cannot start debugging because the debug target is missing

I had the same problems. I had to change file rights. Unmark "read only" in their properties.

xlsxwriter: is there a way to open an existing worksheet in my workbook?

After searching a bit about the method to open the existing sheet in xlxs, i discovered

existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')

You can now append/write any data to the open worksheet. I hope it helps. Thanks

What are the different types of keys in RDBMS?

Ólafur forgot the surrogate key:

A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.

Easy way to make a confirmation dialog in Angular?

In order to reuse a single confirmation dialog implementation in a multi-module application, the dialog must be implemented in a separate module. Here's one way of doing this with Material Design and FxFlex, though both of those can be trimmed back or replaced.

First the shared module (./app.module.ts):

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {MatDialogModule, MatSelectModule} from '@angular/material';
import {ConfirmationDlgComponent} from './confirmation-dlg.component';
import {FlexLayoutModule} from '@angular/flex-layout';

@NgModule({
   imports: [
      CommonModule,
      FlexLayoutModule,
      MatDialogModule
   ],
   declarations: [
      ConfirmationDlgComponent
   ],
   exports: [
      ConfirmationDlgComponent
   ],
   entryComponents: [ConfirmationDlgComponent]
})

export class SharedModule {
}

And the dialog component (./confirmation-dlg.component.ts):

import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material';

@Component({
   selector: 'app-confirmation-dlg',
   template: `
      <div fxLayoutAlign="space-around" class="title colors" mat-dialog-title>{{data.title}}</div>
      <div class="msg" mat-dialog-content>
         {{data.msg}}
      </div>
      <a href="#"></a>
      <mat-dialog-actions fxLayoutAlign="space-around">
         <button mat-button [mat-dialog-close]="false" class="colors">No</button>
         <button mat-button [mat-dialog-close]="true" class="colors">Yes</button>
      </mat-dialog-actions>`,
   styles: [`
      .title {font-size: large;}
      .msg {font-size: medium;}
      .colors {color: white; background-color: #3f51b5;}
      button {flex-basis: 60px;}
   `]
})
export class ConfirmationDlgComponent {
   constructor(@Inject(MAT_DIALOG_DATA) public data: any) {}
}

Then we can use it in another module:

import {FlexLayoutModule} from '@angular/flex-layout';
import {NgModule} from '@angular/core';
import {GeneralComponent} from './general/general.component';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {CommonModule} from '@angular/common';
import {MaterialModule} from '../../material.module';

@NgModule({
   declarations: [
      GeneralComponent
   ],
   imports: [
      FlexLayoutModule,
      MaterialModule,
      CommonModule,
      NgbModule.forRoot()
   ],
   providers: []
})
export class SystemAdminModule {}

The component's click handler uses the dialog:

import {Component} from '@angular/core';
import {ConfirmationDlgComponent} from '../../../shared/confirmation-dlg.component';
import {MatDialog} from '@angular/material';

@Component({
   selector: 'app-general',
   templateUrl: './general.component.html',
   styleUrls: ['./general.component.css']
})
export class GeneralComponent {

   constructor(private dialog: MatDialog) {}

   onWhateverClick() {
      const dlg = this.dialog.open(ConfirmationDlgComponent, {
         data: {title: 'Confirm Whatever', msg: 'Are you sure you want to whatever?'}
      });

      dlg.afterClosed().subscribe((whatever: boolean) => {
         if (whatever) {
            this.whatever();
         }
      });
   }

   whatever() {
      console.log('Do whatever');
   }
}

Just using the this.modal.open(MyComponent); as you did won't return you an object whose events you can subscribe to which is why you can't get it to do something. This code creates and opens a dialog whose events we can subscribe to.

If you trim back the css and html this is really a simple component, but writing it yourself gives you control over its design and layout whereas a pre-written component will need to be much more heavyweight to give you that control.