Programs & Examples On #Dynamic queries

Is there a query language for JSON?

The built-in array.filter() method makes most of these so-called javascript query libraries obsolete

You can put as many conditions inside the delegate as you can imagine: simple comparison, startsWith, etc. I haven't tested but you could probably nest filters too for querying inner collections.

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Python: finding an element in a list

From Dive Into Python:

>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5

ssh: The authenticity of host 'hostname' can't be established

Make sure ~/.ssh/known_hosts is writable. That fixed it for me.

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

Where is my .vimrc file?

Here are a few more tips:

  • In Arch Linux the global one is at /etc/vimrc. There are some comments in there with helpful details.

  • Since the filename starts with a ., it's hidden unless you use ls -a to show ALL files.

  • Typing :version while in Vim will show you a bunch of interesting information including the file location.

  • If you're not sure what ~/.vimrc means look at this question.

Angular 2 Checkbox Two Way Data Binding

I know it may be repeated answer but for any one want to load list of checkboxes with selectall checkbox into angular form i follow this example: Select all/deselect all checkbox using angular 2+

it work fine but just need to add

[ngModelOptions]="{standalone: true}" 

the final HTML should be like this:

<ul>
    <li><input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/></li>
    <li *ngFor="let n of names">
    <input type="checkbox" [(ngModel)]="n.selected" (change)="checkIfAllSelected();">{{n.name}}
    </li>
  </ul>

TypeScript

  selectAll() {
    for (var i = 0; i < this.names.length; i++) {
      this.names[i].selected = this.selectedAll;
    }
  }
  checkIfAllSelected() {
    this.selectedAll = this.names.every(function(item:any) {
        return item.selected == true;
      })
  }

hope this help thnx

How can I count text lines inside an DOM element? Can I?

getClientRects return the client rects like this and if you want to get the lines, use the follow function like this

function getRowRects(element) {
    var rects = [],
        clientRects = element.getClientRects(),
        len = clientRects.length,
        clientRect, top, rectsLen, rect, i;

    for(i=0; i<len; i++) {
        has = false;
        rectsLen = rects.length;
        clientRect = clientRects[i];
        top = clientRect.top;
        while(rectsLen--) {
            rect = rects[rectsLen];
            if (rect.top == top) {
                has = true;
                break;
            }
        }
        if(has) {
            rect.right = rect.right > clientRect.right ? rect.right : clientRect.right;
            rect.width = rect.right - rect.left;
        }
        else {
            rects.push({
                top: clientRect.top,
                right: clientRect.right,
                bottom: clientRect.bottom,
                left: clientRect.left,
                width: clientRect.width,
                height: clientRect.height
            });
        }
    }
    return rects;
}

How to wrap text in textview in Android

Just was working on a TextView inside a layout inside a RecyclerView. I had text getting cut off, ex, for Read this message, I saw: Read this. I tried setting android:maxLines="2" on the TextView, but nothing changed. However, android:lines="2" resulted in Read this on first line and message on the 2nd.

PHP - check if variable is undefined

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Example:

<?php
    $var1 = '';
    if(isset($var1)){
        echo 'This line is printed, because the $var1 is set.';
    }
?>

This code will output "This line is printed, because the $var1 is set."

read more in https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/

How do I change the default port (9000) that Play uses when I execute the "run" command?

Play 2.x

In Play 2, these are implemented with an sbt plugin, so the following instructions are really just sbt tasks. You can use any sbt runner (e In Play 2, these are implemented with an sbt plugin, so the following are really just sbt tasks. You can use any sbt runner (e.g. sbt, play, or activator). Below the sbt runner is used, but you can substitute it for your sbt runner of choice.

Play 2.x - Dev Mode

For browser-reload mode:

sbt "run 8080"

For continuous-reload mode:

sbt "~run 8080"

Play 2.x - Debug Mode

To run in debug mode with the http listener on port 8080, run:

sbt -jvm-debug 9999 "run 8080"

Play 2.x - Prod Mode

Start in Prod mode:

sbt "start -Dhttp.port=8080"

Play 2.x - Staged Distribution

Create a staged distribution:

sbt stage

For Play 2.0.x and 2.1.x use the target/start script (Unix Only):

target/start -Dhttp.port=8080

For Play 2.2.x & 2.3.x use the appropriate start script in the target/universal/stage/bin directory:

target/universal/stage/bin/[appname] -Dhttp.port=8080

With Play 2.2.x & 2.3.x on Windows:

target\universal\stage\bin\[appname].bat -Dhttp.port=8080

Play 2.x - Zip Distribution

To create a zip distribution:

sbt dist

For Play 2.0.x and 2.1.x use the start script (Unix Only) in the extracted zip:

start -Dhttp.port=8080

For Play 2.2.x use the appropriate script in the [appname]-[version]/bin directory:

[appname]-[version]/bin/[appname] -Dhttp.port=8080

With Play 2.2.x on Windows:

[appname]-[version]\bin\[appname].bat -Dhttp.port=8080

Play 1.x

Change the http.port value in the conf/application.conf file or pass it command line:

play run --http.port=8080

standard size for html newsletter template

Short answer: 400-800 pixels.

What I have read is that HTML newsletter width should be as narrow as possible without being too narrow. For instance, 400-500 pixels for a one column layout is a lower limit. Any less may look too weird.

Today's widescreen monitors allow for more horizontal pixels and most web email clients will either be of the two-column variety (Gmail) or 3-pane layout where the content window bellow the inbox list (Hotmail and Yahoo). In either case, you can be okay with 800 pixels if you're targeting the 1280 wide audience. An older or less technical audience may have older, square monitors.

There is the problem of Outlook having a three-column layout. That limits the width of your email even more. With them, you may want to go even narrower.

I just recently created a template that required an ad banner that is 730 pixels wide. It was near in the wide range, but not so much that most people could not double-click the email an open a new window in Outlook (the web email users should be okay for the most part).

Hope this advice helps.

Limiting the number of characters in a JTextField

public void Letters(JTextField a) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent e) {
            char c = e.getKeyChar();
            if (Character.isDigit(c)) {
                e.consume();
            }
            if (Character.isLetter(c)) {
                e.setKeyChar(Character.toUpperCase(c));
            }
        }
    });
}

public void Numbers(JTextField a) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent e) {
            char c = e.getKeyChar();
            if (!Character.isDigit(c)) {
                e.consume();
            }
        }
    });
}

public void Caracters(final JTextField a, final int lim) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent ke) {
            if (a.getText().length() == lim) {
                ke.consume();
            }
        }
    });
}

Get Substring between two characters using javascript

Using jQuery:

get_between <- function(str, first_character, last_character) {
    new_str = str.match(first_character + "(.*)" + last_character)[1].trim()
    return(new_str)
    }

string

my_string = 'and the thing that ! on the @ with the ^^ goes now' 

usage:

get_between(my_string, 'that', 'now')

result:

"! on the @ with the ^^ goes

How do I check for null values in JavaScript?

You can use lodash module to check value is null or undefined

_.isNil(value)
Example 

 country= "Abc"
    _.isNil(country)
    //false

   state= null
    _.isNil(state)
    //true

city= undefined
    _.isNil(state)
    //true

   pin= true
    _.isNil(pin)
    // false   

Reference link: https://lodash.com/docs/#isNil

Disable F5 and browser refresh using JavaScript

It works for me in all the browsers:

document.onkeydown = function(){
  switch (event.keyCode){
        case 116 : //F5 button
            event.returnValue = false;
            event.keyCode = 0;
            return false;
        case 82 : //R button
            if (event.ctrlKey){ 
                event.returnValue = false;
                event.keyCode = 0;
                return false;
            }
    }
}

How to download image using requests

This is the first response that comes up for google searches on how to download a binary file with requests. In case you need to download an arbitrary file with requests, you can use:

import requests
url = 'https://s3.amazonaws.com/lab-data-collections/GoogleNews-vectors-negative300.bin.gz'
open('GoogleNews-vectors-negative300.bin.gz', 'wb').write(requests.get(url, allow_redirects=True).content)

What does ellipsize mean in android?

Text:

 This is my first android application and
 I am trying to make a funny game,
 It seems android is really very easy to play.

Suppose above is your text and if you are using ellipsize's start attribute it will seen like this

This is my first android application and
...t seems android is really very easy to play.

with end attribute

 This is my first android application and
 I am trying to make a funny game,...

How to make promises work in IE11

You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.

used like: window.Promise https://www.npmjs.com/package/promise-polyfill

If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill

android edittext onchange listener

As far as I can think bout it, there's only two ways you can do it. How can you know the user has finished writing a word? Either on focus lost, or clicking on an "ok" button. There's no way on my mind you can know the user pressed the last character...

So call onFocusChange(View v, boolean hasFocus) or add a button and a click listener to it.

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

How can bcrypt have built-in salts?

To make things even more clearer,

Registeration/Login direction ->

The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt:

$2a$COST$BASE64

This value is stored eventually.

What the attacker would need to do in order to find the password ? (other direction <- )

In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random. Then he will need to decrypt the cipher text.

What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

How to call a RESTful web service from Android?

Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/

// The connection URL 
String url = "https://ajax.googleapis.com/ajax/" + 
    "services/search/web?v=1.0&q={query}";

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");

Html.HiddenFor value property not getting set

I believe there is a simpler solution. You must use Html.Hidden instead of Html.HiddenFor. Look:

@Html.Hidden("CRN", ViewData["crn"]);

This will create an INPUT tag of type="hidden", with id="CRN" and name="CRN", and the correct value inside the value attribute.

Hope it helps!

How to colorize diff on the command line?

Character-level color diff: Install ccdiff

ccdiff -r /usr/share/dict/words /tmp/new-dict

Output of ccdiff

Uploading a file in Rails

There is a nice gem especially for uploading files : carrierwave. If the wiki does not help , there is a nice RailsCast about the best way to use it . Summarizing , there is a field type file in Rails forms , which invokes the file upload dialog. You can use it , but the 'magic' is done by carrierwave gem .

I don't know what do you mean with "how to write to a file" , but I hope this is a nice start.

Change location of log4j.properties

In Eclipse you can set a VM argument to:

-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}

Copy a file from one folder to another using vbscripting

Try this. It will check to see if the file already exists in the destination folder, and if it does will check if the file is read-only. If the file is read-only it will change it to read-write, replace the file, and make it read-only again.

Const DestinationFile = "c:\destfolder\anyfile.txt"
Const SourceFile = "c:\sourcefolder\anyfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
    'Check to see if the file already exists in the destination folder
    If fso.FileExists(DestinationFile) Then
        'Check to see if the file is read-only
        If Not fso.GetFile(DestinationFile).Attributes And 1 Then 
            'The file exists and is not read-only.  Safe to replace the file.
            fso.CopyFile SourceFile, "C:\destfolder\", True
        Else 
            'The file exists and is read-only.
            'Remove the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes - 1
            'Replace the file
            fso.CopyFile SourceFile, "C:\destfolder\", True
            'Reapply the read-only attribute
            fso.GetFile(DestinationFile).Attributes = fso.GetFile(DestinationFile).Attributes + 1
        End If
    Else
        'The file does not exist in the destination folder.  Safe to copy file to this folder.
        fso.CopyFile SourceFile, "C:\destfolder\", True
    End If
Set fso = Nothing

Add Favicon with React and Webpack

Browsers look for your favicon in /favicon.ico, so that's where it needs to be. You can double check if you've positioned it in the correct place by navigating to [address:port]/favicon.ico and seeing if your icon appears.

In dev mode, you are using historyApiFallback, so will need to configure webpack to explicitly return your icon for that route:

historyApiFallback: {
    index: '[path/to/index]',
    rewrites: [
        // shows favicon
        { from: /favicon.ico/, to: '[path/to/favicon]' }
    ]
}

In your server.js file, try explicitly rewriting the url:

app.configure(function() {
    app.use('/favicon.ico', express.static(__dirname + '[route/to/favicon]'));
});

(or however your setup prefers to rewrite urls)

I suggest generating a true .ico file rather than using a .png, since I've found that to be more reliable across browsers.

MySQL Multiple Where Clause

SELECT a.image_id 
FROM list a
INNER JOIN list b
   ON a.image_id = b.image_id
   AND b.style_id = 25
   AND b.style_value = 'big'
INNER JOIN list c
   ON a.image_id = c.image_id
   AND c.style_id = 27
   AND c.style_value = 'round'
WHERE a.style_id = 24 
   AND a.style_value = 'red'

What column type/length should I use for storing a Bcrypt hashed password in a Database?

A Bcrypt hash can be stored in a BINARY(40) column.

BINARY(60), as the other answers suggest, is the easiest and most natural choice, but if you want to maximize storage efficiency, you can save 20 bytes by losslessly deconstructing the hash. I've documented this more thoroughly on GitHub: https://github.com/ademarre/binary-mcf

Bcrypt hashes follow a structure referred to as modular crypt format (MCF). Binary MCF (BMCF) decodes these textual hash representations to a more compact binary structure. In the case of Bcrypt, the resulting binary hash is 40 bytes.

Gumbo did a nice job of explaining the four components of a Bcrypt MCF hash:

$<id>$<cost>$<salt><digest>

Decoding to BMCF goes like this:

  1. $<id>$ can be represented in 3 bits.
  2. <cost>$, 04-31, can be represented in 5 bits. Put these together for 1 byte.
  3. The 22-character salt is a (non-standard) base-64 representation of 128 bits. Base-64 decoding yields 16 bytes.
  4. The 31-character hash digest can be base-64 decoded to 23 bytes.
  5. Put it all together for 40 bytes: 1 + 16 + 23

You can read more at the link above, or examine my PHP implementation, also on GitHub.

How do I use a third-party DLL file in Visual Studio C++?

These are two ways of using a DLL file in Windows:

  1. There is a stub library (.lib) with associated header files. When you link your executable with the lib-file it will automatically load the DLL file when starting the program.

  2. Loading the DLL manually. This is typically what you want to do if you are developing a plugin system where there are many DLL files implementing a common interface. Check out the documentation for LoadLibrary and GetProcAddress for more information on this.

For Qt I would suspect there are headers and a static library available that you can include and link in your project.

How do I clear a search box with an 'x' in bootstrap 3?

Do not bind to element id, just use the 'previous' input element to clear.

CSS:

.clear-input > span {
    position: absolute;
    right: 24px;
    top: 10px;
    height: 14px;
    margin: auto;
    font-size: 14px;
    cursor: pointer;
    color: #AAA;
}

Javascript:

function $(document).ready(function() {
    $(".clear-input>span").click(function(){
        // Clear the input field before this clear button
        // and give it focus.

        $(this).prev().val('').focus();
    });
});

HTML Markup, use as much as you like:

<div class="clear-input">
    Pizza: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>
</div>

<div class="clear-input">
    Pasta: <input type="text" class="form-control">
    <span class="glyphicon glyphicon-remove-circle"></span>
</div>

python numpy ValueError: operands could not be broadcast together with shapes

We might confuse ourselves that a * b is a dot product.

But in fact, it is broadcast.

Dot Product : a.dot(b)

Broadcast:

The term broadcasting refers to how numpy treats arrays with different dimensions during arithmetic operations which lead to certain constraints, the smaller array is broadcast across the larger array so that they have compatible shapes.

(m,n) +-/* (1,n) ? (m,n) : the operation will be applied to m rows

How to center links in HTML

Try doing a nav element with a ul element. Mine has a main above but I don't think you need it.

<main>
<nav>
<ul><li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>

The code is something like this.
When ever I put in the code it wouldn't work right so you need to fill in the blank,
then center it.

main
nav
ul> li> a>: href="link of choice":name of link:/a>

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Fast way to get the min/max values among properties of object

var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var maxValue = Math.max(...Object.values(newObj))
var minValue = Math.min(...Object.values(newObj))

java.lang.NoClassDefFoundError in junit

  1. Make sure Environment variable JUNIT_HOME is set to c:\JUNIT.
  2. then In run configuration > select classpath > add external jars junit-4.11.jar

Setting a log file name to include current date in Log4j

I have created an appender that will do that. http://stauffer.james.googlepages.com/DateFormatFileAppender.java

/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.txt file.  */

package sps.log.log4j;

import java.io.IOException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.*;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

/**
 * DateFormatFileAppender is a log4j Appender and extends 
 * {@link FileAppender} so each log is 
 * named based on a date format defined in the File property.
 *
 * Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'
 * Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log
 * @author James Stauffer
 */
public class DateFormatFileAppender extends FileAppender {

  /**
   * The default constructor does nothing.
   */
  public DateFormatFileAppender() {
  }

  /**
   * Instantiate a <code>DailyRollingFileAppender</code> and open the
   * file designated by <code>filename</code>. The opened filename will
   * become the ouput destination for this appender.
   */
  public DateFormatFileAppender (Layout layout, String filename) throws IOException {
    super(layout, filename, true);
  }

  private String fileBackup;//Saves the file pattern
  private boolean separate = false;

  public void setFile(String file) {
    super.setFile(file);
    this.fileBackup = getFile();
  }

  /**
   * If true each LoggingEvent causes that file to close and open.
   * This is useful when the file is a pattern that would often
   * produce a different filename.
   */
  public void setSeparate(boolean separate) {
    this.separate = separate;
  }

  protected void subAppend(LoggingEvent event) {
    if(separate) {
        try {//First reset the file so each new log gets a new file.
            setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());
        } catch(IOException e) {
            LogLog.error("Unable to reset fileName.");
        }
    }
    super.subAppend(event);
  }


  public
  synchronized
  void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)
                                                            throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);
    String actualFileName = sdf.format(new Date());
    makeDirs(actualFileName);
    super.setFile(actualFileName, append, bufferedIO, bufferSize);
  }

  /**
   * Ensures that all of the directories for the given path exist.
   * Anything after the last / or \ is assumed to be a filename.
   */
  private void makeDirs (String path) {
    int indexSlash = path.lastIndexOf("/");
    int indexBackSlash = path.lastIndexOf("\\");
    int index = Math.max(indexSlash, indexBackSlash);
    if(index > 0) {
        String dirs = path.substring(0, index);
//        LogLog.debug("Making " + dirs);
        File dir = new File(dirs);
        if(!dir.exists()) {
            boolean success = dir.mkdirs();
            if(!success) {
                LogLog.error("Unable to create directories for " + dirs);
            }
        }
    }
  }

}

Different CURRENT_TIMESTAMP and SYSDATE in oracle

  • SYSDATE provides date and time of a server.
  • CURRENT_DATE provides date and time of client.(i.e., your system)
  • CURRENT_TIMESTAMP provides data and timestamp of a clinet.

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

SQL Server: Importing database from .mdf?

See: How to: Attach a Database File to SQL Server Express

Login to the database via sqlcmd:

sqlcmd -S Server\Instance

And then issue the commands:

USE [master]
GO
CREATE DATABASE [database_name] ON 
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\<database name>.ldf' )
 FOR ATTACH ;
GO

Function passed as template argument

In your template

template <void (*T)(int &)>
void doOperation()

The parameter T is a non-type template parameter. This means that the behaviour of the template function changes with the value of the parameter (which must be fixed at compile time, which function pointer constants are).

If you want somthing that works with both function objects and function parameters you need a typed template. When you do this, though, you also need to provide an object instance (either function object instance or a function pointer) to the function at run time.

template <class T>
void doOperation(T t)
{
  int temp=0;
  t(temp);
  std::cout << "Result is " << temp << std::endl;
}

There are some minor performance considerations. This new version may be less efficient with function pointer arguments as the particular function pointer is only derefenced and called at run time whereas your function pointer template can be optimized (possibly the function call inlined) based on the particular function pointer used. Function objects can often be very efficiently expanded with the typed template, though as the particular operator() is completely determined by the type of the function object.

css padding is not working in outlook

I changed to following and it worked for me

<tr>
    <td bgcolor="#7d9aaa" style="color: #fff; font-size:15px; font-family:Arial, Helvetica, sans-serif; padding: 12px 2px 12px 0px; ">                              
        <table style="width:620px; border:0; text-align:center;" cellpadding="0" cellspacing="0">               
            <td style="font-weight: bold;padding-right:160px;color: #fff">Order Confirmation </td>                    
            <td style="font-weight: bold;width:260px;color: #fff">Your Confirmation number is {{var order.increment_id}} </td>              
        </table>                    
    </td>
</tr>

Update based on Bsalex request what has actually changed. I replaced span tag

<span style="font-weight: bold;padding-right:150px;padding-left: 35px;">Order Confirmation </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span style="font-weight: bold;width:400px;"> Your Confirmation number is {{var order.increment_id}} </span>

with table and td tags as following

   <table style="width:620px; border:0; text-align:center;" cellpadding="0" cellspacing="0"> 
      <td style="font-weight: bold;padding-right:160px;color: #fff">Order Confirmation </td>
      <td style="font-weight: bold;width:260px;color: #fff">Your Confirmation number is {{var order.increment_id}} </td>
   </table>

How to find the Center Coordinate of Rectangle?

Center x = x + 1/2 of width

Center y = y + 1/2 of height 

If you know the width and height already then you only need one set of coordinates.

java.net.UnknownHostException: Invalid hostname for server: local

Try the following :

String url = "http://www.google.com/search?q=java";
URL urlObj = (URL)new URL(url.trim());
HttpURLConnection httpConn = 
(HttpURLConnection)urlObj.openConnection();
httpConn.setRequestMethod("GET");
Integer rescode = httpConn.getResponseCode();
System.out.println(rescode);

Trim() the URL

Default Activity not found in Android Studio

Have you added ACTION_MAIN intent filter to your main activity? If you don't add this, then android won't know which activity to launch as the main activity.

ex:

<intent-filter>
      <action android:name="android.intent.action.MAIN"/>
      <action android:name="com.package.name.MyActivity"/>
      <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

scipy.misc module has no attribute imread?

python -m pip install pillow

This worked for me.

How do I log a Python error with debug information?

A little bit of decorator treatment (very loosely inspired by the Maybe monad and lifting). You can safely remove Python 3.6 type annotations and use an older message formatting style.

fallible.py

from functools import wraps
from typing import Callable, TypeVar, Optional
import logging


A = TypeVar('A')


def fallible(*exceptions, logger=None) \
        -> Callable[[Callable[..., A]], Callable[..., Optional[A]]]:
    """
    :param exceptions: a list of exceptions to catch
    :param logger: pass a custom logger; None means the default logger, 
                   False disables logging altogether.
    """
    def fwrap(f: Callable[..., A]) -> Callable[..., Optional[A]]:

        @wraps(f)
        def wrapped(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except exceptions:
                message = f'called {f} with *args={args} and **kwargs={kwargs}'
                if logger:
                    logger.exception(message)
                if logger is None:
                    logging.exception(message)
                return None

        return wrapped

    return fwrap

Demo:

In [1] from fallible import fallible

In [2]: @fallible(ArithmeticError)
    ...: def div(a, b):
    ...:     return a / b
    ...: 
    ...: 

In [3]: div(1, 2)
Out[3]: 0.5

In [4]: res = div(1, 0)
ERROR:root:called <function div at 0x10d3c6ae8> with *args=(1, 0) and **kwargs={}
Traceback (most recent call last):
  File "/Users/user/fallible.py", line 17, in wrapped
    return f(*args, **kwargs)
  File "<ipython-input-17-e056bd886b5c>", line 3, in div
    return a / b

In [5]: repr(res)
'None'

You can also modify this solution to return something a bit more meaningful than None from the except part (or even make the solution generic, by specifying this return value in fallible's arguments).

Copy a file in a sane, safe and efficient way

Copy a file in a sane way:

#include <fstream>

int main()
{
    std::ifstream  src("from.ogv", std::ios::binary);
    std::ofstream  dst("to.ogv",   std::ios::binary);

    dst << src.rdbuf();
}

This is so simple and intuitive to read it is worth the extra cost. If we were doing it a lot, better to fall back on OS calls to the file system. I am sure boost has a copy file method in its filesystem class.

There is a C method for interacting with the file system:

#include <copyfile.h>

int
copyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

How do I decompile a .NET EXE into readable C# source code?

Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.

ADDED: My latest favourite is JetBrains' dotPeek.

How to add property to object in PHP >= 5.3 strict mode without generating error

Yes, is possible to dynamically add properties to a PHP object.

This is useful when a partial object is received from javascript.

JAVASCRIPT side:

var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
    if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});

PHP side:

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.

How to blur background images in Android

You can quickly get to blur effect by doing the following.

// Add this to build.gradle app //

Compile ' com.github.jgabrielfreitas:BlurImageView:1.0.1 '

// Add to XML

<com.jgbrielfreitas.core.BlurImageView
    android:id="@+id/iv_blur_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

//Add this to java

Import com.jgabrielfreitas.core.BlueImageView;

// Under public class *activity name * //

BlurImageView myBlurImage;

// Under Oncreate//

myBlurImage = (ImageView) findViewById(R.id.iv_blur_image)
MyBlurImage.setBlue(5)

I hope that helps someone

One line if-condition-assignment

num1 = 20 * someBoolValue or num1

How to link to a named anchor in Multimarkdown?

I tested Github Flavored Markdown for a while and can summarize with four rules:

  1. punctuation marks will be dropped
  2. leading white spaces will be dropped
  3. upper case will be converted to lower
  4. spaces between letters will be converted to -

For example, if your section is named this:

## 1.1 Hello World

Create a link to it this way:

[Link](#11-hello-world)

PHP 7 simpleXML

For Alpine (in docker), you can use apk add php7-simplexml.

If that doesn't work for you, you can run apk add --no-cache php7-simplexml. This is in case you aren't updating the package index first.

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

Could not resolve Spring property placeholder

You may have more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer in your application. Try setting a breakpoint on the setLocations method of the superclass and see if it's called more than once at application startup. If there is more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, you might need to look at configuring the ignoreUnresolvablePlaceholders property so that your application will start up cleanly.

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

Click outside menu to close in jquery

even i came across the same situation and one of my mentor put this idea across to myself.

step:1 when clicked on the button on which we should show the drop down menu. then add the below class name "more_wrap_background" to the current active page like shown below

$('.ui-page-active').append("<div class='more_wrap_background' id='more-wrap-bg'> </div>");

step-2 then add a clicks for the div tag like

$(document).on('click', '#more-wrap-bg', hideDropDown);

where hideDropDown is the function to be called to hide drop down menu

Step-3 and important step while hiding the drop down menu is that remove that class you that added earlier like

$('#more-wrap-bg').remove();

I am removing by using its id in the above code

.more_wrap_background {
  top: 0;
  padding: 0;
  margin: 0;
  background: rgba(0, 0, 0, 0.1);
  position: fixed;
  display: block;
  width: 100% !important;
  z-index: 999;//should be one less than the drop down menu's z-index
  height: 100% !important;
}

What is .htaccess file?

Below are some usage of htaccess files in server:

1) AUTHORIZATION, AUTHENTICATION: .htaccess files are often used to specify the security restrictions for the particular directory, hence the filename "access". The .htaccess file is often accompanied by an .htpasswd file which stores valid usernames and their passwords.

2) CUSTOMIZED ERROR RESPONSES: Changing the page that is shown when a server-side error occurs, for example HTTP 404 Not Found. Example : ErrorDocument 404 /notfound.html

3) REWRITING URLS: Servers often use .htaccess to rewrite "ugly" URLs to shorter and prettier ones.

4) CACHE CONTROL: .htaccess files allow a server to control User agent caching used by web browsers to reduce bandwidth usage, server load, and perceived lag.

More info : http://en.wikipedia.org/wiki/Htaccess

Removing carriage return and new-line from the end of a string in c#

s.TrimEnd();

The above is all I needed to remove '\r\n' from the end of my string.

The upvoted answer seems wrong to me. Firstly, it didn't work when I tried, secondly, if it did work I would expect that s.TrimEnd('\r', '\n') would only remove either a '\r' or a '\n', so I'd have to run it over my string twice - once for when '\n' was at the end and the second time for when '\r' was at the end (now that the '\n' was removed).

How can I find the first and last date in a month using PHP?

You can use DateTimeImmutable::modify() :


$date = DateTimeImmutable::createFromFormat('Y-m-d', '2021-02-13');

var_dump($date->modify('first day of this month')->format('Y-m-d')); // string(10) "2021-02-01"
var_dump($date->modify('last day of this month')->format('Y-m-d')); // string(10) "2021-02-28"

Counting how many times a certain char appears in a string before any other char appears

int count = myString.TakeWhile(c => c == '$').Count();

And without LINQ

int count = 0;
while(count < myString.Length && myString[count] == '$') count++;

How can I create an error 404 in PHP?

In the Drupal or Wordpress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS's 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

Is there a way to compile node.js source files?

You can use the Closure compiler to compile your javascript.

You can also use CoffeeScript to compile your coffeescript to javascript.

What do you want to achieve with compiling?

The task of compiling arbitrary non-blocking JavaScript down to say, C sounds very daunting.

There really isn't that much speed to be gained by compiling to C or ASM. If you want speed gain offload computation to a C program through a sub process.

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

Bootstrap 3 Horizontal and Vertical Divider

You can achieve this by adding border class of bootstrap

like for border left ,you can use border-left

working code

<div class="row">
    <div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="one"><h5>Rich Media Ad Production</h5><img src="images/richmedia.png"></div>
    <div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="two"><h5>Web Design & Development</h5> <img src="images/web.png" ></div>               
    <div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right border-bottom" id="three"><h5>Mobile Apps Development</h5> <img src="images/mobile.png"></div>
    <div class="col-xs-6 col-sm-6 col-md-3 text-center rightspan  border-bottom" id="four"><h5>Creative Design</h5> <img src="images/mobile.png"> </div>
    <div class="col-xs-12"><hr></div>
    <div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="five"><h5>Web Analytics</h5> <img src="images/analytics.png"></div>
    <div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right" id="six"><h5>Search Engine Marketing</h5> <img src="images/searchengine.png"></div>
    <div class="col-xs-6 col-sm-6 col-md-3 text-center leftspan border-right"  id="seven"><h5>Mobile Apps Development</h5> <img src="images/socialmedia.png"></div>
    <div class="col-xs-6 col-sm-6 col-md-3 text-center rightspan" id="eight"><h5>Quality Assurance</h5> <img src="images/qa.png"></div>

    <hr>
</div>

for more refrence al bootstrap classes all classes ,search for border

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

How to use random in BATCH script?

Let's say you want a number 1-5; you could use the following:

    :LOOP
    set NUM=%random:~-1,1%
    if %NUM% GTR 5 (
    goto LOOP )
    goto NEXT

Or you could use :~1,1 in place of :~-1,1. The :~-1,1 is not needed, but it greatly reduces the amount of time it takes to hit the right range. Let's say you want a number 1-50, we need to decide between 2 digits and 1 digit. Use:

    :LOOP
    set RAN1=%random:~-1,1%
    if %RAN1% GTR 5 (
    goto 1 )
    if %RAN1%==5 (
    goto LOOP )
    goto 2

    :1
    set NUM=%random:~-1,1%
    goto NEXT

    :2
    set NUM=%random:~-1,2%
    goto NEXT

You can add more to this algorithm to decide between large ranges, such as 1-1000.

How can I run a function from a script in command line?

Edit: WARNING - seems this doesn't work in all cases, but works well on many public scripts.

If you have a bash script called "control" and inside it you have a function called "build":

function build() { 
  ... 
}

Then you can call it like this (from the directory where it is):

./control build

If it's inside another folder, that would make it:

another_folder/control build

If your file is called "control.sh", that would accordingly make the function callable like this:

./control.sh build

How to declare std::unique_ptr and what is the use of it?

From cppreference, one of the std::unique_ptr constructors is

explicit unique_ptr( pointer p ) noexcept;

So to create a new std::unique_ptr is to pass a pointer to its constructor.

unique_ptr<int> uptr (new int(3));

Or it is the same as

int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);

The different is you don't have to clean up after using it. If you don't use std::unique_ptr (smart pointer), you will have to delete it like this

delete int_ptr;

when you no longer need it or it will cause a memory leak.

How to include a child object's child object in Entity Framework 5

I ended up doing the following and it works:

return DatabaseContext.Applications
     .Include("Children.ChildRelationshipType");

How can I add items to an empty set in python

D = {} is a dictionary not set.

>>> d = {}
>>> type(d)
<type 'dict'>

Use D = set():

>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

Disabling browser print options (headers, footers, margins) from page?

The CSS standard enables some advanced formatting. There is a @page directive in CSS that enables some formatting that applies only to paged media (like paper). See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.

Downside is that behavior in different browsers is not consistent. Safari still does not support setting printer page margin at all, but all the other major browsers now support it.

With the @page directive, you can specify printer margin of the page (which is not the same as normal CSS margin of an HTML element):

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Print Test</title>
    <style type="text/css" media="print">
    @page 
    {
        size:  auto;   /* auto is the initial value */
        margin: 0mm;  /* this affects the margin in the printer settings */
    }

    html
    {
        background-color: #FFFFFF; 
        margin: 0px;  /* this affects the margin on the html before sending to printer */
    }

    body
    {
        border: solid 1px blue ;
        margin: 10mm 15mm 10mm 15mm; /* margin you want for the content */
    }
    </style>
</head>
<body>
  <div>Top line</div>
  <div>Line 2</div>
</body>
</html>

Note that we basically disables the page-specific margins here to achieve the effect of removing the header and footer, so the margin we set on the body will not be used in page breaks (as commented by Konrad) This means that it will only work properly if the printed content is only one page.

This does not work in Firefox 3.6, IE 7, Safari 5.1.7 or Google Chrome 4.1.

Setting the @page margin does have effect in IE 8, Opera 10, Google Chrome 21 and Firefox 19.
Although the page margins are set correctly for your content in these browsers, the behavior is not ideal in trying to solve the hiding of the header/footer.

This is how it behaves in different browsers:

  • In Internet Explorer, the margin is actually set to 0mm in the settings for this printing, and if you do Preview you will get 0mm as default, but the user can change it in the preview.
    You will see that the page content actually are positioned correctly, but the browser print header and footer is shown with non-transparent background, and so effectively hiding the page content at that position.

  • In Firefox newer versions, it is positioned correctly, but both the header/footer text and content text is displayed, so it looks like a bad mix of browser header text and your page content.

  • In Opera, the page content hides the header when using a non-transparent background in the standard css and the header/footer position conflicts with content. Quite good, but looks strange if margin is set to a small value that causes the header to be partially visible. Also the page margin is not set properly.

  • In Chrome newer versions, the browser header and footer is hidden if the @page margin is set so small that the header/footer position conflicts with content. In my opinion, this is exactly how this should behave.

So the conclusion is that Chrome has the best implementation of this in respect to hiding the header/footer.

How can I count the occurrences of a list item?

Another way to get the number of occurrences of each item, in a dictionary:

dict((i, a.count(i)) for i in a)

What does "<>" mean in Oracle

I'm surprised nobody mentioned the null special case. I think the meaning of <> is more something like

has a value which is not equal to

In this case it filters out items which have ordid 605 and items which have a null ordid.

It may be obvious in this context that ordid is never null, but it is never hurts to remember that null is not <> from 605 (or from anything).

Styling an anchor tag to look like a submit button

Using a button tag instead of the input, resetting it and put a span inside, you'll then just have to style both the link and the span in the same way. It involve extra markup, but it worked for me.

the markup:

<button type="submit">
    <span>submit</span>
</button>
<a>cancel</a>

the css:

button[type="submit"] {
    display: inline;
    border: none;
    padding: 0;
    background: none;
}

How to get mouse position in jQuery without mouse-events?

I used this method:

$(document).mousemove(function(e) {
    window.x = e.pageX;
    window.y = e.pageY;
});

function show_popup(str) {
    $("#popup_content").html(str);
    $("#popup").fadeIn("fast");
    $("#popup").css("top", y);
    $("#popup").css("left", x);
}

In this way I'll always have the distance from the top saved in y and the distance from the left saved in x.

Undoing a 'git push'

The accepted solution (from @charles bailey) is highly dangerous if you are working in a shared repo.

As a best practice, all commits pushed to a remote repo that is shared should be considered 'immutable'. Use 'git revert' instead: http://www.kernel.org/pub/software/scm/git/docs/user-manual.html#fixing-mistakes

https://git-scm.com/book/be/v2/Git-Basics-Undoing-Things

iOS Simulator to test website on Mac

You could look into using BrowserStack: http://www.browserstack.com

While not free, it is rather cheap. It allows you to test against several iOS versions on both iPhone and iPad, along with Android, and various desktop browsers and OSs. It has proved quite invaluable to my workplace for doing just these sort of tests.

In Python, can I call the main() of an imported module?

Martijen's answer makes sense, but it was missing something crucial that may seem obvious to others but was hard for me to figure out.

In the version where you use argparse, you need to have this line in the main body.

args = parser.parse_args(args)

Normally when you are using argparse just in a script you just write

args = parser.parse_args()

and parse_args find the arguments from the command line. But in this case the main function does not have access to the command line arguments, so you have to tell argparse what the arguments are.

Here is an example

import argparse
import sys

def x(x_center, y_center):
    print "X center:", x_center
    print "Y center:", y_center

def main(args):
    parser = argparse.ArgumentParser(description="Do something.")
    parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
    parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
    args = parser.parse_args(args)
    x(args.xcenter, args.ycenter)

if __name__ == '__main__':
    main(sys.argv[1:])

Assuming you named this mytest.py To run it you can either do any of these from the command line

python ./mytest.py -x 8
python ./mytest.py -x 8 -y 2
python ./mytest.py 

which returns respectively

X center: 8.0
Y center: 4

or

X center: 8.0
Y center: 2.0

or

X center: 2
Y center: 4

Or if you want to run from another python script you can do

import mytest
mytest.main(["-x","7","-y","6"]) 

which returns

X center: 7.0
Y center: 6.0

How many bytes is unsigned long long?

It must be at least 64 bits. Other than that it's implementation defined.

Strictly speaking, unsigned long long isn't standard in C++ until the C++0x standard. unsigned long long is a 'simple-type-specifier' for the type unsigned long long int (so they're synonyms).

The long long set of types is also in C99 and was a common extension to C++ compilers even before being standardized.

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

Animate visibility modes, GONE and VISIBLE

Like tomash said before: There's no easy way.

You might want to take a look at my answer here.
It explains how to realize a sliding (dimension changing) view.
In this case it was a left and right view: Left expanding, right disappearing.
It's might not do exactly what you need but with inventive spirit you can make it work ;)

Can I install Python 3.x and 2.x on the same Windows computer?

You should make sure that the PATH environment variable doesn't contain both python.exe files ( add the one you're currently using to run scripts on a day to day basis ) , or do as Kniht suggested with the batch files . Aside from that , I don't see why not .

P.S : I have 2.6 installed as my "primary" python and 3.0 as my "play" python . The 2.6 is included in the PATH . Everything works fine .

How to exit when back button is pressed?

Use onBackPressedmethod

@Override
public void onBackPressed() {
    finish();
    super.onBackPressed();
}

This will solve your issue.

How to have comments in IntelliSense for function in Visual Studio?

<c>text</c> - The text you would like to indicate as code.
The <c> tag gives you a way to indicate that text within a description should be marked as code. Use <code> to indicate multiple lines as code.

<code>content</code> - The text you want marked as code.
The <code> tag gives you a way to indicate multiple lines as code. Use <c> to indicate that text within a description should be marked as code.

<example>description</example> - A description of the code sample.
The <example> tag lets you specify an example of how to use a method or other library member. This commonly involves using the <code> tag.

<exception cref="member">description</exception> - A description of the exception.
The <exception> tag lets you specify which exceptions can be thrown. This tag can be applied to definitions for methods, properties, events, and indexers.

<include file='filename' path='tagpath[@name="id"]' />
The <include> tag lets you refer to comments in another file that describe the types and members in your source code. This is an alternative to placing documentation comments directly in your source code file. By putting the documentation in a separate file, you can apply source control to the documentation separately from the source code. One person can have the source code file checked out and someone else can have the documentation file checked out. The <include> tag uses the XML XPath syntax. Refer to XPath documentation for ways to customize your <include> use.

<list type="bullet" | "number" | "table">
    <listheader>
        <term>term</term>
        <description>description</description>
    </listheader>
    <item>
        <term>term</term>
        <description>description</description>
    </item>
</list>

The <listheader> block is used to define the heading row of either a table or definition list. When defining a table, you only need to supply an entry for term in the heading. Each item in the list is specified with an <item> block. When creating a definition list, you will need to specify both term and description. However, for a table, bulleted list, or numbered list, you only need to supply an entry for description. A list or table can have as many <item> blocks as needed.

<para>content</para>
The <para> tag is for use inside a tag, such as <summary>, <remarks>, or <returns>, and lets you add structure to the text.

<param name="name">description</param>
The <param> tag should be used in the comment for a method declaration to describe one of the parameters for the method. To document multiple parameters, use multiple <param> tags.
The text for the <param> tag will be displayed in IntelliSense, the Object Browser, and in the Code Comment Web Report.

<paramref name="name"/>
The <paramref> tag gives you a way to indicate that a word in the code comments, for example in a <summary> or <remarks> block refers to a parameter. The XML file can be processed to format this word in some distinct way, such as with a bold or italic font.

<permission cref="member">description</permission>
The <permission> tag lets you document the access of a member. The PermissionSet class lets you specify access to a member.

<remarks>description</remarks>
The <remarks> tag is used to add information about a type, supplementing the information specified with <summary>. This information is displayed in the Object Browser.

<returns>description</returns>
The <returns> tag should be used in the comment for a method declaration to describe the return value.

<see cref="member"/>
The <see> tag lets you specify a link from within text. Use <seealso> to indicate that text should be placed in a See Also section. Use the cref Attribute to create internal hyperlinks to documentation pages for code elements.

<seealso cref="member"/>
The <seealso> tag lets you specify the text that you might want to appear in a See Also section. Use <see> to specify a link from within text.

<summary>description</summary>
The <summary> tag should be used to describe a type or a type member. Use <remarks> to add supplemental information to a type description. Use the cref Attribute to enable documentation tools such as Sandcastle to create internal hyperlinks to documentation pages for code elements. The text for the <summary> tag is the only source of information about the type in IntelliSense, and is also displayed in the Object Browser.

<typeparam name="name">description</typeparam>
The <typeparam> tag should be used in the comment for a generic type or method declaration to describe a type parameter. Add a tag for each type parameter of the generic type or method. The text for the <typeparam> tag will be displayed in IntelliSense, the Object Browser code comment web report.

<typeparamref name="name"/>
Use this tag to enable consumers of the documentation file to format the word in some distinct way, for example in italics.

<value>property-description</value>
The <value> tag lets you describe the value that a property represents. Note that when you add a property via code wizard in the Visual Studio .NET development environment, it will add a <summary> tag for the new property. You should then manually add a <value> tag to describe the value that the property represents.

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

I installed mongodb with EBS on an EC2 with Ubuntu 14.04 following this tutorial:

http://docs.mongodb.org/ecosystem/platforms/amazon-ec2/

But instead of the suggested chown I did:

sudo chown -R mongodb:mongodb /data /log /journal

To fix the problem

How to duplicate sys.stdout to a log file?

Here is another solution, which is more general than the others -- it supports splitting output (written to sys.stdout) to any number of file-like objects. There's no requirement that __stdout__ itself is included.

import sys

class multifile(object):
    def __init__(self, files):
        self._files = files
    def __getattr__(self, attr, *args):
        return self._wrap(attr, *args)
    def _wrap(self, attr, *args):
        def g(*a, **kw):
            for f in self._files:
                res = getattr(f, attr, *args)(*a, **kw)
            return res
        return g

# for a tee-like behavior, use like this:
sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])

# all these forms work:
print 'abc'
print >>sys.stdout, 'line2'
sys.stdout.write('line3\n')

NOTE: This is a proof-of-concept. The implementation here is not complete, as it only wraps methods of the file-like objects (e.g. write), leaving out members/properties/setattr, etc. However, it is probably good enough for most people as it currently stands.

What I like about it, other than its generality, is that it is clean in the sense it doesn't make any direct calls to write, flush, os.dup2, etc.

How do I subtract minutes from a date in javascript?

This is what I did: see on Codepen

var somedate = 1473888180593;
var myStartDate;
//var myStartDate = somedate - durationInMuntes;

myStartDate = new Date(dateAfterSubtracted('minutes', 100));

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());

function dateAfterSubtracted(range, amount){
    var now = new Date();
    if(range === 'years'){
        return now.setDate(now.getYear() - amount);
    }
    if(range === 'months'){
        return now.setDate(now.getMonth() - amount);
    }
    if(range === 'days'){
        return now.setDate(now.getDate() - amount);
    }
    if(range === 'hours'){
        return now.setDate(now.getHours() - amount);
    }
    if(range === 'minutes'){
        return now.setDate(now.getMinutes() - amount);
    }
    else {
        return null;
    }
}

How do I enumerate the properties of a JavaScript object?

I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..

form with no action and where enter does not reload page

Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:

onKeyPress="if (event.which == 13) return false;"

For example:

<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>

View/edit ID3 data for MP3 files

TagLib Sharp has support for reading ID3 tags.

Shell command to tar directory excluding certain files/folders

You can also use one of the "--exclude-tag" options depending on your needs:

  • --exclude-tag=FILE
  • --exclude-tag-all=FILE
  • --exclude-tag-under=FILE

The folder hosting the specified FILE will be excluded.

Check if a string contains a number

This probably isn't the best approach in Python, but as a Haskeller this lambda/map approach made perfect sense to me and is very short:

anydigit = lambda x: any(map(str.isdigit, x))

Doesn't need to be named of course. Named it could be used like anydigit("abc123"), which feels like what I was looking for!

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

ASP.NET Bundles how to disable minification

Combine several answers, this works for me in ASP.NET MVC 4.

        bundles.Add(new ScriptBundle("~/Scripts/Common/js")
            .Include("~/Scripts/jquery-1.8.3.js")
            .Include("~/Scripts/zizhujy.com.js")
            .Include("~/Scripts/Globalize.js")
            .Include("~/Scripts/common.js")
            .Include("~/Scripts/requireLite/requireLite.js"));

        bundles.Add(new StyleBundle("~/Content/appLayoutStyles")
            .Include("~/Content/AppLayout.css"));

        bundles.Add(new StyleBundle("~/Content/css/App/FunGrapherStyles")
            .Include("~/Content/css/Apps/FunGrapher.css")
            .Include("~/Content/css/tables.css"));

#if DEBUG
        foreach (var bundle in BundleTable.Bundles)
        {
            bundle.Transforms.Clear();
        }
#endif

Is there a way to take the first 1000 rows of a Spark Dataframe?

The method you are looking for is .limit.

Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.

Example usage:

df.limit(1000)

Read files from a Folder present in project

Use this Code for read all files in folder and sub-folders also

class Program
{
    static void Main(string[] args)
    {

        getfiles get = new getfiles();
        List<string> files =  get.GetAllFiles(@"D:\Document");

        foreach(string f in files)
        {
            Console.WriteLine(f);
        }


        Console.Read();
    }


}

class getfiles
{
    public List<string> GetAllFiles(string sDirt)
    {
        List<string> files = new List<string>();

        try
        {
            foreach (string file in Directory.GetFiles(sDirt))
            {
                files.Add(file);
            }
            foreach (string fl in Directory.GetDirectories(sDirt))
            {
                files.AddRange(GetAllFiles(fl));
            }
        }
        catch (Exception ex)
        {

            Console.WriteLine(ex.Message);
        }



        return files;
    }
}

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

MySQL SELECT last few days?

You can use this in your MySQL WHERE clause to return records that were created within the last 7 days/week:

created >= DATE_SUB(CURDATE(),INTERVAL 7 day)

Also use NOW() in the subtraction to give hh:mm:ss resolution. So to return records created exactly (to the second) within the last 24hrs, you could do:

created >= DATE_SUB(NOW(),INTERVAL 1 day)

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

If its a maven project, add the below dependency in your pom file

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.4</version>
    </dependency>

How to convert 2D float numpy array to 2D int numpy array?

Some numpy functions for how to control the rounding: rint, floor,trunc, ceil. depending how u wish to round the floats, up, down, or to the nearest int.

>>> x = np.array([[1.0,2.3],[1.3,2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> y = np.trunc(x)
>>> y
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> z = np.ceil(x)
>>> z
array([[ 1.,  3.],
       [ 2.,  3.]])
>>> t = np.floor(x)
>>> t
array([[ 1.,  2.],
       [ 1.,  2.]])
>>> a = np.rint(x)
>>> a
array([[ 1.,  2.],
       [ 1.,  3.]])

To make one of this in to int, or one of the other types in numpy, astype (as answered by BrenBern):

a.astype(int)
array([[1, 2],
       [1, 3]])

>>> y.astype(int)
array([[1, 2],
       [1, 2]])

How do I ignore files in Subversion?

You can also set a global ignore pattern in SVN's configuration file.

Remove Server Response Header IIS7

Actually the coded modules and the Global.asax examples shown above only work for valid requests.

For example, add < on the end of your URL and you will get a "Bad request" page which still exposes the server header. A lot of developers overlook this.

The registry settings shown do not work either. URLScan is the ONLY way to remove the "server" header (at least in IIS 7.5).

Inversion of Control vs Dependency Injection

1) DI is Child->obj depends on parent-obj. The verb depends is important. 2) IOC is Child->obj perform under a platform. where platform could be school, college, dance class. Here perform is an activity with different implication under any platform provider.

practical example: `

//DI
child.getSchool();
//IOC
child.perform()// is a stub implemented by dance-school
child.flourish()// is a stub implemented by dance-school/school/

`

-AB

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

When you have too complex objects with saveral collection could not be good idea to have all of them with EAGER fetchType, better use LAZY and when you really need to load the collections use: Hibernate.initialize(parent.child) to fetch the data.

Python Infinity - Any caveats?

A VERY BAD CAVEAT : Division by Zero

in a 1/x fraction, up to x = 1e-323 it is inf but when x = 1e-324 or little it throws ZeroDivisionError

>>> 1/1e-323
inf

>>> 1/1e-324
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero

so be cautious!

How to do integer division in javascript (Getting division answer in int not float)?

var x = parseInt(455/10);

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

'uint32_t' does not name a type

I had tha same problem trying to compile a lib I download from the internet. In my case, there was already a #include <cstdint> in the code. I solved it adding a:

using std::uint32_t;

How to create id with AUTO_INCREMENT on Oracle?

Here are three flavors:

  1. numeric. Simple increasing numeric value, e.g. 1,2,3,....
  2. GUID. globally univeral identifier, as a RAW datatype.
  3. GUID (string). Same as above, but as a string which might be easier to handle in some languages.

x is the identity column. Substitute FOO with your table name in each of the examples.

-- numerical identity, e.g. 1,2,3...
create table FOO (
    x number primary key
);
create sequence  FOO_seq;

create or replace trigger FOO_trg
before insert on FOO
for each row
begin
  select FOO_seq.nextval into :new.x from dual;
end;
/

-- GUID identity, e.g. 7CFF0C304187716EE040488AA1F9749A
-- use the commented out lines if you prefer RAW over VARCHAR2.
create table FOO (
    x varchar(32) primary key        -- string version
    -- x raw(32) primary key         -- raw version
);

create or replace trigger FOO_trg
before insert on FOO
for each row
begin
  select cast(sys_guid() as varchar2(32)) into :new.x from dual;  -- string version
  -- select sys_guid() into :new.x from dual;                     -- raw version
end;
/

update:

Oracle 12c introduces these two variants that don't depend on triggers:

create table mytable(id number default mysequence.nextval);
create table mytable(id number generated as identity);

The first one uses a sequence in the traditional way; the second manages the value internally.

jquery .live('click') vs .click()

Always use click if you not dynamically add elements.

live works by adding an event listener to the document root and listens for bubbled up events. An alternative is delegate, which works the same, but binds the event handler to the specified element.
This way, the event has not to bubble up the whole DOM and is caught earlier.

Control cannot fall through from one case label

You missed some breaks there:

switch (searchType)
{
    case "SearchBooks":
        Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
        break;

    case "SearchAuthors":
        Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
        Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
        break;
}

Without them, the compiler thinks you're trying to execute the lines below case "SearchAuthors": immediately after the lines under case "SearchBooks": have been executed, which isn't allowed in C#.

By adding the break statements at the end of each case, the program exits each case after it's done, for whichever value of searchType.

How to convert JSON string into List of Java object?

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});

Put content in HttpResponseMessage object?

For a string specifically, the quickest way is to use the StringContent constructor

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.

How to select option in drop down protractorjs e2e tests

For me worked like a charm

element(by.cssContainingText('option', 'BeaverBox Testing')).click();

How can I add a space in between two outputs?

Like this?

 System.out.println(Name + " " + Income);

Static link of shared library function in gcc

In gcc, this isn't supported. In fact, this isn't supported in any existing compiler/linker i'm aware of.

Get hours difference between two dates in Moment Js

There is a great moment method called fromNow() that will return the time from a specific time in nice human readable form, like this:

moment('2019-04-30T07:30:53.000Z').fromNow() // an hour ago || a day ago || 10 days ago

Or if you want that between two specific dates you can use:

var a = moment([2007, 0, 28]);
var b = moment([2007, 0, 29]);
a.from(b); // "a day ago"

Taken from the Docs:

How to get the first 2 letters of a string in Python?

In general, you can the characters of a string from i until j with string[i:j]. string[:2] is shorthand for string[0:2]. This works for arrays as well.

Learn about python's slice notation at the official tutorial

failed to load ad : 3

W/Ads: Failed to load ad: 3

It Means that your code is correct but due to less amount of request to the server your ads are not Visible. To check the Test ADS you Should put the code in loop for some time, and you have to give multiple requests so that your admob receives multiple requests and will load the ads immediately.

Add the below code

for(int i=0;i<1000;i++) {
            AdRequest adRequest = new AdRequest
                    .Builder()
                    .addTestDevice("B431EE858B5F1986E4D89CA31250F732")
                    .build();
            accountSettingsBinding.adView.loadAd(adRequest);
        } 

Restart Your application multiple times.

Remove the Loop after you start receiving ads.

How to detect when an Android app goes to the background and come back to the foreground

By using below code I'm able to get my app foreground or background state.

For more detail about it's working, strong text click here

import android.content.ComponentCallbacks2;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Context context;
private Toast toast;

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

private void showToast(String message) {
    //If toast is already showing cancel it
    if (toast != null) {
        toast.cancel();
    }

    toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
    toast.show();
}

@Override
protected void onStart() {
    super.onStart();
    showToast("App In Foreground");
}

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
        showToast("App In Background");
    }
  }
}

What's the Kotlin equivalent of Java's String[]?

For Strings and other types, you just use Array<*>. The reason IntArray and others exist is to prevent autoboxing.

So int[] relates to IntArray where Integer[] relates to Array<Int>.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

I prefer this solution:

df = spark.table(selected_table).filter(condition)

counter = df.count()

df = df.select([(counter - count(c)).alias(c) for c in df.columns])

How to center an element in the middle of the browser window?

If I understand you correct, you want to center the element vertically and horizontally based on the window, not the document. It can be a bit of a pain, but you can use javascript to detect the window size, scroll position, element size, etc. and then position the element in the center of the window (not the document, but the viewable window).

If you want this element to remain in the moddule of the window as you scroll you would need to capture the scroll event and adjust the position.

The code for doing this differs from one browser to the next.

How to change indentation in Visual Studio Code?

In my case "EditorConfig for VS Code" extention is overriding VSCode settings. If you have it installed, then check .editorconfig file in the root folder of the project.

Here is an example config. The "indent_size" sets the number of spaces for a tab.

# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

PHP cURL HTTP CODE return 0

If you're using selinux it might be because of security restrictions. Try setting this as root:

# setsebool -P httpd_can_network_connect on

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

How to convert date to string and to date again?

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Specifying number of decimal places in Python

I'm astonished by the second number you mention (and confirm by your requested rounding) -- at first I thought my instinct for mental arithmetic was starting to fail me (I am getting older, after all, so that might be going the same way as my once-sharp memory!-)... but then I confirmed it hasn't, yet, by using, as I imagine you are, Python 3.1, and copying and pasting..:

>>> def input_meal():  
...     mealPrice = input('Enter the meal subtotal: $')  
...     mealPrice = float (mealPrice)  
...     return mealPrice  
... 
>>> def calc_tax(mealPrice):  
...     tax = mealPrice*.06  
...     return tax
... 
>>> m = input_meal()
Enter the meal subtotal: $34.45
>>> print(calc_tax(m))
2.067
>>> 

...as expected -- yet, you say it instead "returns a display of $ 2.607"... which might be a typo, just swapping two digits, except that you then ask "How can I set that to $2.61 instead?" so it really seems you truly mean 2.607 (which might be rounded to 2.61 in various ways) and definitely not the arithmetically correct result, 2.067 (which at best might be rounded to 2.07... definitely not to 2.61 as you request).

I imagine you first had the typo occur in transcription, and then mentally computed the desired rounding from the falsified-by-typo 2.607 rather than the actual original result -- is that what happened? It sure managed to confuse me for a while!-)

Anyway, to round a float to two decimal digits, simplest approach is the built-in function round with a second argument of 2:

>>> round(2.067, 2)
2.07
>>> round(2.607, 2)
2.61

For numbers exactly equidistant between two possibilities, it rounds-to-even:

>>> round(2.605, 2)
2.6
>>> round(2.615, 2)
2.62

or, as the docs put it (exemplifying with the single-argument form of round, which rounds to the closest integer):

if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

However, for computations on money, I second the recommendation, already given in other answers, to stick with what the decimal module offers, instead of float numbers.

How to get the file path from URI?

Here is the answer to the question here

Actually we have to get it from the sharable ContentProvider of Camera Application.

EDIT . Copying answer that worked for me

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;

}

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Things change. The escape/unescape methods have been deprecated.

You can URI encode the string before you Base64-encode it. Note that this does't produce Base64-encoded UTF8, but rather Base64-encoded URL-encoded data. Both sides must agree on the same encoding.

See working example here: http://codepen.io/anon/pen/PZgbPW

// encode string
var base64 = window.btoa(encodeURIComponent('€ ?? æøåÆØÅ'));
// decode string
var str = decodeURIComponent(window.atob(tmp));
// str is now === '€ ?? æøåÆØÅ'

For OP's problem a third party library such as js-base64 should solve the problem.

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I had a similar error but for me it was react-router. Solved it by installing types for it.

npm install --save @types/react-router

Error:

(6,30): error TS7016: Could not find a declaration file for module 'react-router'. '\node_modules\react-router\index.js' implicitly has an 'any' type.

If you would like to disable it site wide you can instead edit tsconfig.json and set noImplicitAny to false.

Launch a shell command with in a python script, wait for the termination and return to the script

subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

http://docs.python.org/library/subprocess.html

Usage:

import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

How to change text transparency in HTML/CSS?

opacity applies to the whole element, so if you have a background, border or other effects on that element, those will also become transparent. If you only want the text to be transparent, use rgba.

#foo {
    color: #000; /* Fallback for older browsers */
    color: rgba(0, 0, 0, 0.5);

    font-size: 16pt;
    font-family: Arial, sans-serif;
}

Also, steer far, far away from <font>. We have CSS for that now.

Gaussian fit for Python

Here is corrected code:

import pylab as plb
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import asarray as ar,exp

x = ar(range(10))
y = ar([0,1,2,3,4,5,4,3,2,1])

n = len(x)                          #the number of data
mean = sum(x*y)/n                   #note this correction
sigma = sum(y*(x-mean)**2)/n        #note this correction

def gaus(x,a,x0,sigma):
    return a*exp(-(x-x0)**2/(2*sigma**2))

popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma])

plt.plot(x,y,'b+:',label='data')
plt.plot(x,gaus(x,*popt),'ro:',label='fit')
plt.legend()
plt.title('Fig. 3 - Fit for Time Constant')
plt.xlabel('Time (s)')
plt.ylabel('Voltage (V)')
plt.show()

result:
enter image description here

How to explain callbacks in plain english? How are they different from calling one function from another function?

Often an application needs to execute different functions based upon its context/state. For this, we use a variable where we would store the information about the function to be called. ?According to its need the application will set this variable with the information about function to be called and will call the function using the same variable.

In javascript, the example is below. Here we use method argument as a variable where we store information about function.

function processArray(arr, callback) {
    var resultArr = new Array(); 
    for (var i = arr.length-1; i >= 0; i--)
        resultArr[i] = callback(arr[i]);
    return resultArr;
}

var arr = [1, 2, 3, 4];
var arrReturned = processArray(arr, function(arg) {return arg * -1;});
// arrReturned would be [-1, -2, -3, -4]

How to apply style classes to td classes?

When using with a reactive bootstrap table, i did not find that the

table.classname td {

syntax worked as there was no <table> tag at all. Often modules like this don't use the outer tag but just dive right in maybe using <thead> and <tbody> for grouping at most.

Simply specifying like this worked great though

td.classname {
    max-width: 500px;
    text-overflow: initial;
    white-space: wrap;
    word-wrap: break-word;
}

as it directly overrides the <td> and can be used only on the elements you want to change. Maybe in your case use

thead.medium td {
  font-size: 40px; 
}
tbody.small td {
  font-size:25px;
}

for consistent font sizing with a bigger header.

Multiple WHERE clause in Linq

@Theo

The LINQ translator is smart enough to execute:

.Where(r => r.UserName !="XXXX" && r.UsernName !="YYYY")

I've test this in LinqPad ==> YES, Linq translator is smart enough :))

Detect a finger swipe through JavaScript on the iPhone and Android

If anyone is trying to use jQuery Mobile on Android and has problems with JQM swipe detection

(I had some on Xperia Z1, Galaxy S3, Nexus 4 and some Wiko phones too) this can be useful :

 //Fix swipe gesture on android
    if(android){ //Your own device detection here
        $.event.special.swipe.verticalDistanceThreshold = 500
        $.event.special.swipe.horizontalDistanceThreshold = 10
    }

Swipe on android wasn't detected unless it was a very long, precise and fast swipe.

With these two lines it works correctly

Return Type for jdbcTemplate.queryForList(sql, object, classType)

A complete solution for JdbcTemplate, NamedParameterJdbcTemplate with or without RowMapper Example.

// Create a Employee table

create table employee(  
id number(10),  
name varchar2(100),  
salary number(10)  
);

======================================================================= //Employee.java

public class Employee {
private int id;  
private String name;  
private float salary;  

//no-arg and parameterized constructors  

public Employee(){};

public Employee(int  id, String name, float salary){
    this.id=id;
    this.name=name;
    this.salary=salary;
}

//getters and setters  
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public float getSalary() {
    return salary;
}
public void setSalary(float salary) {
    this.salary = salary;
}
public String toString(){  
   return id+" "+name+" "+salary;  
}   

}

========================================================================= //EmployeeDao.java

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class EmployeeDao {  
  private JdbcTemplate jdbcTemplate;  
  private NamedParameterJdbcTemplate nameTemplate;  

  public void setnameTemplate(NamedParameterJdbcTemplate template) {  
    this.nameTemplate = template;  
 }   

 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  this.jdbcTemplate = jdbcTemplate;  
 }  

 // BY using JdbcTemplate
 public int saveEmployee(Employee e){  
 int id = e.getId();
 String name = e.getName();
 float salary = e.getSalary();
 Object p[] = {id, name, salary};
    String query="insert into employee values(?,?,?)";
      return jdbcTemplate.update(query, p);
    /*String query="insert into employee     values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; 
      return jdbcTemplate.update(query);
    */

}  

//By using NameParameterTemplate
public void insertEmploye(Employee e) {  
String query="insert into employee values (:id,:name,:salary)";  
Map<String,Object> map=new HashMap<String,Object>();  
map.put("id",e.getId());  
map.put("name",e.getName());  
map.put("salary",e.getSalary());  

nameTemplate.execute(query,map,new MyPreparedStatement());

 }
// Updating Employee
public int updateEmployee(Employee e){  
String query="update employee set  name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
  return jdbcTemplate.update(query);  
 }
 // Deleting a Employee row
 public int deleteEmployee(Employee e){  
 String query="delete from employee where id='"+e.getId()+"' ";  
 return jdbcTemplate.update(query);  
 }  
 //Selecting Single row with condition and also all rows
    public int selectEmployee(Employee e){  
     //String query="select * from employee where id='"+e.getId()+"' ";
      String query="select * from employee";
      List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
       for(Map<String, Object> row : rows){
          String id = row.get("id").toString();
          String name = (String)row.get("name");
          String salary = row.get("salary").toString();
          System.out.println(id + " " + name + " " + salary );
        }

      return 1;
   }  

   // Can use MyrowMapper class an implementation class for RowMapper interface
    public void getAllEmployee()
    {

    String query="select * from employee";
    List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());

    Iterator it=l.iterator();
    while(it.hasNext())
    {
      Employee e=(Employee)it.next();
      System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
    }
   }  

  //Can use directly a RowMapper implementation class without an object creation
  public List<Employee> getAllEmployee1(){
    return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){  
      @Override  
      public Employee mapRow(ResultSet rs, int rownumber) throws  SQLException    {  
            Employee e=new Employee();  
            e.setId(rs.getInt(1));  
            e.setName(rs.getString(2));  
            e.setSalary(rs.getFloat(3));  
            return e;  
          }  
      });  
      }
     // End of all the function

     }

================================================================ //MyrowMapper.java

 import java.sql.ResultSet;
 import java.sql.SQLException;
 import org.springframework.jdbc.core.RowMapper;

 public class MyrowMapper implements RowMapper<Employee> {

  @Override  
  public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
   {  
    System.out.println("mapRow()====:"+rownumber);
    Employee e=new Employee();  
     e.setId(rs.getInt("id"));  
     e.setName(rs.getString("name"));  
     e.setSalary(rs.getFloat("salary"));  
     return e;  
      }
    } 

========================================================== //MyPreparedStatement.java

import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;


 public class MyPreparedStatement implements  PreparedStatementCallback<Object> {

 @Override
 public Object doInPreparedStatement(PreparedStatement ps)
        throws SQLException, DataAccessException {

     return ps.executeUpdate(); 
  } 

 } 

===================================================================== //Test.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {  

public static void main(String[] args) {  
 ApplicationContext ctx=new     ClassPathXmlApplicationContext("applicationContext.xml");  

 EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); 

  // By calling constructor for insert
 /* 
    int status=dao.saveEmployee(new Employee(103,"Ajay",35000));  
    System.out.println(status);  
 */
 // By calling PreparedStatement
  dao.insertEmploye(new Employee(103,"Roh",25000));


 // By calling setter-getter for update
 /* 
    Employee e=new Employee(); 
    e.setId(102);
    e.setName("Rohit");
    e.setSalary(8000000);
    int status=dao.updateEmployee(e);
*/
 // By calling constructor for update
 /*
    int status=dao.updateEmployee(new Employee(102,"Sadhan",15000)); 
    System.out.println(status); 
 */ 
 // Deleting a record 
 /*      
    Employee e=new Employee(); 
    e.setId(102); 
    int status=dao.deleteEmployee(e); 
    System.out.println(status);
 */
 // Selecting single or all rows
 /*
    Employee e=new Employee(); 
    e.setId(102);
    int status=dao.selectEmployee(e);
    System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface

    dao.getAllEmployee();

// Can use directly a RowMapper implementation class without an object creation
 /*
    List<Employee> list=dao.getAllEmployee1();  
    for(Employee e1:list)  
    System.out.println(e1);  
  */   
   }  

 } 

================================================================== //applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
 xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans   
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="ds"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
 <property name="username" value="hr" />  
 <property name="password" value="hr" />  
 </bean>  

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
 <property name="dataSource" ref="ds"></property>  
 </bean>  

<bean id="nameTemplate"   
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
<constructor-arg ref="ds"></constructor-arg>  
</bean>  

<bean id="edao" class="EmployeeDao"> 
<!-- Can use both --> 
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property> 
</bean>  

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

How to remove duplicate values from a multi-dimensional array in PHP

I've given this problem a lot of thought and have determined that the optimal solution should follow two rules.

  1. For scalability, modify the array in place; no copying to a new array
  2. For performance, each comparison should be made only once

With that in mind and given all of PHP's quirks, below is the solution I came up with. Unlike some of the other answers, it has the ability to remove elements based on whatever key(s) you want. The input array is expected to be numeric keys.

$count_array = count($input);
for ($i = 0; $i < $count_array; $i++) {
    if (isset($input[$i])) {
        for ($j = $i+1; $j < $count_array; $j++) {
            if (isset($input[$j])) {
                //this is where you do your comparison for dupes
                if ($input[$i]['checksum'] == $input[$j]['checksum']) {
                    unset($input[$j]);
                }
            }
        }
    }
}

The only drawback is that the keys are not in order when the iteration completes. This isn't a problem if you're subsequently using only foreach loops, but if you need to use a for loop, you can put $input = array_values($input); after the above to renumber the keys.

How to replace all occurrences of a string in Javascript?

Update:

It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (\b)

'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"

This is a simple regex that avoids replacing parts of words in most cases. However, a dash - is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat:

'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"

basically, this question is the same as the question here: Javascript replace " ' " with " '' "

@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!

var newText = "the cat looks like a cat".split('cat').join('dog');

Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:

var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");

The output is the same as the accepted answer, however, using the /cat/g expression on this string:

var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ?? 

Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:

var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"

My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.

http://www.javascriptkit.com/jsref/regexp.shtml

http://www.regular-expressions.info


Final addition:

Given that this question still gets a lot of views, I thought I might add an example of .replace used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing both cat and cats in one go:

'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
   .replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
    {
       //check 1st, capitalize if required
       var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
       if (char1 === ' ' && char2 === 's')
       {//replace plurals, too
           cat = replacement + 's';
       }
       else
       {//do not replace if dashes are matched
           cat = char1 === '-' || char2 === '-' ? cat : replacement;
       }
       return char1 + cat + char2;//return replacement string
    });
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar

Run as java application option disabled in eclipse

Run As > Java Application wont show up if the class that you want to run does not contain the main method. Make sure that the class you trying to run has main defined in it.

How can I set a cookie in react?

By default, when you fetch your URL, React native sets the cookie.

To see cookies and make sure that you can use the https://www.npmjs.com/package/react-native-cookie package. I used to be very satisfied with it.

Of course, Fetch does this when it does

credentials: "include",// or "some-origin"

Well, but how to use it

--- after installation this package ----

to get cookies:

import Cookie from 'react-native-cookie';

Cookie.get('url').then((cookie) => {
   console.log(cookie);
});

to set cookies:

Cookie.set('url', 'name of cookies', 'value  of cookies');

only this

But if you want a few, you can do it

1- as nested:

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1')
        .then(() => {
            Cookie.set('url', 'name of cookies 2', 'value  of cookies 2')
            .then(() => {
                ...
            })
        })

2- as back together

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1');
Cookie.set('url', 'name of cookies 2', 'value  of cookies 2');
Cookie.set('url', 'name of cookies 3', 'value  of cookies 3');
....

Now, if you want to make sure the cookies are set up, you can get it again to make sure.

Cookie.get('url').then((cookie) => {
  console.log(cookie);
});

How to use BigInteger?

BigInteger is immutable. The javadocs states that add() "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change sum, you need to reassign the result of the add method to sum variable.

sum = sum.add(BigInteger.valueOf(i));

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Finding repeated words on a string and counting the repetitions

Using java8

private static void findWords(String s, List<String> output, List<Integer> count){
    String[] words = s.split(", ");
    Map<String, Integer> map = new LinkedHashMap<>();
    Arrays.stream(words).forEach(e->map.put(e, map.getOrDefault(e, 0) + 1));
    map.forEach((k,v)->{
        output.add(k);
        count.add(v);
    });
}

Also, use a LinkedHashMap if you want to preserve the order of insertion

private static void findWords(){
    String s = "House, House, House, Dog, Dog, Dog, Dog";
    List<String> output = new ArrayList<>();
    List<Integer> count = new ArrayList<>();
    findWords(s, output, count);
    System.out.println(output);
    System.out.println(count);
}

Output

[House, Dog]
[3, 4]

How to add click event to a iframe with JQuery

Try using this : iframeTracker jQuery Plugin, like that :

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});

How to set Toolbar text and back arrow color

If we follow the activity template created by Android Studios, it's the AppBarLayout that needs to have an android theme of AppBarOverlay, which you should define in the your styles.xml. That should give you your white color toobar/actionbar color text.

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">  ...

In styles.xml, make sure the following exists:

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

How to hide close button in WPF window?

Try adding a Closing event to the window. Add this code to the event handler.

e.Cancel = true;

This will prevent the window from closing. This has the same effect as hiding the close button.

PHP mPDF save file as PDF

Try this:

$mpdf->Output('my_filename.pdf','D'); 

because:

D - means Download
F - means File-save only

How do I grep for all non-ASCII characters?

In perl

perl -ane '{ if(m/[[:^ascii:]]/) { print  } }' fileName > newFile

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

jQuery UI Dialog - missing close icon

This is a comment on the top answer, but I felt it was worth its own answer because it helped me answer the problem.

If you want to keep Bootstrap declared after JQuery UI (I did because I wanted to use the Bootstrap tooltip), declaring the following (I declared it after $(document).ready) will allow the button to appear again (answer from https://stackoverflow.com/a/23428433/4660870)

var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton            // give $().bootstrapBtn the Bootstrap functionality

Does List<T> guarantee insertion order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?

Convert Rows to columns using 'Pivot' in SQL Server

Just give you some idea how other databases solve this problem. DolphinDB also has built-in support for pivoting and the sql looks much more intuitive and neat. It is as simple as specifying the key column (Store), pivoting column (Week), and the calculated metric (sum(xCount)).

//prepare a 10-million-row table
n=10000000
t=table(rand(100, n) + 1 as Store, rand(54, n) + 1 as Week, rand(100, n) + 1 as xCount)

//use pivot clause to generate a pivoted table pivot_t
pivot_t = select sum(xCount) from t pivot by Store, Week

DolphinDB is a columnar high performance database. The calculation in the demo costs as low as 546 ms on a dell xps laptop (i7 cpu). To get more details, please refer to online DolphinDB manual https://www.dolphindb.com/help/index.html?pivotby.html

Get access to parent control from user control - C#

Not Ideal, but try this...

Change the usercontrol to Component class (In the code editor), build the solution and remove all the code with errors (Related to usercontrols but not available in components so the debugger complains about it)

Change the usercontrol back to usercontrol class...

Now it recognises the name and parent property but shows the component as non-visual as it is no longer designable.

How do I get my solution in Visual Studio back online in TFS?

You can go use registry editor.

  1. Turn off all VS instances.
  2. Open registry editor and go to: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\TeamFoundation\Instances
  3. Find proper server e.g: team32system1
  4. Go to Collection and nex DefaultCollection: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\TeamFoundation\Instances\team32system1\Collections\DefaultCollection
  5. Set Offline key to 0
  6. Open solution in VS. Afterwards pop up should appear which question would you like bring solution to online mode.

NullPointerException in Java with no StackTrace

(Your question is still unclear on whether your code is calling printStackTrace() or this is being done by a logging handler.)

Here are some possible explanations about what might be happening:

  • The logger / handler being used has been configured to only output the exception's message string, not a full stack trace.

  • Your application (or some third-party library) is logging the exception using LOG.error(ex); rather than the 2-argument form of (for example) the log4j Logger method.

  • The message is coming from somewhere different to where you think it is; e.g. it is actually coming some third-party library method, or some random stuff left over from earlier attempts to debug.

  • The exception that is being logged has overloaded some methods to obscure the stacktrace. If that is the case, the exception won't be a genuine NullPointerException, but will be some custom subtype of NPE or even some unconnected exception.

I think that the last possible explanation is pretty unlikely, but people do at least contemplate doing this kind of thing to "prevent" reverse engineering. Of course it only really succeeds in making life difficult for honest developers.

Debugging WebSocket in Google Chrome

Chrome developer tools allows to see handshake request which stays pending during the opened connection, but you can't see traffic as far as I know. However you can sniff it for example.

Updating version numbers of modules in a multi-module Maven project

If you want to fully automate the process (i.e. you want to increment the version number without having to know what the current version number is), you can do this:

mvn build-helper:parse-version versions:set -DnewVersion=\${parsedVersion.majorVersion}.\${parsedVersion.minorVersion}.\${parsedVersion.nextIncrementalVersion} versions:commit

Vue equivalent of setTimeout?

It is likely a scope issue. Try the following instead:

addToBasket: function(){
    item = this.photo;
    this.$http.post('/api/buy/addToBasket', item);
    this.basketAddSuccess = true;
    var self = this;
    setTimeout(function(){
        self.basketAddSuccess = false;
    }, 2000);
}

How can I render repeating React elements?

This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:

Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)

kudos to https://php.quicoto.com/create-loop-inside-react-jsx/

How to delete only the content of file in python

You can do this:

def deleteContent(pfile):
    fn=pfile.name 
    pfile.close()
    return open(fn,'w')

What are .tpl files? PHP, web design

Number 3 hit on Google for "tpl file" (even though it's one of those annoying "Fix TPL errors now", "Scan TPL files with our virus scanner", sell-you-everything-under-the-sun-with-flashy-ugly-ads-when-all-you-wanted-was-the-file-description sites) is:

Used by PHP web development and PHP web applications as a template file. Mostly used by Smarty template engine. Template is a common text file (like .html file) and contains user defined variables that are replaced by user defined output content when PHP web application parsing a template file.

Convert an integer to a float number

intutils.ToFloat32

// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
    return float32(in)
}

// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
    return float64(in)
}

How to get URL parameter using jQuery or plain JavaScript?

http://example.com?sent=yes

Best solution here.

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.href);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
};

With the function above, you can get individual parameter values:

getUrlParameter('sent');

Return datetime object of previous month

I use this for government fiscal years where Q4 starts October 1st. Note I convert the date into quarters and undo it as well.

import pandas as pd

df['Date'] = '1/1/2020'
df['Date'] = pd.to_datetime(df['Date'])              #returns 2020-01-01
df['NewDate'] = df.Date - pd.DateOffset(months=3)    #returns 2019-10-01 <---- answer

# For fun, change it to FY Quarter '2019Q4'
df['NewDate'] = df['NewDate'].dt.year.astype(str) + 'Q' + df['NewDate'].dt.quarter.astype(str)

# Convert '2019Q4' back to 2019-10-01
df['NewDate'] = pd.to_datetime(df.NewDate)

How can I run PowerShell with the .NET 4 runtime?

The best solution I have found is in the blog post Using Newer Version(s) of .NET with PowerShell. This allows powershell.exe to run with .NET 4 assemblies.

Simply modify (or create) $pshome\powershell.exe.config so that it contains the following:

<?xml version="1.0"?> 
<configuration> 
    <startup useLegacyV2RuntimeActivationPolicy="true"> 
        <supportedRuntime version="v4.0.30319"/> 
        <supportedRuntime version="v2.0.50727"/> 
    </startup> 
</configuration> 

Additional, quick setup notes:

Locations and files are somewhat platform dependent; however will give you an inline gist of how to make the solution work for you.

  • You can find PowerShell's location on your computer by executing cd $pshome in the Powershell window (doesn't work from DOS prompt).
    • Path will be something like (example) C:\Windows\System32\WindowsPowerShell\v1.0\
  • The filename to put configuration in is: powershell.exe.config if your PowerShell.exe is being executed (create the config file if need be).
    • If PowerShellISE.Exe is running then you need to create its companion config file as PowerShellISE.Exe.config

Change the icon of the exe file generated from Visual Studio 2010

I found it easier to edit the project file directly e.g. YourApp.csproj.

You can do this by modifying ApplicationIcon property element:

<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>

Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.

EditorFor() and html properties

I solved this by creating an EditorTemplate named String.ascx in my /Views/Shared/EditorTemplates folder:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% int size = 10;
   int maxLength = 100;
   if (ViewData["size"] != null)
   {
       size = (int)ViewData["size"];
   }
   if (ViewData["maxLength"] != null)
   {
       maxLength = (int)ViewData["maxLength"];
   }
%>
<%= Html.TextBox("", Model, new { Size=size, MaxLength=maxLength }) %>

In my view, I use

<%= Html.EditorFor(model => model.SomeStringToBeEdited, new { size = 15, maxLength = 10 }) %>

Works like a charm for me!

How to start a background process in Python?

Note: This answer is less current than it was when posted in 2009. Using the subprocess module shown in other answers is now recommended in the docs

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)


If you want your process to start in the background you can either use system() and call it in the same way your shell script did, or you can spawn it:

import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

(or, alternatively, you may try the less portable os.P_NOWAIT flag).

See the documentation here.

Leap year calculation

In shell you can use cal -j YYYY which prints the julian day of the year, If the last julian day is 366, then it is a leap year.

$ function check_leap_year
 {
  year=$1
   if [ `cal -j $year | awk 'NF>0' | awk 'END { print $NF } '` -eq 366 ];
   then
      echo "$year -> Leap Year";
   else
      echo "$year -> Normal Year" ;
   fi
 }
$ check_leap_year 1900
1900 -> Normal Year
$ check_leap_year 2000
2000 -> Leap Year
$ check_leap_year 2001
2001 -> Normal Year
$ check_leap_year 2020
2020 -> Leap Year
$

Using awk, you can do

$ awk -v year=1900 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
365
$ awk -v year=2000 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
366
$ awk -v year=2001 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
365
$ awk -v year=2020 ' BEGIN { jul=strftime("%j",mktime(year " 12 31 0 0 0 ")); print jul } '
366
$

How can I make a program wait for a variable change in javascript?

I would recommend a wrapper that will handle value being changed. For example you can have JavaScript function, like this:

?function Variable(initVal, onChange)
{
    this.val = initVal;          //Value to be stored in this object
    this.onChange = onChange;    //OnChange handler

    //This method returns stored value
    this.GetValue = function()  
    {
        return this.val;
    }

    //This method changes the value and calls the given handler       
    this.SetValue = function(value)
    {
        this.val = value;
        this.onChange();
    }


}

And then you can make an object out of it that will hold value that you want to monitor, and also a function that will be called when the value gets changed. For example, if you want to be alerted when the value changes, and initial value is 10, you would write code like this:

var myVar = new Variable(10, function(){alert("Value changed!");});

Handler function(){alert("Value changed!");} will be called (if you look at the code) when SetValue() is called.

You can get value like so:

alert(myVar.GetValue());

You can set value like so:

myVar.SetValue(12);

And immediately after, an alert will be shown on the screen. See how it works: http://jsfiddle.net/cDJsB/

Access to the path is denied

Had a directory by the same name as the file i was trying to write, so people can look out for that as well.

How to use the 'main' parameter in package.json?

For OpenShift, you only get one PORT and IP pair to bind to (per application). It sounds like you should be able to serve both services from a single nodejs instance by adding internal routes for each service endpoint.

I have some info on how OpenShift uses your project's package.json to start your application here: https://www.openshift.com/blogs/run-your-nodejs-projects-on-openshift-in-two-simple-steps#package_json

127 Return code from $?

127 - command not found

example: $caat The error message will

bash:

caat: command not found

now you check using echo $?

Changing cursor to waiting in javascript/jquery

You don't need JavaScript for this. You can change the cursor to anything you want using CSS :

selector {
    cursor: url(myimage.jpg), auto;
}

See here for browser support as there are some subtle differences depending on browser

Yes or No confirm box using jQuery

I had trouble getting the answer back from the dialog box but eventually came up with a solution by combining the answer from this other question display-yes-and-no-buttons-instead-of-ok-and-cancel-in-confirm-box with part of the code from the modal-confirmation dialog

This is what was suggested for the other question:

Create your own confirm box:

<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>

Create your own confirm() method:

function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

Call it by your code:

doConfirm("Are you sure?", function yes()
{
    form.submit();
}, function no()
{
    // do nothing
});

MY CHANGES I have tweaked the above so that instead of calling confirmBox.show() I used confirmBox.dialog({...}) like this

confirmBox.dialog
    ({
      autoOpen: true,
      modal: true,
      buttons:
        {
          'Yes': function () {
            $(this).dialog('close');
            $(this).find(".yes").click();
          },
          'No': function () {
            $(this).dialog('close');
            $(this).find(".no").click();
          }
        }
    });

The other change I made was to create the confirmBox div within the doConfirm function, like ThulasiRam did in his answer.

How to throw a C++ exception

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

rbind error: "names do not match previous names"

rbind() needs the two object names to be the same. For example, the first object names: ID Age, the next object names: ID Gender,if you want to use rbind(), it will print out:

names do not match previous names

How to detect online/offline event cross-browser?

The best way which works now on all Major Browsers is the following Script:

(function () {
    var displayOnlineStatus = document.getElementById("online-status"),
        isOnline = function () {
            displayOnlineStatus.innerHTML = "Online";
            displayOnlineStatus.className = "online";
        },
        isOffline = function () {
            displayOnlineStatus.innerHTML = "Offline";
            displayOnlineStatus.className = "offline";
        };

    if (window.addEventListener) {
        /*
            Works well in Firefox and Opera with the 
            Work Offline option in the File menu.
            Pulling the ethernet cable doesn't seem to trigger it.
            Later Google Chrome and Safari seem to trigger it well
        */
        window.addEventListener("online", isOnline, false);
        window.addEventListener("offline", isOffline, false);
    }
    else {
        /*
            Works in IE with the Work Offline option in the 
            File menu and pulling the ethernet cable
        */
        document.body.ononline = isOnline;
        document.body.onoffline = isOffline;
    }
})();

Source: http://robertnyman.com/html5/offline/online-offline-events.html

Android SeekBar setOnSeekBarChangeListener

Seekbar called onProgressChanged method when we initialize first time. We can skip by using below code We need to check boolean it return false when initialize automatically

volumeManager.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(b){
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

Using regular expressions to do mass replace in Notepad++ and Vim

In Notepad++ :

<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D


Find what: (.*)(>)(.)
Replace with: \3

Replace All


A
B
C
D

SyntaxError: non-default argument follows default argument

Let me clarify two points here :

  • Firstly non-default argument should not follow the default argument, it means you can't define (a = 'b',c) in function. The correct order of defining parameter in function are :
  • positional parameter or non-default parameter i.e (a,b,c)
  • keyword parameter or default parameter i.e (a = 'b',r= 'j')
  • keyword-only parameter i.e (*args)
  • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(*ab) is var-keyword parameter

so first re-arrange your parameters

  • now the second thing is you have to define len1 when you are doing hgt=len1 the len1 argument is not defined when default values are saved, Python computes and saves default values when you define the function len1 is not defined, does not exist when this happens (it exists only when the function is executed)

so second remove this "len1 = hgt" it's not allowed in python.

keep in mind the difference between argument and parameters.

Get the index of a certain value in an array in PHP

You'll have to create a function for this. I don't think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

<?php

$given_array = array('Monday' => 'boring',
'Friday' => 'yay',
'boring',
'Sunday' => 'fun',
7 => 'boring',
'Saturday' => 'yay fun',
'Wednesday' => 'boring',
'my life' => 'boring');

$repeating_value = "boring";

function array_value_positions($array, $value){
    $index = 0;
    $value_array = array();
        foreach($array as $v){
            if($value == $v){
                $value_array[$index] = $value;
            }
        $index++;
        }
    return $value_array;
}

$value_array = array_value_positions($given_array, $repeating_value);

$result = "The value '$value_array[0]' was found at these indices in the given array: ";

$key_string = implode(', ',array_keys($value_array));

echo $result . $key_string . "\n";//Output: The value 'boring' was found at these indices in the given array: 0, 2, 4, 6, 7

Remove duplicate rows in MySQL

I have this query snipet for SQLServer but I think It can be used in others DBMS with little changes:

DELETE
FROM Table
WHERE Table.idTable IN  (  
    SELECT MAX(idTable)
    FROM idTable
    GROUP BY field1, field2, field3
    HAVING COUNT(*) > 1)

I forgot to tell you that this query doesn't remove the row with the lowest id of the duplicated rows. If this works for you try this query:

DELETE
FROM jobs
WHERE jobs.id IN  (  
    SELECT MAX(id)
    FROM jobs
    GROUP BY site_id, company, title, location
    HAVING COUNT(*) > 1)