Programs & Examples On #Jfugue

JFugue is an open-source library for programming music for Java and JVM languages.

'AND' vs '&&' as operator

Since and has lower precedence than = you can use it in condition assignment:

if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false

HashMap and int as key

Please use HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();

Oracle TNS names not showing when adding new connection to SQL Developer

You can always find out the location of the tnsnames.ora file being used by running TNSPING to check connectivity (9i or later):

C:\>tnsping dev

TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 08-JAN-2009 12:48:38

Copyright (c) 1997, 2005, Oracle.  All rights reserved.

Used parameter files:
C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\sqlnet.ora


Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = DEV)))
OK (30 msec)

C:\>

Sometimes, the problem is with the entry you made in tnsnames.ora, not that the system can't find it. That said, I agree that having a tns_admin environment variable set is a Good Thing, since it avoids the inevitable issues that arise with determining exactly which tnsnames file is being used in systems with multiple oracle homes.

Python DNS module import error

I was getting an error while using "import dns.resolver". I tried dnspython, py3dns but they failed. dns won't install. after much hit and try I installed pubdns module and it solved my problem.

What does set -e mean in a bash script?

Script 1: without setting -e
#!/bin/bash
decho "hi"
echo "hello"
This will throw error in decho and program continuous to next line

Script 2: With setting -e
#!/bin/bash
set -e
decho "hi" 
echo "hello"
# Up to decho "hi" shell will process and program exit, it will not proceed further

Which maven dependencies to include for spring 3.0?

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

Plot a horizontal line using matplotlib

In addition to the most upvoted answer here, one can also chain axhline after calling plot on a pandas's DataFrame.

import pandas as pd

(pd.DataFrame([1, 2, 3])
   .plot(kind='bar', color='orange')
   .axhline(y=1.5));

enter image description here

C# - Winforms - Global Variables

The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.

static class Program
{
    public static string globalString = "This is a global string.";

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

And use it as such:

public partial class Form1 : Form
{
    public Form1()
    {
        Program.globalString = "Accessible in Form1.";

        InitializeComponent();
    }
}

Turn a simple socket into an SSL socket

Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>

#include <breakermindsslserver.h>

using namespace std;

int main(int argc, char *argv[])
{
    BreakermindSslServer boom;
    boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
    return 0;
}

What are all the common ways to read a file in Ruby?

You can read the file all at once:

content = File.readlines 'file.txt'
content.each_with_index{|line, i| puts "#{i+1}: #{line}"}

When the file is large, or may be large, it is usually better to process it line-by-line:

File.foreach( 'file.txt' ) do |line|
  puts line
end

Sometimes you want access to the file handle though or control the reads yourself:

File.open( 'file.txt' ) do |f|
  loop do
    break if not line = f.gets
    puts "#{f.lineno}: #{line}"
  end
end

In case of binary files, you may specify a nil-separator and a block size, like so:

File.open('file.bin', 'rb') do |f|
  loop do
    break if not buf = f.gets(nil, 80)
    puts buf.unpack('H*')
  end
end

Finally you can do it without a block, for example when processing multiple files simultaneously. In that case the file must be explicitly closed (improved as per comment of @antinome):

begin
  f = File.open 'file.txt'
  while line = f.gets
    puts line
  end
ensure
  f.close
end

References: File API and the IO API.

Android toolbar center title and custom font

No one has mentioned this, but there are some attributes for Toolbar:

app:titleTextColor for setting the title text color

app:titleTextAppearance for setting the title text appearance

app:titleMargin for setting the margin

And there are other specific-side margins such as marginStart, etc.

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Slide a layout up from bottom of screen

Here is what worked in the end for me.

Layouts:

activity_main.xml

<RelativeLayout
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:layout_alignParentTop="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:layout_centerInParent="true" />

    <Button
        android:id="@+id/slideButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Slide up / down"
        android:layout_alignParentBottom="true" 
        android:onClick="slideUpDown"/>

</RelativeLayout>

hidden_panel.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/hidden_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Test" />
</LinearLayout>

Java: package com.example.slideuplayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;

public class MainActivity extends Activity {

private ViewGroup hiddenPanel;
private ViewGroup mainScreen;
private boolean isPanelShown;
private ViewGroup root;

int screenHeight = 0;

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

    mainScreen = (ViewGroup)findViewById(R.id.main_screen);
    ViewTreeObserver vto = mainScreen.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() { 
            screenHeight = mainScreen.getHeight();
            mainScreen.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        } 
    }); 

    root = (ViewGroup)findViewById(R.id.root);

    hiddenPanel = (ViewGroup)getLayoutInflater().inflate(R.layout.hidden_panel, root, false);
    hiddenPanel.setVisibility(View.INVISIBLE);

    root.addView(hiddenPanel);

    isPanelShown = false;
}

@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;
}

public void slideUpDown(final View view) {
    if(!isPanelShown) {
        // Show the panel
        mainScreen.layout(mainScreen.getLeft(),
                          mainScreen.getTop() - (screenHeight * 25/100), 
                          mainScreen.getRight(),
                          mainScreen.getBottom() - (screenHeight * 25/100));



        hiddenPanel.layout(mainScreen.getLeft(), mainScreen.getBottom(), mainScreen.getRight(), screenHeight);
        hiddenPanel.setVisibility(View.VISIBLE);

        Animation bottomUp = AnimationUtils.loadAnimation(this,
                R.anim.bottom_up);

        hiddenPanel.startAnimation(bottomUp);

        isPanelShown = true;
    }
    else {
        isPanelShown = false;

        // Hide the Panel
        Animation bottomDown = AnimationUtils.loadAnimation(this,
                R.anim.bottom_down);
        bottomDown.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                isPanelShown = false;

                mainScreen.layout(mainScreen.getLeft(),
                          mainScreen.getTop() + (screenHeight * 25/100), 
                          mainScreen.getRight(),
                          mainScreen.getBottom() + (screenHeight * 25/100));

                hiddenPanel.layout(mainScreen.getLeft(), mainScreen.getBottom(), mainScreen.getRight(), screenHeight);
            }
        });
        hiddenPanel.startAnimation(bottomDown);
    }
}
}

Convert a SQL query result table to an HTML table for email

based on JustinStolle code (thank you), I wanted a solution that could be generic without having to specify the column names.

This sample is using the data of a temp table but of course it can be adjusted as required.

Here is what I got:

DECLARE @htmlTH VARCHAR(MAX) = '',
        @htmlTD VARCHAR(MAX)

--get header, columns name
SELECT @htmlTH = @htmlTH + '<TH>' +  name + '</TH>' FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb.dbo.#results')

--convert table to XML PATH, ELEMENTS XSINIL is used to include NULL values
SET @htmlTD = (SELECT * FROM #results FOR XML PATH('TR'), ELEMENTS XSINIL)

--convert the way ELEMENTS XSINIL display NULL to display word NULL
SET @htmlTD = REPLACE(@htmlTD, ' xsi:nil="true"/>', '>NULL</TD>')
SET @htmlTD = REPLACE(@htmlTD, '<TR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">', '<TR>')

--FOR XML PATH will set tags for each column name, <columnName1>abc</columnName1><columnName2>def</columnName2>
--this will replace all the column names with TD (html table data tag)
SELECT @htmlTD = REPLACE(REPLACE(@htmlTD, '<' + name + '>', '<TD>'), '</' + name + '>', '</TD>')
FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb.dbo.#results')


SELECT '<TABLE cellpadding="2" cellspacing="2" border="1">'
     + '<TR>' + @htmlTH + '</TR>'
     + @htmlTD
     + '</TABLE>'

PHP - iterate on string characters

If your strings are in Unicode you should use preg_split with /u modifier

From comments in php documentation:

function mb_str_split( $string ) { 
    # Split at all position not after the start: ^ 
    # and not before the end: $ 
    return preg_split('/(?<!^)(?!$)/u', $string ); 
} 

How to get the file path from URI?

File myFile = new File(uri.toString());
myFile.getAbsolutePath()

should return u the correct path

EDIT

As @Tron suggested the working code is

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

How to launch PowerShell (not a script) from the command line

The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:

explorer.exe "Windows PowerShell.lnk"

The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell

What's the difference between Docker Compose vs. Dockerfile

Dockerfile

enter image description here

A Dockerfile is a simple text file that contains the commands a user could call to assemble an image.

Example, Dockerfile

FROM ubuntu:latest
MAINTAINER john doe 

RUN apt-get update
RUN apt-get install -y python python-pip wget
RUN pip install Flask

ADD hello.py /home/hello.py

WORKDIR /home

Docker Compose

enter image description here

Docker Compose

  • is a tool for defining and running multi-container Docker applications.

  • define the services that make up your app in docker-compose.yml so they can be run together in an isolated environment.

  • get an app running in one command by just running docker-compose up

Example, docker-compose.yml

version: "3"
services:
  web:
    build: .
    ports:
    - '5000:5000'
    volumes:
    - .:/code
    - logvolume01:/var/log
    links:
    - redis
  redis:
    image: redis
    volumes:
      logvolume01: {}

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Java word count program

public static void main (String[] args) {

     System.out.println("Simple Java Word Count Program");

     String str1 = "Today is Holdiay Day";

     String[] wordArray = str1.trim().split("\\s+");
     int wordCount = wordArray.length;

     System.out.println("Word count is = " + wordCount);
}

The ideas is to split the string into words on any whitespace character occurring any number of times. The split function of the String class returns an array containing the words as its elements. Printing the length of the array would yield the number of words in the string.

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

How do I get a PHP class constructor to call its parent's parent's constructor?

You can call Grandpa::__construct from where you want and the $this keyword will refer to your current class instance. But be carefull with this method you cannot access to protected properties and methods of current instance from this other context, only to public elements. => All work and officialy supported.

Example

// main class that everything inherits
class Grandpa 
{
    public function __construct()
    {
        echo $this->one; // will print 1
        echo $this->two; // error cannot access protected property
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public $one = 1;
    protected $two = 2;
    public function __construct()
    {
        Grandpa::__construct();
    }
}

new Kiddo();

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

I solved this by restarting my computer. I'm guessing that this port was being occupied by a process that needed to be killed.

How to use sed to replace only the first occurrence in a file?

Just add the number of occurrence at the end:

sed s/#include/#include "newfile.h"\n#include/1

Understanding .get() method in Python

The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).

So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:

def myget(d, k, v=None):
  try: return d[k]
  except KeyError: return v

The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).

Sample random rows in dataframe

Outdated answer. Please use dplyr::sample_frac() or dplyr::sample_n() instead.

In my R package there is a function sample.rows just for this purpose:

install.packages('kimisc')

library(kimisc)
example(sample.rows)

smpl..> set.seed(42)

smpl..> sample.rows(data.frame(a=c(1,2,3), b=c(4,5,6),
                               row.names=c('a', 'b', 'c')), 10, replace=TRUE)
    a b
c   3 6
c.1 3 6
a   1 4
c.2 3 6
b   2 5
b.1 2 5
c.3 3 6
a.1 1 4
b.2 2 5
c.4 3 6

Enhancing sample by making it a generic S3 function was a bad idea, according to comments by Joris Meys to a previous answer.

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

Fetch: POST json data

It might be useful to somebody:

I was having the issue that formdata was not being sent for my request

In my case it was a combination of following headers that were also causing the issue and the wrong Content-Type.

So I was sending these two headers with the request and it wasn't sending the formdata when I removed the headers that worked.

"X-Prototype-Version" : "1.6.1",
"X-Requested-With" : "XMLHttpRequest"

Also as other answers suggest that the Content-Type header needs to be correct.

For my request the correct Content-Type header was:

"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"

So bottom line if your formdata is not being attached to the Request then it could potentially be your headers. Try bringing your headers to a minimum and then try adding them one by one to see if your problem is rsolved.

In C#, can a class inherit from another class and an interface?

No, not exactly. But it can inherit from a class and implement one or more interfaces.

Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.

Is it a good practice to place C++ definitions in header files?

Code in headers is generally a bad idea since it forces recompilation of all files that includes the header when you change the actual code rather than the declarations. It will also slow down compilation since you'll need to parse the code in every file that includes the header.

A reason to have code in header files is that it's generally needed for the keyword inline to work properly and when using templates that's being instanced in other cpp files.

Comparing two .jar files

Extract each jar to it's own directory using the jar command with parameters xvf. i.e. jar xvf myjar.jar for each jar.

Then, use the UNIX command diff to compare the two directories. This will show the differences in the directories. You can use diff -r dir1 dir2 two recurse and show the differences in text files in each directory(.xml, .properties, etc).

This will also show if binary class files differ. To actually compare the class files you will have to decompile them as noted by others.

How do I disable TextBox using JavaScript?

You can use disabled attribute to disable the textbox.

document.getElementById('color').disabled = true;

Check if an array is empty or exists

If you do not have a variable declared as array you can create a check:

if(x && x.constructor==Array && x.length){
   console.log("is array and filed");
}else{
    var x= [];
    console.log('x = empty array');
}

This checks if variable x exists and if it is, checks if it is a filled array. else it creates an empty array (or you can do other stuff);

If you are certain there is an array variable created there is a simple check:

var x = [];

if(!x.length){
    console.log('empty');
} else {
    console.log('full');
}

You can check my fiddle here with shows most possible ways to check array.

Script not served by static file handler on IIS7.5

i received this message for an application on iis 7.5 with a classic app pool assigned to .net 2.0. i needed to go to Handler Mappings and add two script maps, both were the same with except for the name. one name was svc-ISAPI-2.0-64, the other was svc-ISAPI-2.0. The request path was .svc. And the Executable was %SystemRoot%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll. i restarted iis and all was happy

How to check a not-defined variable in JavaScript

The error is telling you that x doesn’t even exist! It hasn’t been declared, which is different than being assigned a value.

var x; // declaration
x = 2; // assignment

If you declared x, you wouldn’t get an error. You would get an alert that says undefined because x exists/has been declared but hasn’t been assigned a value.

To check if the variable has been declared, you can use typeof, any other method of checking if a variable exists will raise the same error you got initially.

if(typeof x  !==  "undefined") {
    alert(x);
}

This is checking the type of the value stored in x. It will only return undefined when x hasn’t been declared OR if it has been declared and was not yet assigned.

Responsive image align center bootstrap 3

<div class="col-md-12 text-center">
    <img class="img-responsive tocenter" />
</div>

.

<style>
   .tocenter {
    margin:0 auto;
    display: inline;
    }
</style>

internet explorer 10 - how to apply grayscale filter?

IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.

However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

svg {
    background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}

(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)

Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/

More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

Can I access variables from another file?

Using Node.js you can export the variable via module.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
module.exports = { colorCode };

Then, import the module/variable in second file using require.

//second.js
const { colorCode } = require('./first.js')

You can use the import and export aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.

$watch an object

you must changes in $watch ....

_x000D_
_x000D_
function MyController($scope) {_x000D_
    $scope.form = {_x000D_
        name: 'my name',_x000D_
    }_x000D_
_x000D_
    $scope.$watch('form.name', function(newVal, oldVal){_x000D_
        console.log('changed');_x000D_
     _x000D_
    });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
    <div ng-controller="MyController">_x000D_
        <label>Name:</label> <input type="text" ng-model="form.name"/>_x000D_
            _x000D_
        <pre>_x000D_
            {{ form }}_x000D_
        </pre>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to generate a random string of a fixed length in Go?

Here is my way ) Use math rand or crypto rand as you wish.

func randStr(len int) string {
    buff := make([]byte, len)
    rand.Read(buff)
    str := base64.StdEncoding.EncodeToString(buff)
    // Base 64 can be longer than len
    return str[:len]
}

img onclick call to JavaScript function

Well your onclick function works absolutely fine its your this line
window.external.values(a.value, b.value, c.value, d.value, e.value);

window.external is object and has no method name values

<html>
    <head>
     <script type="text/javascript">
          function exportToForm(a,b,c,d,e) {
             // window.external.values(a.value, b.value, c.value, d.value, e.value);
          //use alert to check its working 
         alert("HELLO");
}
      </script>
    </head>
    <body>
      <img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
      <button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
    </body>

    </html>

What does "if (rs.next())" mean?

First thing, you don't need to write

ResultSet rs = stmt.executeQuery(sql);

just write

ResultSet rs = stmt.executeQuery();

The above mentioned syntax is used for Statements not for PreparedStatement.

Second thing, rs.next() checks if the result set contains any values or not. It returns a boolean value as well as it moves the cursor to the first value in the result set because initially it is at BEFORE FIRST Position. So if you want to access first value in result set, you need to write rs.next().

How to find the extension of a file in C#?

string FileExtn = System.IO.Path.GetExtension(fpdDocument.PostedFile.FileName);

The above method works fine with the firefox and IE , i am able to view all types of files like zip,txt,xls,xlsx,doc,docx,jpg,png

but when i try to find the extension of file from googlechrome , i failed.

How to add property to a class dynamically?

You don't need to use a property for that. Just override __setattr__ to make them read only.

class C(object):
    def __init__(self, keys, values):
        for (key, value) in zip(keys, values):
            self.__dict__[key] = value

    def __setattr__(self, name, value):
        raise Exception("It is read only!")

Tada.

>>> c = C('abc', [1,2,3])
>>> c.a
1
>>> c.b
2
>>> c.c
3
>>> c.d
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'd'
>>> c.d = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __setattr__
Exception: It is read only!
>>> c.a = 'blah'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __setattr__
Exception: It is read only!

JSON to string variable dump

Here is the code I use. You should be able to adapt it to your needs.

function process_test_json() {
  var jsonDataArr = { "Errors":[],"Success":true,"Data":{"step0":{"collectionNameStr":"dei_ideas_org_Private","url_root":"http:\/\/192.168.1.128:8500\/dei-ideas_org\/","collectionPathStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwrootchapter0-2\\verity_collections\\","writeVerityLastFileNameStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot\\chapter0-2\\VerityLastFileName.txt","doneFlag":false,"state_dbrec":{},"errorMsgStr":"","fileroot":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot"}}};

  var htmlStr= "<h3 class='recurse_title'>[jsonDataArr] struct is</h3> " + recurse( jsonDataArr );
  alert( htmlStr );
  $( document.createElement('div') ).attr( "class", "main_div").html( htmlStr ).appendTo('div#out');
  $("div#outAsHtml").text( $("div#out").html() ); 
}
function recurse( data ) {
  var htmlRetStr = "<ul class='recurseObj' >"; 
  for (var key in data) {
        if (typeof(data[key])== 'object' && data[key] != null) {
            htmlRetStr += "<li class='keyObj' ><strong>" + key + ":</strong><ul class='recurseSubObj' >";
            htmlRetStr += recurse( data[key] );
            htmlRetStr += '</ul  ></li   >';
        } else {
            htmlRetStr += ("<li class='keyStr' ><strong>" + key + ': </strong>&quot;' + data[key] + '&quot;</li  >' );
        }
  };
  htmlRetStr += '</ul >';    
  return( htmlRetStr );
}

</script>
</head><body>
<button onclick="process_test_json()" >Run process_test_json()</button>
<div id="out"></div>
<div id="outAsHtml"></div>
</body>

Custom Cell Row Height setting in storyboard is not responding

If you want to set a static row height, you can do something like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

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

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

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

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

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

    ServicePointManager.SecurityProtocol = combined;
}

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

How can I convert byte size into a human-readable format in Java?

Kotlin Version via Extension Property

If you are using kotlin, it's pretty easy to format file size by these extension properties. It is loop-free and completely based on pure math.


HumanizeUtils.kt

import java.io.File
import kotlin.math.log2
import kotlin.math.pow

/**
 * @author aminography
 */

val File.formatSize: String
    get() = length().formatAsFileSize

val Int.formatAsFileSize: String
    get() = toLong().formatAsFileSize

val Long.formatAsFileSize: String
    get() = log2(if (this != 0L) toDouble() else 1.0).toInt().div(10).let {
        val precision = when (it) {
            0 -> 0; 1 -> 1; else -> 2
        }
        val prefix = arrayOf("", "K", "M", "G", "T", "P", "E", "Z", "Y")
        String.format("%.${precision}f ${prefix[it]}B", toDouble() / 2.0.pow(it * 10.0))
    }

Usage:

println("0:          " + 0.formatAsFileSize)
println("170:        " + 170.formatAsFileSize)
println("14356:      " + 14356.formatAsFileSize)
println("968542985:  " + 968542985.formatAsFileSize)
println("8729842496: " + 8729842496.formatAsFileSize)

println("file: " + file.formatSize)

Result:

0:          0 B
170:        170 B
14356:      14.0 KB
968542985:  923.67 MB
8729842496: 8.13 GB

file: 6.15 MB

How to set time to 24 hour format in Calendar

if you replace in the function SimpleDateFormat("hh") with ("HH") will format the hour in 24 hours instead of 12.

SimpleDateFormat df = new SimpleDateFormat("HH:mm");

Search for value in DataGridView in a column

//     This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
    string searchValue=textBoxSearch.Text;
    int rowIndex = 1;  //this one is depending on the position of cell or column
    //string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        bool valueResulet = true;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dataGridView1.Rows[rowIndex].Selected = true;
                rowIndex++;
                valueResulet = false;
            }
        }
        if (valueResulet != false)
        {
            MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

Oracle Not Equals Operator

They are the same (as is the third form, ^=).

Note, though, that they are still considered different from the point of view of the parser, that is a stored outline defined for a != won't match <> or ^=.

This is unlike PostgreSQL where the parser treats != and <> yet on parsing stage, so you cannot overload != and <> to be different operators.

Using CSS to affect div style inside iframe

Yes. Take a look at this other thread for details: How to apply CSS to iframe?

var cssLink = document.createElement("link");
cssLink.href = "style.css";  
cssLink.rel = "stylesheet";  
cssLink.type = "text/css";  
frames['frame1'].document.body.appendChild(cssLink); 

How can I view the Git history in Visual Studio Code?

Git Graph seems like a decent extension. After installing, you can open the graph view from the bottom status bar.

C# - How to get Program Files (x86) on Windows 64 bit

One-liner using the new method in .NET. Will always return x86 Program Files folder.

Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable("ProgramFiles(x86)") : Environment.GetEnvironmentVariable("ProgramFiles"))

Set a button background image iPhone programmatically

Swift

Set the button image like this:

let myImage = UIImage(named: "myImageName")
myButton.setImage(myImage , forState: UIControlState.Normal)

where myImageName is the name of your image in your asset catalog.

Scroll back to the top of scrollable div

This is the only way it worked for me, with smooth scrolling transition:

  $('html, body').animate({
    scrollTop: $('#containerDiv').offset().top,
  }, 250);

Javascript find json value

I suggest using JavaScript's Array method filter() to identify an element by value. It filters data by using a "function to test each element of the array. Return true to keep the element, false otherwise.."

The following function filters the data, returning data for which the callback returns true, i.e. where data.code equals the requested country code.

function getCountryByCode(code) {
  return data.filter(
      function(data){ return data.code == code }
  );
}

var found = getCountryByCode('DZ');

See the demonstration below:

_x000D_
_x000D_
var data = [{_x000D_
  "name": "Afghanistan",_x000D_
  "code": "AF"_x000D_
}, {_x000D_
  "name": "Åland Islands",_x000D_
  "code": "AX"_x000D_
}, {_x000D_
  "name": "Albania",_x000D_
  "code": "AL"_x000D_
}, {_x000D_
  "name": "Algeria",_x000D_
  "code": "DZ"_x000D_
}];_x000D_
_x000D_
_x000D_
function getCountryByCode(code) {_x000D_
  return data.filter(_x000D_
    function(data) {_x000D_
      return data.code == code_x000D_
    }_x000D_
  );_x000D_
}_x000D_
_x000D_
var found = getCountryByCode('DZ');_x000D_
_x000D_
document.getElementById('output').innerHTML = found[0].name;
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Here's a JSFiddle.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

How to sort dates from Oldest to Newest in Excel?

I was having the same problem and realised one of my dates was incorrect, I had 31/11/2017, but there is no 31/11/17. When I adjusted to 30/11/17 it sorted correctly. Hope that helps.

numpy: most efficient frequency counts for unique values in an array

from collections import Counter
x = array( [1,1,1,2,2,2,5,25,1,1] )
mode = counter.most_common(1)[0][0]

Get first 100 characters from string, respecting full words

Another a simpler way I do.

function limit_words($string, $word_limit = 10)
{
    $words = explode(" ", $string);
    if (count($words) > $word_limit) {
        return implode(" ", array_splice($words, 0, $word_limit)) . ' ...';
    }
    return implode(" ", array_splice($words, 0, $word_limit));
}

How to add elements of a Java8 stream into an existing List

You just have to refer your original list to be the one that the Collectors.toList() returns.

Here's a demo:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Reference {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    System.out.println(list);

    // Just collect even numbers and start referring the new list as the original one.
    list = list.stream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());
    System.out.println(list);
  }
}

And here's how you can add the newly created elements to your original list in just one line.

List<Integer> list = ...;
// add even numbers from the list to the list again.
list.addAll(list.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList())
);

That's what this Functional Programming Paradigm provides.

How do I delete files programmatically on Android?

I tested this code on Nougat emulator and it worked:

In manifest add:

<application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create empty xml folder in res folder and past in the provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  </paths>

Then put the next snippet into your code (for instance fragment):

File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(), 
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);

What does DIM stand for in Visual Basic and BASIC?

DIM stands for Declaration In Memory DIM x As New Integer creates a space in memory where the variable x is stored

Nexus 5 USB driver

Well @sonida's answer helped me but Here I am posting complete step How I did it.

Change Mobile Device Settings:

  1. Unplug the device from the computer
  2. Go to Mobile Settings -> Storage.
  3. In the ActionBar, click the option menu and choose "USB computer connection".
  4. Check "Camera (PTP)" connection.

enter image description here

enter image description here

Download Google USB Driver:

5 .Now go to http://developer.android.com/sdk/win-usb.html#top and download USB Drivers --> unzip folder.

enter image description here

Install USB Drivers and Get Connected Device:

6.Then Right click on My computer -->Manage --> Device Manager.

enter image description here

7.You should seed Nexus 5 in the list.

8.Right click on Nexus 5 --> Update Driver Software... --> Browse my computer for driver software

enter image description here

9.select the folder we downloaded/unzipped "latest_usb_driver_windows" and Next ...Ok.

enter image description here

10.Now you will see pop-up dialogue asking for Allow device --> Ok.

11 .That's it!! device is connected now, you can see in DDMS.

enter image description here

Hope this will help someone.

Adding an image to a PDF using iTextSharp and scale it properly

I solved it using the following:

foreach (var image in images)
{
    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);

    if (pic.Height > pic.Width)
    {
        //Maximum height is 800 pixels.
        float percentage = 0.0f;
        percentage = 700 / pic.Height;
        pic.ScalePercent(percentage * 100);
    }
    else
    {
        //Maximum width is 600 pixels.
        float percentage = 0.0f;
        percentage = 540 / pic.Width;
        pic.ScalePercent(percentage * 100);
    }

    pic.Border = iTextSharp.text.Rectangle.BOX;
    pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
    pic.BorderWidth = 3f;
    document.Add(pic);
    document.NewPage();
}

How to import classes defined in __init__.py

If lib/__init__.py defines the Helper class then in settings.py you can use:

from . import Helper

This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via __all__.

(Confirmed with python 2.7.10, running on Windows.)

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

Java: How to set Precision for double value?

Maybe this method would help you for precising double values.

double truncate(double number)
    {
        int integerPart = (int) number;
        double fractionalPart = number - integerPart;
        fractionalPart *= 100;  //It is for upto two decimal values after point.
                                //You can increase the zeros to fulfill your needs.
        int fractPart = (int) fractionalPart;
        fractionalPart = (double) (integerPart) + (double) (fractPart)/100;
        return fractionalPart;
    }

This method will allow to set the precision level.

double truncate(double number, int precision)
{
    double prec = Math.pow(10, precision);
    int integerPart = (int) number;
    double fractionalPart = number - integerPart;
    fractionalPart *= prec;
    int fractPart = (int) fractionalPart;
    fractionalPart = (double) (integerPart) + (double) (fractPart)/prec;
    return fractionalPart;
}

HTML <sup /> tag affecting line height, how to make it consistent?

I like Milingu Kilu's solution but in the same spirit I prefer

sup { vertical-align:top; line-height:100%; }

Month name as a string

Russian.

Month
.MAY
.getDisplayName(
    TextStyle.FULL_STANDALONE ,
    new Locale( "ru" , "RU" )
)

???

English in the United States.

Month
.MAY
.getDisplayName(
    TextStyle.FULL_STANDALONE ,
    Locale.US
)

May

See this code run live at IdeOne.com.

ThreeTenABP and java.time

Here’s the modern answer. When this question was asked in 2011, Calendar and GregorianCalendar were commonly used for dates and times even though they were always poorly designed. That’s 8 years ago now, and those classes are long outdated. Assuming you are not yet on API level 26, my suggestion is to use the ThreeTenABP library, which contains an Android adapted backport of java.time, the modern Java date and time API. java.time is so much nicer to work with.

Depending on your exact needs and situation there are two options:

  1. Use Month and its getDisplayName method.
  2. Use a DateTimeFormatter.

Use Month

    Locale desiredLanguage = Locale.ENGLISH;
    Month m = Month.MAY;
    String monthName = m.getDisplayName(TextStyle.FULL, desiredLanguage);
    System.out.println(monthName);

Output from this snippet is:

May

In a few languages it will make a difference whether you use TextStyle.FULL or TextStyle.FULL_STANDALONE. You will have to see, maybe check with your users, which of the two fits into your context.

Use a DateTimeFormatter

If you’ve got a date with or without time of day, I find a DateTimeFormatter more practical. For example:

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", desiredLanguage);

    ZonedDateTime dateTime = ZonedDateTime.of(2019, 5, 31, 23, 49, 51, 0, ZoneId.of("America/Araguaina"));
    String monthName = dateTime.format(monthFormatter);

I am showing the use of a ZonedDateTime, the closest replacement for the old Calendar class. The above code will work for a LocalDate, a LocalDateTime, MonthDay, OffsetDateTime and a YearMonth too.

What if you got a Calendar from a legacy API not yet upgraded to java.time? Convert to a ZonedDateTime and proceed as above:

    Calendar c = getCalendarFromLegacyApi();
    ZonedDateTime dateTime = DateTimeUtils.toZonedDateTime(c);

The rest is the same as before.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

How can I compile my Perl script so it can be executed on systems without perl installed?

  1. Install PAR::Packer. Example for *nix:

    sudo cpan -i PAR::Packer

    For Strawberry Perl for Windows or for ActivePerl and MSVC installed:

    cpan -i PAR::Packer
  2. Pack it with pp. It will create an executable named "example" or "example.exe" on Windows.

    pp -o example example.pl

This would work only on the OS where it was built.

P.S. It is really hard to find a Unix clone without Perl. Did you mean Windows?

C#: List All Classes in Assembly

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflection namespace.

If you want to examine an assembly that you have no reference to, you can use either of these:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentation for more information.

Once you have the reference to the Assembly object, you can use assembly.GetTypes() like Jon already demonstrated.

Display images in asp.net mvc

It is possible to use a handler to do this, even in MVC4. Here's an example from one i made earlier:

public class ImageHandler : IHttpHandler
{
    byte[] bytes;

    public void ProcessRequest(HttpContext context)
    {
        int param;
        if (int.TryParse(context.Request.QueryString["id"], out param))
        {
            using (var db = new MusicLibContext())
            {
                if (param == -1)
                {
                    bytes = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/add.png"));

                    context.Response.ContentType = "image/png";
                }
                else
                {
                    var data = (from x in db.Images
                                where x.ImageID == (short)param
                                select x).FirstOrDefault();

                    bytes = data.ImageData;

                    context.Response.ContentType = "image/" + data.ImageFileType;
                }

                context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
                context.Response.End();
            }
        }
        else
        {
            //image not found
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

In the view, i added the ID of the photo to the query string of the handler.

iPhone App Minus App Store?

  • Build your app
  • Upload to a crack site
  • (If you app is good enough) the crack version will be posted minutes later and ready for everyone to download ;-)

Overriding css style?

Instead of override you can add another class to the element and then you have an extra abilities. for example:

HTML

<div class="style1 style2"></div>

CSS

//only style for the first stylesheet
.style1 {
   width: 100%;      
}
//only style for second stylesheet
.style2 {
   width: 50%;     
}
//override all
.style1.style2 { 
   width: 70%;
}

VirtualBox Cannot register the hard disk already exists

The solution that worked for me is as follows:

  1. Make sure VirtualBox Manager is not running.
  2. Back up the files ~\.VirtualBox\VirtualBox.xml and ~\.VirtualBox\VirtualBox.xml-prev.
  3. Edit these files to modify the <HardDisks>...</HardDisks> section to remove the duplicate entry of <HardDisk />.
  4. Now run VirtualBox Manager.

Example:

  <HardDisks>
    <HardDisk uuid="{38f266bd-0959-4caf-a0de-27ac9d52e3663}" location="~/VirtualBox VMs/VM1/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{a6708d79-7393-4d96-89da-2539f75c5465e}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
    <HardDisk uuid="{bdce5d4e-9a1c-4f57-acfd-e2acfc8920552}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
  </HardDisks>

Note in the above fragment that the last two entries refer to the same VM but have different uuid's. One of them is invalid and should be removed. Which one is invalid can be found out by hit and trial -- first remove the second entry and try; if it doesn't work, remove the third entry.

How can I convert String[] to ArrayList<String>

You can do the following:

String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:

 <?php 
    require_once('mylib.php');
    session_start();
 ?>

In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.

HTH

Parsing JSON from XmlHttpRequest.responseJSON

New ways I: fetch

TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.

A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch() to send a request and ResponseBody.json() to parse the response:

fetch(url)
  .then(function(response) {
    return response.json();
  })
  .then(function(jsonResponse) {
    // do something with jsonResponse
  });

Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.

New ways II: responseType

As Londeren has written in his answer, newer browsers allow you to use the responseType property to define the expected format of the response. The parsed response data can then be accessed via the response property:

var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = req.response;
   // do something with jsonResponse
};
req.send(null);

Compatibility: responseType = 'json' is not supported by IE11.

The classic way

The standard XMLHttpRequest has no responseJSON property, just responseText and responseXML. As long as bitly really responds with some JSON to your request, responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse():

var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload  = function() {
   var jsonResponse = JSON.parse(req.responseText);
   // do something with jsonResponse
};
req.send(null);

Compatibility: This approach should work with any browser that supports XMLHttpRequest and JSON.

JSONHttpRequest

If you prefer to use responseJSON, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON property. All you have to change in your code would be the first line:

var req = new JSONHttpRequest();

JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.

Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.

git: patch does not apply

What I looked for is not exactly pointed out in here in SO, I'm writing for the benefit of others who might search for similar. I faced an issue with one file (present in old repo) getting removed in the repo. And when I apply the patch, it fails as it couldn't find the file to be applied. (so my case is git patch fails for file got removed) '#git apply --reject' definitely gave a view but didn't quite get me to the fix. I couldn't use wiggle as it is not available for us in our build servers. In my case, I got through this problem by removing the entry of the 'file which got removed in the repo' from patch file I've tried applying, so I got all other changes applied without an issue (using 3 way merge, avoiding white space errors), And then manually merging content of file removed into where its moved.

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

How to extract string following a pattern with grep, regex or perl

this could do it:

perl -ne 'if(m/name="(.*?)"/){ print $1 . "\n"; }'

Set environment variables from file of key/value pairs

Not exactly sure why, or what I missed, but after running trough most of the answers and failing. I realized that with this .env file:

MY_VAR="hello there!"
MY_OTHER_VAR=123

I could simply do this:

source .env
echo $MY_VAR

Outputs: Hello there!

Seems to work just fine in Ubuntu linux.

How to change the foreign key referential action? (behavior)

You can simply use one query to rule them all: ALTER TABLE products DROP FOREIGN KEY oldConstraintName, ADD FOREIGN KEY (product_id, category_id) REFERENCES externalTableName (foreign_key_name, another_one_makes_composite_key) ON DELETE CASCADE ON UPDATE CASCADE

Add views in UIStackView programmatically

Swift 5.0

//Image View
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blue
imageView.heightAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 120.0).isActive = true
imageView.image = UIImage(named: "buttonFollowCheckGreen")

//Text Label
let textLabel = UILabel()
textLabel.backgroundColor = UIColor.yellow
textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true
textLabel.text  = "Hi World"
textLabel.textAlignment = .center

//Stack View
let stackView   = UIStackView()
stackView.axis  = NSLayoutConstraint.Axis.vertical
stackView.distribution  = UIStackView.Distribution.equalSpacing
stackView.alignment = UIStackView.Alignment.center
stackView.spacing   = 16.0

stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(textLabel)
stackView.translatesAutoresizingMaskIntoConstraints = false

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true

Based on @user1046037 answer.

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

How to make an HTTP request + basic auth in Swift

go plain for SWIFT 3 and APACHE simple Auth:

func urlSession(_ session: URLSession, task: URLSessionTask,
                didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    let credential = URLCredential(user: "test",
                                   password: "test",
                                   persistence: .none)

    completionHandler(.useCredential, credential)


}

Removing specific rows from a dataframe

One simple solution:

cond1 <- df$sub == 1 & df$day == 2

cond2 <- df$sub == 3 & df$day == 4

df <- df[!(cond1 | cond2),]

Crop image in android

This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.

You will crop your images with a few lines of code.

1 - Add the dependecies into buid.gradle (Module: app)

compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'

2 - Add the permissions into AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

3 - Add CropImageActivity into AndroidManifest.xml

<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
 android:theme="@style/Base.Theme.AppCompat"/>

4 - Start the activity with one of the cases below, depending on your requirements.

// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);

// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
.start(this);

// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
.start(getContext(), this);

5 - Get the result in onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}

You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.

PermGen elimination in JDK 8

Oracle's JVM implementation for Java 8 got rid of the PermGen model and replaced it with Metaspace.

exclude @Component from @ComponentScan

Using explicit types in scan filters is ugly for me. I believe more elegant approach is to create own marker annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreDuringScan {
}

Mark component that should be excluded with it:

@Component("foo") 
@IgnoreDuringScan
class Foo {
    ...
}

And exclude this annotation from your component scan:

@ComponentScan(excludeFilters = @Filter(IgnoreDuringScan.class))
public class MySpringConfiguration {}

Android lollipop change navigation bar color

Here is how to do it programatically:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {                
   getWindow().setNavigationBarColor(getResources().getColor(R.color.your_awesome_color));
}

Using Compat library:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}

Here is how to do it with xml in the values-v21/style.xml folder:

<item name="android:navigationBarColor">@color/your_color</item>

How can I stop a running MySQL query?

You need to run following command to kill the process. Find out the id of the process which you wanted to kill by

> show processlist;

Take the value from id column and fire below command

kill query <processId>;

Query parameter specifies that we need to kill query command process.

The syntax for kill process as follows

KILL [CONNECTION | QUERY] processlist_id

Please refer this link for more information.

Get AVG ignoring Null or Zero values

You already attempt to filter out NULL values with NOT NULL. I have changed this to IS NOT NULL in the WHERE clause so it will execute. We can refactor this by removing the ISNULL function in the AVG method. Also, I doubt you'll actually need bigint so we can remove the cast.

SELECT distinct
     AVG(a.SecurityW) as Average1
     ,AVG(a.TransferW) as Average2
     ,AVG(a.StaffW) as Average3
FROM Table1 a,  Table2 b
WHERE a.SecurityW <> 0 AND a.SecurityW IS NOT NULL
AND a.TransferW<> 0 AND a.TransferWIS IS NOT NULL
AND a.StaffW<> 0 AND a.StaffWIS IS NOT NULL
AND MONTH(a.ActualTime) = 4
AND YEAR(a.ActualTime) = 2013

Open Facebook Page in Facebook App (if installed) on Android

This works on the latest version:

Go to https://graph.facebook.com/ (https://graph.facebook.com/fsintents for instance).

Copy your id Use this method:

public static Intent getOpenFacebookIntent(Context context) {
    try {
        context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
        return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
    } catch (Exception e) {
        return new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.facebook.com/<user_name_here>"));
    }
}

WebView link click open default browser

I had to do the same thing today and I have found a very useful answer on StackOverflow that I want to share here in case someone else needs it.

Source (from sven)

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
});

How to convert Observable<any> to array[]

//Component. home.ts :

  contacts:IContacts[];


ionViewDidLoad() {
this.rest.getContacts()
.subscribe( res=> this.contacts= res as IContacts[]) ;

// reorderArray. accepts only Arrays

    Reorder(indexes){
  reorderArray(this.contacts, indexes)
}

// Service . res.ts

getContacts(): Observable<IContacts[]> {
return this.http.get<IContacts[]>(this.apiUrl+"?results=5")

And it works fine

Android read text raw resource file

@borislemke you can do this by similar way like

TextView  tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
 try {
 i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
   }
    inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
 e.printStackTrace();
 }

 return byteArrayOutputStream.toString();
 }

How to retrieve data from a SQL Server database in C#?

we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields

class Db
{
    private readonly static string ConnectionString =
            ConfigurationManager.ConnectionStrings
                        ["DbConnectionString"].ConnectionString;
    public static List<string> GetValuesFromDB(string LocationCode)
    {
        List<string> ValuesFromDB = new List<string>();
        string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
            $"from [CustomerLocations] where LocationCode='{LocationCode}';";
        using (SqlConnection Locationconnection =
                                 new SqlConnection(ConnectionString))
        {
            SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
            try
            {
                Locationconnection.Open();
                SqlDataReader Locationreader = command.ExecuteReader();
                while (Locationreader.Read())
                {
                    for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
                    {
                        ValuesFromDB.Add(Locationreader[i].ToString());
                    }
                }
                Locationreader.Close();
                return ValuesFromDB;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

    }

}

hope this might helpful

Note: you guys need connection string (in our case "DbConnectionString")

TypeScript: Creating an empty typed container array

For publicly access use like below:

public arr: Criminal[] = [];

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.

Laravel 5.4 Specific Table Migration

Just look at the migrations table in your database, there will be a list of migration file name and batch number value.

Suppose you have following structure,

id     migration                                           batch

1      2014_10_12_000000_create_users_table                  1 
2      2014_10_12_100000_create_password_resets_table        1
3      2016_09_07_103432_create_tabel_roles                  1

If you want to just rollback 2016_09_07_103432_create_tabel_roles migration, change it's migration batch value to 2 which is highest among all and then just execute following.

php artisan migrate:rollback

Here only table with batch value 2 will be rolled back. Now, make changes to that table and run following console command.

php artisan migrate

Batch value in the migrations table defines order of the migrations. when you rollback, migrations that are latest or have highest batch value are rolled back at first and then others. So, you can change the value in database and then rollback a particular migration file.

Although it's not a good idea to change batch number every time because of relationship among the table structure, we can use this case for some cases where single table rollback doesn't violates the integrity among the tables.

Hope you understand.

How to force a html5 form validation without submitting it via jQuery

I had a rather complex situation, where I needed multiple submit buttons to process different things. For example, Save and Delete.

The basis was that it was also unobtrusive, so I couldn't just make it a normal button. But also wanted to utilize html5 validation.

As well the submit event was overridden in case the user pressed enter to trigger the expected default submission; in this example save.

Here is the efforts of the processing of the form to still work with/without javascript and with html5 validation, with both submit and click events.

jsFiddle Demo - HTML5 validation with submit and click overrides

xHTML

<form>
    <input type="text" required="required" value="" placeholder="test" />
    <button type="submit" name="save">Save</button>
    <button type="submit" name="delete">Delete</button>
</form>

JavaScript

//wrap our script in an annonymous function so that it can not be affected by other scripts and does not interact with other scripts
//ensures jQuery is the only thing declared as $
(function($){
    var isValid = null;
    var form = $('form');
    var submitButton = form.find('button[type="submit"]')
    var saveButton = submitButton.filter('[name="save"]');
    var deleteButton = submitButton.filter('[name="delete"]');

    //submit form behavior
    var submitForm = function(e){
        console.log('form submit');
        //prevent form from submitting valid or invalid
        e.preventDefault();
        //user clicked and the form was not valid
        if(isValid === false){
            isValid = null;
            return false;
        }
        //user pressed enter, process as if they clicked save instead
        saveButton.trigger('click');
    };

    //override submit button behavior
    var submitClick = function(e){
        //Test form validitiy (HTML5) and store it in a global variable so both functions can use it
        isValid = form[0].checkValidity();
        if(false === isValid){
            //allow the browser's default submit event behavior 
            return true;
        }
        //prevent default behavior
        e.preventDefault();
        //additional processing - $.ajax() etc
        //.........
        alert('Success');
    };

    //override submit form event
    form.submit(submitForm);

    //override submit button click event
    submitButton.click(submitClick);
})(jQuery);

The caveat to using Javascript is that the browser's default onclick must propagate to the submit event MUST occur in order to display the error messages without supporting each browser in your code. Otherwise if the click event is overridden with event.preventDefault() or return false it will never propagate to the browser's submit event.

The thing to point out is that in some browsers will not trigger the form submit when the user presses enter, instead it will trigger the first submit button in the form. Hence there is a console.log('form submit') to show that it does not trigger.

How to create a generic array?

checked :

public Constructor(Class<E> c, int length) {

    elements = (E[]) Array.newInstance(c, length);
}

or unchecked :

public Constructor(int s) {
    elements = new Object[s];
}

Google map V3 Set Center to specific Marker

To build upon @6twenty's answer...I prefer panTo(LatLng) over setCenter(LatLng) as panTo animates for smoother transition to center "if the change is less than both the width and height of the map". https://developers.google.com/maps/documentation/javascript/reference#Map

The below uses Google Maps API v3.

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(latitude, longitude),
    title: markerTitle,
    map: map,
});
google.maps.event.addListener(marker, 'click', function () {
    map.panTo(marker.getPosition());
    //map.setCenter(marker.getPosition()); // sets center without animation
});

How to fix 'Microsoft Excel cannot open or save any more documents'

If none of the above worked, try these as well:

  • In Component services >Computes >My Computer>Dcom config>Microsoft Excel Application>Properties, go to security tab, click on customize on all three sections and add the user that want to run the application, and give full permissions to the user.

  • Go to C:\Windows\Temp make sure it exists and it doesn't prompt you for entering.

Git diff against a stash

One way to do this without moving anything is to take advantage of the fact that patch can read git diff's (unified diffs basically)

git stash show -p | patch -p1 --verbose --dry-run

This will show you a step-by-step preview of what patch would ordinarily do. The added benefit to this is that patch won't prevent itself from writing the patch to the working tree either, if for some reason you just really need git to shut up about commiting-before-modifying, go ahead and remove --dry-run and follow the verbose instructions.

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

For an IIS MVC 5 / Angular CLI ( Yes, I am well aware your problem is with Angular JS ) project with API I did the following:

web.config under <system.webServer> node

    <staticContent>
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
    </staticContent>
    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, atv2" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
      </customHeaders>
    </httpProtocol>

global.asax.cs

protected void Application_BeginRequest() {
  if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) && Request.HttpMethod == "OPTIONS") {
    Response.Flush();
    Response.End();
  }
}

That should fix your issues for both MVC and WebAPI without having to do all the other run around. I then created an HttpInterceptor in the Angular CLI project that automatically added in the the relevant header information. Hope this helps someone out in a similar situation.

Reading specific columns from a text file in python

It may help:

import csv
with open('csv_file','r') as f:
    # Printing Specific Part of CSV_file
    # Printing last line of second column
    lines = list(csv.reader(f, delimiter = ' ', skipinitialspace = True))
    print(lines[-1][1])
    # For printing a range of rows except 10 last rows of second column
    for i in range(len(lines)-10):
        print(lines[i][1])

How can I resize an image using Java?

FWIW I just released (Apache 2, hosted on GitHub) a simple image-scaling library for Java called imgscalr (available on Maven central).

The library implements a few different approaches to image-scaling (including Chris Campbell's incremental approach with a few minor enhancements) and will either pick the most optimal approach for you if you ask it to, or give you the fastest or best looking (if you ask for that).

Usage is dead-simple, just a bunch of static methods. The simplest use-case is:

BufferedImage scaledImage = Scalr.resize(myImage, 200);

All operations maintain the image's original proportions, so in this case you are asking imgscalr to resize your image within a bounds of 200 pixels wide and 200 pixels tall and by default it will automatically select the best-looking and fastest approach for that since it wasn't specified.

I realize on the outset this looks like self-promotion (it is), but I spent my fair share of time googling this exact same subject and kept coming up with different results/approaches/thoughts/suggestions and decided to sit down and write a simple implementation that would address that 80-85% use-cases where you have an image and probably want a thumbnail for it -- either as fast as possible or as good-looking as possible (for those that have tried, you'll notice doing a Graphics.drawImage even with BICUBIC interpolation to a small enough image, it still looks like garbage).

How to fix request failed on channel 0

As you already found the -T flag that create a PTY, I will just respond to the second part:

shell request failed on channel 0

You should pass a command:

ssh [email protected] -p 22 help

After reading back the manual here: https://www.jenkins.io/doc/book/managing/cli/, I find it not really clear that it would not work without a command. But as stated by @U.V., the ssh interface is not a console interface, rather a connection utility. So you need to pass a command...

If someone from the "jenkins" team pass accross this post, it would be great that if we pass no command, the help would show up :-)

How do I unlock a SQLite database?

The DatabaseIsLocked page listed below is no longer available. The File Locking And Concurrency page describes changes related to file locking introduced in v3 and may be useful for future readers. https://www.sqlite.org/lockingv3.html

The SQLite wiki DatabaseIsLocked page offers a good explanation of this error message. It states, in part, that the source of contention is internal (to the process emitting the error).

What this page doesn't explain is how SQLite decides that something in your process holds a lock and what conditions could lead to a false positive.

Receiver not registered exception error?

EDIT: This is the answer for inazaruk and electrichead... I had run into a similar issue to them and found out the following...

There is a long-standing bug for this problem here: http://code.google.com/p/android/issues/detail?id=6191

Looks like it started around Android 2.1 and has been present in all of the Android 2.x releases since. I'm not sure if it is still a problem in Android 3.x or 4.x though.

Anyway, this StackOverflow post explains how to workaround the problem correctly (it doesn't look relevant by the URL but I promise it is)

Why does keyboard-slide crash my app?

figure of imshow() is too small

That's strange, it definitely works for me:

from matplotlib import pyplot as plt

plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')

I am using the "MacOSX" backend, btw.

Get the Id of current table row with Jquery

$('input[type=button]' ).click(function() {
   var bid = jQuery(this).attr('id'); // button ID 
   var trid = $(this).parents('tr:first').attr('id'); // table row ID 
 });

Open Form2 from Form1, close Form1 from Form2

This works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Hide()
    Form2.Show()

How can I set focus on an element in an HTML form using JavaScript?

Usually when we focus on a textbox, we should also scroll into view

function setFocusToTextBox(){
    var textbox = document.getElementById("yourtextbox");
    textbox.focus();
    textbox.scrollIntoView();
}

Check if it helps.

How to fix 'android.os.NetworkOnMainThreadException'?

android.os.NetworkOnMainThreadException is thrown when network operations are performed on the main thread. You better do this in AsyncTask to remove this Exception. Write it this way:

    new AsyncTask<Void,String,String>(){

        @Override
        protected Void doInBackground(Void... params) {
            // Perform your network operation.
            // Get JSON or XML string from the server.
            // Store in a local variable (say response) and return.
            return response;
        }

        protected void onPostExecute(String results){
            // Response returned by doInBackGround() will be received
            // by onPostExecute(String results).
            // Now manipulate your jason/xml String(results).
        }

    }.execute();
}

Leading zeros for Int in Swift

For left padding add a string extension like this:

Swift 2.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".stringByPaddingToLength(toPad, withString: with, startingAtIndex: 0) + self
    }
}

Swift 3.0 +

extension String {
    func padLeft (totalWidth: Int, with: String) -> String {
        let toPad = totalWidth - self.characters.count
        if toPad < 1 { return self }
        return "".padding(toLength: toPad, withPad: with, startingAt: 0) + self
    }
}

Using this method:

for myInt in 1...3 {
    print("\(myInt)".padLeft(totalWidth: 2, with: "0"))
}

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

Redirect website after certain amount of time

Here's a complete (yet simple) example of redirecting after X seconds, while updating a counter div:

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
    <div id="counter">5</div>_x000D_
    <script>_x000D_
        setInterval(function() {_x000D_
            var div = document.querySelector("#counter");_x000D_
            var count = div.textContent * 1 - 1;_x000D_
            div.textContent = count;_x000D_
            if (count <= 0) {_x000D_
                window.location.replace("https://example.com");_x000D_
            }_x000D_
        }, 1000);_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The initial content of the counter div is the number of seconds to wait.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

How to set background color of view transparent in React Native

Use rgba value for the backgroundColor.

For example,

backgroundColor: 'rgba(52, 52, 52, 0.8)'

This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, 0.8. This value can be anything from 0.0 to 1.0.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

What is the meaning of "__attribute__((packed, aligned(4))) "

The attribute packed means that the compiler will not add padding between fields of the struct. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.

aligned(4) means that the struct should be aligned to an address that is divisible by 4.

What is the time complexity of indexing, inserting and removing from common data structures?

Amortized Big-O for hashtables:

  • Insert - O(1)
  • Retrieve - O(1)
  • Delete - O(1)

Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

You could also use it clean and simple (but wrong! because you should use format like Mark Byers said) by doing:

print 'This is my %s formatted with %d arguments' % ('string', 2)

Resizing an iframe based on content

We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the same origin policy was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.

There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid.

There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:

 www.foo.com/home.html, which iframes
 |-> www.bar.net/framed.html, which iframes
     |-> www.foo.com/helper.html

then home.html can communicate with framed.html (iframed) and helper.html (same domain).

 Communication options for each page:
 +-------------------------+-----------+-------------+-------------+
 |                         | home.html | framed.html | helper.html |
 +-------------------------+-----------+-------------+-------------+
 | www.foo.com/home.html   |    N/A    |     YES     |     YES     |
 | www.bar.net/framed.html |    NO     |     N/A     |     YES     |
 | www.foo.com/helper.html |    YES    |     YES     |     N/A     |
 +-------------------------+-----------+-------------+-------------+

framed.html can send messages to helper.html (iframed) but not home.html (child can't communicate cross-domain with parent).

The key here is that helper.html can receive messages from framed.html, and can also communicate with home.html.

So essentially, when framed.html loads, it works out its own height, tells helper.html, which passes the message on to home.html, which can then resize the iframe in which framed.html sits.

The simplest way we found to pass messages from framed.html to helper.html was through a URL argument. To do this, framed.html has an iframe with src='' specified. When its onload fires, it evaluates its own height, and sets the src of the iframe at this point to helper.html?height=N

There's an explanation here of how facebook handle it, which may be slightly clearer than mine above!


Code

In www.foo.com/home.html, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):

<script>
  // Resize iframe to full height
  function resizeIframe(height)
  {
    // "+60" is a general rule of thumb to allow for differences in
    // IE & and FF height reporting, can be adjusted as required..
    document.getElementById('frame_name_here').height = parseInt(height)+60;
  }
</script>
<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>

In www.bar.net/framed.html:

<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>

<script type="text/javascript">
  function iframeResizePipe()
  {
     // What's the page height?
     var height = document.body.scrollHeight;

     // Going to 'pipe' the data to the parent through the helpframe..
     var pipe = document.getElementById('helpframe');

     // Cachebuster a precaution here to stop browser caching interfering
     pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();

  }
</script>

Contents of www.foo.com/helper.html:

<html> 
<!-- 
This page is on the same domain as the parent, so can
communicate with it to order the iframe window resizing
to fit the content 
--> 
  <body onload="parentIframeResize()"> 
    <script> 
      // Tell the parent iframe what height the iframe needs to be
      function parentIframeResize()
      {
         var height = getParam('height');
         // This works as our parent's parent is on our domain..
         parent.parent.resizeIframe(height);
      }

      // Helper function, parse param from request string
      function getParam( name )
      {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
          return "";
        else
          return results[1];
      }
    </script> 
  </body> 
</html>

Eclipse - Unable to install breakpoint due to missing line number attributes

For Web project with Tomcat server, I resolved it by using following steps.

  1. Open Window -> Show view -> Other -> Servers.
  2. Double click on the running tomcat server. (Overview of tomcat server will be opened)
  3. Now Click on Launch configuration link.
  4. Click on the sources Tab.
  5. Click on Add.
  6. Choose java project
  7. All your projects will be displayed.
  8. Select the on You want to debug.
  9. Save the configuration and Restart or build the application again.

MySQL - Rows to Columns

My solution :

select h.hostid, sum(ifnull(h.A,0)) as A, sum(ifnull(h.B,0)) as B, sum(ifnull(h.C,0)) as  C from (
select
hostid,
case when itemName = 'A' then itemvalue end as A,
case when itemName = 'B' then itemvalue end as B,
case when itemName = 'C' then itemvalue end as C
  from history 
) h group by hostid

It produces the expected results in the submitted case.

How to use ESLint with Jest

The docs show you are now able to add:

"env": {
    "jest/globals": true
}

To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings.

How to check if a service is running on Android?

This applies more towards Intent Service debugging since they spawn a thread, but may work for regular services as well. I found this thread thanks to Binging

In my case, I played around with the debugger and found the thread view. It kind of looks like the bullet point icon in MS Word. Anyways, you don't have to be in debugger mode to use it. Click on the process and click on that button. Any Intent Services will show up while they are running, at least on the emulator.

Why can't I see the "Report Data" window when creating reports?

I had the same problem, but in c# 2012 I closed the "report data" and I couldn't find it and I finally found a solution to this issue.

This is my method:

VIEW >> TOOLBARS >> CUSTOMIZE >> COMMANDS ... select from the "Menu bar" .. VIEW.

OK now in the "Controls" find the "REPORT DATA", select it and MOVE it UP, close the menu. After that select a file.rdlc and click on the "View" ... OK Finally will be appeared "REPORT DATA"...

TimePicker Dialog from clicking EditText

public void onClick1(View v) {
  DatePickerDialog dialog = new DatePickerDialog(this, this, 2013, 2, 18);
  dialog.show();
}

public void onDateSet1(DatePicker view, int year1, int month1, int day1) {
  e1.setText(day1 + "/" + (month1+1) + "/" + year1);
}

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

Increment a database field by 1

If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:

INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;

If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.

The endpoint reference (EPR) for the Operation not found is

This error is coming because while calling the service, it is not getting the WSDL file of your service.

Just check whether WSDL file of your service is there--> run server and from browser run axis 2 apps on local host and check the deployed services and click on your service, then it shows WSDL file of your service.....or check the service path in your client file.

I hope it may help you to resolve the problem.

How to force IE10 to render page in IE9 document mode

By what this says, IE10 (the article is referred to a preview release, anyway) it's able to use X-UA-Compatible only if the document is in quirks mode (no DOCTYPE), otherwise IE10 won't react to the request.

Here's an excerpt:

Thus, to make IE10 react to the X-UA-Compatible directive, one must either create a page that triggers quirks-mode per the rules of HTML5 (that is: an a page with no doctype). One can also send the directive as a HTTP header, however: A HTTP sent directive appears to have no effect if you use it to downgrade the rendering — it can only be used to upgrade the rendering

So, you've to do it manually with Dvelopers Tools, or with quirks mode (but I suggest to stay in IE10 mode which is for the first time aligned to the other browers' standard)

EDIT: The follows are some useful link to read:

http://msdn.microsoft.com/en-us/library/cc288325(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/jj676915(v=vs.85).aspx

http://blogs.msdn.com/b/ie/archive/2011/12/14/interoperable-html5-quirks-mode-in-ie10.aspx

How to do something to each file in a directory with a batch script

Use

for /r path %%var in (*.*) do some_command %%var

with:

  • path being the starting path.
  • %%var being some identifier.
  • *.* being a filemask OR the contents of a variable.
  • some_command being the command to execute with the path and var concatenated as parameters.

Calendar Recurring/Repeating Events - Best Storage Method

While the currently accepted answer was a huge help to me, I wanted to share some useful modifications that simplify the queries and also increase performance.


"Simple" Repeat Events

To handle events which recur at regular intervals, such as:

Repeat every other day 

or

Repeat every week on Tuesday 

You should create two tables, one called events like this:

ID    NAME
1     Sample Event
2     Another Event

And a table called events_meta like this:

ID    event_id      repeat_start       repeat_interval
1     1             1369008000         604800            -- Repeats every Monday after May 20th 2013
1     1             1369008000         604800            -- Also repeats every Friday after May 20th 2013

With repeat_start being a unix timestamp date with no time (1369008000 corresponds to May 20th 2013) , and repeat_interval an amount in seconds between intervals (604800 is 7 days).

By looping over each day in the calendar you can get repeat events using this simple query:

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE  (( 1299736800 - repeat_start) % repeat_interval = 0 )

Just substitute in the unix-timestamp (1299736800) for each date in your calendar.

Note the use of the modulo (% sign). This symbol is like regular division, but returns the ''remainder'' instead of the quotient, and as such is 0 whenever the current date is an exact multiple of the repeat_interval from the repeat_start.

Performance Comparison

This is significantly faster than the previously suggested "meta_keys"-based answer, which was as follows:

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
RIGHT JOIN `events_meta` EM2 ON EM2.`meta_key` = CONCAT( 'repeat_interval_', EM1.`id` )
WHERE EM1.meta_key = 'repeat_start'
    AND (
        ( CASE ( 1299132000 - EM1.`meta_value` )
            WHEN 0
              THEN 1
            ELSE ( 1299132000 - EM1.`meta_value` )
          END
        ) / EM2.`meta_value`
    ) = 1

If you run EXPLAIN this query, you'll note that it required the use of a join buffer:

+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref              | rows | Extra                          |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
|  1 | SIMPLE      | EM1   | ALL    | NULL          | NULL    | NULL    | NULL             |    2 | Using where                    |
|  1 | SIMPLE      | EV    | eq_ref | PRIMARY       | PRIMARY | 4       | bcs.EM1.event_id |    1 |                                |
|  1 | SIMPLE      | EM2   | ALL    | NULL          | NULL    | NULL    | NULL             |    2 | Using where; Using join buffer |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+

The solution with 1 join above requires no such buffer.


"Complex" Patterns

You can add support for more complex types to support these types of repeat rules:

Event A repeats every month on the 3rd of the month starting on March 3, 2011

or

Event A repeats second Friday of the month starting on March 11, 2011

Your events table can look exactly the same:

ID    NAME
1     Sample Event
2     Another Event

Then to add support for these complex rules add columns to events_meta like so:

ID    event_id      repeat_start       repeat_interval    repeat_year    repeat_month    repeat_day    repeat_week    repeat_weekday
1     1             1369008000         604800             NULL           NULL            NULL          NULL           NULL             -- Repeats every Monday after May 20, 2013
1     1             1368144000         604800             NULL           NULL            NULL          NULL           NULL             -- Repeats every Friday after May 10, 2013
2     2             1369008000         NULL               2013           *               *             2              5                -- Repeats on Friday of the 2nd week in every month    

Note that you simply need to either specify a repeat_interval or a set of repeat_year, repeat_month, repeat_day, repeat_week, and repeat_weekday data.

This makes selection of both types simultaneously very simple. Just loop through each day and fill in the correct values, (1370563200 for June 7th 2013, and then the year, month, day, week number and weekday as follows):

SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE  (( 1370563200 - repeat_start) % repeat_interval = 0 )
  OR ( 
    (repeat_year = 2013 OR repeat_year = '*' )
    AND
    (repeat_month = 6 OR repeat_month = '*' )
    AND
    (repeat_day = 7 OR repeat_day = '*' )
    AND
    (repeat_week = 2 OR repeat_week = '*' )
    AND
    (repeat_weekday = 5 OR repeat_weekday = '*' )
    AND repeat_start <= 1370563200
  )

This returns all events that repeat on the Friday of the 2nd week, as well as any events that repeat every Friday, so it returns both event ID 1 and 2:

ID    NAME
1     Sample Event
2     Another Event

*Sidenote in the above SQL I used PHP Date's default weekday indexes, so "5" for Friday


Hope this helps others as much as the original answer helped me!

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

You want to look into 'Splash' Screens.

Display another 'Splash' form and wait until the processing is done.

Here is an example on how to do it.

Mailto links do nothing in Chrome but work in Firefox?

On macOS check also the Mail.app settings, which App is selected as default email App / associated with mailto: links:

If you ever clicked that notification on Gmail, which allows to open links in Gmail instead your App - and after this reset the Chrome handler, you have to edit this manually in your Mail.app Settings.

Screenshot

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

Ajax using https on an http page

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.

How to find third or n?? maximum salary from salary table?

declare @nHighestSalary as int
set @nHighestSalary = 3
SELECT TOP 1 salary FROM (
   SELECT TOP @nHighestSalary salary 
   FROM employees 
   ORDER BY salary DESC) AS emp 
ORDER BY salary ASC

Write applications in C or C++ for Android?

Short answer: You can't.

@Backslash17: Looking through the article and the following link with installation instructions, all the company got working is to launch a self compiled executable on the emulator, bypassing the android framework. Once you have the emulator you can telnet in and have a linux shell. Running a linux program there is trivial of course. But that's not working for phones without jailbreak(aka root access) and not deliverable on the market.

Unless Google opens other opportunities or someone writes a custom compiler that compiles Language X into Dalvik bytecode (Dalvik is the VM that runs Android programs) you won't be able to write native code.

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

check if a std::vector contains a certain object?

Checking if v contains the element x:

#include <algorithm>

if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

Checking if v contains elements (is non-empty):

if(!v.empty()){
    /* v is non-empty */
} else {
    /* v is empty */
}

re.sub erroring with "Expected string or bytes-like object"

I suppose better would be to use re.match() function. here is an example which may help you.

import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]  
sentences

Cannot find java. Please use the --jdkhome switch

ATTENTION MAC OS USERS


First, please remember that in a Mac computer the netbeans.conf file is stored at

/Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc/netbeans.conf

(if you had used the default installation package.)

Then, also remember that the directory you MUST use on either "netbeans_jdkhome" or "--jdkhome" it's NOT the /Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/ but the following one:

/Library/Java/JavaVirtualMachines/jdk1.8.0_172.jdk/Contents/Home //<-- Please, notice the /Contents/Home at the end. That's the "trick"!

Note: of course, you must change the versions for both NetBeans and JDK you're using.

ADB No Devices Found

This situation seems to arise with some ADB drivers. I have encountered the same thing with a couple of Google devices and installing the Universal ADB windows driver has fixed it for me every time.

Detect if PHP session exists

function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();

What is a loop invariant?

Definition by How to Think About Algorithms, by Jeff Edmonds

A loop invariant is an assertion that is placed at the top of a loop and that must hold true every time the computation returns to the top of the loop.

how to use List<WebElement> webdriver

Try the following code:

//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
  System.out.println(e.getText());
}

It will returns with the whole content of the <li> tags, like:

<a class="extra">Vše</a> (950)</li>

But you can easily get the number now from it, for example by using split() and/or substring().

Is there a Google Sheets formula to put the name of the sheet into a cell?

if you want to use build-in functions:

=REGEXEXTRACT(cell("address";'Sheet1'!A1);"^'(.*)'!\$A\$1$")

Explanation: cell("address";'Sheet1'!A1) gives you the address of the sheet, output is 'Sheet1'!$A$1. Now we need to extract the actual sheet name from this output. I'm using REGEXEXTRACT to match it by regex ^'(.*)'!\$A\$1$, but you can either use more/less specific regex or use functions like SUBSTITUTE or REPLACE

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

You need to subclass UITableViewCell and subclass method willTransitionToState:(UITableViewCellStateMask)state which is called whenever user swipes the cell. The state flags will let you know if the Delete button is showing, and show/hide your More button there.

Unfortunately this method gives you neither the width of the Delete button nor the animation time. So you need to observer & hard-code your More button's frame and animation time into your code (I personally think Apple needs to do something about this).

How can I count the occurrences of a string within a file?

None of the existing answers worked for me with a single-line 10GB file. Grep runs out of memory even on a machine with 768 GB of RAM!

$ cat /proc/meminfo | grep MemTotal
MemTotal:       791236260 kB
$ ls -lh test.json
-rw-r--r-- 1 me all 9.2G Nov 18 15:54 test.json
$ grep -o '0,0,0,0,0,0,0,0,' test.json  | wc -l
grep: memory exhausted
0

So I wrote a very simple Rust program to do it.

  1. Install Rust.
  2. cargo install count_occurences
$ count_occurences '0,0,0,0,0,0,0,0,' test.json
99094198

It's a little slow (1 minute for 10GB), but at least it doesn't run out of memory!

Best way to clear a PHP array's values

i have used unset() to clear the array but i have come to realize that unset() will render the array null hence the need to re-declare the array like for example

<?php 
    $arr = array();
    array_push($arr , "foo");
    unset($arr); // this will set the array to null hence you need the line below or redeclaring it.
    $arr  = array();

    // do what ever you want here
?>

Correct way of using log4net (logger naming)

Regarding how you log messages within code, I would opt for the second approach:

ILog log = LogManager.GetLogger(typeof(Bar));
log.Info("message");

Where messages sent to the log above will be 'named' using the fully-qualifed type Bar, e.g.

MyNamespace.Foo.Bar [INFO] message

The advantage of this approach is that it is the de-facto standard for organising logging, it also allows you to filter your log messages by namespace. For example, you can specify that you want to log INFO level message, but raise the logging level for Bar specifically to DEBUG:

<log4net>
    <!-- appenders go here -->
    <root>
        <level value="INFO" />
        <appender-ref ref="myLogAppender" />
    </root>

    <logger name="MyNamespace.Foo.Bar">
        <level value="DEBUG" />
    </logger>
</log4net>

The ability to filter your logging via name is a powerful feature of log4net, if you simply log all your messages to "myLog", you loose much of this power!

Regarding the EPiServer CMS, you should be able to use the above approach to specify a different logging level for the CMS and your own code.

For further reading, here is a codeproject article I wrote on logging:

Entity framework linq query Include() multiple children entities

You might find this article of interest which is available at codeplex.com.

The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.

Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.

How to update value of a key in dictionary in c#?

Dictionary is a key value pair. Catch Key by

dic["cat"] 

and assign its value like

dic["cat"] = 5

How to pass in password to pg_dump?

This one liner helps me while creating dump of a single database.

PGPASSWORD="yourpassword" pg_dump -U postgres -h localhost mydb > mydb.pgsql

Cause of a process being a deadlock victim

Although @Remus Rusanu's is already an excelent answer, in case one is looking forward a better insight on SQL Server's Deadlock causes and trace strategies, I would suggest you to read Brad McGehee's How to Track Down Deadlocks Using SQL Server 2005 Profiler

How to convert between bytes and strings in Python 3?

The 'mangler' in the above code sample was doing the equivalent of this:

bytesThing = stringThing.encode(encoding='UTF-8')

There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

newStringThing = bytesThing.decode(encoding='UTF-8')

When we do this, the original string is recovered.

Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

Visual Studio Code how to resolve merge conflicts with git?

With VSCode you can find the merge conflicts easily with the following UI. enter image description here

(if you do not have the topbar, set "editor.codeLens": true in User Preferences)

It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD.

If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming, etc.

How do I print the content of a .txt file in Python?

Opening a file in python for reading is easy:

f = open('example.txt', 'r')

To get everything in the file, just use read()

file_contents = f.read()

And to print the contents, just do:

print (file_contents)

Don't forget to close the file when you're done.

f.close()

How to increment a variable on a for loop in jinja template?

if anyone want to add a value inside loop then you can use this its working 100%

{% set ftotal= {'total': 0} %} 
{%- for pe in payment_entry -%}
    {% if ftotal.update({'total': ftotal.total + 5}) %}{% endif %} 
{%- endfor -%}

{{ftotal.total}}

output = 5

Android, How to read QR code in my application?

Easy QR Code Library

A simple Android Easy QR Code Library. It is very easy to use, to use this library follow these steps.

For Gradle:

Step 1. Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

Step 2. Add the dependency:

dependencies {
        compile 'com.github.mrasif:easyqrlibrary:v1.0.0'
}

For Maven:

Step 1. Add the JitPack repository to your build file:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

Step 2. Add the dependency:

<dependency>
    <groupId>com.github.mrasif</groupId>
    <artifactId>easyqrlibrary</artifactId>
    <version>v1.0.0</version>
</dependency>

For SBT:

Step 1. Add the JitPack repository to your build.sbt file:

resolvers += "jitpack" at "https://jitpack.io"

Step 2. Add the dependency:

libraryDependencies += "com.github.mrasif" % "easyqrlibrary" % "v1.0.0"

For Leiningen:

Step 1. Add it in your project.clj at the end of repositories:

:repositories [["jitpack" "https://jitpack.io"]]

Step 2. Add the dependency:

:dependencies [[com.github.mrasif/easyqrlibrary "v1.0.0"]]

Add this in your layout xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="No QR Data"/>
    <Button
        android:id="@+id/btnQRScan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="QR Scan"/>

</LinearLayout>

Add this in your activity java files:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView tvData;
    Button btnQRScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvData=findViewById(R.id.tvData);
        btnQRScan=findViewById(R.id.btnQRScan);

        btnQRScan.setOnClickListener(this);
    }

    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btnQRScan: {
                Intent intent=new Intent(MainActivity.this, QRScanner.class);
                startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
            } break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case EasyQR.QR_SCANNER_REQUEST: {
                if (resultCode==RESULT_OK){
                    tvData.setText(data.getStringExtra(EasyQR.DATA));
                }
            } break;
        }
    }
}

For customized scanner screen just add these lines when you start the scanner Activity.

Intent intent=new Intent(MainActivity.this, QRScanner.class);
intent.putExtra(EasyQR.IS_TOOLBAR_SHOW,true);
intent.putExtra(EasyQR.TOOLBAR_DRAWABLE_ID,R.drawable.ic_audiotrack_dark);
intent.putExtra(EasyQR.TOOLBAR_TEXT,"My QR");
intent.putExtra(EasyQR.TOOLBAR_BACKGROUND_COLOR,"#0588EE");
intent.putExtra(EasyQR.TOOLBAR_TEXT_COLOR,"#FFFFFF");
intent.putExtra(EasyQR.BACKGROUND_COLOR,"#000000");
intent.putExtra(EasyQR.CAMERA_MARGIN_LEFT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_TOP,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_RIGHT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_BOTTOM,50);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);

You are done. Ref. Link: https://mrasif.github.io/easyqrlibrary

What is the definition of "interface" in object oriented programming

An interface is one of the more overloaded and confusing terms in development.

It is actually a concept of abstraction and encapsulation. For a given "box", it declares the "inputs" and "outputs" of that box. In the world of software, that usually means the operations that can be invoked on the box (along with arguments) and in some cases the return types of these operations.

What it does not do is define what the semantics of these operations are, although it is commonplace (and very good practice) to document them in proximity to the declaration (e.g., via comments), or to pick good naming conventions. Nevertheless, there are no guarantees that these intentions would be followed.

Here is an analogy: Take a look at your television when it is off. Its interface are the buttons it has, the various plugs, and the screen. Its semantics and behavior are that it takes inputs (e.g., cable programming) and has outputs (display on the screen, sound, etc.). However, when you look at a TV that is not plugged in, you are projecting your expected semantics into an interface. For all you know, the TV could just explode when you plug it in. However, based on its "interface" you can assume that it won't make any coffee since it doesn't have a water intake.

In object oriented programming, an interface generally defines the set of methods (or messages) that an instance of a class that has that interface could respond to.

What adds to the confusion is that in some languages, like Java, there is an actual interface with its language specific semantics. In Java, for example, it is a set of method declarations, with no implementation, but an interface also corresponds to a type and obeys various typing rules.

In other languages, like C++, you do not have interfaces. A class itself defines methods, but you could think of the interface of the class as the declarations of the non-private methods. Because of how C++ compiles, you get header files where you could have the "interface" of the class without actual implementation. You could also mimic Java interfaces with abstract classes with pure virtual functions, etc.

An interface is most certainly not a blueprint for a class. A blueprint, by one definition is a "detailed plan of action". An interface promises nothing about an action! The source of the confusion is that in most languages, if you have an interface type that defines a set of methods, the class that implements it "repeats" the same methods (but provides definition), so the interface looks like a skeleton or an outline of the class.

Javascript: The prettiest way to compare one value against multiple values

Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:

if (foobar === foo || foobar === bar) {
     //do something
}

And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:

// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);

// test the Set at runtime
if (tSet.has(foobar)) {
    // do something
}

For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

a) Open the "php.ini". For XAMPP,it is located in C:\XAMPP\php\php.ini. Find out if you are using WAMP or LAMP server. Note : Make a backup of php.ini file 

b) Search [mail function] in the php.ini file. 

You can find like below.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25


; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost


Change the localhost to the smtp server name of your ISP. No need to change the smtp_port. Leave it as 25. Change sendmail_from from postmaster@localhost to your domain email address which will be used as from address.. 

So for me, it will become like this.
[mail function]
; For Win32 only.
SMTP = smtp.planetghost.com
smtp_port = 25
; For Win32 only.
sendmail_from = [email protected]
auth_username = [email protected]
auth_password = example_password


c) Restart the XAMPP or WAMP(apache server) so that changes will start working.

d) Now try to send the mail using the mail() function , 

mail("[email protected]","Success","Great, Localhost Mail works");

credit

================================================================================

Another way

Gmail servers use SMTP Authentication under SSL. I think that there is no way to use the mail() function under that circumstances, so you might want to check these alternatives:

  1. PEAR: Mail
  2. phpMailer

They both support SMTP auth under SSL.

Credit : Check reference answer here

Upload failed You need to use a different version code for your APK because you already have one with version code 2

If you're using Building Standalone Apps with Expo, the versionCode error might creep up owing to the fact that the standard app.json config only has a reference to the version property.

I was able to add a versionCode property under android as follows:

Sample App.json

{
  "expo": {
    "sdkVersion": "29.0.0",
    "name": "App Name",
    "version": "1.1.0",
    "slug": "app-name",
    "icon": "src/images/app-icon.png",
    "privacy": "public",
    "android": {
      "package": "com.madhues.app",
      "permissions": [],
      "versionCode": 2 // Notice the versionCode added under android.
    }
  }
}

Detailed documentation: https://docs.expo.io/versions/v32.0.0/workflow/configuration/#versioncode

What operator is <> in VBA

This is an Inequality operator.

Also,this might be helpful for future: Operators listed by Functionality

How do I interpret precision and scale of a number in a database?

Precision, Scale, and Length in the SQL Server 2000 documentation reads:

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

How do I format currencies in a Vue component?

I have created a filter. The filter can be used in any page.

Vue.filter('toCurrency', function (value) {
    if (typeof value !== "number") {
        return value;
    }
    var formatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 0
    });
    return formatter.format(value);
});

Then I can use this filter like this:

        <td class="text-right">
            {{ invoice.fees | toCurrency }}
        </td>

I used these related answers to help with the implementation of the filter:

Removing duplicate characters from a string

from collections import OrderedDict
def remove_duplicates(value):
        m=list(OrderedDict.fromkeys(value))
        s=''
        for i in m:
            s+=i
        return s
print(remove_duplicates("11223445566666ababzzz@@@123#*#*"))

How can I get device ID for Admob

If you are displaying ads using XML layout and if you already have "ads:testDevices=" in your layout XML file, AdMob will NOT print the "To get test ads on this device..." message in the LogCat output. Take that out and then you will see the LogCat message.

Here is a nice tutorial on how to find device id in LogCat: http://webhole.net/2011/12/02/android-sdk-tutorial-get-admob-test-device-id/

how to convert a string to date in mysql?

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAY

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

@theczechsensation's solution is already half way there.

For those who like to exclude noisy log messages and keep the log to their app only this is the solution:

New Logcat Filter Settings

Add your exclusions to Log Tag like this: ^(?!(eglCodecCommon|tagToExclude))

Add your package name or prefix to Package Name: com.mycompany.

This way it is possible to filter for as many strings you like and keep the log to your package.

Jquery href click - how can I fire up an event?

Try:

$(document).ready(function(){
   $('a .sign_new').click(function(){
      alert('Sign new href executed.'); 
   }); 
});

You've mixed up the class and href names / selector type.

Laravel view not found exception

In my case, Laravel 5.3

Route::get('/', function(){
    return View('test');
});

test.blade.php was not rendering but some other views were rendering on localhost via XAMPP on mac. Upon running artisan server, the view started rendering for same url over XAMPP.

php artisan serve

To avoid any such scenario, one should test the Laravel apps with artisan server only.

Best practice: PHP Magic Methods __set and __get

I have been exactly in your case in the past. And I went for magic methods.

This was a mistake, the last part of your question says it all :

  • this is slower (than getters/setters)
  • there is no auto-completion (and this is a major problem actually), and type management by the IDE for refactoring and code-browsing (under Zend Studio/PhpStorm this can be handled with the @property phpdoc annotation but that requires to maintain them: quite a pain)
  • the documentation (phpdoc) doesn't match how your code is supposed to be used, and looking at your class doesn't bring much answers as well. This is confusing.
  • added after edit: having getters for properties is more consistent with "real" methods where getXXX() is not only returning a private property but doing real logic. You have the same naming. For example you have $user->getName() (returns private property) and $user->getToken($key) (computed). The day your getter gets more than a getter and needs to do some logic, everything is still consistent.

Finally, and this is the biggest problem IMO : this is magic. And magic is very very bad, because you have to know how the magic works to use it properly. That's a problem I've met in a team: everybody has to understand the magic, not just you.

Getters and setters are a pain to write (I hate them) but they are worth it.

How to get a complete list of object's methods and attributes?

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

SSIS Excel Connection Manager failed to Connect to the Source

The workaround is, I I save the excel file as excel 97-2003 then it works fine

Match the path of a URL, minus the filename extension

There's no need to use a regular expression to dissect a URL. PHP has built-in functions for this, pathinfo() and parse_url().

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

Android/Java - Date Difference in days

use these functions

    public static int getDateDifference(int previousYear, int previousMonthOfYear, int previousDayOfMonth, int nextYear, int nextMonthOfYear, int nextDayOfMonth, int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    Calendar previousDate = Calendar.getInstance();
    previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    previousDate.set(Calendar.MONTH, previousMonthOfYear);
    previousDate.set(Calendar.YEAR, previousYear);

    Calendar nextDate = Calendar.getInstance();
    nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    nextDate.set(Calendar.MONTH, previousMonthOfYear);
    nextDate.set(Calendar.YEAR, previousYear);

    return getDateDifference(previousDate,nextDate,differenceToCount);
}
public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    //raise an exception if previous is greater than nextdate.
    if(previousDate.compareTo(nextDate)>0){
        throw new RuntimeException("Previous Date is later than Nextdate");
    }

    int difference=0;
    while(previousDate.compareTo(nextDate)<=0){
        difference++;
        previousDate.add(differenceToCount,1);
    }
    return difference;
}

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

The following method may work:

git rebase HEAD master
git checkout master

This will rebase your current HEAD changes on top of the master. Then you can switch the branch.


Alternative way is to checkout the branch first:

git checkout master

Then Git should display SHA1 of your detached commits, then you can cherry pick them, e.g.

git cherry-pick YOURSHA1

Or you can also merge the latest one:

git merge YOURSHA1

To see all of your commits from different branches (to make sure you've them), run: git reflog.

Scala how can I count the number of occurrences in a list

using cats

import cats.implicits._

"Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.combineAll
"Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.foldMap(identity)

How to set custom header in Volley Request

You can see this solution. It shows how to get/set cookies, but cookies are just one of the headers in a request/response. You have to override one of the Volley's *Request classes and set the required headers in getHeaders()


Here is the linked source:

public class StringRequest extends com.android.volley.toolbox.StringRequest {

private final Map<String, String> _params;

/**
 * @param method
 * @param url
 * @param params
 *            A {@link HashMap} to post with the request. Null is allowed
 *            and indicates no parameters will be posted along with request.
 * @param listener
 * @param errorListener
 */
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
        ErrorListener errorListener) {
    super(method, url, listener, errorListener);

    _params = params;
}

@Override
protected Map<String, String> getParams() {
    return _params;
}

/* (non-Javadoc)
 * @see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
 */
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    // since we don't know which of the two underlying network vehicles
    // will Volley use, we have to handle and store session cookies manually
    MyApp.get().checkSessionCookie(response.headers);

    return super.parseNetworkResponse(response);
}

/* (non-Javadoc)
 * @see com.android.volley.Request#getHeaders()
 */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    MyApp.get().addSessionCookie(headers);

    return headers;
}

}

And MyApp class:

public class MyApp extends Application {
    private static final String SET_COOKIE_KEY = "Set-Cookie";
    private static final String COOKIE_KEY = "Cookie";
    private static final String SESSION_COOKIE = "sessionid";

    private static MyApp _instance;
    private RequestQueue _requestQueue;
    private SharedPreferences _preferences;

    public static MyApp get() {
        return _instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        _instance = this;
            _preferences = PreferenceManager.getDefaultSharedPreferences(this);
        _requestQueue = Volley.newRequestQueue(this);
    }

    public RequestQueue getRequestQueue() {
        return _requestQueue;
    }


    /**
     * Checks the response headers for session cookie and saves it
     * if it finds it.
     * @param headers Response Headers.
     */
    public final void checkSessionCookie(Map<String, String> headers) {
        if (headers.containsKey(SET_COOKIE_KEY)
                && headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
                String cookie = headers.get(SET_COOKIE_KEY);
                if (cookie.length() > 0) {
                    String[] splitCookie = cookie.split(";");
                    String[] splitSessionId = splitCookie[0].split("=");
                    cookie = splitSessionId[1];
                    Editor prefEditor = _preferences.edit();
                    prefEditor.putString(SESSION_COOKIE, cookie);
                    prefEditor.commit();
                }
            }
    }

    /**
     * Adds session cookie to headers if exists.
     * @param headers
     */
    public final void addSessionCookie(Map<String, String> headers) {
        String sessionId = _preferences.getString(SESSION_COOKIE, "");
        if (sessionId.length() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append(SESSION_COOKIE);
            builder.append("=");
            builder.append(sessionId);
            if (headers.containsKey(COOKIE_KEY)) {
                builder.append("; ");
                builder.append(headers.get(COOKIE_KEY));
            }
            headers.put(COOKIE_KEY, builder.toString());
        }
    }

}

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

How to check if object has any properties in JavaScript?

You can use the following:

Double bang !! property lookup

var a = !![]; // true
var a = !!null; // false

hasOwnProperty This is something that I used to use:

var myObject = {
  name: 'John',
  address: null
};
if (myObject.hasOwnProperty('address')) { // true
  // do something if it exists.
}

However, JavaScript decided not to protect the method’s name, so it could be tampered with.

var myObject = {
  hasOwnProperty: 'I will populate it myself!'
};

prop in myObject

var myObject = {
  name: 'John',
  address: null,
  developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.

typeof

if (typeof myObject.name !== 'undefined') {
  // do something
}

However, it doesn't check for null.

I think this is the best way.

in operator

var myObject = {
  name: 'John',
  address: null
};

if('name' in myObject) {
  console.log("Name exists in myObject");
}else{
  console.log("Name does not exist in myObject");
}

result:

Name exists in myObject

Here is a link that goes into more detail on the in operator: Determining if an object property exists

How can I introduce multiple conditions in LIKE operator?

This might help:

select * from tbl where col like '[ABC-XYZ-PQR]%'

I've used this in SQL Server 2005 and it worked.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I liked Addison Klinke's post the most, as being the simplest, but used Wojciech Moszczynsk’s suggestion for filtering and charting, but extended the filter to avoid absolute values, so given a large correlation matrix, filter it, chart it, and then flatten it:

Created, Filtered and Charted

dfCorr = df.corr()
filteredDf = dfCorr[((dfCorr >= .5) | (dfCorr <= -.5)) & (dfCorr !=1.000)]
plt.figure(figsize=(30,10))
sn.heatmap(filteredDf, annot=True, cmap="Reds")
plt.show()

filtered heat map

Function

In the end, I created a small function to create the correlation matrix, filter it, and then flatten it. As an idea, it could easily be extended, e.g., asymmetric upper and lower bounds, etc.

def corrFilter(x: pd.DataFrame, bound: float):
    xCorr = x.corr()
    xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr !=1.000)]
    xFlattened = xFiltered.unstack().sort_values().drop_duplicates()
    return xFlattened

corrFilter(df, .7)

enter image description here

Using Java 8's Optional with Stream::flatMap

Java 9

Optional.stream has been added to JDK 9. This enables you to do the following, without the need of any helper method:

Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(Optional::stream)
          .findFirst();

Java 8

Yes, this was a small hole in the API, in that it's somewhat inconvenient to turn an Optional<T> into a zero-or-one length Stream<T>. You could do this:

Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
          .findFirst();

Having the ternary operator inside the flatMap is a bit cumbersome, though, so it might be better to write a little helper function to do this:

/**
 * Turns an Optional<T> into a Stream<T> of length zero or one depending upon
 * whether a value is present.
 */
static <T> Stream<T> streamopt(Optional<T> opt) {
    if (opt.isPresent())
        return Stream.of(opt.get());
    else
        return Stream.empty();
}

Optional<Other> result =
    things.stream()
          .flatMap(t -> streamopt(resolve(t)))
          .findFirst();

Here, I've inlined the call to resolve() instead of having a separate map() operation, but this is a matter of taste.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

If you want everyone to be able to access the Node app, then try using

res.header('Access-Control-Allow-Origin', "*")

That will allow requests from any origin. The CORS enable site has a lot of information on the different Access-Control-Allow headers and how to use them.

I you are using Chrome, please look at this bug bug regarding localhost and Access-Control-Allow-Origin. There is another StackOverflow question here that details the issue.