Programs & Examples On #Marker interfaces

Excluding Maven dependencies

Global exclusions look like they're being worked on, but until then...

From the Sonatype maven reference (bottom of the page):

Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

As an example:

  <dependencies>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
      <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <exclusions>
          <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
          </exclusion>
        </exclusions>
      </dependency>
    </dependencies>
  </dependencyManagement>

It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

Disable activity slide-in animation when launching new activity?

IMHO this answer here solve issue in the most elegant way..

Developer should create a style,

<style name="noAnimTheme" parent="android:Theme">
  <item name="android:windowAnimationStyle">@null</item>
</style>

then in manifest set it as theme for activity or whole application.

<activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
</activity>

Voila! Nice and easy..

P.S. credits to original author please

What does 'git blame' do?

From git-blame:

Annotates each line in the given file with information from the revision which last modified the line. Optionally, start annotating from the given revision.

When specified one or more times, -L restricts annotation to the requested lines.

Example:

[email protected]:~# git blame .htaccess
...
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  4) allow from all
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  5)
^e1fb2d7 (John Doe 2015-07-03 06:30:25 -0300  6) <IfModule mod_rewrite.c>
^72fgsdl (Arthur King 2015-07-03 06:34:12 -0300  7)     RewriteEngine On
...

Please note that git blame does not show the per-line modifications history in the chronological sense. It only shows who was the last person to have changed a line in a document up to the last commit in HEAD.

That is to say that in order to see the full history/log of a document line, you would need to run a git blame path/to/file for each commit in your git log.

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

Fill username and password using selenium in python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait

# If you want to open Chrome
driver = webdriver.Chrome()
# If you want to open Firefox
driver = webdriver.Firefox()

username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")
username.send_keys("YourUsername")
password.send_keys("YourPassword")
driver.find_element_by_id("submit_btn").click()

How to get a list of column names

SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

Then parse this value with Reg Exp (it's easy) which could looks similar to this: [(.*?)]

Alternatively you can use:

PRAGMA table_info(table_name)

How to convert nanoseconds to seconds using the TimeUnit enum?

TimeUnit Enum

The following expression uses the TimeUnit enum (Java 5 and later) to convert from nanoseconds to seconds:

TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS)

Rails 3 check if attribute changed

For rails 5.1+ callbacks

As of Ruby on Rails 5.1, the attribute_changed? and attribute_was ActiveRecord methods will be deprecated

Use saved_change_to_attribute? instead of attribute_changed?

@user.saved_change_to_street1? # => true/false

More examples here

Android textview outline text

credit to @YGHM add shadow support enter image description here

package com.megvii.demo;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;

public class TextViewOutline extends android.support.v7.widget.AppCompatTextView {

// constants
private static final int DEFAULT_OUTLINE_SIZE = 0;
private static final int DEFAULT_OUTLINE_COLOR = Color.TRANSPARENT;

// data
private int mOutlineSize;
private int mOutlineColor;
private int mTextColor;
private float mShadowRadius;
private float mShadowDx;
private float mShadowDy;
private int mShadowColor;

public TextViewOutline(Context context) {
    this(context, null);
}

public TextViewOutline(Context context, AttributeSet attrs) {
    super(context, attrs);
    setAttributes(attrs);
}

private void setAttributes(AttributeSet attrs) {
    // set defaults
    mOutlineSize = DEFAULT_OUTLINE_SIZE;
    mOutlineColor = DEFAULT_OUTLINE_COLOR;
    // text color   
    mTextColor = getCurrentTextColor();
    if (attrs != null) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextViewOutline);
        // outline size
        if (a.hasValue(R.styleable.TextViewOutline_outlineSize)) {
            mOutlineSize = (int) a.getDimension(R.styleable.TextViewOutline_outlineSize, DEFAULT_OUTLINE_SIZE);
        }
        // outline color
        if (a.hasValue(R.styleable.TextViewOutline_outlineColor)) {
            mOutlineColor = a.getColor(R.styleable.TextViewOutline_outlineColor, DEFAULT_OUTLINE_COLOR);
        }
        // shadow (the reason we take shadow from attributes is because we use API level 15 and only from 16 we have the get methods for the shadow attributes)
        if (a.hasValue(R.styleable.TextViewOutline_android_shadowRadius)
                || a.hasValue(R.styleable.TextViewOutline_android_shadowDx)
                || a.hasValue(R.styleable.TextViewOutline_android_shadowDy)
                || a.hasValue(R.styleable.TextViewOutline_android_shadowColor)) {
            mShadowRadius = a.getFloat(R.styleable.TextViewOutline_android_shadowRadius, 0);
            mShadowDx = a.getFloat(R.styleable.TextViewOutline_android_shadowDx, 0);
            mShadowDy = a.getFloat(R.styleable.TextViewOutline_android_shadowDy, 0);
            mShadowColor = a.getColor(R.styleable.TextViewOutline_android_shadowColor, Color.TRANSPARENT);
        }

        a.recycle();
    }

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setPaintToOutline();
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

private void setPaintToOutline() {
    Paint paint = getPaint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(mOutlineSize);
    super.setTextColor(mOutlineColor);
    super.setShadowLayer(0, 0, 0, Color.TRANSPARENT);

}

private void setPaintToRegular() {
    Paint paint = getPaint();
    paint.setStyle(Paint.Style.FILL);
    paint.setStrokeWidth(0);
    super.setTextColor(mTextColor);
    super.setShadowLayer(mShadowRadius, mShadowDx, mShadowDy, mShadowColor);
}


@Override
public void setTextColor(int color) {
    super.setTextColor(color);
    mTextColor = color;
}


public void setOutlineSize(int size) {
    mOutlineSize = size;
}

public void setOutlineColor(int color) {
    mOutlineColor = color;
}

@Override
protected void onDraw(Canvas canvas) {
    setPaintToOutline();
    super.onDraw(canvas);

    setPaintToRegular();
    super.onDraw(canvas);
}

}

attr define

<declare-styleable name="TextViewOutline">
    <attr name="outlineSize" format="dimension"/>
    <attr name="outlineColor" format="color|reference"/>
    <attr name="android:shadowRadius"/>
    <attr name="android:shadowDx"/>
    <attr name="android:shadowDy"/>
    <attr name="android:shadowColor"/>
</declare-styleable>

xml code below

<com.megvii.demo.TextViewOutline
    android:id="@+id/product_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="110dp"
    android:background="#f4b222"
    android:fontFamily="@font/kidsmagazine"
    android:padding="10dp"
    android:shadowColor="#d7713200"
    android:shadowDx="0"
    android:shadowDy="8"
    android:shadowRadius="1"
    android:text="LIPSTICK SET"
    android:textColor="@android:color/white"
    android:textSize="30sp"
    app:outlineColor="#cb7800"
    app:outlineSize="3dp" />

linux script to kill java process

Use jps to list running java processes. The command returns the process id along with the main class. You can use kill command to kill the process with the returned id or use following one liner script.

kill $(jps | grep <MainClass> | awk '{print $1}')

MainClass is a class in your running java program which contains the main method.

Is there a git-merge --dry-run option?

Git introduced a --ff-only option when merging.

From: http://git-scm.com/docs/git-merge


--ff-only

Refuse to merge and exit with a non-zero status unless the current HEAD is already up-to-date or the merge can be resolved as a fast-forward.

Doing this will attempt to merge and fast-forward, and if it can't it aborts and prompts you that the fast-forward could not be performed, but leaves your working branch untouched. If it can fast-forward, then it will perform the merge on your working branch. This option is also available on git pull. Thus, you could do the following:

git pull --ff-only origin branchA #See if you can pull down and merge branchA

git merge --ff-only branchA branchB #See if you can merge branchA into branchB

Is background-color:none valid CSS?

The answer is no.

Incorrect

.class {
    background-color: none; /* do not do this */
}

Correct

.class {
    background-color: transparent;
}

background-color: transparent accomplishes the same thing what you wanted to do with background-color: none.

Importing modules from parent folder

Relative imports (as in from .. import mymodule) only work in a package. To import 'mymodule' that is in the parent directory of your current module:

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

import mymodule

edit: the __file__ attribute is not always given. Instead of using os.path.abspath(__file__) I now suggested using the inspect module to retrieve the filename (and path) of the current file

What is the difference between String and StringBuffer in Java?

From the API:

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

What is a provisioning profile used for when developing iPhone applications?

You need it to install development iPhone applications on development devices.

Here's how to create one, and the reference for this answer:
http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone

Another link: http://iphone.timefold.com/provisioning.html

React Native fixed footer

You might also want to take a look at NativeBase (http://nativebase.io). This a library of components for React Native that include some nice layout structure (http://nativebase.io/docs/v2.0.0/components#anatomy) including Headers and Footers.

It's a bit like Bootstrap for Mobile.

Classes vs. Modules in VB.NET

It is acceptable to use Module. Module is not used as a replacement for Class. Module serves its own purpose. The purpose of Module is to use as a container for

  • extension methods,
  • variables that are not specific to any Class, or
  • variables that do not fit properly in any Class.

Module is not like a Class since you cannot

  • inherit from a Module,
  • implement an Interface with a Module,
  • nor create an instance of a Module.

Anything inside a Module can be directly accessed within the Module assembly without referring to the Module by its name. By default, the access level for a Module is Friend.

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

Maybe your application is compiled with a different JRE than Tomcat.

Check java -version on your server and then compile your code with the same version. I had the error because my Eclipse standard JRE was 1.6 and Tomcat used 1.5 - this can't work.

Dynamically change color to lighter or darker by percentage CSS (Javascript)

If you need to brute force it for older browser compatibility, you can use Colllor to automatically select similar color variations.

Example (color: #a9dbb4):

enter image description here

Clear text in EditText when entered

For Kotlin:

Create two extensions, one for EditText and one for TextView

EditText:

fun EditText.clear() { text.clear() }

TextView:

fun TextView.clear() { text = "" }

and use it like

myEditText.clear()

myTextView.clear()

Why don’t my SVG images scale using the CSS "width" property?

Open SVG using any text editor and remove width and height attributes from the root node.

Before

<svg width="12px" height="20px" viewBox="0 0 12 20" ...

After

<svg viewBox="0 0 12 20" ...

Now the image will always fill all the available space and will scale using CSS width and height. It will not stretch though so it will only grow to available space.

How to make a <div> appear in front of regular text/tables

z-index only works on absolute or relatively positioned elements. I would use an outer div set to position relative. Set the div on top to position absolute to remove it from the flow of the document.

_x000D_
_x000D_
.wrapper {position:relative;width:500px;}_x000D_
_x000D_
.front {_x000D_
  border:3px solid #c00;_x000D_
  background-color:#fff;_x000D_
  width:300px;_x000D_
  position:absolute;_x000D_
  z-index:10;_x000D_
  top:30px;_x000D_
  left:50px;_x000D_
 }_x000D_
  _x000D_
.behind {background-color:#ccc;}
_x000D_
<div class="wrapper">_x000D_
    <p class="front">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>_x000D_
    <div class="behind">_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
        <table>_x000D_
            <thead>_x000D_
                <tr>_x000D_
                    <th>aaa</th>_x000D_
                    <th>bbb</th>_x000D_
                    <th>ccc</th>_x000D_
                    <th>ddd</th>_x000D_
                </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
                <tr>_x000D_
                    <td>111</td>_x000D_
                    <td>222</td>_x000D_
                    <td>333</td>_x000D_
                    <td>444</td>_x000D_
                </tr>_x000D_
            </tbody>_x000D_
        </table>_x000D_
        <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>_x000D_
    </div> _x000D_
</div> 
_x000D_
_x000D_
_x000D_

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

Getting title and meta tags from external website

Now a days, most of the sites add meta tags to their sites providing information about their site or any particular article page. Such as news or blog sites.

I have created a Meta API which gives you required meta data ac like OpenGraph, Schema.Org, etc.

Check it out - https://api.sakiv.com/docs

Find index of last occurrence of a sub-string using T-SQL

If you are using Sqlserver 2005 or above, using REVERSE function many times is detrimental to performance, below code is more efficient.

DECLARE @FilePath VARCHAR(50) = 'My\Super\Long\String\With\Long\Words'
DECLARE @FindChar VARCHAR(1) = '\'

-- Shows text before last slash
SELECT LEFT(@FilePath, LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath))) AS Before
-- Shows text after last slash
SELECT RIGHT(@FilePath, CHARINDEX(@FindChar,REVERSE(@FilePath))-1) AS After
-- Shows the position of the last slash
SELECT LEN(@FilePath) - CHARINDEX(@FindChar,REVERSE(@FilePath)) AS LastOccuredAt

How does cookie based authentication work?

I realize this is years late, but I thought I could expand on Conor's answer and add a little bit more to the discussion.

Can someone give me a step by step description of how cookie based authentication works? I've never done anything involving either authentication or cookies. What does the browser need to do? What does the server need to do? In what order? How do we keep things secure?

Step 1: Client > Signing up

Before anything else, the user has to sign up. The client posts a HTTP request to the server containing his/her username and password.

Step 2: Server > Handling sign up

The server receives this request and hashes the password before storing the username and password in your database. This way, if someone gains access to your database they won't see your users' actual passwords.

Step 3: Client > User login

Now your user logs in. He/she provides their username/password and again, this is posted as a HTTP request to the server.

Step 4: Server > Validating login

The server looks up the username in the database, hashes the supplied login password, and compares it to the previously hashed password in the database. If it doesn't check out, we may deny them access by sending a 401 status code and ending the request.

Step 5: Server > Generating access token

If everything checks out, we're going to create an access token, which uniquely identifies the user's session. Still in the server, we do two things with the access token:

  1. Store it in the database associated with that user
  2. Attach it to a response cookie to be returned to the client. Be sure to set an expiration date/time to limit the user's session

Henceforth, the cookies will be attached to every request (and response) made between the client and server.

Step 6: Client > Making page requests

Back on the client side, we are now logged in. Every time the client makes a request for a page that requires authorization (i.e. they need to be logged in), the server obtains the access token from the cookie and checks it against the one in the database associated with that user. If it checks out, access is granted.

This should get you started. Be sure to clear the cookies upon logout!

How can I get current date in Android?

This is the code I used:

final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

// Set current date into textview
tvDisplayDate.setText(new StringBuilder()
    .append(month + 1).append("-") // Month is 0 based, add 1
    .append(day).append("-")
    .append(year).append("   Today is :" + thursday ) );

// Set current date into datepicker
dpResult.init(year, month, day, null);

How can I know when an EditText loses focus?

Its Working Properly

EditText et_mobile= (EditText) findViewById(R.id.edittxt);

et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {          
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            // code to execute when EditText loses focus
            if (et_mobile.getText().toString().trim().length() == 0) {
                CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
            }
        }
    }
});



public static void showAlert(String message, Activity context) {

    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message).setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    try {
        builder.show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

How do I see which checkbox is checked?

you can check that by either isset() or empty() (its check explicit isset) weather check box is checked or not

for example

  <input type='checkbox' name='Mary' value='2' id='checkbox' />

here you can check by

if (isset($_POST['Mary'])) {
    echo "checked!";
}

or

if (!empty($_POST['Mary'])) {
    echo "checked!";
}

the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like

<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />

php

  $aDoor = $_POST['formDoor'];
  if(empty($aDoor))
  {
    echo("You didn't select any buildings.");
  }
  else
  {
    $N = count($aDoor);
    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo htmlspecialchars($aDoor[$i] ). " ";
    }
  }

How to improve Netbeans performance?

Don't invest time in optimizing your NB installation as long as you can scale vertically: get a SSD (and faster hardware in general).

Also:

  • Add an exception for all relevant folders (e.g. project dir, temp dir) to your anti virus software (or better, get rid of it).
  • Don't use network drives for your projects
    • check if your home drive is local
    • check if your IDE uses non-local folders (e.g. %AppData%)

Open Excel file for reading with VBA without display

Even though you've got your answer, for those that find this question, it is also possible to open an Excel spreadsheet as a JET data store. Borrowing the connection string from a project I've used it on, it will look kinda like this:

strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & objFile.Path & ";Extended Properties=""Excel 8.0;HDR=Yes"""
strSQL = "SELECT * FROM [RegistrationList$] ORDER BY DateToRegister DESC"

Note that "RegistrationList" is the name of the tab in the workbook. There are a few tutorials floating around on the web with the particulars of what you can and can't do accessing a sheet this way.

Just thought I'd add. :)

How can I force users to access my page over HTTPS instead of HTTP?

If you want to use PHP to do this then this way worked really well for me:


<?php

if(!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on") {
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"], true, 301);
    //Prevent the rest of the script from executing.
    exit;
}
?>

It checks the HTTPS variable in the $_SERVER superglobal array to see if it equal to “on”. If the variable is not equal to on.

Java check if boolean is null

null is a value assigned to a reference type. null is a reserved value, indicating that a reference does not resemble an instance of an object.

A boolean is not an instance of an Object. It is a primitive type, like int and float. In the same way that: int x has a value of 0, boolean x has a value of false.

How to embed images in email

Actually, there are two ways to include images in email.

The first way ensures that the user will see the image, even if in some cases it’s only as an attachment to the message. This method is exactly what we call as “embedding images in email" in daily life.
Essentially, you’re attaching the image to the email. The plus side is that, in one way or another, the user is sure to get the image. While the downside is two fold. Firstly, spam filters look for large, embedded images and often give you a higher spam score for embedding images in email (Lots of spammers use images to avoid having the inappropriate content in their emails read by the spam filters.). Secondly, if you pay to send your email by weight or kilobyte, this increases the size of your message. If you’re not careful, it can even make your message too big for the parameters of the email provider.

The second way to include images (and the far more common way) is the same way that you put an image on a web page. Within the email, you provide a url that is the reference to the image’s location on your server, exactly the same way that you would on a web page. This has several benefits. Firstly, you won’t get caught for spamming or for your message “weighing” too much because of the image. Secondly, you can make changes to the images after the email has been sent if you find errors in them. On the flip side, your recipient will need to actively turn on image viewing in their email client to see your images.

delete all from table

This should be faster:

DELETE * FROM table_name;

because RDBMS don't have to look where is what.

You should be fine with truncate though:

truncate table table_name

How can you determine a point is between two other points on a line segment?

Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.

But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b.

In non-optimized pseudocode:

def isBetween(a, b, c):
    crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)

    # compare versus epsilon for floating point values, or != 0 if using integers
    if abs(crossproduct) > epsilon:
        return False

    dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
    if dotproduct < 0:
        return False

    squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
    if dotproduct > squaredlengthba:
        return False

    return True

How does Google reCAPTCHA v2 work behind the scenes?

Please remember that Google also use reCaptcha together with

Canvas fingerprinting 

to uniquely recognize User/Browsers without cookies!

Java: Array with loop

The Array has declared without intializing the values and if you want to insert values by itterating the loop this code will work.

Public Class Program
{

public static void main(String args[])

{
 //Array Intialization
 int my[] = new int[6];

 for(int i=0;i<=5;i++)

{

//Storing array values in array
my[i]= i;

//Printing array values

System.out.println(my[i]);

}

}

}

How is a JavaScript hash map implemented?

<html>
<head>
<script type="text/javascript">
function test(){
var map= {'m1': 12,'m2': 13,'m3': 14,'m4': 15}
     alert(map['m3']);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="test()"/>
</body>
</html>

Draw Circle using css alone

yes it is possible you can use border-radius CSS property. For more info have a look at http://zeeshanmkhan.com/post/2/css-rounded-corner-gradient-drop-shadow-and-opacity

Installing a plain plugin jar in Eclipse 3.5

Simplest way - just put in the Eclipse plugins folder. You can start Eclipse with the -clean option to make sure Eclipse cleans its' plugins cache and sees the new plugin.

In general, it is far more recommended to install plugins using proper update sites.

Is quitting an application frowned upon?

If you are unable to fathom how to make your data/connections (and thereby your "application") persistent, then you will be unable to do what you "need" to do with Android.

Those who do download those cutesy little App Killers usually find they do not help battery life or memory usage, but hinder the OS from doing it's job of managing memory efficiently...

http://android-developers.blogspot.com/2010/04/multitasking-android-way.html

Powershell import-module doesn't find modules

I think that the Import-Module is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules.

Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules

Can Console.Clear be used to only clear a line instead of whole console?

"ClearCurrentConsoleLine", "ClearLine" and the rest of the above functions should use Console.BufferWidth instead of Console.WindowWidth (you can see why when you try to make the window smaller). The window size of the console currently depends of its buffer and cannot be wider than it. Example (thanks goes to Dan Cornilescu):

public static void ClearLastLine()
{
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.BufferWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

index.php not loading by default

Try creating a .htaccess file with the following

DirectoryIndex index.php

Edit: Actually, isn't there a 'php-apache' package or something that you're supposed to install with both of them?

Ansible - Use default if a variable is not defined

You can use Jinja's default:

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"

box-shadow on bootstrap 3 container

http://jsfiddle.net/Y93TX/2/

     @import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");

.row {
    height: 100px;
    background-color: green;
}
.container {
    margin-top: 50px;
    box-shadow: 0 0 30px black;
    padding:0 15px 0 15px;
}



    <div class="container">
        <div class="row">one</div>
        <div class="row">two</div>
        <div class="row">three</div>
    </div>
</body>

What is the equivalent of ngShow and ngHide in Angular 2+?

Use hidden like you bind any model with control and specify css for it:

HTML:

<input type="button" class="view form-control" value="View" [hidden]="true" />

CSS:

[hidden] {
   display: none;
}

How Do I Take a Screen Shot of a UIView?

There is new API from iOS 10

extension UIView {
    func makeScreenshot() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
        return renderer.image { (context) in
            self.layer.render(in: context.cgContext)
        }
    }
}

Take screenshots in the iOS simulator

For people using Xcode 11.4, to get rid of the simulator top bar, this is far from ideal but you can disable shadows for the screenshot application in a terminal with the following command :

$ defaults write com.apple.screencapture disable-shadow -bool TRUE; killall SystemUIServer

Then, you can use ? + ? + 4 and select the simulator to take a screenshot. Without the shadow, you can easily crop the top bar with the preview app. To re-enable the shadow for the screenshot application :

$ defaults write com.apple.screencapture disable-shadow -bool FALSE; killall SystemUIServer

Source of this answer here.

Difference between binary semaphore and mutex

"binary semaphore" is a programming language circumvent to use a «semaphore» like «mutex». Apparently there are two very big differences:

  1. The way you call each one of them.

  2. The maximum length of the "identifier".

Add php variable inside echo statement as href link address?

If you want to print in the tabular form with, then you can use this:

echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;

What does __FILE__ mean in Ruby?

__FILE__ is the filename with extension of the file containing the code being executed.

In foo.rb, __FILE__ would be "foo.rb".

If foo.rb were in the dir /home/josh then File.dirname(__FILE__) would return /home/josh.

C default arguments

Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.

In funcB() i use a special value (-1) to signal that i need the default value for the 'b' parameter.

#include <stdio.h> 

int funcA( int a, int b, ... ){ return a+b; }
#define funcA( a, ... ) funcA( a, ##__VA_ARGS__, 8 ) 


int funcB( int a, int b ){
  if( b == -1 ) b = 8;
  return a+b;
}

int main(void){
  printf("funcA(1,2): %i\n", funcA(1,2) );
  printf("funcA(1):   %i\n", funcA(1)   );

  printf("funcB(1, 2): %i\n", funcB(1, 2) );
  printf("funcB(1,-1): %i\n", funcB(1,-1) );
}

How to find prime numbers between 0 - 100?

You can try this method also, this one is basic but easy to understand:

 var tw = 2, th = 3, fv = 5, se = 7; 

 document.write(tw + "," + th + ","+ fv + "," + se + ",");


for(var n = 0; n <= 100; n++)
{

  if((n % tw !== 0) && (n % th !==0) && (n % fv !==0 ) && (n % se !==0))

  {
      if (n == 1)
      {
          continue;
      }

    document.write(n +",");
  }
}

sudo echo "something" >> /etc/privilegedFile doesn't work

The problem is that the shell does output redirection, not sudo or echo, so this is being done as your regular user.

Try the following code snippet:

sudo sh -c "echo 'something' >> /etc/privilegedfile"

Getting the HTTP Referrer in ASP.NET

Like this: HttpRequest.UrlReferrer Property

Uri myReferrer = Request.UrlReferrer;
string actual = myReferrer.ToString();

Removing MySQL 5.7 Completely

Run these commands in the terminal:

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo apt-get autoremove

sudo apt-get autoclean

Run these commands separately as each command requires confirmation & if run as a block, the command below the one currently running will cancel the confirmation (leading to the command not being run).

Please refer to How do I uninstall Mysql?

How to get the user input in Java?

Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.

import java.util.Scanner;

public class PrintNumber {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = 0;
        int sum = 0;

        System.out.println(
            "Please enter a number to show its digits");
        num = scan.nextInt();

        System.out.println(
            "Here are the digits and the sum of the digits");
        while (num > 0) {
            System.out.println("==>" + num % 10);
            sum += num % 10;
            num = num / 10;   
        }
        System.out.println("Sum is " + sum);            
    }
}

Runnable with a parameter?

Since Java 8, the best answer is to use Consumer<T>:

https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html

It's one of the functional interfaces, which means you can call it as a lambda expression:

void doSomething(Consumer<String> something) {
    something.accept("hello!");
}

...

doSomething( (something) -> System.out.println(something) )

...

Listing files in a specific "folder" of a AWS S3 bucket

Based on @davioooh answer. This code is worked for me.

ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName("your-bucket")
            .withPrefix("your/folder/path/").withDelimiter("/");

htaccess "order" Deny, Allow, Deny

Just use order allow,deny instead and remove the deny from all line.

Code not running in IE 11, works fine in Chrome

String.prototype.startsWith is a standard method in the most recent version of JavaScript, ES6.

Looking at the compatibility table below, we can see that it is supported on all current major platforms, except versions of Internet Explorer.

+-------------------------------------------------------------------------------+
¦    Feature    ¦ Chrome ¦ Firefox ¦ Edge  ¦ Internet Explorer ¦ Opera ¦ Safari ¦
¦---------------+--------+---------+-------+-------------------+-------+--------¦
¦ Basic Support ¦    41+ ¦     17+ ¦ (Yes) ¦ No Support        ¦    28 ¦      9 ¦
+-------------------------------------------------------------------------------+

You'll need to implement .startsWith yourself. Here is the polyfill:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

Insert Data Into Temp Table with Query

use as at end of query

Select * into #temp (select * from table1,table2) as temp_table

Which Eclipse version should I use for an Android app?

Get the full Android-SDK plus the dependencies at http://developer.android.com/sdk/index.html.

Do have Java installed :)

Change CSS properties on click

<div id="foo">hello world!</div>
<img src="zoom.png" id="click_me" />

JS

$('#click_me').click(function(){
  $('#foo').css({
    'background-color':'red',
    'color':'white',
    'font-size':'44px'
  });
});

RGB to hex and hex to RGB

Here is the Javascript code to change HEX Color value to the Red, Green, Blue individually.

R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");

function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #else
      //define something for Windows (32-bit only)
   #endif
#elif __APPLE__
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

The defined macros depend on the compiler that you are going to use.

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

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

  • Usually the white-box testing is not possible for testers. Thus the only viable answer for testers is to emphasize black-box approach.

  • However, with aspect-oriented-programming and design-by-contract methodology, when the testing goals are programmed into the target code as contracts (seen from the static view of a program), and/or when the testing temporal logic is programmed into the code as cross-cuts (dynamic view of the test logic), white-box testing would become not only possible but also a preferred take for testers. Given that said, it will need be an expertise-demanding take, the testers need to be not only good testers, but also good programmers or more than good programmers.

Disable and later enable all table indexes in Oracle

From here: http://forums.oracle.com/forums/thread.jspa?messageID=2354075

alter session set skip_unusable_indexes = true;

alter index your_index unusable;

do import...

alter index your_index rebuild [online];

How do I handle the window close event in Tkinter?

Matt has shown one classic modification of the close button.
The other is to have the close button minimize the window.
You can reproduced this behavior by having the iconify method
be the protocol method's second argument.

Here's a working example, tested on Windows 7 & 10:

# Python 3
import tkinter
import tkinter.scrolledtext as scrolledtext

root = tkinter.Tk()
# make the top right close button minimize (iconify) the main window
root.protocol("WM_DELETE_WINDOW", root.iconify)
# make Esc exit the program
root.bind('<Escape>', lambda e: root.destroy())

# create a menu bar with an Exit command
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)

# create a Text widget with a Scrollbar attached
txt = scrolledtext.ScrolledText(root, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')

root.mainloop()

In this example we give the user two new exit options:
the classic File ? Exit, and also the Esc button.

"Submit is not a function" error in JavaScript

giving a form element a name of submit will simple shadow the submit property . make sure you don't have a form element with the name submit and you should be able to access the submit function just fine .

How to cast or convert an unsigned int to int in C?

If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

C Linking Error: undefined reference to 'main'

You should provide output file name after -o option. In your case runexp.o is treated as output file name, not input object file and thus your main function is undefined.

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

How to get 2 digit year w/ Javascript?

The specific answer to this question is found in this one line below:

_x000D_
_x000D_
//pull the last two digits of the year_x000D_
//logs to console_x000D_
//creates a new date object (has the current date and time by default)_x000D_
//gets the full year from the date object (currently 2017)_x000D_
//converts the variable to a string_x000D_
//gets the substring backwards by 2 characters (last two characters)    _x000D_
console.log(new Date().getFullYear().toString().substr(-2));
_x000D_
_x000D_
_x000D_

Formatting Full Date Time Example (MMddyy): jsFiddle

JavaScript:

_x000D_
_x000D_
//A function for formatting a date to MMddyy_x000D_
function formatDate(d)_x000D_
{_x000D_
    //get the month_x000D_
    var month = d.getMonth();_x000D_
    //get the day_x000D_
    //convert day to string_x000D_
    var day = d.getDate().toString();_x000D_
    //get the year_x000D_
    var year = d.getFullYear();_x000D_
    _x000D_
    //pull the last two digits of the year_x000D_
    year = year.toString().substr(-2);_x000D_
    _x000D_
    //increment month by 1 since it is 0 indexed_x000D_
    //converts month to a string_x000D_
    month = (month + 1).toString();_x000D_
_x000D_
    //if month is 1-9 pad right with a 0 for two digits_x000D_
    if (month.length === 1)_x000D_
    {_x000D_
        month = "0" + month;_x000D_
    }_x000D_
_x000D_
    //if day is between 1-9 pad right with a 0 for two digits_x000D_
    if (day.length === 1)_x000D_
    {_x000D_
        day = "0" + day;_x000D_
    }_x000D_
_x000D_
    //return the string "MMddyy"_x000D_
    return month + day + year;_x000D_
}_x000D_
_x000D_
var d = new Date();_x000D_
console.log(formatDate(d));
_x000D_
_x000D_
_x000D_

How to schedule a stored procedure in MySQL

I used this query and it worked for me:

CREATE EVENT `exec`
  ON SCHEDULE EVERY 5 SECOND
  STARTS '2013-02-10 00:00:00'
  ENDS '2015-02-28 00:00:00'
  ON COMPLETION NOT PRESERVE ENABLE
DO 
  call delete_rows_links();

How can I have same rule for two locations in NGINX config?

This is short, yet efficient and proven approach:

location ~ (patternOne|patternTwo){ #rules etc. }

So one can easily have multiple patterns with simple pipe syntax pointing to the same location block / rules.

How to fix git error: RPC failed; curl 56 GnuTLS

You can set some option to resolve the issue

Either at global level: (needed if you clone, don't forget to reset after)

$ git config --global http.sslVerify false
$ git config --global http.postBuffer 1048576000

or on a local repository

$ git config http.sslVerify false
$ git config http.postBuffer 1048576000

Play infinitely looping video on-load in HTML5

The loop attribute should do it:

<video width="320" height="240" autoplay loop>
  <source src="movie.mp4" type="video/mp4" />
  <source src="movie.ogg" type="video/ogg" />
  Your browser does not support the video tag.
</video>

Should you have a problem with the loop attribute (as we had in the past), listen to the videoEnd event and call the play() method when it fires.

Note1: I'm not sure about the behavior on Apple's iPad/iPhone, because they have some restrictions against autoplay.

Note2: loop="true" and autoplay="autoplay" are deprecated

How does paintComponent work?

Two things you can do here:

  1. Read Painting in AWT and Swing
  2. Use a debugger and put a breakpoint in the paintComponent method. Then travel up the stacktrace and see how provides the Graphics parameter.

Just for info, here is the stacktrace that I got from the example of code I posted at the end:

Thread [AWT-EventQueue-0] (Suspended (breakpoint at line 15 in TestPaint))  
    TestPaint.paintComponent(Graphics) line: 15 
    TestPaint(JComponent).paint(Graphics) line: 1054    
    JPanel(JComponent).paintChildren(Graphics) line: 887    
    JPanel(JComponent).paint(Graphics) line: 1063   
    JLayeredPane(JComponent).paintChildren(Graphics) line: 887  
    JLayeredPane(JComponent).paint(Graphics) line: 1063 
    JLayeredPane.paint(Graphics) line: 585  
    JRootPane(JComponent).paintChildren(Graphics) line: 887 
    JRootPane(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5228   
    RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1482 
    RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1413  
    RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1206   
    JRootPane(JComponent).paint(Graphics) line: 1040    
    GraphicsCallback$PaintCallback.run(Component, Graphics) line: 39    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runOneComponent(Component, Rectangle, Graphics, Shape, int) line: 78    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runComponents(Component[], Graphics, int) line: 115 
    JFrame(Container).paint(Graphics) line: 1967    
    JFrame(Window).paint(Graphics) line: 3867   
    RepaintManager.paintDirtyRegions(Map<Component,Rectangle>) line: 781    
    RepaintManager.paintDirtyRegions() line: 728    
    RepaintManager.prePaintDirtyRegions() line: 677 
    RepaintManager.access$700(RepaintManager) line: 59  
    RepaintManager$ProcessingRunnable.run() line: 1621  
    InvocationEvent.dispatch() line: 251    
    EventQueue.dispatchEventImpl(AWTEvent, Object) line: 705    
    EventQueue.access$000(EventQueue, AWTEvent, Object) line: 101   
    EventQueue$3.run() line: 666    
    EventQueue$3.run() line: 664    
    AccessController.doPrivileged(PrivilegedAction<T>, AccessControlContext) line: not available [native method]    
    ProtectionDomain$1.doIntersectionPrivilege(PrivilegedAction<T>, AccessControlContext, AccessControlContext) line: 76    
    EventQueue.dispatchEvent(AWTEvent) line: 675    
    EventDispatchThread.pumpOneEventForFilters(int) line: 211   
    EventDispatchThread.pumpEventsForFilter(int, Conditional, EventFilter) line: 128    
    EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 117   
    EventDispatchThread.pumpEvents(int, Conditional) line: 113  
    EventDispatchThread.pumpEvents(Conditional) line: 105   
    EventDispatchThread.run() line: 90  

The Graphics parameter comes from here:

RepaintManager.paintDirtyRegions(Map) line: 781 

The snippet involved is the following:

Graphics g = JComponent.safelyGetGraphics(
                        dirtyComponent, dirtyComponent);
                // If the Graphics goes away, it means someone disposed of
                // the window, don't do anything.
                if (g != null) {
                    g.setClip(rect.x, rect.y, rect.width, rect.height);
                    try {
                        dirtyComponent.paint(g); // This will eventually call paintComponent()
                    } finally {
                        g.dispose();
                    }
                }

If you take a look at it, you will see that it retrieve the graphics from the JComponent itself (indirectly with javax.swing.JComponent.safelyGetGraphics(Component, Component)) which itself takes it eventually from its first "Heavyweight parent" (clipped to the component bounds) which it self takes it from its corresponding native resource.

Regarding the fact that you have to cast the Graphics to a Graphics2D, it just happens that when working with the Window Toolkit, the Graphics actually extends Graphics2D, yet you could use other Graphics which do "not have to" extends Graphics2D (it does not happen very often but AWT/Swing allows you to do that).

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

class TestPaint extends JPanel {

    public TestPaint() {
        setBackground(Color.WHITE);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(0, 0, getWidth(), getHeight());
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(300, 300);
        jFrame.add(new TestPaint());
        jFrame.setVisible(true);
    }
}

TypeError: a bytes-like object is required, not 'str' in python and CSV

just change wb to w

outfile=open('./immates.csv','wb')

to

outfile=open('./immates.csv','w')

Android: set view style programmatically

if inside own custom view : val editText = TextInputEditText(context, attrs, defStyleAttr)

Use of alloc init instead of new

If new does the job for you, then it will make your code modestly smaller as well. If you would otherwise call [[SomeClass alloc] init] in many different places in your code, you will create a Hot Spot in new's implementation - that is, in the objc runtime - that will reduce the number of your cache misses.

In my understanding, if you need to use a custom initializer use [[SomeClass alloc] initCustom].

If you don't, use [SomeClass new].

npm install doesn't create node_modules directory

For node_modules you have to follow the below steps

1) In Command prompt -> Goto your project directory.

2) Command :npm init

3) It asks you to set up your package.json file

4) Command: npm install or npm update

Check string length in PHP

Try the common syntax instead:

if (strlen($message)<140) {
    echo "less than 140";
}
else
    if (strlen($message)>140) {
        echo "more than 140";
    }
    else {
        echo "exactly 140";
    }

Reading a file line by line in Go

Use:

  • reader.ReadString('\n')
    • If you don't mind that the line could be very long (i.e. use a lot of RAM). It keeps the \n at the end of the string returned.
  • reader.ReadLine()
    • If you care about limiting RAM consumption and don't mind the extra work of handling the case where the line is greater than the reader's buffer size.

I tested the various solutions suggested by writing a program to test the scenarios which are identified as problems in other answers:

  • A file with a 4MB line.
  • A file which doesn't end with a line break.

I found that:

  • The Scanner solution does not handle long lines.
  • The ReadLine solution is complex to implement.
  • The ReadString solution is the simplest and works for long lines.

Here is code which demonstrates each solution, it can be run via go run main.go, or at https://play.golang.org/p/RAW3sGblbas

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "io"
    "os"
)

func readFileWithReadString(fn string) (err error) {
    fmt.Println("readFileWithReadString")

    file, err := os.Open(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    // Start reading from the file with a reader.
    reader := bufio.NewReader(file)
    var line string
    for {
        line, err = reader.ReadString('\n')
        if err != nil && err != io.EOF {
            break
        }

        // Process the line here.
        fmt.Printf(" > Read %d characters\n", len(line))
        fmt.Printf(" > > %s\n", limitLength(line, 50))

        if err != nil {
            break
        }
    }
    if err != io.EOF {
        fmt.Printf(" > Failed with error: %v\n", err)
        return err
    }
    return
}

func readFileWithScanner(fn string) (err error) {
    fmt.Println("readFileWithScanner (scanner fails with long lines)")

    // Don't use this, it doesn't work with long lines...

    file, err := os.Open(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    // Start reading from the file using a scanner.
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()

        // Process the line here.
        fmt.Printf(" > Read %d characters\n", len(line))
        fmt.Printf(" > > %s\n", limitLength(line, 50))
    }
    if scanner.Err() != nil {
        fmt.Printf(" > Failed with error %v\n", scanner.Err())
        return scanner.Err()
    }
    return
}

func readFileWithReadLine(fn string) (err error) {
    fmt.Println("readFileWithReadLine")

    file, err := os.Open(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    // Start reading from the file with a reader.
    reader := bufio.NewReader(file)
    for {
        var buffer bytes.Buffer

        var l []byte
        var isPrefix bool
        for {
            l, isPrefix, err = reader.ReadLine()
            buffer.Write(l)
            // If we've reached the end of the line, stop reading.
            if !isPrefix {
                break
            }
            // If we're at the EOF, break.
            if err != nil {
                if err != io.EOF {
                    return err
                }
                break
            }
        }
        line := buffer.String()

        // Process the line here.
        fmt.Printf(" > Read %d characters\n", len(line))
        fmt.Printf(" > > %s\n", limitLength(line, 50))

        if err == io.EOF {
            break
        }
    }
    if err != io.EOF {
        fmt.Printf(" > Failed with error: %v\n", err)
        return err
    }
    return
}

func main() {
    testLongLines()
    testLinesThatDoNotFinishWithALinebreak()
}

func testLongLines() {
    fmt.Println("Long lines")
    fmt.Println()

    createFileWithLongLine("longline.txt")
    readFileWithReadString("longline.txt")
    fmt.Println()
    readFileWithScanner("longline.txt")
    fmt.Println()
    readFileWithReadLine("longline.txt")
    fmt.Println()
}

func testLinesThatDoNotFinishWithALinebreak() {
    fmt.Println("No linebreak")
    fmt.Println()

    createFileThatDoesNotEndWithALineBreak("nolinebreak.txt")
    readFileWithReadString("nolinebreak.txt")
    fmt.Println()
    readFileWithScanner("nolinebreak.txt")
    fmt.Println()
    readFileWithReadLine("nolinebreak.txt")
    fmt.Println()
}

func createFileThatDoesNotEndWithALineBreak(fn string) (err error) {
    file, err := os.Create(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    w := bufio.NewWriter(file)
    w.WriteString("Does not end with linebreak.")
    w.Flush()
    return
}

func createFileWithLongLine(fn string) (err error) {
    file, err := os.Create(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    w := bufio.NewWriter(file)
    fs := 1024 * 1024 * 4 // 4MB
    // Create a 4MB long line consisting of the letter a.
    for i := 0; i < fs; i++ {
        w.WriteRune('a')
    }
    // Terminate the line with a break.
    w.WriteRune('\n')

    // Put in a second line, which doesn't have a linebreak.
    w.WriteString("Second line.")
    w.Flush()
    return
}

func limitLength(s string, length int) string {
    if len(s) < length {
        return s
    }
    return s[:length]
}

I tested on:

  • go version go1.15 darwin/amd64
  • go version go1.7 windows/amd64
  • go version go1.6.3 linux/amd64
  • go version go1.7.4 darwin/amd64

The test program outputs:

Long lines

readFileWithReadString
 > Read 4194305 characters
 > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 > Read 12 characters
 > > Second line.

readFileWithScanner (scanner fails with long lines)
 > Failed with error bufio.Scanner: token too long

readFileWithReadLine
 > Read 4194304 characters
 > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 > Read 12 characters
 > > Second line.
 > Read 0 characters
 > > 

No linebreak

readFileWithReadString
 > Read 28 characters
 > > Does not end with linebreak.

readFileWithScanner (scanner fails with long lines)
 > Read 28 characters
 > > Does not end with linebreak.

readFileWithReadLine
 > Read 28 characters
 > > Does not end with linebreak.
 > Read 0 characters
 > > 

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

C#: calling a button event handler method without actually clicking the button

You can call the btnTest_Click just like any other function.

The most basic form would be this:

btnTest_Click(this, null);

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

Java out.println() how is this possible?

@sfussenegger's answer explains how to make this work. But I'd say don't do it!

Experienced Java programmers use, and expect to see

        System.out.println(...);

and not

        out.println(...);

A static import of System.out or System.err is (IMO) bad style because:

  • it breaks the accepted idiom, and
  • it makes it harder to track down unwanted trace prints that were added during testing and not removed.

If you find yourself doing lots of output to System.out or System.err, I think it is a better to abstract the streams into attributes, local variables or methods. This will make your application more reusable.

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

Caching a jquery ajax response in javascript/browser

        function getDatas() {
            let cacheKey = 'memories';

            if (cacheKey in localStorage) {
                let datas = JSON.parse(localStorage.getItem(cacheKey));

                // if expired
                if (datas['expires'] < Date.now()) {
                    localStorage.removeItem(cacheKey);

                    getDatas()
                } else {
                    setDatas(datas);
                }
            } else {
                $.ajax({
                    "dataType": "json",
                    "success": function(datas, textStatus, jqXHR) {
                        let today = new Date();

                        datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days

                        setDatas(datas);

                        localStorage.setItem(cacheKey, JSON.stringify(datas));
                    },
                    "url": "http://localhost/phunsanit/snippets/PHP/json.json_encode.php",
                });
            }
        }

        function setDatas(datas) {
            // display json as text
            $('#datasA').text(JSON.stringify(datas));

            // your code here
           ....

        }

        // call
        getDatas();

enter link description here

Find oldest/youngest datetime object in a list

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

'mvn' is not recognized as an internal or external command, operable program or batch file

To solve this problem please follow the steps below:

  1. Download the maven zip file from http://maven.apache.org/download.cgi
  2. Extract the maven zip file
  3. Open the environment variable and in user variable section click on new button and make a variable called MAVEN_HOME and assign it the value of bin path of extracted maven zip
  4. Now in System Variable click on Path and click on Edit button --> Now Click on New button and paste the bin path of maven zip
  5. Now click on OK button
  6. Open CMD and type mvn -version
  7. Installed Maven version will be displayed and your setup is completed

How can I symlink a file in Linux?

ln -s EXISTING_FILE_OR_DIRECTORY SYMLINK_NAME

How can I use Async with ForEach?

List<T>.ForEach doesn't play particularly well with async (neither does LINQ-to-objects, for the same reasons).

In this case, I recommend projecting each element into an asynchronous operation, and you can then (asynchronously) wait for them all to complete.

using (DataContext db = new DataLayer.DataContext())
{
    var tasks = db.Groups.ToList().Select(i => GetAdminsFromGroupAsync(i.Gid));
    var results = await Task.WhenAll(tasks);
}

The benefits of this approach over giving an async delegate to ForEach are:

  1. Error handling is more proper. Exceptions from async void cannot be caught with catch; this approach will propagate exceptions at the await Task.WhenAll line, allowing natural exception handling.
  2. You know that the tasks are complete at the end of this method, since it does an await Task.WhenAll. If you use async void, you cannot easily tell when the operations have completed.
  3. This approach has a natural syntax for retrieving the results. GetAdminsFromGroupAsync sounds like it's an operation that produces a result (the admins), and such code is more natural if such operations can return their results rather than setting a value as a side effect.

How to get first two characters of a string in oracle query?

SUBSTR (documentation):

SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName from shipment

When selected, it's like any other column. You should give it a name (with As keyword), and you can selected other columns in the same statement:

SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName, column2, ... from shipment

PhpMyAdmin not working on localhost

Same Object Not Found problem here - both in Xampp as well as in Wamp. It turns out the root name of "phpmyadmin" was "PhpMyAdmin". I got rid of all the capitals, renaming the folder to "phpmyadmin", and after a couple of reloads phpmyadmin was working.

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

JavaScript closures vs. anonymous functions

I wrote this a while ago to remind myself of what a closure is and how it works in JS.

A closure is a function that, when called, uses the scope in which it was declared, not the scope in which it was called. In javaScript, all functions behave like this. Variable values in a scope persist as long as there is a function that still points to them. The exception to the rule is 'this', which refers to the object that the function is inside when it is called.

var z = 1;
function x(){
    var z = 2; 
    y(function(){
      alert(z);
    });
}
function y(f){
    var z = 3;
    f();
}
x(); //alerts '2' 

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

How to append output to the end of a text file

For example your file contains :

 1.  mangesh@001:~$ cat output.txt
    1
    2
    EOF

if u want to append at end of file then ---->remember spaces between 'text' >> 'filename'

  2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt 
    1
    2
    EOF
    somthing to append

And to overwrite contents of file :

  3.  mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx
    somthing new to write

Difference between try-catch and throw in java

try - Add sensitive code catch - to handle exception finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block throw - To handover our created exception to JVM manually. Used to throw customized exception throws - To delegate the responsibility of exception handling to caller method or main method.

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

What's the syntax to import a class in a default package in Java?

That's not possible.

The alternative is using reflection:

 Class.forName("SomeClass").getMethod("someMethod").invoke(null);

What is the &#xA; character?

It's a linefeed character. How you use it would be up to you.

How do I use Apache tomcat 7 built in Host Manager gui?

For tomcat 8

1.Go to context.xml file located for instance../home/ubuntu/tomcat/webapps/manager/META-INF/

comment out valve tag. save and exit

2.Go to tomcat-users.xml file located in conf directory of tomcat. Add the respective roles

under the tomcat-users tag. Save and exit.

  1. Restart the tomcat.

Now, you will be able to have access to the manager app.

How do you get current active/default Environment profile programmatically in Spring?

Here is a more complete example.

Autowire Environment

First you will want to autowire the environment bean.

@Autowired
private Environment environment;

Check if Profiles exist in Active Profiles

Then you can use getActiveProfiles() to find out if the profile exists in the list of active profiles. Here is an example that takes the String[] from getActiveProfiles(), gets a stream from that array, then uses matchers to check for multiple profiles(Case-Insensitive) which returns a boolean if they exist.

//Check if Active profiles contains "local" or "test"
if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("test") 
   || env.equalsIgnoreCase("local")) )) 
{
   doSomethingForLocalOrTest();
}
//Check if Active profiles contains "prod"
else if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("prod")) )) 
{
   doSomethingForProd();
}

You can also achieve similar functionality using the annotation @Profile("local") Profiles allow for selective configuration based on a passed-in or environment parameter. Here is more information on this technique: Spring Profiles

How to get a table creation script in MySQL Workbench?

It is located in server administration rather than in SQL development.

  • From the home screen select the database server instance your database is located on from the server administration section on the far right.
  • From the menu on the right select Data Export.
  • Select the database you want to export and choose a location.
  • Click start export.

Convert String to int array in java

You can do it easily by using StringTokenizer class defined in java.util package.

void main()
    {
    int i=0;
    int n[]=new int[2];//for integer array of numbers
    String st="[1,2]";
    StringTokenizer stk=new StringTokenizer(st,"[,]"); //"[,]" is the delimeter
    String s[]=new String[2];//for String array of numbers
     while(stk.hasMoreTokens())
     {
        s[i]=stk.nextToken();
        n[i]=Integer.parseInt(s[i]);//Converting into Integer
       i++;
     }
  for(i=0;i<2;i++)
  System.out.println("number["+i+"]="+n[i]);
}

Output :-number[0]=1 number[1]=2

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Cordova app not displaying correctly on iPhone X (Simulator)

I'm developing cordova apps for 2 years and I spent weeks to solve related problems (eg: webview scrolls when keyboard open). Here's a tested and proven solution for both ios and android

P.S.: I'm using iScroll for scrolling content

  1. Never use viewport-fit=cover at index.html's meta tag, leave the app stay out of statusbar. iOS will handle proper area for all iPhone variants.
  2. In XCode uncheck hide status bar and requires full screen and don't forget to select Launch Screen File as CDVLaunchScreen
  3. In config.xml set fullscreen as false
  4. Finally, (thanks to Eddy Verbruggen for great plugins) add his plugin cordova-plugin-webviewcolor to set statusbar and bottom area background color. This plugin will allow you to set any color you want.
  5. Add below to config.xml (first ff after x is opacity)

    <preference name="BackgroundColor" value="0xff088c90" />
    
  6. Handle your scroll position yourself by adding focus events to input elements

    iscrollObj.scrollToElement(elm, transitionduration ... etc)
    

For android, do the same but instead of cordova-plugin-webviewcolor, install cordova-plugin-statusbar and cordova-plugin-navigationbar-color

Here's a javascript code using those plugins to work on both ios and android:

function setStatusColor(colorCode) {
    //colorCode is smtg like '#427309';
    if (cordova.platformId == 'android') {
        StatusBar.backgroundColorByHexString(colorCode);
        NavigationBar.backgroundColorByHexString(colorCode);
    } else if (cordova.platformId == 'ios') {
        window.plugins.webviewcolor.change(colorCode);
    }
}

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html

Save plot to image file instead of displaying it using Matplotlib

The Solution :

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')

If you do want to display the image as well as saving the image use:

%matplotlib inline

after import matplotlib

Laravel Eloquent limit and offset

Please try like this,

return Article::where('id',$article)->with(['products'=>function($products, $offset, $limit) {
    return $products->offset($offset*$limit)->limit($limit);
}])

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

1 - You can set a timeout in your application :

var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite

It is in milliseconds.

2 - Also you can increase timeout value in httpruntime tag in web/app.config :

<configuration>
     <system.web>
          <httpRuntime executionTimeout="<<**seconds**>>" />
          ...
     </system.web>
</configuration>

For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source

Is there Selected Tab Changed Event in the standard WPF Tab Control

You could still use that event. Just check that the sender argument is the control you actually care about and if so, run the event code.

Convert timedelta to total seconds

Use timedelta.total_seconds().

>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0

Java IOException "Too many open files"

Recently, I had a program batch processing files, I have certainly closed each file in the loop, but the error still there.

And later, I resolved this problem by garbage collect eagerly every hundreds of files:

int index;
while () {
    try {
        // do with outputStream...
    } finally {
        out.close();
    }
    if (index++ % 100 = 0)
        System.gc();
}

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Possibly too late to be of benefit now, but is this not the easiest way to do things?

SELECT     empName, projIDs = replace
                          ((SELECT Surname AS [data()]
                              FROM project_members
                              WHERE  empName = a.empName
                              ORDER BY empName FOR xml path('')), ' ', REQUIRED SEPERATOR)
FROM         project_members a
WHERE     empName IS NOT NULL
GROUP BY empName

SSH to AWS Instance without key pairs

I came here through Google looking for an answer to how to setup cloud init to not disable PasswordAuthentication on AWS. Both the answers don't address the issue. Without it, if you create an AMI then on instance initialization cloud init will again disable this option.

The correct method to do this, is instead of manually changing sshd_config you need to correct the setting for cloud init (Open source tool used to configure an instance during provisioning. Read more at: https://cloudinit.readthedocs.org/en/latest/). The configuration file for cloud init is found at: /etc/cloud/cloud.cfg

This file is used for setting up a lot of the configuration used by cloud init. Read through this file for examples of items you can configure on cloud-init. This includes items like default username on a newly created instance)

To enable or disable password login over SSH you need to change the value for the parameter ssh_pwauth. After changing the parameter ssh_pwauth from 0 to 1 in the file /etc/cloud/cloud.cfg bake an AMI. If you launch from this newly baked AMI it will have password authentication enabled after provisioning.

You can confirm this by checking the value of the PasswordAuthentication in the ssh config as mentioned in the other answers.

Detecting the onload event of a window opened with window.open

onload event handler must be inside popup's HTML <body> markup.

Ansible - read inventory hosts and variables to group_vars/all file

Just in case if the problem is still there, You can refer to ansible inventory through ‘hostvars’, ‘group_names’, and ‘groups’ ansible variables.

Example:

To be able to get ip addresses of all servers within group "mygroup", use the below construction:

- debug: msg="{{ hostvars[item]['ansible_eth0']['ipv4']['address'] }}" 
  with_items:
     - "{{ groups['mygroup'] }}"

HTML CSS How to stop a table cell from expanding

No javascript, just CSS. Works fine!

   .no-break-out {
      /* These are technically the same, but use both */
      overflow-wrap: break-word;
      word-wrap: break-word;

      -ms-word-break: break-all;
      /* This is the dangerous one in WebKit, as it breaks things wherever */
      word-break: break-all;
      /* Instead use this non-standard one: */
      word-break: break-word;

      /* Adds a hyphen where the word breaks, if supported (No Blink) */
      -ms-hyphens: auto;
      -moz-hyphens: auto;
      -webkit-hyphens: auto;
      hyphens: auto;

    }

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Column names must be unique in the table. You cannot have two columns named asd in the same table.

Converting to upper and lower case in Java

Try this on for size:

String properCase (String inputVal) {
    // Empty strings should be returned as-is.

    if (inputVal.length() == 0) return "";

    // Strings with only one character uppercased.

    if (inputVal.length() == 1) return inputVal.toUpperCase();

    // Otherwise uppercase first letter, lowercase the rest.

    return inputVal.substring(0,1).toUpperCase()
        + inputVal.substring(1).toLowerCase();
}

It basically handles special cases of empty and one-character string first and correctly cases a two-plus-character string otherwise. And, as pointed out in a comment, the one-character special case isn't needed for functionality but I still prefer to be explicit, especially if it results in fewer useless calls, such as substring to get an empty string, lower-casing it, then appending it as well.

Add back button to action bar

There are two ways to approach this.

Option 1: Update the Android Manifest If the settings Activity is always called from the same activity, you can make the relationship in the Android Manifest. Android will automagically show the 'back' button in the ActionBar

<activity
    android:name=".SettingsActivity"
    android:label="Setting Activity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.example.MainActivity" />
</activity>

Option 2: Change a setting for the ActionBar If you don't know which Activity will call the Settings Activity, you can create it like this. First in your activity that extends ActionBarActivity (Make sure your @imports match the level of compatibility you are looking for).

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings_test);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
}

Then, detect the 'back button' press and tell Android to close the currently open Activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

That should do it!

What is the most efficient way to get first and last line of a text file?

First open the file in read mode.Then use readlines() method to read line by line.All the lines stored in a list.Now you can use list slices to get first and last lines of the file.

    a=open('file.txt','rb')
    lines = a.readlines()
    if lines:
        first_line = lines[:1]
        last_line = lines[-1]

The system cannot find the file specified. in Visual Studio

I resolved this issue after deleting folder where I was trying to add the file in Visual Studio. Deleted folder from window explorer also. After doing all this, successfully able to add folder and file.

How to only get file name with Linux 'find'?

If you are using GNU find

find . -type f -printf "%f\n"

Or you can use a programming language such as Ruby(1.9+)

$ ruby -e 'Dir["**/*"].each{|x| puts File.basename(x)}'

If you fancy a bash (at least 4) solution

shopt -s globstar
for file in **; do echo ${file##*/}; done

Return back to MainActivity from another activity

This usually works as well :)

navigateUpTo(new Intent(getBaseContext(), MainActivity.class));

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Writing files in Node.js

You can of course make it a little more advanced. Non-blocking, writing bits and pieces, not writing the whole file at once:

var fs = require('fs');
var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
  stream.write("My first row\n");
  stream.write("My second row\n");
  stream.end();
});

What is the difference between a function expression vs declaration in JavaScript?

The first statement depends on the context in which it is declared.

If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.

If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"

EDIT:

I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.

END EDIT

Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore

var foo = function foo() { return 5; }

Is the same as

var foo = function fooYou() { return 5; }

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

How to Disable GUI Button in Java

Is there a reason you are not doing something like:

public class IPGUI extends JFrame implements ActionListener 
{
    private static JPanel contentPane;

    private JButton btnConvertDocuments;
    private JButton btnExtractImages;
    private JButton btnParseRIDValues;
    private JButton btnParseImageInfo;

    public IPGUI() 
    {
        ...

        btnConvertDocuments = new JButton("1. Convert Documents");

        ...

        btnExtractImages = new JButton("2. Extract Images");

        ...

        //etc.
    }

    public void actionPerformed(ActionEvent event) 
    {
        String command = event.getActionCommand();

        if (command.equals("w"))
        {
            FileConverter fc = new FileConverter();
            btnConvertDocuments.setEnabled( false );
        }
        else if (command.equals("x"))
        {
            ImageExtractor ie = new ImageExtractor();
            btnExtractImages.setEnabled( false );
        }

        // etc.
    }    
}

The if statement with your disabling code won't get called unless you keep calling the IPGUI constructor.

How to remove focus without setting focus to another control?

Old question, but I came across it when I had a similar issue and thought I'd share what I ended up doing.

The view that gained focus was different each time so I used the very generic:

View current = getCurrentFocus();
if (current != null) current.clearFocus();

find vs find_by vs where

The accepted answer generally covers it all, but I'd like to add something, just incase you are planning to work with the model in a way like updating, and you are retrieving a single record(whose id you do not know), Then find_by is the way to go, because it retrieves the record and does not put it in an array

irb(main):037:0> @kit = Kit.find_by(number: "3456")
  Kit Load (0.9ms)  SELECT "kits".* FROM "kits" WHERE "kits"."number" = 
 '3456' LIMIT 1
=> #<Kit id: 1, number: "3456", created_at: "2015-05-12 06:10:56",   
updated_at: "2015-05-12 06:10:56", job_id: nil>

irb(main):038:0> @kit.update(job_id: 2)
(0.2ms)  BEGIN Kit Exists (0.4ms)  SELECT 1 AS one FROM "kits" WHERE  
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.5ms)   
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE  "kits"."id" = 
1  [["job_id", 2], ["updated_at", Tue, 12 May 2015 07:16:58 UTC +00:00]] 
(0.6ms)  COMMIT => true

but if you use where then you can not update it directly

irb(main):039:0> @kit = Kit.where(number: "3456")
Kit Load (1.2ms)  SELECT "kits".* FROM "kits" WHERE "kits"."number" =  
'3456' => #<ActiveRecord::Relation [#<Kit id: 1, number: "3456", 
created_at: "2015-05-12 06:10:56", updated_at: "2015-05-12 07:16:58", 
job_id: 2>]>

irb(main):040:0> @kit.update(job_id: 3)
ArgumentError: wrong number of arguments (1 for 2)

in such a case you would have to specify it like this

irb(main):043:0> @kit[0].update(job_id: 3)
(0.2ms)  BEGIN Kit Exists (0.6ms)  SELECT 1 AS one FROM "kits" WHERE 
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.6ms)   
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE "kits"."id" = 1  
[["job_id", 3], ["updated_at", Tue, 12 May 2015 07:28:04 UTC +00:00]]
(0.5ms)  COMMIT => true

jQuery iframe load() event?

Without code in iframe + animate:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">

function resizeIframe(obj) {

    jQuery(document).ready(function($) {

        $(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)

    });

}    
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

SSRS Query execution failed for dataset

I had the similar issue showing the error

For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.

Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.

2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.

How can I find the number of days between two Date objects in Ruby?

In Ruby 2.1.3 things have changed:

> endDate = Date.new(2014, 1, 2)
 => #<Date: 2014-01-02 ((2456660j,0s,0n),+0s,2299161j)> 
> beginDate = Date.new(2014, 1, 1)
 => #<Date: 2014-01-01 ((2456659j,0s,0n),+0s,2299161j)> 
> days = endDate - beginDate
 => (1/1) 
> days.class
 => Rational 
> days.to_i
 => 1 

How can I check MySQL engine type for a specific table?

If you are a linux user:

To show the engines for all tables for all databases on a mysql server, without tables information_schema, mysql, performance_schema:

less < <({ for i in $(mysql -e "show databases;" | cat | grep -v -e Database-e information_schema -e mysql -e performance_schema); do echo "--------------------$i--------------------";  mysql -e "use $i; show table status;"; done } | column -t)

You might love this, if you are on linux, at least.

Will open all info for all tables in less, press -S to chop overly long lines.

Example output:

--------------------information_schema--------------------
Name                                                        Engine              Version  Row_format  Rows   Avg_row_length  Data_length  Max_data_length     Index_length  Data_free  Auto_increment  Create_time  Update_time  Check_time  C
CHARACTER_SETS                                              MEMORY              10       Fixed       NULL   384             0            16434816            0             0          NULL            2015-07-13   15:48:45     NULL        N
COLLATIONS                                                  MEMORY              10       Fixed       NULL   231             0            16704765            0             0          NULL            2015-07-13   15:48:45     NULL        N
COLLATION_CHARACTER_SET_APPLICABILITY                       MEMORY              10       Fixed       NULL   195             0            16357770            0             0          NULL            2015-07-13   15:48:45     NULL        N
COLUMNS                                                     MyISAM              10       Dynamic     NULL   0               0            281474976710655     1024          0          NULL            2015-07-13   15:48:45     2015-07-13  1
COLUMN_PRIVILEGES                                           MEMORY              10       Fixed       NULL   2565            0            16757145            0             0          NULL            2015-07-13   15:48:45     NULL        N
ENGINES                                                     MEMORY              10       Fixed       NULL   490             0            16574250            0             0          NULL            2015-07-13   15:48:45     NULL        N
EVENTS                                                      MyISAM              10       Dynamic     NULL   0               0            281474976710655     1024          0          NULL            2015-07-13   15:48:45     2015-07-13  1
FILES                                                       MEMORY              10       Fixed       NULL   2677            0            16758020            0             0          NULL            2015-07-13   15:48:45     NULL        N
GLOBAL_STATUS                                               MEMORY              10       Fixed       NULL   3268            0            16755036            0             0          NULL            2015-07-13   15:48:45     NULL        N
GLOBAL_VARIABLES                                            MEMORY              10       Fixed       NULL   3268            0            16755036            0             0          NULL            2015-07-13   15:48:45     NULL        N
KEY_COLUMN_USAGE                                            MEMORY              10       Fixed       NULL   4637            0            16762755            0 

.
.
.

Generating a random & unique 8 character string using MySQL

This problem consists of two very different sub-problems:

  • the string must be seemingly random
  • the string must be unique

While randomness is quite easily achieved, the uniqueness without a retry loop is not. This brings us to concentrate on the uniqueness first. Non-random uniqueness can trivially be achieved with AUTO_INCREMENT. So using a uniqueness-preserving, pseudo-random transformation would be fine:

  • Hash has been suggested by @paul
  • AES-encrypt fits also
  • But there is a nice one: RAND(N) itself!

A sequence of random numbers created by the same seed is guaranteed to be

  • reproducible
  • different for the first 8 iterations
  • if the seed is an INT32

So we use @AndreyVolk's or @GordonLinoff's approach, but with a seeded RAND:

e.g. Assumin id is an AUTO_INCREMENT column:

INSERT INTO vehicles VALUES (blah); -- leaving out the number plate
SELECT @lid:=LAST_INSERT_ID();
UPDATE vehicles SET numberplate=concat(
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed)*36+1, 1)
)
WHERE id=@lid;

How to install JDK 11 under Ubuntu?

For anyone running a JDK on Ubuntu and want to upgrade to JDK11, I'd recommend installing via sdkman. SDKMAN is a tool for switching JVMs, removing and upgrading.

SDKMAN is a tool for managing parallel versions of multiple Software Development Kits on most Unix based systems. It provides a convenient Command Line Interface (CLI) and API for installing, switching, removing and listing Candidates.

Install SDKMAN

$ curl -s "https://get.sdkman.io" | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
$ sdk version

Install Java (11.0.3-zulu)

$ sdk install java

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How do I tell CMake to link in a static library in the source directory?

CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}, doing the following should succeed:

add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)

How can I create a table with borders in Android?

Another solution is to use linear layouts and set dividers between rows and cells like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="#8000"/>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        ></LinearLayout>

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"></LinearLayout>

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="#8000"/>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        ></LinearLayout>

    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"></LinearLayout>
    <View
        android:layout_width="@dimen/border"
        android:layout_height="match_parent"
        android:background="#8000"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"/>
</LinearLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="#8000"/>
</LinearLayout>

It's a dirty solution, but it's simple and also works with transparent background and borders.

How and when to use ‘async’ and ‘await’

Showing the above explanations in action in a simple console program:

class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public async static void TestAsyncAwaitMethods()
    {
        await LongRunningMethod();
    }

    public static async Task<int> LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
        return 1;
    }
}

And the output is:

Starting Long Running method...
Press any key to exit...
End Long Running method...

Thus,

  1. Main starts the long running method via TestAsyncAwaitMethods. That immediately returns without halting the current thread and we immediately see 'Press any key to exit' message
  2. All this while, the LongRunningMethod is running in the background. Once its completed, another thread from Threadpool picks up this context and displays the final message

Thus, not thread is blocked.

How to read file from relative path in Java project? java.io.File cannot find the path specified

InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
} catch (Exception e) {
    e.printStackTrace();
}

How to extract file name from path?

This is taken from snippets.dzone.com:

Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'

    If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
        GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
    End If
End Function

How to resolve "local edit, incoming delete upon update" message

Try to resolve the conflict using

svn resolve --accept=working PATH

How to save as a new file and keep working on the original one in Vim?

Use the :w command with a filename:

:w other_filename

Rails: select unique values from a column

If anyone is looking for the same with Mongoid, that is

Model.distinct(:rating)

How to replace (or strip) an extension from a filename in Python?

Expanding on AnaPana's answer, how to remove an extension using pathlib (Python >= 3.4):

>>> from pathlib import Path

>>> filename = Path('/some/path/somefile.txt')

>>> filename_wo_ext = filename.with_suffix('')

>>> filename_replace_ext = filename.with_suffix('.jpg')

>>> print(filename)
/some/path/somefile.ext    

>>> print(filename_wo_ext)
/some/path/somefile

>>> print(filename_replace_ext)
/some/path/somefile.jpg

What good are SQL Server schemas?

At an ORACLE shop I worked at for many years, schemas were used to encapsulate procedures (and packages) that applied to different front-end applications. A different 'API' schema for each application often made sense as the use cases, users, and system requirements were quite different. For example, one 'API' schema was for a development/configuration application only to be used by developers. Another 'API' schema was for accessing the client data via views and procedures (searches). Another 'API' schema encapsulated code that was used for synchronizing development/configuration and client data with an application that had it's own database. Some of these 'API' schemas, under the covers, would still share common procedures and functions with eachother (via other 'COMMON' schemas) where it made sense.

I will say that not having a schema is probably not the end of the world, though it can be very helpful. Really, it is the lack of packages in SQL Server that really creates problems in my mind... but that is a different topic.

printf a variable in C

Your printf needs a format string:

printf("%d\n", x);

This reference page gives details on how to use printf and related functions.

iOS 8 UITableView separator inset 0 not working

simply put this two lines in cellForRowAtIndexPath method

  • if you want to all separator lines are start from zero [cell setSeparatorInset:UIEdgeInsetsZero]; [cell setLayoutMargins:UIEdgeInsetsZero];

if you want to Specific separator line are start from zero suppose here is last line is start from zero

if (indexPath.row == array.count-1) 
{
   [cell setSeparatorInset:UIEdgeInsetsZero];
   [cell setLayoutMargins:UIEdgeInsetsZero];
}
else
   tblView.separatorInset=UIEdgeInsetsMake(0, 10, 0, 0);

convert a JavaScript string variable to decimal/money

It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.

check if directory exists and delete in one command unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

Install msi with msiexec in a Specific Directory

This one worked for me too

msiexec /i "msi path" INSTALLDIR="D:\myfolder" /q

I had tried two other iterations and both installed in the default C:\Program Files

INSTALLDIR="D:\myfolder" /q got it installed on the other drive.

Understanding events and event handlers in C#

I agree with KE50 except that I view the 'event' keyword as an alias for 'ActionCollection' since the event holds a collection of actions to be performed (ie. the delegate).

using System;

namespace test{

class MyTestApp{
    //The Event Handler declaration
    public delegate void EventAction();

    //The Event Action Collection 
    //Equivalent to 
    //  public List<EventAction> EventActions=new List<EventAction>();
    //        
    public event EventAction EventActions;

    //An Action
    public void Hello(){
        Console.WriteLine("Hello World of events!");
    }
    //Another Action
    public void Goodbye(){
        Console.WriteLine("Goodbye Cruel World of events!");
    }

    public static void Main(){
        MyTestApp TestApp = new MyTestApp();

        //Add actions to the collection
        TestApp.EventActions += TestApp.Hello;
        TestApp.EventActions += TestApp.Goodbye;

        //Invoke all event actions
        if (TestApp.EventActions!= null){
            //this peculiar syntax hides the invoke 
            TestApp.EventActions();
            //using the 'ActionCollection' idea:
            // foreach(EventAction action in TestApp.EventActions)
            //     action.Invoke();
        }
    }

}   

}

Spring Boot application as a Service

It can be done using Systemd service in Ubuntu

[Unit]
Description=A Spring Boot application
After=syslog.target

[Service]
User=baeldung
ExecStart=/path/to/your-app.jar SuccessExitStatus=143

[Install] 
WantedBy=multi-user.target

You can follow this link for more elaborated description and different ways to do so. http://www.baeldung.com/spring-boot-app-as-a-service

Special characters like @ and & in cURL POST data

cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com

Visual studio code CSS indentation and formatting

Go to Files menu -> Preference -> Extentions Then type CSS Formatter wait for it to load and click install

Android : How to read file in bytes?

The easiest solution today is to used Apache common io :

http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)

byte bytes[] = FileUtils.readFileToByteArray(photoFile)

The only drawback is to add this dependency in your build.gradle app :

implementation 'commons-io:commons-io:2.5'

+ 1562 Methods count

How to replace all occurrences of a string in Javascript?

There is a way to use the new "replaceAll" function.

But you need to use a cutting-edge browser or a javascript run time environment.

you can check the browser compatibility in here.

Python POST binary data

This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.

More about csrf tokens here:

What is a CSRF token ? What is its importance and how does it work?

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Creating layout constraints programmatically

Hi I have been using this page a lot for constraints and "how to". It took me forever to get to the point of realizing I needed:

myView.translatesAutoresizingMaskIntoConstraints = NO;

to get this example to work. Thank you Userxxx, Rob M. and especially larsacus for the explanation and code here, it has been invaluable.

Here is the code in full to get the examples above to run:

UIView *myView = [[UIView alloc] init];
myView.backgroundColor = [UIColor redColor];
myView.translatesAutoresizingMaskIntoConstraints = NO;  //This part hung me up 
[self.view addSubview:myView];
//needed to make smaller for iPhone 4 dev here, so >=200 instead of 748
[self.view addConstraints:[NSLayoutConstraint
                           constraintsWithVisualFormat:@"V:|-[myView(>=200)]-|"
                           options:NSLayoutFormatDirectionLeadingToTrailing
                           metrics:nil
                           views:NSDictionaryOfVariableBindings(myView)]];

[self.view addConstraints:[NSLayoutConstraint
                           constraintsWithVisualFormat:@"H:[myView(==200)]-|"
                           options:NSLayoutFormatDirectionLeadingToTrailing
                           metrics:nil
                           views:NSDictionaryOfVariableBindings(myView)]];

Running npm command within Visual Studio Code

Try to install PowerShell extension provided by VS code.

PowerShell Extension

After install click on PowerShell and It will start new PowerShell Console where you can run all script

PowerShell Console

How to change the order of DataFrame columns?

How about using T?

df = df.T.reindex(['mean', 0, 1, 2, 3, 4]).T

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

Conda command is not recognized on Windows 10

When you install anaconda on windows now, it doesn't automatically add Python or Conda.

If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt

enter image description here

Next, you can add Python and Conda to your path by using the setx command in your command prompt. enter image description here

Next close that command prompt and open a new one. Congrats you can now use conda and python

Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444

Conda activate not working?

Have you tried with Anaconda command prompt or, cmd it works for me. Giving no error and activation is not working in PowerShell may be some path issue.

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

Expanding a parent <div> to the height of its children

Using something like self-clearing div is perfect for a situation like this. Then you'll just use a class on the parent... like:

<div id="parent" class="clearfix">

How to remove a package in sublime text 2

If you installed with package control, search for "Package Control: Remove Package" in the command palette (accessed with Ctrl+Shift+P). Otherwise you can just remove the Emmet directory.

If you wish to use a custom caption to access commands, create Default.sublime-commands in your User folder. Then insert something similar to the following.

[
    {
        "caption": "Package Control: Uninstall Package",
        "command": "remove_package"
    }
]

Of course, you can customize the command and caption as you see fit.

Global constants file in Swift

Or just in GlobalConstants.swift:

import Foundation

let someNotification = "aaaaNotification"

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

You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use keytool to convert to the standard format. Make sure you use the same password for both files (private key password, not the keystore password) or you will get odd failures later on in the second step.

keytool -importkeystore -srckeystore keystore.jks \
    -destkeystore intermediate.p12 -deststoretype PKCS12

Next, use OpenSSL to do the extraction to PEM:

openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes

You should be able to handle that PEM file easily enough; it's plain text with an encoded unencrypted private key and certificate(s) inside it (in a pretty obvious format).

When you do this, take care to keep the files created secure. They contain secret credentials. Nothing will warn you if you fail to secure them correctly. The easiest method for securing them is to do all of this in a directory which doesn't have any access rights for anyone other than the user. And never put your password on the command line or in environment variables; it's too easy for other users to grab.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I am facing the same problem. The problem I found that I have a library project, in that project's manifest file, there is no targetSdkVersion property. I have added that property under (uses-sdk) tag. Then clean my project. Now my app runs normally.

Java switch statement multiple cases

The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}

What is the Git equivalent for revision number?

For people who have an Ant build process, you can generate a version number for a project on git with this target:

<target name="generate-version">

    <exec executable="git" outputproperty="version.revisions">
        <arg value="log"/>
        <arg value="--oneline"/>
    </exec>

    <resourcecount property="version.revision" count="0" when="eq">
        <tokens>
            <concat>
                <filterchain>
                    <tokenfilter>
                        <stringtokenizer delims="\r" />
                    </tokenfilter>
                </filterchain>
            <propertyresource name="version.revisions" />
            </concat>
        </tokens>
    </resourcecount>
    <echo>Revision : ${version.revision}</echo>

    <exec executable="git" outputproperty="version.hash">
        <arg value="rev-parse"/>
        <arg value="--short"/>
        <arg value="HEAD"/>
    </exec>
    <echo>Hash : ${version.hash}</echo>


    <exec executable="git" outputproperty="version.branch">
        <arg value="rev-parse"/>
        <arg value="--abbrev-ref"/>
        <arg value="HEAD"/>
    </exec>
    <echo>Branch : ${version.branch}</echo>

    <exec executable="git" outputproperty="version.diff">
        <arg value="diff"/>
    </exec>

    <condition property="version.dirty" value="" else="-dirty">
        <equals arg1="${version.diff}" arg2=""/>
    </condition>

    <tstamp>
        <format property="version.date" pattern="yyyy-mm-dd.HH:mm:ss" locale="en,US"/>
    </tstamp>
    <echo>Date : ${version.date}</echo>

    <property name="version" value="${version.revision}.${version.hash}.${version.branch}${version.dirty}.${version.date}" />

    <echo>Version : ${version}</echo>

    <echo file="version.properties" append="false">version = ${version}</echo>

</target>

The result looks like this:

generate-version:
    [echo] Generate version
    [echo] Revision : 47
    [echo] Hash : 2af0b99
    [echo] Branch : master
    [echo] Date : 2015-04-20.15:04:03
    [echo] Version : 47.2af0b99.master-dirty.2015-04-20.15:04:03

The dirty flag is here when you have file(s) not committed when you generate the version number. Because usually, when you build/package your application, every code modification has to be in the repository.

How to format JSON in notepad++

The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.

  • Click on Configure ( As Soon Android studio open )
  • Click Project Default
  • Click Project Structure
  • Clik Android Sdk Location

  • Select & Browse your Android SDK Location (Like: C:\Android\sdk)

  • Uncheck USE EMBEDDED JDK LOCATION

  • Set & Browse JDK Location, Like C:\Program Files\Java\jdk1.8.0_121

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

Full width layout with twitter bootstrap

You'll find a great tutorial here: bootstrap-3-grid-introduction and answer for your question is <div class="container-fluid"> ... </div>

Redirect all output to file in Bash

Credits to osexp2003 and j.a. …


Instead of putting:

&>> your_file.log

behind a line in:

crontab -e

I use:

#!/bin/bash
exec &>> your_file.log
…

at the beginning of a BASH script.

Advantage: You have the log definitions within your script. Good for Git etc.

Fast query runs slow in SSRS

I had the report html output trouble on report retrieving 32000 lines. The query ran fast but the output into web browser was very slow. In my case I had to activate “Interactive Paging” to allow user to see first page and be able to generate Excel file. The pros of this solution is that first page appears fast and user can generate export to Excel or PDF, the cons is that user can scroll only current page. If user wants to see more content he\she must use navigation buttons above the grid. In my case user accepted this behavior because the export to Excel was more important.

To activate “Interactive Paging” you must click on the free area in the report pane and change property “InteractiveSize”\ “Height” on the report level in Properties pane. Set this property to different from 0. I set to 8.5 inches in my case. Also ensure that you unchecked “Keep together on one page if possible” property on the Tablix level (right click on the Tablix, then “Tablix Properties”, then “General”\ “Page Break Options”).

enter image description here

Is there any difference between GROUP BY and DISTINCT

MusiGenesis' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then what you actually mean is "Distinct" - and therefore it generates an execution plan as if you'd simply used "Distinct."

However, I think it's important to note Hank's response as well - cavalier treatment of "Group By" and "Distinct" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is "not a question about aggregates" because you're asking about the functional difference between two SQL query keywords, one of which is meant to be used with aggregates and one of which is not.

A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother?

(for the purposes of this analogy, Hammer : Screwdriver :: GroupBy : Distinct and screw => get list of unique values in a table column)

How to determine if a number is odd in JavaScript

You can use a for statement and a conditional to determine if a number or series of numbers is odd:

for (var i=1; i<=5; i++) 
if (i%2 !== 0) {
    console.log(i)
}

This will print every odd number between 1 and 5.

Use Font Awesome Icon in Placeholder

I added both text and icon together in a placeholder.

placeholder="Edit &nbsp; &#xf040;"

CSS :

font-family: FontAwesome,'Merriweather Sans', sans-serif;

Why do multiple-table joins produce duplicate rows?

Ok in this example you are getting duplicates because you are joining both D and S onto M. I assume you should be joining D.id onto S.id like below:

SELECT *
FROM M
INNER JOIN S
    on M.Id = S.Id
INNER JOIN D
    ON S.Id = D.Id
INNER JOIN H
    ON D.Id = H.Id

Can you write nested functions in JavaScript?

Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:

    function calculate(a,b,fn) {
      var c = a * 3 + b + fn(a,b);
      return  c;
    }

    function sum(a,b) {
      return a+b;
    }

    function product(a,b) {
      return a*b;
    }

    document.write(calculate (10,20,sum)); //80
    document.write(calculate (10,20,product)); //250