Programs & Examples On #Scramble

a way to encode information to make the information unintelligible.

Best way to use PHP to encrypt and decrypt passwords?

This will only give you marginal protection. If the attacker can run arbitrary code in your application they can get at the passwords in exactly the same way your application can. You could still get some protection from some SQL injection attacks and misplaced db backups if you store a secret key in a file and use that to encrypt on the way to the db and decrypt on the way out. But you should use bindparams to completely avoid the issue of SQL injection.

If decide to encrypt, you should use some high level crypto library for this, or you will get it wrong. You'll have to get the key-setup, message padding and integrity checks correct, or all your encryption effort is of little use. GPGME is a good choice for one example. Mcrypt is too low level and you will probably get it wrong.

changing permission for files and folder recursively using shell command in mac

I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:

find . -type d -exec chmod 755 {} \+

but this also does the same thing:

chmod 755 `find . -type d`

and so does this:

chmod 755 $(find . -type d)

The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.

So I think in your case that the following will do what you want.

chmod 777 $(find "/Users/Test/Desktop/PATH")

Setting up SSL on a local xampp/apache server

I have been through all the answers and tutorials over the internet but here are the basic steps to enable SSL (https) on localhost with XAMPP:

Required:

  1. Run -> "C:\xampp\apache\makecert.bat" (double-click on windows) Fill passowords of your choice, hit Enter for everything BUT define "localhost"!!! Be careful when asked here:

    Common Name (e.g. server FQDN or YOUR name) []:localhost

    (Certificates are issued per domain name zone only!)

  2. Restart apache
  3. Chrome -> Settings -> Search "Certificate" -> Manage Certificates -> Trusted Root Certification Authorities -> Import -> "C:\xampp\apache\conf\ssl.crt\server.crt" -> Must Ask "YES" for confirmation!
  4. https://localhost/testssl.php -> [OK, Now Green!] (any html test file)

Optional: (if above doesn't work, do more of these steps)

  1. Run XAMPP As admin (Start -> XAMPP -> right-click -> Run As Administrator)
  2. XAMPP -> Apache -> Config -> httpd.conf ("C:\xampp\apache\conf\httpd.conf")

    LoadModule ssl_module modules/mod_ssl.so (remove # form the start of line)

  3. XAMPP -> Apache -> Config -> php.ini ("C:\xampp\php\php.ini")

    extension=php_openssl.dll (remove ; from the start of line)

  4. Restart apache and chrome!

Check any problems or the status of your certificate:

Chrome -> F12 -> Security -> View Certificate

Android WebView progress bar

wait until the process is over ...

while(webview.getProgress()< 100){}
progressBar.setVisibility(View.GONE);

Android SDK location

The default location for Android sdk(s) on a Mac is:

/Users/*username*/Library/Android/sdk

Time stamp in the C programming language

U can try routines in c time library (time.h). Plus take a look at the clock() in the same lib. It gives the clock ticks since the prog has started. But you can save its value before the operation you want to concentrate on, and then after that operation capture the cliock ticks again and find the difference between then to get the time difference.

Batch program to to check if process exists

TASKLIST does not set errorlevel.

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch

Rails 3: I want to list all paths defined in my rails application

rake routes | grep <specific resource name>

displays resource specific routes, if it is a pretty long list of routes.

How to use JQuery with ReactJS

To install it, just run the command

npm install jquery

or

yarn add jquery

then you can import it in your file like

import $ from 'jquery';

How to get a certain element in a list, given the position?

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'
}

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
{
    std::list<Object>::iterator it = std::next(l.begin(), N);
}

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

Cache an HTTP 'Get' service response in AngularJS?

As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

Check for special characters in string

Your regexp use ^ and $ so it tries to match the entire string. And if you want only a boolean as the result, use test instead of match.

var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;

if(format.test(string)){
  return true;
} else {
  return false;
}

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

How to increase the timeout period of web service in asp.net?

you can do this in different ways:

  1. Setting a timeout in the web service caller from code (not 100% sure but I think I have seen this done);
  2. Setting a timeout in the constructor of the web service proxy in the web references;
  3. Setting a timeout in the server side, web.config of the web service application.

see here for more details on the second case:

http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14

and here for details on the last case:

How to increase the timeout to a web service request?

How to install python modules without root access?

Important question. The server I use (Ubuntu 12.04) had easy_install3 but not pip3. This is how I installed Pip and then other packages to my home folder

  1. Asked admin to install Ubuntu package python3-setuptools

  2. Installed pip

Like this:

 easy_install3 --prefix=$HOME/.local pip
 mkdir -p $HOME/.local/lib/python3.2/site-packages
 easy_install3 --prefix=$HOME/.local pip
  1. Add Pip (and other Python apps to path)

Like this:

PATH="$HOME/.local/bin:$PATH"
echo PATH="$HOME/.local/bin:$PATH" > $HOME/.profile
  1. Install Python package

like this

pip3 install --user httpie

# test httpie package
http httpbin.org

What is the simplest way to convert array to vector?

You're asking the wrong question here - instead of forcing everything into a vector ask how you can convert test to work with iterators instead of a specific container. You can provide an overload too in order to retain compatibility (and handle other containers at the same time for free):

void test(const std::vector<int>& in) {
  // Iterate over vector and do whatever
}

becomes:

template <typename Iterator>
void test(Iterator begin, const Iterator end) {
    // Iterate over range and do whatever
}

template <typename Container>
void test(const Container& in) {
    test(std::begin(in), std::end(in));
}

Which lets you do:

int x[3]={1, 2, 3};
test(x); // Now correct

(Ideone demo)

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

How can I check whether a numpy array is empty or not?

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

import numpy as np
a = np.array([])

if a.size == 0:
    # Do something when `a` is empty

How to redirect stdout to both file and console with scripting?

you can redirect the output to a file by using >> python with print rint's "chevron" syntax as indicated in the docs

let see,

fp=open('test.log','a')   # take file  object reference 
print >> fp , "hello world"            #use file object with in print statement.
print >> fp , "every thing will redirect to file "
fp.close()    #close the file 

checkout the file test.log you will have the data and to print on console just use plain print statement .

Use xml.etree.ElementTree to print nicely formatted xml files

You can use the function toprettyxml() from xml.dom.minidom in order to do that:

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ElementTree.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

The idea is to print your Element in a string, parse it using minidom and convert it again in XML using the toprettyxml function.

Source: http://pymotw.com/2/xml/etree/ElementTree/create.html

How can I check if a command exists in a shell script?

which <cmd>

also see options which supports for aliases if applicable to your case.

Example

$ which foobar
which: no foobar in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/PC Connectivity Solution:/cygdrive/c/Windows/system32/System32/WindowsPowerShell/v1.0:/cygdrive/d/Program Files (x86)/Graphviz 2.28/bin:/cygdrive/d/Program Files (x86)/GNU/GnuPG
$ if [ $? -eq 0 ]; then echo "foobar is found in PATH"; else echo "foobar is NOT found in PATH, of course it does not mean it is not installed."; fi
foobar is NOT found in PATH, of course it does not mean it is not installed.
$

PS: Note that not everything that's installed may be in PATH. Usually to check whether something is "installed" or not one would use installation related commands relevant to the OS. E.g. rpm -qa | grep -i "foobar" for RHEL.

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

npm start error with create-react-app

I might be very late to answer this question but this is what has worked for me and it might help someone to get back on the development track!

nvm install v12.0 // You may need to install nvm, if not already done
rm -rd node_modules/
npm cache clean --force
npm install

Cheers!!

Insert php variable in a href

You could try:

<a href="<?php echo $directory ?>">The link to the file</a>

Or for PHP 5.4+ (<?= is the PHP short echo tag):

<a href="<?= $directory ?>">The link to the file</a>

But your path is relative to the server, don't forget that.

SQL Server - INNER JOIN WITH DISTINCT

add "distinct" after "select".

select distinct a.FirstName, a.LastName, v.District , v.LastName
from AddTbl a 
inner join ValTbl v  where a.LastName = v.LastName  order by Firstname

Fast ceiling of an integer division in C / C++

How about this? (requires y non-negative, so don't use this in the rare case where y is a variable with no non-negativity guarantee)

q = (x > 0)? 1 + (x - 1)/y: (x / y);

I reduced y/y to one, eliminating the term x + y - 1 and with it any chance of overflow.

I avoid x - 1 wrapping around when x is an unsigned type and contains zero.

For signed x, negative and zero still combine into a single case.

Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.

How to add line breaks to an HTML textarea?

You need to use \n for linebreaks inside textarea

How do I filter date range in DataTables?

Here is DataTable with Single DatePicker as "from" Date Filter

LiveDemo

Here is DataTable with Two DatePickers for DateRange (To and From) Filter

LiveDemo

Why is this jQuery click function not working?

Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/

The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.

<!DOCTYPE html>
<html>
<head>


<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script src="https://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
  <a href="#" id="clicker" value="Click Me!" >Click Me</a>
  <script type="text/javascript">

        $("#clicker").click(function () {
            alert("Hello!");
            $(".hide_div").hide();

        });


</script>

</body>
</html>

Notice: In the demo replace http with https there in the code, or use this variant Demo

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:

function modify_jquery() {
    if (!is_admin()) {
        wp_deregister_script('jquery');
        wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
        wp_enqueue_script('jquery');
    }
}
add_action('init', 'modify_jquery');

Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/

Proper use cases for Android UserManager.isUserAGoat()?

This appears to be an inside joke at Google. It's also featured in the Google Chrome task manager. It has no purpose, other than some engineers finding it amusing. Which is a purpose by itself, if you will.

  1. In Chrome, open the Task Manager with Shift+Esc.
  2. Right click to add the Goats Teleported column.
  3. Wonder.

There is even a huge Chromium bug report about too many teleported goats.

chrome

The following Chromium source code snippet is stolen from the HN comments.

int TaskManagerModel::GetGoatsTeleported(int index) const {
  int seed = goat_salt_ * (index + 1);
  return (seed >> 16) & 255;
}

Twitter-Bootstrap-2 logo image on top of navbar

You should remove navbar-fixed-top class otherwise navbar stays fixed on top of page where you want logo.


If you want to place logo inside navbar:

Navbar height (set in @navbarHeight LESS variable) is 40px by default. Your logo has to fit inside or you have to make navbar higher first.

Then use brand class:

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
    </div>
  </div>
</div>

If your logo is higher than 20px, you have to fix stylesheets as well.

If you do that in LESS:

.navbar .brand {
  @elementHeight: 32px;
  padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}

@elementHeight should be set to your image height.

Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52

Alternatively you can calculate padding values yourself and use pure CSS.

This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;

public void clickOnSubmitButton() {
    submitButton.click();
}   

How do I send a file in Android from a mobile device to server using http?

Wrap it all up in an Async task to avoid threading errors.

public class AsyncHttpPostTask extends AsyncTask<File, Void, String> {

    private static final String TAG = AsyncHttpPostTask.class.getSimpleName();
    private String server;

    public AsyncHttpPostTask(final String server) {
        this.server = server;
    }

    @Override
    protected String doInBackground(File... params) {
        Log.d(TAG, "doInBackground");
        HttpClient http = AndroidHttpClient.newInstance("MyApp");
        HttpPost method = new HttpPost(this.server);
        method.setEntity(new FileEntity(params[0], "text/plain"));
        try {
            HttpResponse response = http.execute(method);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            final StringBuilder out = new StringBuilder();
            String line;
            try {
                while ((line = rd.readLine()) != null) {
                    out.append(line);
                }
            } catch (Exception e) {}
            // wr.close();
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // final String serverResponse = slurp(is);
            Log.d(TAG, "serverResponse: " + out.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Alarm Manager Example

This code will help you to make a repeating alarm. The repeating time can set by you.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" 
     android:background="#000000"
     android:paddingTop="100dp">

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center" >

    <EditText
        android:id="@+id/ethr"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Hr"
    android:singleLine="true" >


        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/etmin"
    android:layout_width="55dp"
    android:layout_height="wrap_content"

    android:ems="10"
    android:hint="Min"
    android:singleLine="true" />

    <EditText
        android:id="@+id/etsec"
    android:layout_width="50dp"
    android:layout_height="wrap_content"

    android:ems="10"
    android:hint="Sec"
    android:singleLine="true" />

    </LinearLayout>

   <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:gravity="center"
    android:paddingTop="10dp">


    <Button
        android:id="@+id/setAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClickSetAlarm"
        android:text="Set Alarm" />

</LinearLayout>

</LinearLayout>

MainActivity.java

public class MainActivity extends Activity {
    int hr = 0;
    int min = 0;
    int sec = 0;
    int result = 1;

    AlarmManager alarmManager;
    PendingIntent pendingIntent;
    BroadcastReceiver mReceiver;

    EditText ethr;
    EditText etmin;
    EditText etsec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ethr = (EditText) findViewById(R.id.ethr);
        etmin = (EditText) findViewById(R.id.etmin);
        etsec = (EditText) findViewById(R.id.etsec);
        RegisterAlarmBroadcast();
    } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    public void onClickSetAlarm(View v) {
        String shr = ethr.getText().toString();
        String smin = etmin.getText().toString();
        String ssec = etsec.getText().toString();

        if(shr.equals("")) 
            hr = 0;
        else {
            hr = Integer.parseInt(ethr.getText().toString());
            hr=hr*60*60*1000;
        }

        if(smin.equals(""))
            min = 0;
        else {
            min = Integer.parseInt(etmin.getText().toString());
            min = min*60*1000;
        }

        if(ssec.equals(""))
            sec = 0;
        else {
             sec = Integer.parseInt(etsec.getText().toString());
             sec = sec * 1000;
        }
        result = hr+min+sec;
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent); 
    }

    private void RegisterAlarmBroadcast() {
        mReceiver = new BroadcastReceiver() {
            // private static final String TAG = "Alarm Example Receiver";
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show();
            }
        };

        registerReceiver(mReceiver, new IntentFilter("sample"));
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0);
        alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE));
    }

    private void UnregisterAlarmBroadcast() {
        alarmManager.cancel(pendingIntent); 
        getBaseContext().unregisterReceiver(mReceiver);
    }
}

If you need alarm only for a single time then replace

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent);

with

 alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent );

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

Calculating average of an array list?

Use a double for the sum, otherwise you are doing an integer division and you won't get any decimals:

private double calculateAverage(List <Integer> marks) {
    if (marks == null || marks.isEmpty()) {
        return 0;
    }

    double sum = 0;
    for (Integer mark : marks) {
        sum += mark;
    }

    return sum / marks.size();
}

or using the Java 8 stream API:

    return marks.stream().mapToInt(i -> i).average().orElse(0);

Configure hibernate to connect to database via JNDI Datasource

I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.

The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.

C++ error: "Array must be initialized with a brace enclosed initializer"

The syntax to statically initialize an array uses curly braces, like this:

int array[10] = { 0 };

This will zero-initialize the array.

For multi-dimensional arrays, you need nested curly braces, like this:

int cipher[Array_size][Array_size]= { { 0 } };

Note that Array_size must be a compile-time constant for this to work. If Array_size is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector).

Jenkins: Is there any way to cleanup Jenkins workspace?

Workspace Cleanup Plugin

In Jenkins file add

cleanWs()

This will delete the workspace after the build is complete

How can I change column types in Spark SQL's DataFrame?

You can use selectExpr to make it a little cleaner:

df.selectExpr("cast(year as int) as year", "upper(make) as make",
    "model", "comment", "blank")

Simulating Slow Internet Connection

On Linux machines u can use wondershaper

apt-get install wondershaper

$ sudo wondershaper {interface} {down} {up}

the {down} and {up} are bandwidth in kpbs

So for example if you want to limit the bandwidth of interface eth1 to 256kbps uplink and 128kbps downlink,

$ sudo wondershaper eth1 256 128

To clear the limit,

$ sudo wondershaper clear eth1 

Get Path from another app (WhatsApp)

You can also convert the URI to file and then to bytes if you want to upload the photo to your server.

Check out : https://www.stackoverflow.com/a/49575321

How to create <input type=“text”/> dynamically

The core idea of the solution is:

  • create a new input element
  • Add the type text
  • append the element to the DOM

This can be done via this simple script:

var input = document.createElement('input');
input.setAttribute('type', 'text');
document.getElementById('parent').appendChild(input);

Now the question is, how to render this process dynamic. As stated in the question, there is another input where the user insert the number of input to generate. This can be done as follows:

_x000D_
_x000D_
function renderInputs(el){
  var n = el.value && parseInt(el.value, 10);
  if(isNaN(n)){
    return;
  }
  
  var input;
  var parent = document.getElementById("parent");
  
  cleanDiv(parent);
  for(var i=0; i<n; i++){
    input = document.createElement('input');
    input.setAttribute('type', 'text');
    parent.appendChild(input);
  }
}

function cleanDiv(div){
  div.innerHTML = '';
}
_x000D_
Insert number of input to generate: </br>
<input type="text" onchange="renderInputs(this)"/>

<div id="parent">
Generated inputs:
</div>
_x000D_
_x000D_
_x000D_

but usually adding just an input is not really usefull, it would be better to add a name to the input, so that it can be easily sent as a form. This snippet add also a name:

_x000D_
_x000D_
function renderInputs(el){
  var n = el.value;
  var input, label;
  var parent = document.getElementById("parent");
  cleanDiv(parent);
  
  el.value.split(',').forEach(function(name){
    input = document.createElement('input');
    input.setAttribute('type', 'text');
    input.setAttribute('name', name);
    label = document.createElement('label');
    label.setAttribute('for', name);
    label.innerText = name;
    parent.appendChild(label);
    parent.appendChild(input);
    parent.appendChild(document.createElement('br'));
  });
}

function cleanDiv(div){
  div.innerHTML = '';
}
_x000D_
Insert the names, separated by comma, of the inputs to generate: </br>
<input type="text" onchange="renderInputs(this)"/>
<br>
Generated inputs: </br>
<div id="parent">

</div>
_x000D_
_x000D_
_x000D_

How to dynamically create a class?

I know i reopen this old task but with c# 4.0 this task is absolutely painless.

dynamic expando = new ExpandoObject();
expando.EmployeeID=42;
expando.Designation="unknown";
expando.EmployeeName="curt"

//or more dynamic
AddProperty(expando, "Language", "English");

for more see https://www.oreilly.com/learning/building-c-objects-dynamically

vi/vim editor, copy a block (not usual action)

Another option which may be easier to remember would be to place marks on the two lines with ma and mb, then run :'a,'byank.

Many different ways to accomplish this task, just offering another.

How to enter newline character in Oracle?

begin   
   dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
end;

accepting HTTPS connections with self-signed certificates

The first thing you need to do is to set the level of verification. Such levels is not so much:

  • ALLOW_ALL_HOSTNAME_VERIFIER
  • BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
  • STRICT_HOSTNAME_VERIFIER

Although the method setHostnameVerifier() is obsolete for new library apache, but for version in Android SDK is normal. And so we take ALLOW_ALL_HOSTNAME_VERIFIER and set it in the method factory SSLSocketFactory.setHostnameVerifier().

Next, You need set our factory for the protocol to https. To do this, simply call the SchemeRegistry.register() method.

Then you need to create a DefaultHttpClient with SingleClientConnManager. Also in the code below you can see that on default will also use our flag (ALLOW_ALL_HOSTNAME_VERIFIER) by the method HttpsURLConnection.setDefaultHostnameVerifier()

Below code works for me:

HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier     
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

// Example send http request
final String url = "https://encrypted.google.com/";
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);

Identifying and removing null characters in UNIX

Use the following sed command for removing the null characters in a file.

sed -i 's/\x0//g' null.txt

this solution edits the file in place, important if the file is still being used. passing -i'ext' creates a backup of the original file with 'ext' suffix added.

nodemon not working: -bash: nodemon: command not found

If you want to run it locally instead of globally, you can run it from your node_modules:

npx nodemon

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Overriding the input directive does seem to do the job. I made some minor alterations to Dan Hunsaker's code:

  • Added a check for ngModel before trying to use $parse().assign() on fields without a ngModel attributes.
  • Corrected the assign() function param order.
app.directive('input', function ($parse) {
  return {
    restrict: 'E',
    require: '?ngModel',
    link: function (scope, element, attrs) {
      if (attrs.ngModel && attrs.value) {
        $parse(attrs.ngModel).assign(scope, attrs.value);
      }
    }
  };
});

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

Adjusting and image Size to fit a div (bootstrap)

Simply add the class img-responsive to your img tag, it is applicable in bootstrap 3 onward!

What to do with commit made in a detached head

This is what I did:

Basically, think of the detached HEAD as a new branch, without name. You can commit into this branch just like any other branch. Once you are done committing, you want to push it to the remote.

So the first thing you need to do is give this detached HEAD a name. You can easily do it like, while being on this detached HEAD:

git checkout -b some-new-branch

Now you can push it to remote like any other branch.

In my case, I also wanted to fast-forward this branch to master along with the commits I made in the detached HEAD (now some-new-branch). All I did was

git checkout master

git pull # To make sure my local copy of master is up to date

git checkout some-new-branch

git merge master // This added current state of master to my changes

Of course, I merged it later to master.

That's about it.

Multiple submit buttons in the same form calling different Servlets

In addition to the previous response, the best option to submit a form with different buttons without language problems is actually using a button tag.

<form>
    ...
    <button type="submit" name="submit" value="servlet1">Go to 1st Servlet</button>
    <button type="submit" name="submit" value="servlet2">Go to 2nd Servlet</button>
</form>

Sort ObservableCollection<string> through C#

This is an ObservableCollection<T>, that automatically sorts itself upon a change, triggers a sort only when necessary, and only triggers a single move collection change action.

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

namespace ConsoleApp4
{
  using static Console;

  public class SortableObservableCollection<T> : ObservableCollection<T>
  {
    public Func<T, object> SortingSelector { get; set; }
    public bool Descending { get; set; }
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
      base.OnCollectionChanged(e);
      if (SortingSelector == null 
          || e.Action == NotifyCollectionChangedAction.Remove
          || e.Action == NotifyCollectionChangedAction.Reset)
        return;

      var query = this
        .Select((item, index) => (Item: item, Index: index));
      query = Descending
        ? query.OrderBy(tuple => SortingSelector(tuple.Item))
        : query.OrderByDescending(tuple => SortingSelector(tuple.Item));

      var map = query.Select((tuple, index) => (OldIndex:tuple.Index, NewIndex:index))
       .Where(o => o.OldIndex != o.NewIndex);

      using (var enumerator = map.GetEnumerator())
       if (enumerator.MoveNext())
          Move(enumerator.Current.OldIndex, enumerator.Current.NewIndex);


    }
  }


  //USAGE
  class Program
  {
    static void Main(string[] args)
    {
      var xx = new SortableObservableCollection<int>() { SortingSelector = i => i };
      xx.CollectionChanged += (sender, e) =>
       WriteLine($"action: {e.Action}, oldIndex:{e.OldStartingIndex},"
         + " newIndex:{e.NewStartingIndex}, newValue: {xx[e.NewStartingIndex]}");

      xx.Add(10);
      xx.Add(8);
      xx.Add(45);
      xx.Add(0);
      xx.Add(100);
      xx.Add(-800);
      xx.Add(4857);
      xx.Add(-1);

      foreach (var item in xx)
        Write($"{item}, ");
    }
  }
}

Output:

action: Add, oldIndex:-1, newIndex:0, newValue: 10
action: Add, oldIndex:-1, newIndex:1, newValue: 8
action: Move, oldIndex:1, newIndex:0, newValue: 8
action: Add, oldIndex:-1, newIndex:2, newValue: 45
action: Add, oldIndex:-1, newIndex:3, newValue: 0
action: Move, oldIndex:3, newIndex:0, newValue: 0
action: Add, oldIndex:-1, newIndex:4, newValue: 100
action: Add, oldIndex:-1, newIndex:5, newValue: -800
action: Move, oldIndex:5, newIndex:0, newValue: -800
action: Add, oldIndex:-1, newIndex:6, newValue: 4857
action: Add, oldIndex:-1, newIndex:7, newValue: -1
action: Move, oldIndex:7, newIndex:1, newValue: -1
-800, -1, 0, 8, 10, 45, 100, 4857,

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

jQuery get mouse position within an element

This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):

function getXY(evt) {
    var element = document.getElementById('elementId');  //replace elementId with your element's Id.
    var rect = element.getBoundingClientRect();
    var scrollTop = document.documentElement.scrollTop?
                    document.documentElement.scrollTop:document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft?                   
                    document.documentElement.scrollLeft:document.body.scrollLeft;
    var elementLeft = rect.left+scrollLeft;  
    var elementTop = rect.top+scrollTop;

        if (document.all){ //detects using IE   
            x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
            y = event.clientY+scrollTop-elementTop;
        }
        else{
            x = evt.pageX-elementLeft;
            y = evt.pageY-elementTop;
    }

Output single character in C

As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.

What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.

Using printf is like using a machine gun to fire one bullet.

how can I enable scrollbars on the WPF Datagrid?

Put the DataGrid in a Grid, DockPanel, ContentControl or directly in the Window. A vertically-oriented StackPanel will give its children whatever vertical space they ask for - even if that means it is rendered out of view.

Hibernate table not mapped error in HQL query

In the Spring configuration typo applicationContext.xml where the sessionFactory configured put this property

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="packagesToScan" value="${package.name}"/>

MySQL: update a field only if condition is met

Another solution which, in my opinion, is easier to read would be:

UPDATE test 
    SET something = 1, field = IF(condition is true, 1, field) 
    WHERE id = 123

What this does is set 'field' to 1 (like OP used as example) if the condition is met and use the current value of 'field' if not met. Using the previous value is the same as not changing, so there you go.

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Check free disk space for current partition in bash

A complete example for someone who may want to use this to monitor a mount point on a server. This example will check if /var/spool is under 5G and email the person :

  #!/bin/bash
  # -----------------------------------------------------------------------------------------
  # SUMMARY: Check if MOUNT is under certain quota, mail us if this is the case
  # DETAILS: If under 5G we have it alert us via email. blah blah  
  # -----------------------------------------------------------------------------------------
  # CRON: 0 0,4,8,12,16 * * * /var/www/httpd-config/server_scripts/clear_root_spool_log.bash

  MOUNTP=/var/spool  # mount drive to check
  LIMITSIZE=5485760 # 5G = 10*1024*1024k   # limit size in GB   (FLOOR QUOTA)
  FREE=$(df -k --output=avail "$MOUNTP" | tail -n1) # df -k not df -h
  LOG=/tmp/log-$(basename ${0}).log
  MAILCMD=mail
  EMAILIDS="[email protected]"
  MAILMESSAGE=/tmp/tmp-$(basename ${0})

  # -----------------------------------------------------------------------------------------

  function email_on_failure(){

          sMess="$1"
          echo "" >$MAILMESSAGE
          echo "Hostname: $(hostname)" >>$MAILMESSAGE
          echo "Date & Time: $(date)" >>$MAILMESSAGE

          # Email letter formation here:
          echo -e "\n[ $(date +%Y%m%d_%H%M%S%Z) ] Current Status:\n\n" >>$MAILMESSAGE
          cat $sMess >>$MAILMESSAGE

          echo "" >>$MAILMESSAGE
          echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE
          echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE

          # sending email (need to have an email client set up or sendmail)
          $MAILCMD -s "Urgent MAIL Alert For $(hostname) AWS Server" "$EMAILIDS" < $MAILMESSAGE

          [[ -f $MAILMESSAGE ]] && rm -f $MAILMESSAGE

  }

  # -----------------------------------------------------------------------------------------

  if [[ $FREE -lt $LIMITSIZE ]]; then
          echo "Writing to $LOG"
          echo "MAIL ERROR: Less than $((($FREE/1000))) MB free (QUOTA) on $MOUNTP!" | tee ${LOG}
          echo -e "\nPotential Files To Delete:" | tee -a ${LOG}
          find $MOUNTP -xdev -type f -size +500M -exec du -sh {} ';' | sort -rh | head -n20 | tee -a ${LOG}
          email_on_failure ${LOG}
  else
          echo "Currently $(((($FREE-$LIMITSIZE)/1000))) MB of QUOTA available of on $MOUNTP. "
  fi

how to download image from any web page in java

This works for me:

URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg");
InputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream("Image-Porkeri_001.jpg"));

for ( int i; (i = in.read()) != -1; ) {
    out.write(i);
}
in.close();
out.close();

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

Using jQuery UI in combination with the excellent datetimepicker plugin from http://trentrichardson.com/examples/timepicker/

You can specify the dateFormat and timeFormat

$('#datepicker').datetimepicker({
    dateFormat: "yy-mm-dd",
    timeFormat:  "hh:mm:ss"
});

How to include external Python code to use in other files?

I've found the python inspect module to be very useful

For example with teststuff.py

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":

    dostuff()

And from the another script or the python console

import teststuff

exec(DOSTUFF_SOURCE)

dostuff()

And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

I also read the Spring docs, as lapkritinis suggested - and luckily this brought me on the right path! But I don´t think, that the Spring docs explain this good right now. At least for me, they aren´t consistent IMHO.

The original problem/question is on what to do, if you upgrade an existing Spring Boot 1.5.x application to 2.0.x, which is using PostgreSQL/Hibernate. The main reason, you get your described error, is that Spring Boot 2.0.x uses HikariCP instead of Tomcat JDBC pooling DataSource as a default - and Hikari´s DataSource doesn´t know the spring.datasource.url property, instead it want´s to have spring.datasource.jdbc-url (lapkritinis also pointed that out).

So far so good. BUT the docs also suggest - and that´s the problem here - that Spring Boot uses spring.datasource.url to determine, if the - often locally used - embedded Database like H2 has to back off and instead use a production Database:

You should at least specify the URL by setting the spring.datasource.url property. Otherwise, Spring Boot tries to auto-configure an embedded database.

You may see the dilemma. If you want to have your embedded DataBase like you´re used to, you have to switch back to Tomcat JDBC. This is also much more minimally invasive to existing applications, as you don´t have to change source code! To get your existing application working after the Spring Boot 1.5.x --> 2.0.x upgrade with PostgreSQL, just add tomcat-jdbc as a dependency to your pom.xml:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jdbc</artifactId>
    </dependency>

And then configure Spring Boot to use it accordingly inside application.properties:

spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

Hope to help some folks with this, was quite a time consuming problem. I also hope my beloved Spring folks update the docs - and the way new Hikari pool is configured - to get a more consistent Spring Boot user experience :)

Python MySQLdb TypeError: not all arguments converted during string formatting

Instead of this:

cur.execute( "SELECT * FROM records WHERE email LIKE '%s'", search )

Try this:

cur.execute( "SELECT * FROM records WHERE email LIKE %s", [search] )

See the MySQLdb documentation. The reasoning is that execute's second parameter represents a list of the objects to be converted, because you could have an arbitrary number of objects in a parameterized query. In this case, you have only one, but it still needs to be an iterable (a tuple instead of a list would also be fine).

How to delete a localStorage item when the browser window/tab is closed?

You can simply use sessionStorage. Because sessionStorage allow to clear all key value when browser window will be closed .

See there : SessionStorage- MDN

How to play ringtone/alarm sound in Android

For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri() instead of RingtoneManager.getDefaultUri(). According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri():

Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.

Meanwhile getDefaultUri() says this:

Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.

How do I compare two columns for equality in SQL Server?

A solution avoiding CASE WHEN is to use COALESCE.

SELECT
    t1.Col2 AS t1Col2,
    t2.Col2 AS t2Col2,
    COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)) as NULL_IF_SAME
 FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID

NULL_IF_SAME column will give NULL for all rows where t1.col2 = t2.col2 (including NULL). Though this is not more readable than CASE WHEN expression, it is ANSI SQL.

Just for the sake of fun, if one wants to have boolean bit values of 0 and 1 (though it is not very readable, hence not recommended), one can use (which works for all datatypes):

1/ISNULL(LEN(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+2,1) as BOOL_BIT_SAME.

Now if you have one of the numeric data types and want bits, in the above LEN function converts to string first which may be problematic,so instead this should work:

1/(CAST(ISNULL(ABS(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+1,0)as bit)+1) as FAST_BOOL_BIT_SAME_NUMERIC

Above will work for Integers without CAST.

NOTE: also in SQLServer 2012, we have IIF function.

How to Use -confirm in PowerShell

Here's a solution I've used, similiar to Ansgar Wiechers' solution;

$title = "Lorem"
$message = "Ipsum"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "This means Yes"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "This means No"

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $Options, 0)

Switch ($result)
     {
          0 { "You just said Yes" }
          1 { "You just said No" }
     }

Importing PNG files into Numpy?

Using a (very) commonly used package is prefered:

import matplotlib.pyplot as plt
im = plt.imread('image.png')

Capitalize only first character of string and leave others alone? (Rails)

Most of these answers edit the string in place, when you are just formatting for view output you may not want to be changing the underlying string so you can use tap after a dup to get an edited copy

'test'.dup.tap { |string| string[0] = string[0].upcase }

Copy data into another table

Try this:

Insert Into table2
Select * from table1

Get screen width and height in Android

As an android official document said for the default display use Context#getDisplay() because this method was deprecated in API level 30.

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

This bowl of code help to determine width and height.

public static int getWidth(Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    Display display = context.getDisplay();
    if (display != null) {
        display.getRealMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
    return -1;
}

For the Height:

public static int getHeight(Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    Display display = context.getDisplay();
    if (display != null) {
        display.getRealMetrics(displayMetrics);
        return displayMetrics.heightPixels;
    }
    return -1;
}

how to check if a file is a directory or regular file in python?

Many of the Python directory functions are in the os.path module.

import os
os.path.isdir(d)

Converting bool to text in C++

I use a ternary in a printf like this:

printf("%s\n", b?"true":"false");

If you macro it :

B2S(b) ((b)?"true":"false")

then you need to make sure whatever you pass in as 'b' doesn't have any side effects. And don't forget the brackets around the 'b' as you could get compile errors.

C# How to change font of a label

You need to create a new Font

mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);

Apache SSL Configuration Error (SSL Connection Error)

I had the same problem as @User39604, and had to follow VARIOUS advices. Since he doesnt remember the precise path he followed, let me list my path:

  1. check if you have SSL YES using <?php echo phpinfo();?>

  2. if necessary

    A. enable ssl on apache sudo a2enmod ssl

    B. install openssl sudo apt-get install openssl

    C. check if port 443 is open sudo netstat -lp

    D. if necessary, change /etc/apache2/ports.conf, this works

    NameVirtualHost *:80
    Listen 80
    
    <IfModule mod_ssl.c>
        # If you add NameVirtualHost *:443 here, you will also have to change
        # the VirtualHost statement in /etc/apache2/sites-available/default-ssl
        # to <VirtualHost *:443>
        # Server Name Indication for SSL named virtual hosts is currently not
        # supported by MSIE on Windows XP.
        NameVirtualHost *:443
        Listen 443
    </IfModule>
    
    <IfModule mod_gnutls.c>
        Listen 443
    </IfModule>
    
  3. acquire a key and a certificate by

    A. paying a Certificating Authority (Comodo, GoDaddy, Verisign) for a pair

    B. generating your own* - see below (testing purposes ONLY)

  4. change your configuration (in ubuntu12 /etc/apache2/httpd.conf - default is an empty file) to include a proper <VirtualHost> (replace MYSITE.COM as well as key and cert path/name to point to your certificate and key):

    <VirtualHost _default_:443> 
    ServerName MYSITE.COM:443
    SSLEngine on
    SSLCertificateKeyFile /etc/apache2/ssl/MYSITE.COM.key
    SSLCertificateFile /etc/apache2/ssl/MYSITE.COM.cert
    ServerAdmin MYWEBGUY@localhost
    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>
    
    
    ErrorLog ${APACHE_LOG_DIR}/errorSSL.log
    
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
    
    CustomLog ${APACHE_LOG_DIR}/accessSSL.log combined
    
    </VirtualHost>
    

while many other virtualhost configs wil be available in /etc/apache2/sites-enabled/ and in /etc/apache2/sites-available/ it was /etc/apache2/httpd.conf that was CRUCIAL to solving all problems.

for further info:

http://wiki.vpslink.com/Enable_SSL_on_Apache2

http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#selfcert

*generating your own certificate (self-signed) will result in a certificate whose authority the user's browser will not recognize. therefore, the browser will scream bloody murder and the user will have to "understand the risks" a dozen times before the browser actually opens up the page. so, it only works for testing purposes. having said that, this is the HOW-TO:

  1. goto the apache folder (in ubuntu12 /etc/apache2/)
  2. create a folder like ssl (or anything that works for you, the name is not a system requirement)
  3. goto chosen directory /etc/apache2/ssl
  4. run sudo openssl req -new -x509 -nodes -out MYSITE.COM.crt -keyout MYSITE.COM.key
  5. use MYSITE.COM.crt and MYSITE.COM.key in your <VirtualHost> tag

name format is NOT under a strict system requirement, must be the same as the file :) - names like 212-MYSITE.COM.crt, june2014-Godaddy-MYSITE.COM.crt should work.

Excel tab sheet names vs. Visual Basic sheet names

Using the sheet codename was the answer I needed too to stop a series of macros falling over - ccampj's answer above mirrors this solution (with screen pics)

SSIS Connection not found in package

For package developed in Visual Studio 2015, I found i must supply a value for the parameter (which would be the case when you deploy or run on different server) which sets the connection manager's connection string instead of using the design time value. This will suppress the error message. I think this could be a bug.

dtexec /project c:\mypath\ETL.ispac /package mypackage.dtsx /SET \Package.Variables[$Project::myParameterName];"myValueForTheParameter"

I tested this without or without parameterize the connection string, which is at the project level. The result was the same: i.e. I have to set the value for the parameter even thought it was not used.

How to figure out the SMTP server host?

Quick example:

On Ubuntu, if you are interested, for instance, in Gmail then open the Terminal and type:

nslookup -q=mx gmail.com

Browser: Identifier X has already been declared

I had a very close issue but in my case, it was Identifier 'e' has already been declared.

In my case caused because of using try {} catch (e) { var e = ... } where letter e is generated via minifier (uglifier).

So better solution could be use catch(ex){} (ex as an Excemption)

Hope somebody who searched with the similar question could find this question helpful.

What is the difference between '@' and '=' in directive scope in AngularJS?

If you would like to see more how this work with a live example. http://jsfiddle.net/juanmendez/k6chmnch/

var app = angular.module('app', []);
app.controller("myController", function ($scope) {
    $scope.title = "binding";
});
app.directive("jmFind", function () {
    return {
        replace: true,
        restrict: 'C',
        transclude: true,
        scope: {
            title1: "=",
            title2: "@"
        },
        template: "<div><p>{{title1}} {{title2}}</p></div>"
    };
});

ReadFile in Base64 Nodejs

I think that the following example demonstrates what you need:http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html

The essence of the article is this code part:

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

// function to create file from base64 encoded string
function base64_decode(base64str, file) {
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
    var bitmap = new Buffer(base64str, 'base64');
    // write buffer to file
    fs.writeFileSync(file, bitmap);
    console.log('******** File created from base64 encoded string ********');
}

// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg');

How to convert enum names to string in c

A function like that without validating the enum is a trifle dangerous. I suggest using a switch statement. Another advantage is that this can be used for enums that have defined values, for example for flags where the values are 1,2,4,8,16 etc.

Also put all your enum strings together in one array:-

static const char * allEnums[] = {
    "Undefined",
    "apple",
    "orange"
    /* etc */
};

define the indices in a header file:-

#define ID_undefined       0
#define ID_fruit_apple     1
#define ID_fruit_orange    2
/* etc */

Doing this makes it easier to produce different versions, for example if you want to make international versions of your program with other languages.

Using a macro, also in the header file:-

#define CASE(type,val) case val: index = ID_##type##_##val; break;

Make a function with a switch statement, this should return a const char * because the strings static consts:-

const char * FruitString(enum fruit e){

    unsigned int index;

    switch(e){
        CASE(fruit, apple)
        CASE(fruit, orange)
        CASE(fruit, banana)
        /* etc */
        default: index = ID_undefined;
    }
    return allEnums[index];
}

If programming with Windows then the ID_ values can be resource values.

(If using C++ then all the functions can have the same name.

string EnumToString(fruit e);

)

Align text in JLabel to the right

To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:

JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);     

And if you have an image:

JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);

But, I believe you want to make the label such that there are only 2 words on 1 line.

In that case try this:

String urText="<html>You can<br>use basic HTML<br>in Swing<br> components," 
   +"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);

System.MissingMethodException: Method not found?

I had a test project that references 2 other projects that each referenced different versions (in different locations) of the same dll. This confused the compiler.

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

How to check whether a file is empty or not?

An important gotcha: a compressed empty file will appear to be non-zero when tested with getsize() or stat() functions:

$ python
>>> import os
>>> os.path.getsize('empty-file.txt.gz')
35
>>> os.stat("empty-file.txt.gz").st_size == 0
False

$ gzip -cd empty-file.txt.gz | wc
0 0 0

So you should check whether the file to be tested is compressed (e.g. examine the filename suffix) and if so, either bail or uncompress it to a temporary location, test the uncompressed file, and then delete it when done.

How should I multiple insert multiple records?

static void InsertSettings(IEnumerable<Entry> settings) {
    using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
        oConnection.Open();
        using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
            using (SqlCommand oCommand = oConnection.CreateCommand()) {
                oCommand.Transaction = oTransaction;
                oCommand.CommandType = CommandType.Text;
                oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
                oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
                oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
                try {
                    foreach (var oSetting in settings) {
                        oCommand.Parameters[0].Value = oSetting.Key;
                        oCommand.Parameters[1].Value = oSetting.Value;
                        if (oCommand.ExecuteNonQuery() != 1) {
                            //'handled as needed, 
                            //' but this snippet will throw an exception to force a rollback
                            throw new InvalidProgramException();
                        }
                    }
                    oTransaction.Commit();
                } catch (Exception) {
                    oTransaction.Rollback();
                    throw;
                }
            }
        }
    }
}

ArrayList of int array in java

More simple than that.

List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));

arrayIntegers.get(1);

In the first line you create the object and in the constructor you pass an array parameter to List.

In the second line you have all the methods of the List class: .get (...)

Ruby on Rails: How do I add placeholder text to a f.text_field?

In your view template, set a default value:

f.text_field :password, :value => "password"

In your Javascript (assuming jquery here):

$(document).ready(function() {
  //add a handler to remove the text
});

error_log per Virtual Host?

php_value error_log "/var/log/httpd/vhost_php_error_log"

It works for me, but I have to change the permission of the log file.

or Apache will write the log to the its error_log.

To the power of in C?

For another approach, note that all the standard library functions work with floating point types. You can implement an integer type function like this:

unsigned power(unsigned base, unsigned degree)
{
    unsigned result = 1;
    unsigned term = base;
    while (degree)
    {
        if (degree & 1)
            result *= term;
        term *= term;
        degree = degree >> 1;
    }
    return result;
}

This effectively does repeated multiples, but cuts down on that a bit by using the bit representation. For low integer powers this is quite effective.

What is a "web service" in plain English?

In over simplified terms a web service is something that provides data as a service over the http protocol. Granted that isn't alway the case....but it is close.

Standard Web Services use The SOAP protocol which defines the communication and structure of messages, and XML is the data format.

Web services are designed to allow applications built using different technologies to communicate with each other without issues.

Examples of web services are things like Weather.com providing weather information for that you can use on your site, or UPS providing a method to request shipping quotes or tracking of packages.

Edit

Changed wording in reference to SOAP, as it is not always SOAP as I mentioned, but wanted to make it more clear. The key is providing data as a service, not a UI element.

HTML character codes for this ? or this ?

The Big and small black triangles facing the 4 directions can be represented thus:

&#x25B2;

&#x25B4;

&#x25B6;

&#x25B8;

&#x25BA;

&#x25BC;

&#x25BE;

&#x25C0;

&#x25C2;

&#x25C4;

C# naming convention for constants?

The ALL_CAPS is taken from the C and C++ way of working I believe. This article here explains how the style differences came about.

In the new IDE's such as Visual Studio it is easy to identify the types, scope and if they are constant so it is not strictly necessary.

The FxCop and Microsoft StyleCop software will help give you guidelines and check your code so everyone works the same way.

how do you filter pandas dataframes by multiple columns

In case somebody wonders what is the faster way to filter (the accepted answer or the one from @redreamality):

import pandas as pd
import numpy as np

length = 100_000
df = pd.DataFrame()
df['Year'] = np.random.randint(1950, 2019, size=length)
df['Gender'] = np.random.choice(['Male', 'Female'], length)

%timeit df.query('Gender=="Male" & Year=="2014" ')
%timeit df[(df['Gender']=='Male') & (df['Year']==2014)]

Results for 100,000 rows:

6.67 ms ± 557 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.54 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Results for 10,000,000 rows:

326 ms ± 6.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
472 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So results depend on the size and the data. On my laptop, query() gets faster after 500k rows. Further, the string search in Year=="2014" has an unnecessary overhead (Year==2014 is faster).

Using Javascript in CSS

IE supports CSS expressions:

width:expression(document.body.clientWidth > 955 ? "955px": "100%" );

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

Use a default form value to avoid the error.

Instead of using the accepted answer of applying detectChanges() in ngAfterViewInit() (which also solved the error in my case), I decided instead to save a default value for a dynamically required form field, so that when the form is later updated, it's validity is not changed if the user decides to change an option on the form that would trigger the new required fields (and cause the submit button to be disabled).

This saved a tiny bit of code in my component, and in my case the error was avoided altogether.

How to add a spinner icon to button when it's in the Loading state?

To make the solution by @flion look really great, you could adjust the center point for that icon so it doesn't wobble up and down. This looks right for me at a small font size:

.glyphicon-refresh.spinning {
  transform-origin: 48% 50%;
}

HTML for the Pause symbol in audio and video control

If you want one that's a single character to match the right-facing triangle for "play," try Roman numeral 2. ? is &#8545; in HTML. If you can put formatting tags around it, it looks really good in bold. ? is <b>&#8545;</b> in HTML. This has much better support than the previously mentioned double vertical bar.

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.

PHP UML Generator

Well to be honest, first and foremost you shouldn't generate UML model from code, but code from UML model ;).

Even if you are in a rare situation, when you need to do this reverse engineering, it is generally suggested that you do it by hand or at least tidy-up the diagrams, as auto-generated UML has really poor visual (=information) value most of the time.

If you just need to generate the diagrams, it's probably a good thing to ask yourself why exactly? Who is the intended audience and what is the goal? What does the auto-generated diagram have to offer, what code doesn't?

Basicly I accept only one answer to that question. It just got too big and incomprehensible.

Which again is a reason to start with UML in the first place, as opposed to start coding ;) It's called analysis and it's on decline, because every second guy in business thinks it's a bit too expensive and not really necessary.

How do I list / export private keys from a keystore?

Here is a shorter version of the above code, in Groovy. Also has built-in base64 encoding:

import java.security.Key
import java.security.KeyStore

if (args.length < 3)
        throw new IllegalArgumentException('Expected args: <Keystore file> <Keystore format> <Keystore password> <alias> <key password>')

def keystoreName = args[0]
def keystoreFormat = args[1]
def keystorePassword = args[2]
def alias = args[3]
def keyPassword = args[4]

def keystore = KeyStore.getInstance(keystoreFormat)
keystore.load(new FileInputStream(keystoreName), keystorePassword.toCharArray())
def key = keystore.getKey(alias, keyPassword.toCharArray())

println "-----BEGIN PRIVATE KEY-----"
println key.getEncoded().encodeBase64()
println "-----END PRIVATE KEY-----"

How to change collation of database, table, column?

Better variant to generate SQL script by SQL request. It will not ruin defaults/nulls.

SELECT concat
    (
        'ALTER TABLE ', 
            t1.TABLE_SCHEMA, 
            '.', 
            t1.table_name, 
            ' MODIFY ', 
            t1.column_name, 
            ' ', 
            t1.column_type,
            ' CHARACTER SET utf8 COLLATE utf8_general_ci',
            if(t1.is_nullable='YES', ' NULL', ' NOT NULL'),
            if(t1.column_default is not null, concat(' DEFAULT \'', t1.column_default, '\''), ''),
            ';'
    )
from 
    information_schema.columns t1
where 
    t1.TABLE_SCHEMA like 'your_table_here' AND
    t1.COLLATION_NAME IS NOT NULL AND
    t1.COLLATION_NAME NOT IN ('utf8_general_ci');

How to spyOn a value property (rather than a method) with Jasmine

You can not mock variable but you can create getter function for it and mock that method in your spec file.

Dynamically create Bootstrap alerts box through JavaScript

just recap:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
_x000D_
    $('button').on( "click", function() {_x000D_
_x000D_
      showAlert( "OK", "alert-success" );_x000D_
_x000D_
    } );_x000D_
_x000D_
});_x000D_
_x000D_
function showAlert( message, alerttype ) {_x000D_
_x000D_
    $('#alert_placeholder').append( $('#alert_placeholder').append(_x000D_
      '<div id="alertdiv" class="alert alert-dismissible fade in ' +  alerttype + '">' +_x000D_
          '<a class="close" data-dismiss="alert" aria-label="close" >×</a>' +_x000D_
          '<span>' + message + '</span>' + _x000D_
      '</div>' )_x000D_
    );_x000D_
_x000D_
    // close it in 3 secs_x000D_
    setTimeout( function() {_x000D_
        $("#alertdiv").remove();_x000D_
    }, 3000 );_x000D_
_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />_x000D_
_x000D_
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
        _x000D_
<button onClick="" >Show Alert</button>_x000D_
      _x000D_
<div id="alert_placeholder" class="container" ></div>
_x000D_
_x000D_
_x000D_

codepen

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

Create a new class that wraps your Blog object and provides the equality/hashcode method you need. For maximum efficiency I would add two static methods on the wrapper, one to convert Blogs list -> Blog Wrapper list and the other to convert Blog Wrapper list -> Blog list. Then you would:

  1. Convert your blog list to blog wrapper list
  2. Add your blog wrapper list to a Hash Set
  3. Get the condensed blog wrapper list back out of the Hash Set
  4. Convert the blog wrapper list to a blog list

Code for Blog Wrapper would be something like this:

import java.util.ArrayList;
import java.util.List;

public class BlogWrapper {
    public static List<Blog> unwrappedList(List<BlogWrapper> blogWrapperList) {
        if (blogWrapperList == null)
            return new ArrayList<Blog>(0);

        List<Blog> blogList = new ArrayList<Blog>(blogWrapperList.size());
        for (BlogWrapper bW : blogWrapperList) {
            blogList.add(bW.getBlog());
        }

        return blogList;
    }

    public static List<BlogWrapper> wrappedList(List<Blog> blogList) {
        if (blogList == null)
            return new ArrayList<BlogWrapper>(0);

        List<BlogWrapper> blogWrapperList = new ArrayList<BlogWrapper>(blogList
                .size());
        for (Blog b : blogList) {
            blogWrapperList.add(new BlogWrapper(b));
        }

        return blogWrapperList;
    }

    private Blog blog = null;

    public BlogWrapper() {
        super();
    }

    public BlogWrapper(Blog aBlog) {
        super();
        setBlog(aBlog);
    }

    public boolean equals(Object other) {
        // Your equality logic here
        return super.equals(other);
    }

    public Blog getBlog() {
        return blog;
    }

    public int hashCode() {
        // Your hashcode logic here
        return super.hashCode();
    }

    public void setBlog(Blog blog) {
        this.blog = blog;
    }
}

And you could use this like so:

List<BlogWrapper> myBlogWrappers = BlogWrapper.wrappedList(your blog list here);
Set<BlogWrapper> noDupWrapSet = new HashSet<BlogWrapper>(myBlogWrappers);
List<BlogWrapper> noDupWrapList = new ArrayList<BlogWrapper>(noDupSet);
List<Blog> noDupList = BlogWrapper.unwrappedList(noDupWrapList);

Quite obviously you can make the above code more efficient, particularly by making the wrap and unwrap methods on Blog Wrapper take collections instead of Lists.

An alternative route to wrapping the Blog class would be to use a byte code manipulation library like BCEL to actually change the equals and hashcode method for Blog. But of course, that could have unintended consequences to the rest of your code if they require the original equals/hashcode behaviour.

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

I got mine to autoplay by making it muted. I think Google rules won't let chrome auto-play unless it's muted.

<video id="video" controls autoplay muted
        border:0px solid black;"
        width="300"
        height="300">
    <source src="~/Videos/Lumen5_CTAS_Home2.mp4"
            type="video/mp4" />
    Your browser does not support the video tag.
    Please download the mp4 plugin to see the CTAS Intro.
</video>

how to add lines to existing file using python

Use 'a', 'a' means append. Anything written to a file opened with 'a' attribute is written at the end of the file.

with open('file.txt', 'a') as file:
    file.write('input')

Laravel 5.4 Specific Table Migration

You need to put the file(s) into a new directory (ex:selected) and then apply

php artisan migrate  --path=/database/migrations/selected

if you need rollback:

php artisan migrate:rollback  --path=/database/migrations/selected

Note:

php artisan migrate:refresh

this will rollback and then migrate all the migrations files in the default directory (/database/migrations)

What exactly is nullptr?

It is a keyword because the standard will specify it as such. ;-) According to the latest public draft (n2914)

2.14.7 Pointer literals [lex.nullptr]

pointer-literal:
nullptr

The pointer literal is the keyword nullptr. It is an rvalue of type std::nullptr_t.

It's useful because it does not implicitly convert to an integral value.

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

iPhone Debugging: How to resolve 'failed to get the task for process'?

Go to Edit Schemes and under Run -> Info -> Build Configuration, change from Ad-Hoc to Debug. Click OK to save.

How to run .NET Core console app from the command line

before you run in cmd prompt, make sure "appsettings.json" has same values as "appsettings.Development.json".

In command prompt, go all the way to bin/debug/netcoreapp2.0 folder. then run "dotnet applicationname.dll"

Min width in window resizing

You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:

body{
   min-width:1000px;        /* Suppose you want minimum width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;            /* As IE6 ignores !important it will set width as 1000px; */
}

Or:

body{
   min-width:1000px; // Suppose you want minimum width of 1000px
   _width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}

Best way to check function arguments?

I did quite a bit of investigation on that topic recently since I was not satisfied with the many libraries I found out there.

I ended up developing a library to address this, it is named valid8. As explained in the documentation, it is for value validation mostly (although it comes bundled with simple type validation functions too), and you might wish to associate it with a PEP484-based type checker such as enforce or pytypes.

This is how you would perform validation with valid8 alone (and mini_lambda actually, to define the validation logic - but it is not mandatory) in your case:

# for type validation
from numbers import Integral
from valid8 import instance_of

# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len

@validate_arg('a', instance_of(Integral))
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', instance_of(str), Len(s) > 0)
def my_function(a: Integral, b, c: str):
    """an example function I'd like to check the arguments of."""
    # check that a is an int
    # check that 0 < b < 10
    # check that c is not an empty string

# check that it works
my_function(0.2, 1, 'r')  # InputValidationError for 'a' HasWrongType: Value should be an instance of <class 'numbers.Integral'>. Wrong value: [0.2].
my_function(0, 0, 'r')    # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0)      # InputValidationError for 'c' Successes: [] / Failures: {"instance_of_<class 'str'>": "HasWrongType: Value should be an instance of <class 'str'>. Wrong value: [0]", 'len(s) > 0': "TypeError: object of type 'int' has no len()"}.
my_function(0, 1, '')     # InputValidationError for 'c' Successes: ["instance_of_<class 'str'>"] / Failures: {'len(s) > 0': 'False'}

And this is the same example leveraging PEP484 type hints and delegating type checking to enforce:

# for type validation
from numbers import Integral
from enforce import runtime_validation, config
config(dict(mode='covariant'))  # type validation will accept subclasses too

# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len

@runtime_validation
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', Len(s) > 0)
def my_function(a: Integral, b, c: str):
    """an example function I'd like to check the arguments of."""
    # check that a is an int
    # check that 0 < b < 10
    # check that c is not an empty string

# check that it works
my_function(0.2, 1, 'r')  # RuntimeTypeError 'a' was not of type <class 'numbers.Integral'>
my_function(0, 0, 'r')    # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0)      # RuntimeTypeError 'c' was not of type <class 'str'>
my_function(0, 1, '')     # InputValidationError for 'c' [len(s) > 0] returned [False].

Trim spaces from end of a NSString

Taken from this answer here: https://stackoverflow.com/a/5691567/251012

- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
    NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
                                                               options:NSBackwardsSearch];
    if (rangeOfLastWantedCharacter.location == NSNotFound) {
        return @"";
    }
    return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}

how to call scalar function in sql server 2008

For Scalar Function Syntax is

Select dbo.Function_Name(parameter_name)

Select dbo.Department_Employee_Count('HR')

jQuery multiple events to trigger the same function

The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.

I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:

  • 2.0.2
  • 1.10.1
  • 1.6.4
  • Mobile 1.3.0b1
  • Mobile 1.4.2
  • Mobile 1.2.0

My workaround have been to first define the function,

function myFunction() {
    ...
}

and then handle the events individually

// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);

This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue

How to redirect output to a file and stdout

$ program [arguments...] 2>&1 | tee outfile

2>&1 dumps the stderr and stdout streams. tee outfile takes the stream it gets and writes it to the screen and to the file "outfile".

This is probably what most people are looking for. The likely situation is some program or script is working hard for a long time and producing a lot of output. The user wants to check it periodically for progress, but also wants the output written to a file.

The problem (especially when mixing stdout and stderr streams) is that there is reliance on the streams being flushed by the program. If, for example, all the writes to stdout are not flushed, but all the writes to stderr are flushed, then they'll end up out of chronological order in the output file and on the screen.

It's also bad if the program only outputs 1 or 2 lines every few minutes to report progress. In such a case, if the output was not flushed by the program, the user wouldn't even see any output on the screen for hours, because none of it would get pushed through the pipe for hours.

Update: The program unbuffer, part of the expect package, will solve the buffering problem. This will cause stdout and stderr to write to the screen and file immediately and keep them in sync when being combined and redirected to tee. E.g.:

$ unbuffer program [arguments...] 2>&1 | tee outfile

automating telnet session using bash scripts

Telnet is often used when you learn HTTP protocol. I used to use that script as a part of my web-scraper:

echo "open www.example.com 80" 
sleep 2 
echo "GET /index.html HTTP/1.1" 
echo "Host: www.example.com" 
echo 
echo 
sleep 2

let's say the name of the script is get-page.sh then:

get-page.sh | telnet

will give you a html document.

Hope it will be helpful to someone ;)

Reading a .txt file using Scanner class in Java

  1. You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
  2. The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
  3. While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.

PHP - Get bool to echo false when false

The %b option of sprintf() will convert a boolean to an integer:

echo sprintf("False will print as %b", false); //False will print as 0
echo sprintf("True will print as %b", true); //True will print as 1

If you're not familiar with it: You can give this function an arbitrary amount of parameters while the first one should be your ouput string spiced with replacement strings like %b or %s for general string replacement.

Each pattern will be replaced by the argument in order:

echo sprintf("<h1>%s</h1><p>%s<br/>%s</p>", "Neat Headline", "First Line in the paragraph", "My last words before this demo is over");

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

the below lines would also work

!python script.py

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

1.add a Data Conversion tool from toolbox
2.Open it,It shows all coloumns from excel ,convert it to desire output. take note of the Output Alias of
each applicable column (they are named Copy Of [original column name] by default)
3.now, in the Destination step, click on Mappings

How do I pause my shell script for a second before continuing?

You can make it wait using $RANDOM, a default random number generator. In the below I am using 240 seconds. Hope that helps @

> WAIT_FOR_SECONDS=`/usr/bin/expr $RANDOM % 240` /bin/sleep
> $WAIT_FOR_SECONDS

Returning http status code from Web Api controller

You can also do the following if you want to preserve the action signature as returning User:

public User GetUser(int userId, DateTime lastModifiedAtClient) 

If you want to return something other than 200 then you throw an HttpResponseException in your action and pass in the HttpResponseMessage you want to send to the client.

Setting different color for each series in scatter plot on matplotlib

An easy fix

If you have only one type of collections (e.g. scatter with no error bars) you can also change the colours after that you have plotted them, this sometimes is easier to perform.

import matplotlib.pyplot as plt
from random import randint
import numpy as np

#Let's generate some random X, Y data X = [ [frst group],[second group] ...]
X = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
Y = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
labels = range(1,len(X)+1)

fig = plt.figure()
ax = fig.add_subplot(111)
for x,y,lab in zip(X,Y,labels):
        ax.scatter(x,y,label=lab)

The only piece of code that you need:

#Now this is actually the code that you need, an easy fix your colors just cut and paste not you need ax.
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired  
colorst = [colormap(i) for i in np.linspace(0, 0.9,len(ax.collections))]       
for t,j1 in enumerate(ax.collections):
    j1.set_color(colorst[t])


ax.legend(fontsize='small')

The output gives you differnent colors even when you have many different scatter plots in the same subplot.

enter image description here

Set padding for UITextField with UITextBorderStyleNone

I found a neat little hack to set the left padding for this exact situation.

Basically, you set the leftView property of the UITextField to be an empty view of the size of the padding you want:

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;

Worked like a charm for me!

In Swift 3/ Swift 4, it can be done by doing that

let paddingView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 20))
textField.leftView = paddingView
textField.leftViewMode = .always

Oracle insert if not exists statement

insert into OPT       (email,        campaign_id) 
select 'mom@coxnet' as email, 100 as campaign_id from dual MINUS
select                 email,        campaign_id from OPT;

If there is already a record with [email protected]/100 in OPT, the MINUS will subtract this record from the select 'mom@coxnet' as email, 100 as campaign_id from dual record and nothing will be inserted. On the other hand, if there is no such record, the MINUS does not subract anything and the values mom@coxnet/100 will be inserted.

As p.marino has already pointed out, merge is probably the better (and more correct) solution for your problem as it is specifically designed to solve your task.

jQuery and TinyMCE: textarea value doesn't submit

First of all:

  1. You must include tinymce jquery plugin in your page (jquery.tinymce.min.js)

  2. One of the simplest and safest ways is to use getContent and setContent with triggerSave. Example:

    tinyMCE.get('editor_id').setContent(tinyMCE.get('editor_id').getContent()+_newdata);
    tinyMCE.triggerSave();
    

How can I export the schema of a database in PostgreSQL?

pg_dump -d <databasename> -h <hostname> -p <port> -n <schemaname> -f <location of the dump file>

Please notice that you have sufficient privilege to access that schema. If you want take backup as specific user add user name in that command preceded by -U

Parameter "stratify" from method "train_test_split" (scikit Learn)

Try running this code, it "just works":

from sklearn import cross_validation, datasets 

iris = datasets.load_iris()

X = iris.data[:,:2]
y = iris.target

x_train, x_test, y_train, y_test = cross_validation.train_test_split(X,y,train_size=.8, stratify=y)

y_test

array([0, 0, 0, 0, 2, 2, 1, 0, 1, 2, 2, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 2, 2,
       1, 2, 1, 1, 0, 2, 1])

How to know if a Fragment is Visible?

One thing to be aware of, is that isVisible() returns the visible state of the current fragment. There is a problem in the support library, where if you have nested fragments, and you hide the parent fragment (and therefore all the children), the child still says it is visible.

isVisible() is final, so can't override unfortunately. My workaround was to create a BaseFragment class that all my fragments extend, and then create a method like so:

public boolean getIsVisible()
{
    if (getParentFragment() != null && getParentFragment() instanceof BaseFragment)
    {
        return isVisible() && ((BaseFragment) getParentFragment()).getIsVisible();
    }
    else
    {
        return isVisible();
    }
}

I do isVisible() && ((BaseFragment) getParentFragment()).getIsVisible(); because we want to return false if any of the parent fragments are hidden.

This seems to do the trick for me.

What, exactly, is needed for "margin: 0 auto;" to work?

It will also work with display:table - a useful display property in this case because it doesn't require a width to be set. (I know this post is 5 years old, but it's still relevant to passers-by ;)

SQL How to replace values of select return?

You have a number of choices:

  1. Join with a domain table with TRUE, FALSE Boolean value.
  2. Use (as pointed in this answer)

    SELECT CASE WHEN hide = 0 THEN FALSE ELSE TRUE END FROM
    

    Or if Boolean is not supported:

    SELECT CASE WHEN hide = 0 THEN 'false' ELSE 'true' END FROM
    

How to check if a DateTime field is not null or empty?

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}

Spring RestTemplate GET with parameters

    String uri = http://my-rest-url.org/rest/account/{account};

    Map<String, String> uriParam = new HashMap<>();
    uriParam.put("account", "my_account");

    UriComponents builder = UriComponentsBuilder.fromHttpUrl(uri)
                .queryParam("pageSize","2")
                        .queryParam("page","0")
                        .queryParam("name","my_name").build();

    HttpEntity<String> requestEntity = new HttpEntity<>(null, getHeaders());

    ResponseEntity<String> strResponse = restTemplate.exchange(builder.toUriString(),HttpMethod.GET, requestEntity,
                        String.class,uriParam);

    //final URL: http://my-rest-url.org/rest/account/my_account?pageSize=2&page=0&name=my_name

RestTemplate: Build dynamic URI using UriComponents (URI variable and Request parameters)

Set colspan dynamically with jquery

How about

$([your selector]).attr('colspan',3);

I would imagine that to work but have no way to test at the moment. Using .attr() would be the usual jQuery way of setting attributes of elements in the wrapped set.

As has been mentioned in another answer, in order to get this to work would require removing the td elements that have no text in them from the DOM. It may be easier to do this all server side

EDIT:

As was mentioned in the comments, there is a bug in attempting to set colspan using attr() in IE, but the following works in IE6 and FireFox 3.0.13.

Working Demo

notice the use of the attribute colSpan and not colspan - the former works in both IE and Firefox, but the latter does not work in IE. Looking at jQuery 1.3.2 source, it would appear that attr() attempts to set the attribute as a property of the element if

  1. it exists as a property on the element (colSpan exists as a property and defaults to 1 on <td> HTMLElements in IE and FireFox)
  2. the document is not xml and
  3. the attribute is none of href, src or style

using colSpan as opposed to colspan works with attr() because the former is a property defined on the element whereas the latter is not.

the fall-through for attr() is to attempt to use setAttribute() on the element in question, setting the value to a string, but this causes problems in IE (bug #1070 in jQuery)

// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value ); 

In the demo, for each row, the text in each cell is evaluated. If the text is a blank string, then the cell is removed and a counter incremented. The first cell in the row that does not have class="colTime" has a colspan attribute set to the value of the counter + 1 (for the span it occupies itself).

After this, for each row, the text in the cell with class="colspans" is set to the colspan attribute values of each cell in the row from left to right.

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
td { text-align: center; }
</style>
</head>
<body>
<table  class="tblSimpleAgenda" cellpadding="5" cellspacing="0">
 <tbody>
        <tr>
            <th align="left">Time</th>
            <th align="left">Room 1</th>
            <th align="left">Room 2</th>
            <th align="left">Room 3</th> 
            <th align="left">Colspans (L -> R)</th>
        </tr>
        <tr valign="top">
            <td class="colTime">09:00 – 10:00</td>
            <td class="col1"></td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>
        </tr>

        <tr valign="top">
            <td class="colTime">10:00 – 10:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>    
             <td class="colspans">holder</td> 
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3">Meeting 3</td>
            <td class="colspans">holder</td>     
        </tr>

        <tr valign="top">
            <td class="colTime">11:00 – 11:45</td>
            <td class="col1">Meeting 1</td>
            <td class="col2">Meeting 2</td>
            <td class="col3"></td>
            <td class="colspans">holder</td>     
        </tr>
</tbody>
</table>

</body>
</html>

jQuery code

$(function() {

  $('table.tblSimpleAgenda tr').each(function() {
    var tr = this;
    var counter = 0;

    $('td', tr).each(function(index, value) {
      var td = $(this);

      if (td.text() == "") {
        counter++;
        td.remove();
      }
    });

    if (counter !== 0) {
      $('td:not(.colTime):first', tr)
        .attr('colSpan', '' + parseInt(counter + 1,10) + '');
    }
  });

  $('td.colspans').each(function(){
    var td = $(this);
    var colspans = [];

    td.siblings().each(function() {
      colspans.push(($(this).attr('colSpan')) == null ? 1 : $(this).attr('colSpan'));
    });

    td.text(colspans.join(','));
  });

});

This is just a demonstration to show that attr() can be used, but to be aware of it's implementation and the cross-browser quirks that come with it. I've also made some assumptions about your table layout in the demo (i.e. apply the colspan to the first "non-Time" cell in each row), but hopefully you get the idea.

How do I access ViewBag from JS

You can achieve the solution, by doing this:

JavaScript:

var myValue = document.getElementById("@(ViewBag.CC)").value;

or if you want to use jQuery, then:

jQuery

var myValue = $('#' + '@(ViewBag.CC)').val();

Create a new object from type parameter in generic class

Here is example if you need parameters in constructor:

class Sample {
    public innerField: string;

    constructor(data: Partial<Sample>) {
        this.innerField = data.innerField;
    }
}

export class GenericWithParams<TType> {
    public innerItem: TType;

    constructor(data: Partial<GenericWithParams<TType>>, private typePrototype: new (i: Partial<TType>) => TType) {
        this.innerItem = this.factoryMethodOnModel(data.innerItem);
    }

    private factoryMethodOnModel = (item: Partial<TType>): TType => {
        return new this.typePrototype(item);
    };
}

const instance = new GenericWithParams<Sample>({ innerItem : { innerField: 'test' }}, Sample);

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

Syntax error: Illegal return statement in JavaScript

return only makes sense inside a function. There is no function in your code.

Also, your code is worthy if the Department of Redundancy Department. Assuming you move it to a proper function, this would be better:

return confirm(".json_encode($message).");

EDIT much much later: Changed code to use json_encode to ensure the message contents don't break just because of an apostrophe in the message.

Convert categorical data in pandas dataframe

First, to convert a Categorical column to its numerical codes, you can do this easier with: dataframe['c'].cat.codes.
Further, it is possible to select automatically all columns with a certain dtype in a dataframe using select_dtypes. This way, you can apply above operation on multiple and automatically selected columns.

First making an example dataframe:

In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),  'col3':list('ababb')})

In [76]: df['col2'] = df['col2'].astype('category')

In [77]: df['col3'] = df['col3'].astype('category')

In [78]: df.dtypes
Out[78]:
col1       int64
col2    category
col3    category
dtype: object

Then by using select_dtypes to select the columns, and then applying .cat.codes on each of these columns, you can get the following result:

In [80]: cat_columns = df.select_dtypes(['category']).columns

In [81]: cat_columns
Out[81]: Index([u'col2', u'col3'], dtype='object')

In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)

In [84]: df
Out[84]:
   col1  col2  col3
0     1     0     0
1     2     1     1
2     3     2     0
3     4     0     1
4     5     1     1

What are best practices for REST nested resources?

What you have done is correct. In general there can be many URIs to the same resource - there are no rules that say you shouldn't do that.

And generally, you may need to access items directly or as a subset of something else - so your structure makes sense to me.

Just because employees are accessible under department:

company/{companyid}/department/{departmentid}/employees

Doesn't mean they can't be accessible under company too:

company/{companyid}/employees

Which would return employees for that company. It depends on what is needed by your consuming client - that is what you should be designing for.

But I would hope that all URLs handlers use the same backing code to satisfy the requests so that you aren't duplicating code.

Twitter Bootstrap 3: how to use media queries?

Here is a more modular example using LESS to mimic Bootstrap without importing the less files.

@screen-xs-max: 767px;
@screen-sm-min: 768px;
@screen-sm-max: 991px;
@screen-md-min: 992px;
@screen-md-max: 1199px;
@screen-lg-min: 1200px;

//xs only
@media(max-width: @screen-xs-max) {

}
//small and up
@media(min-width: @screen-sm-min) {

}
//sm only
@media(min-width: @screen-sm-min) and (max-width: @screen-sm-max) {

}
//md and up
@media(min-width: @screen-md-min) {

}
//md only
@media(min-width: @screen-md-min) and (max-width: @screen-md-max) {

}
//lg and up
@media(min-width: @screen-lg-min) {

}

What is the difference between HTML tags <div> and <span>?

This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.

For example:

<div>This a large main division, with <span>a small bit</span> of spanned text!</div>

Note that it is illegal to place a block-level element within an inline element, so:

<div>Some <span>text that <div>I want</div> to mark</span> up</div>

...is illegal.


EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference here for a pretty clear listing. The above is still illegal, as <span> only accepts phrasing content, and <div> is flow content.


You asked for some concrete examples, so is one taken from my bowling website, BowlSK:

_x000D_
_x000D_
<div id="header">_x000D_
  <div id="userbar">_x000D_
    Hi there, <span class="username">Chris Marasti-Georg</span> |_x000D_
    <a href="/edit-profile.html">Profile</a> |_x000D_
    <a href="https://www.bowlsk.com/_ah/logout?...">Sign out</a>_x000D_
  </div>_x000D_
  <h1><a href="/">Bowl<span class="sk">SK</span></a></h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ok, what's going on?

At the top of my page, I have a logical section, the "header". Since this is a section, I use a div (with an appropriate id). Within that, I have a couple of sections: the user bar and the actual page title. The title uses the appropriate tag, h1. The userbar, being a section, is wrapped in a div. Within that, the username is wrapped in a span, so that I can change the style. As you can see, I have also wrapped a span around 2 letters in the title - this allows me to change their color in my stylesheet.

Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc.

Section 4.4 of the HTML 5 working draft lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is "final" yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE - You need to create one of each element using document.createElement before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you - a quick Google search turned up html5shiv.

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

How to Use Order By for Multiple Columns in Laravel 4?

Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:

public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
    $result = $this->model->with($with);
    $dataSet = $result->where($where)
        // Conditionally use $orderBy if not empty
        ->when(!empty($orderBy), function ($query) use ($orderBy) {
            // Break $orderBy into pairs
            $pairs = array_chunk($orderBy, 2);
            // Iterate over the pairs
            foreach ($pairs as $pair) {
                // Use the 'splat' to turn the pair into two arguments
                $query->orderBy(...$pair);
            }
        })
        ->paginate($limit)
        ->appends(Input::except('page'));

    return $dataSet;
}

Now, you can make your call like this:

$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);

Maven dependency for Servlet 3.0 API?

I'd prefer to only add the Servlet API as dependency,

To be honest, I'm not sure to understand why but never mind...

Brabster separate dependencies have been replaced by Java EE 6 Profiles. Is there a source that confirms this assumption?

The maven repository from Java.net indeed offers the following artifact for the WebProfile:

<repositories>
  <repository>
    <id>java.net2</id>
    <name>Repository hosting the jee6 artifacts</name>
    <url>http://download.java.net/maven/2</url>
  </repository>
</repositories>        
<dependencies>
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>

This jar includes Servlet 3.0, EJB Lite 3.1, JPA 2.0, JSP 2.2, EL 1.2, JSTL 1.2, JSF 2.0, JTA 1.1, JSR-45, JSR-250.

But to my knowledge, nothing allows to say that these APIs won't be distributed separately (in java.net repository or somewhere else). For example (ok, it may a particular case), the JSF 2.0 API is available separately (in the java.net repository):

<dependency>
   <groupId>com.sun.faces</groupId>
   <artifactId>jsf-api</artifactId>
   <version>2.0.0-b10</version>
   <scope>provided</scope>
</dependency>

And actually, you could get javax.servlet-3.0.jar from there and install it in your own repository.

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

If the "Customer don't want to install and buy MS Office on a server not at any price", then you cannot use Excel ... But I cannot get the trick: it's all about one basic Office licence which costs something like 150 USD ... And I guess that spending time finding an alternative will cost by far more than this amount!

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

Pass a string parameter in an onclick function

<!----  script ---->
<script>
function myFunction(x) {
  document.getElementById("demo").style.backgroundColor = x; 
}
</script>

<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>

<!----  buttons & function call ----> 
<a  onClick="myFunction('red')" />RED</a> 
<a  onClick="myFunction('blue')" />BLUE</a> 
<a  onClick="myFunction('black')" />BLACK</a>

Django Admin - change header 'Django administration' text

There are two methods to do this:

1] By overriding base_site.html in django/contrib/admin/templates/admin/base_site.html: Following is the content of base_site.html:

{% extends "admin/base.html" %}

{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}

{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1>
{% endblock %}

{% block nav-global %}{% endblock %}

Edit the site_title & site_header in the above code snippet. This method works but it is not recommendable since its a static change.

2] By adding following lines in urls.py of project's directory:

admin.site.site_header = "AppHeader"
admin.site.site_title = "AppTitle"
admin.site.index_title = "IndexTitle"
admin.site.site_url = "Url for view site button"

This method is recommended one since we can change the site-header, site-title & index-title without editing base_site.html.

How can I change NULL to 0 when getting a single value from a SQL function?

ORACLE/PLSQL:

NVL FUNCTION

SELECT NVL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

This SQL statement would return 0 if the SUM(Price) returned a null value. Otherwise, it would return the SUM(Price) value.

Get image dimensions

<?php 
    list($width, $height) = getimagesize("http://site.com/image.png"); 
    $arr = array('h' => $height, 'w' => $width );
?>

How do I list all tables in a schema in Oracle SQL?

If you need to get the size of the table as well, this will be handy:

select SEGMENT_NAME, PARTITION_NAME, BYTES from user_segments where SEGMENT_TYPE='TABLE' order by 1

How to programmatically take a screenshot on Android?

Take screenshot of a view in android.

public static Bitmap getViewBitmap(View v) {
    v.clearFocus();
    v.setPressed(false);

    boolean willNotCache = v.willNotCacheDrawing();
    v.setWillNotCacheDrawing(false);

    int color = v.getDrawingCacheBackgroundColor();
    v.setDrawingCacheBackgroundColor(0);

    if (color != 0) {
        v.destroyDrawingCache();
    }
    v.buildDrawingCache();
    Bitmap cacheBitmap = v.getDrawingCache();
    if (cacheBitmap == null) {
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

    v.destroyDrawingCache();
    v.setWillNotCacheDrawing(willNotCache);
    v.setDrawingCacheBackgroundColor(color);

    return bitmap;
}

Pretty printing XML in Python

from lxml import etree
import xml.dom.minidom as mmd

xml_root = etree.parse(xml_fiel_path, etree.XMLParser())

def print_xml(xml_root):
    plain_xml = etree.tostring(xml_root).decode('utf-8')
    urgly_xml = ''.join(plain_xml .split())
    good_xml = mmd.parseString(urgly_xml)
    print(good_xml.toprettyxml(indent='    ',))

It's working well for the xml with Chinese!

What does the 'b' character do in front of a string literal?

In addition to what others have said, note that a single character in unicode can consist of multiple bytes.

The way unicode works is that it took the old ASCII format (7-bit code that looks like 0xxx xxxx) and added multi-bytes sequences where all bytes start with 1 (1xxx xxxx) to represent characters beyond ASCII so that Unicode would be backwards-compatible with ASCII.

>>> len('Öl')  # German word for 'oil' with 2 characters
2
>>> 'Öl'.encode('UTF-8')  # convert str to bytes 
b'\xc3\x96l'
>>> len('Öl'.encode('UTF-8'))  # 3 bytes encode 2 characters !
3

How to get child process from parent process

To get the child process and thread, pstree -p PID. It also show the hierarchical tree

PHP not displaying errors even though display_errors = On

I had the same issue and finally solved it. My mistake was that I tried to change /etc/php5/cli/php.ini, but then I found another php.ini here: /etc/php5/apache2/php.ini, changed display_errors = On, restarted the web-server and it worked!

May be it would be helpful for someone absent-minded like me.

Does Java have a complete enum for HTTP response codes?

Everyone seems to be ignoring the "enum type" portion of your question.

While there is no canonical source for HTTP Status Codes there is an simple way to add any missing Status constants you need to those provided by javax.ws.rs.core.Response.Status without adding any additional dependencies to your project.

javax.ws.rs.core.Response.Status is just one implementation of the javax.ws.rs.core.Response.StatusType interface. You simply need to create your own implementation enum with definitions for the Status Codes that you want.

Core libraries like Javax, Jersey, etc. are written to the interface StatusType not the implementation Status (or they certainly should be). Since your new Status enum implements StatusType it can be used anyplace you would use a javax.ws.rs.core.Response.Status constant.

Just remember that your own code should also be written to the StatusType interface. This will enable you to use both your own Status Codes along side the "standard" ones.

Here's a gist with a simple implementation with constants defined for the "Informational 1xx" Status Codes: https://gist.github.com/avendasora/a5ed9acf6b1ee709a14a

Change <select>'s option and trigger events with JavaScript

Fiddle of my solution is here. But just in case it expires I will paste the code as well.

HTML:

<select id="sel">
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" id="button" value="Change option to 2" />

JS:

var sel = document.getElementById('sel'),
    button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;

    // firing the event properly according to StackOverflow
    // http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually
    if ("createEvent" in document) {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent("change", false, true);
        sel.dispatchEvent(evt);
    }
    else {
        sel.fireEvent("onchange");
    }
});

sel.addEventListener('change', function (e) {
    alert('changed');
});

Tool for comparing 2 binary files in Windows

In Cygwin:

$cmp -bl <file1> <file2>

diffs binary offsets and values are in decimal and octal respectively.. Vladi.

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

Python extending with - using super() Python 3 vs Python 2

In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__. So if you don't define it in your class, you will get the one from the base.

Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__, your class will inherit the first one only.

In such cases, you should really use super if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).

If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super):

class A:
    def __init__(self):
        print('A')
        super().__init__()

class B:
    def __init__(self):
        print('B')
        super().__init__()

class C(A, B):
    pass

C()
#prints:
#A
#B

Notice how both base classes use super even though they don't have their own base classes.

What super does is: it calls the method from the next class in MRO (method resolution order). The MRO for C is: (C, A, B, object). You can print C.__mro__ to see it.

So, C inherits __init__ from A and super in A.__init__ calls B.__init__ (B follows A in MRO).

So by doing nothing in C, you end up calling both, which is what you want.

Now if you were not using super, you would end up inheriting A.__init__ (as before) but this time there's nothing that would call B.__init__ for you.

class A:
    def __init__(self):
        print('A')

class B:
    def __init__(self):
        print('B')

class C(A, B):
    pass

C()
#prints:
#A

To fix that you have to define C.__init__:

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

The problem with that is that in more complicated MI trees, __init__ methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.

Selecting/excluding sets of columns in pandas

You just need to convert your set to a list

import pandas as pd
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
my_cols = set(df.columns)
my_cols.remove('B')
my_cols.remove('D')
my_cols = list(my_cols)
df2 = df[my_cols]

Printing Even and Odd using two Threads in Java

This is my solution to the problem. I have two classes implementing Runnable, one prints odd sequence and the other prints even. I have an instance of Object, that I use for lock. I initialize the two classes with the same object. There is a synchronized block inside the run method of the two classes, where, inside a loop, each method prints one of the numbers, notifies the other thread, waiting for lock on the same object and then itself waits for the same lock again.

The classes :

public class PrintEven implements Runnable{
private Object lock;
public PrintEven(Object lock) {
    this.lock =  lock;
}
@Override
public void run() {
    synchronized (lock) {
        for (int i = 2; i <= 10; i+=2) {
            System.out.println("EVEN:="+i);
            lock.notify();
            try {
                //if(i!=10) lock.wait();
                lock.wait(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

  }
}


public class PrintOdd implements Runnable {
private Object lock;
public PrintOdd(Object lock) {
    this.lock =  lock;
}
@Override
public void run() {
    synchronized (lock) {
        for (int i = 1; i <= 10; i+=2) {
            System.out.println("ODD:="+i);
            lock.notify();
            try {
                //if(i!=9) lock.wait();
                lock.wait(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
}

public class PrintEvenOdd {
public static void main(String[] args){
    Object lock = new Object(); 
    Thread thread1 =  new Thread(new PrintOdd(lock));
    Thread thread2 =  new Thread(new PrintEven(lock));
    thread1.start();
    thread2.start();
}
}

The upper limit in my example is 10. Once the odd thread prints 9 or the even thread prints 10, then we don't need any of the threads to wait any more. So, we can handle that using one if-block. Or, we can use the overloaded wait(long timeout) method for the wait to be timed out. One flaw here though. With this code, we cannot guarantee which thread will start execution first.

Another example, using Lock and Condition

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionOddEven {
 public static void main(String[] args) {
    Lock lock =  new ReentrantLock();
    Condition evenCondition = lock.newCondition();
    Condition oddCondition = lock.newCondition();
    Thread evenThread =  new Thread(new EvenPrinter(10, lock, evenCondition, oddCondition));
    Thread oddThread =  new Thread(new OddPrinter(10, lock, evenCondition, oddCondition));
    oddThread.start();
    evenThread.start();
}

static class OddPrinter implements Runnable{
    int i = 1;
    int limit;
    Lock lock;
    Condition evenCondition;
    Condition oddCondition;

    public OddPrinter(int limit) {
        super();
        this.limit = limit;
    }

    public OddPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {
        super();
        this.limit = limit;
        this.lock = lock;
        this.evenCondition = evenCondition;
        this.oddCondition = oddCondition;
    }

    @Override
    public void run() {
        while( i <=limit) {
            lock.lock();
            System.out.println("Odd:"+i);
            evenCondition.signal();
            i+=2;
            try {
                oddCondition.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

static class EvenPrinter implements Runnable{
    int i = 2;
    int limit;
    Lock lock;
    Condition evenCondition;
    Condition oddCondition;

    public EvenPrinter(int limit) {
        super();
        this.limit = limit;
    }


    public EvenPrinter(int limit, Lock lock, Condition evenCondition, Condition oddCondition) {
        super();
        this.limit = limit;
        this.lock = lock;
        this.evenCondition = evenCondition;
        this.oddCondition = oddCondition;
    }


    @Override
    public void run() {
        while( i <=limit) {
            lock.lock();
            System.out.println("Even:"+i);
            i+=2;
            oddCondition.signal();
            try {
                evenCondition.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

}

Oracle JDBC intermittent Connection Issue

I was facing exactly the same problem. With Windows Vista I could not reproduce the problem but on Ubuntu I reproduced the 'connection reset'-Error constantly.

I found http://forums.oracle.com/forums/thread.jspa?threadID=941911&tstart=0&messageID=3793101

According to a user on that forum:

I opened a ticket with Oracle and this is what they told me.

java.security.SecureRandom is a standard API provided by sun. Among various methods offered by this class void nextBytes(byte[]) is one. This method is used for generating random bytes. Oracle 11g JDBC drivers use this API to generate random number during login. Users using Linux have been encountering SQLException("Io exception: Connection reset").

The problem is two fold

  1. The JVM tries to list all the files in the /tmp (or alternate tmp directory set by -Djava.io.tmpdir) when SecureRandom.nextBytes(byte[]) is invoked. If the number of files is large the method takes a long time to respond and hence cause the server to timeout

  2. The method void nextBytes(byte[]) uses /dev/random on Linux and on some machines which lack the random number generating hardware the operation slows down to the extent of bringing the whole login process to a halt. Ultimately the the user encounters SQLException("Io exception: Connection reset")

Users upgrading to 11g can encounter this issue if the underlying OS is Linux which is running on a faulty hardware.

Cause The cause of this has not yet been determined exactly. It could either be a problem in your hardware or the fact that for some reason the software cannot read from dev/random

Solution Change the setup for your application, so you add the next parameter to the java command:

-Djava.security.egd=file:/dev/../dev/urandom

We made this change in our java.security file and it has gotten rid of the error.

which solved my problem.

Order a MySQL table by two columns

ORDER BY article_rating ASC , article_time DESC

DESC at the end will sort by both columns descending. You have to specify ASC if you want it otherwise

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

Try by changing X[:,3] to X.iloc[:,3] in label encoder

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

What's the regular expression that matches a square bracket?

If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [ sign or the ] sign: /[\[\]]/

What's the difference between unit tests and integration tests?

A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.

When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test

Modal width (increase)

Bootstrap 4 includes sizing utilities. You can change the size to 25/50/75/100% of the page width (I wish there were even more increments).

To use these we will replace the modal-lg class. Both the default width and modal-lg use css max-width to control the modal's width, so first add the mw-100 class to effectively disable max-width. Then just add the width class you want, e.g. w-75.

Note that you should place the mw-100 and w-75 classes in the div with the modal-dialog class, not the modal div e.g.,

<div class='modal-dialog mw-100 w-75'>
    ...
</div>

Disable vertical scroll bar on div overflow: auto

Add the following:

body{
overflow-y:hidden;
}

Set a:hover based on class

Set a:hover based on class you can simply try:

a.main-nav-item:hover { }

close fancy box from function from within open 'fancybox'

to close fancybox by funciton its necessary to make setTimtout to the function that will close the fancybox Fancybox needs some time to acept the close function If you call the function directly will not work

function close_fancybox(){
$.fancybox.close();
                     }
setTimeout(close_fancybox, 50);

How can we programmatically detect which iOS version is device running on?

In MonoTouch:

To get the Major version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[0]

For minor version use:

UIDevice.CurrentDevice.SystemVersion.Split('.')[1]

DOM element to corresponding vue.js component

The proper way to do with would be to use the v-el directive to give it a reference. Then you can do this.$$[reference].

Update for vue 2

In Vue 2 refs are used for both elements and components: http://vuejs.org/guide/migration.html#v-el-and-v-ref-replaced

How do I use boolean variables in Perl?

Beautiful explanation given by bobf for Boolean values : True or False? A Quick Reference Guide

Truth tests for different values

                       Result of the expression when $var is:

Expression          | 1      | '0.0'  | a string | 0     | empty str | undef
--------------------+--------+--------+----------+-------+-----------+-------
if( $var )          | true   | true   | true     | false | false     | false
if( defined $var )  | true   | true   | true     | true  | true      | false
if( $var eq '' )    | false  | false  | false    | false | true      | true
if( $var == 0 )     | false  | true   | true     | true  | true      | true

Simple PHP Pagination script

 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    }
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

Tablix: Repeat header rows on each page not working - Report Builder 3.0

It depends on the tablix structure you are using. In a table, for example, you do not have column groups, so Reporting Services does not recognize which textboxes are the column headers and setting RepeatColumnHeaders property to True doesn't work.

Instead, you need to:

  1. Open Advanced Mode in the Groupings pane. (Click the arrow to the right of the Column Groups and select Advanced Mode.)
    • Screenshot
  2. In the Row Groups area (not Column Groups), click on a Static group, which highlights the corresponding textbox in the tablix. Click through each Static group until it highlights the leftmost column header. This is generally the first Static group listed.
  3. In the Properties window, set the RepeatOnNewPage property to True.
    • Screenshot
  4. Make sure that the KeepWithGroup property is set to After.

The KeepWithGroup property specifies which group to which the static member needs to stick. If set to After then the static member sticks with the group after it, or below it, acting as a group header. If set to Before, then the static member sticks with the group before, or above it, acting as a group footer. If set to None, Reporting Services decides where to put the static member.

Now when you view the report, the column headers repeat on each page of the tablix.

This video shows how to set it exactly as the answer described.

Illegal mix of collations error in MySql

The problem here mainly, just Cast the field like this cast(field as varchar) or cast(fields as date)

case statement in SQL, how to return multiple variables?

or you can

SELECT
  String_to_array(CASE
    WHEN <condition 1> THEN a1||','||b1
    WHEN <condition 2> THEN a2||','||b2
    ELSE a3||','||b3
  END, ',') K
FROM <table>

How to iterate through range of Dates in Java?

Apache Commons

    for (Date dateIter = fromDate; !dateIter.after(toDate); dateIter = DateUtils.addDays(dateIter, 1)) {
        // ...
    }

Pure CSS multi-level drop-down menu

I needed a multilevel dropdown menu in css. I couldn't find an error-free menu that I searched. Then I created a menu instance using the Css hover transition effect.I hope it will be useful for users.

enter image description here Css codes:

#AnaMenu {
width: 920px;            /* Menu width */
height: 30px;           /* Menu height */
position: relative;
background: #0080ff;
margin:0 0 0 -30px;
padding: 10px 0 0 15px;
border: 0;              
}
#nav { display:block;background:transparent;
margin:0;padding: 0;border: 0 }
#nav ul { float: none; display:block;
height:35px; 
margin:16px 0 0 0;border:0;
padding: 15px 0 3px 0; 
overflow: visible;
 }
#nav ul li{border:0;}
#nav li a, #nav li a:link, #nav li a:visited {height:23px;
-webkit-transition: background-color 1s ease-out;
-moz-transition: background-color 1s ease-out;
-o-transition: background-color 1s ease-out;
transition: background-color 1s ease-out;
color: #fff;                               /* Change colour of link */
display: block;border:0;border-right:1px solid #efefef;text-decoration:none;
margin: 0;letter-spacing:0.6px;
padding: 2px 10px 2px 10px;             
}
#nav li a:hover, #nav li a:active {
color: #fff;  
margin: 0;background:#6ab5ff;border:0;
padding: 2px 10px 2px 10px;      
}
#nav li li a, #nav li li a:link, #nav li li a:visited {
background: #fafafa;      
width: 200px;
color: #05429b;           /* Link text color */
float: none;
margin: 0;border-bottom:1px solid #9be6e9;
padding: 8px 15px;        
}
#nav li li a:hover, #nav li li a:active {
background: #2793ff;        /* Mouse hover color */
color: #fff;               
padding: 8px 15px;border:0 ;text-decoration:none}
#nav li {float: none; display: inline-block;margin: 0; padding: 0; border: 0 }
#nav li ul { z-index: 9999; position: absolute; left: -999em; height: auto; width: 200px; margin: 0; padding: 0;background:transparent}
#nav li ul a { width: 170px;border:0;text-decoration:none;font-size:14px } 
#nav li ul ul { margin: -40px 0 0 230px }
#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li.sfhover ul ul, #nav li.sfhover ul ul ul {left: -999em; } 
#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li.sfhover ul, #nav li li.sfhover ul, #nav li li li.sfhover ul { left: auto; } 
#nav li:hover, #nav li.sfhover {position: static;}

Multilevel dropdown menu can be used in Blogger blogs. Details at : Css multilevel dropdown menu

In Bash, how do I add a string after each line in a file?

If you have it, the lam (laminate) utility can do it, for example:

$ lam filename -s "string after each line"

How can I write output from a unit test?

It is indeed depending on the test runner as @jonzim mentioned. For NUnit 3 I had to use NUnit.Framework.TestContext.Progress.WriteLine() to get running output in the Output window of Visual Studio 2017.

NUnit describes how to: here

To my understanding this revolves around the added parallelization of test execution the test runners have received.

Taking pictures with camera on Android programmatically

There are two ways to take a photo:

1 - Using an Intent to make a photo

2 - Using the camera API

I think you should use the second way and there is a sample code here for two of them.