Programs & Examples On #Interopbitmapimage

Error occurred during initialization of boot layer FindException: Module not found

You say that your module-info.java contains

module myModule {}

That means it declares a module called myModule, not com.pantech.myModule. Pointing this from the command format:

 -m <module-name>/<main-class>

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

If you want to allow Html tags only for few textbox in mvc

You can do one thing

in controller

 [ValidateInput(false)]
public ActionResult CreateNewHtml()  //view
{
    return View();
}
[ValidateInput(false)]
[HttpPost]
public ActionResult CreateNewHtml(cbs obj)//view cbs is database class
{
    repo.AddHtml(obj);
    return View();
}

Check if number is prime number

You can also try this:

bool isPrime(int number)
    {
        return (Enumerable.Range(1, number).Count(x => number % x == 0) == 2);
    }

How to use OR condition in a JavaScript IF statement?

You can use Like

if(condition1 || condition2 || condition3 || ..........)
{       
     enter code here
}

Best way to move files between S3 buckets?

For new version aws2.

aws2 s3 sync s3://SOURCE_BUCKET_NAME s3://NEW_BUCKET_NAME

How do I debug "Error: spawn ENOENT" on node.js?

Before anyone spends to much time debugging this problem, most of the time it can be resolved by deleting node_modules and reinstalling the packages.

To Install:

If a lockfile exists you might use

yarn install --frozen-lockfile

or

npm ci

respectivly. if not then

yarn install

or

npm i

What does %s and %d mean in printf in the C language?

The first argument to printf is a string of identifiers.

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

How can I count the rows with data in an Excel sheet?

If you don't mind VBA, here is a function that will do it for you. Your call would be something like:

=CountRows(1:10) 
Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.

How to convert xml into array in php?

easy!

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

How to minify php page html output?

All of the preg_replace() solutions above have issues of single line comments, conditional comments and other pitfalls. I'd recommend taking advantage of the well-tested Minify project rather than creating your own regex from scratch.

In my case I place the following code at the top of a PHP page to minify it:

function sanitize_output($buffer) {
    require_once('min/lib/Minify/HTML.php');
    require_once('min/lib/Minify/CSS.php');
    require_once('min/lib/JSMin.php');
    $buffer = Minify_HTML::minify($buffer, array(
        'cssMinifier' => array('Minify_CSS', 'minify'),
        'jsMinifier' => array('JSMin', 'minify')
    ));
    return $buffer;
}
ob_start('sanitize_output');

Insert value into a string at a certain position?

If you have a string and you know the index you want to put the two variables in the string you can use:

string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);

But if it is a simple line you can use it this way:

string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

Use oracle.jdbc.OracleDriver, not oracle.jdbc.driver.OracleDriver. You do not need to register it if the driver jar file is in the "WEB-INF\lib" directory, if you are using Tomcat. Save this as test.jsp and put it in your web directory, and redeploy your web app folder in Tomcat manager:

<%@ page import="java.sql.*" %>

<HTML>
<HEAD>
<TITLE>Simple JSP Oracle Test</TITLE>
</HEAD><BODY>
<%
Connection conn = null;
try {
    Class.forName("oracle.jdbc.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@XXX.XXX.XXX.XXX:XXXX:dbName", "user", "password");
    Statement stmt = conn.createStatement();
    out.println("Connection established!");
}
catch (Exception ex)
{
    out.println("Exception: " + ex.getMessage() + "");

}
finally
{
    if (conn != null) {
        try {
            conn.close();   
        }
        catch (Exception ignored) {
            // ignore
        }
    }
}

%>

default select option as blank

For those who are using <select multiple> (combobox; no dropdown), this worked for me:

_x000D_
_x000D_
<select size=1 disabled multiple>
  <option hidden selected></option>
  <option>My Option</option>
</select>
_x000D_
_x000D_
_x000D_

Using Mockito to test abstract classes

Try using a custom answer.

For example:

import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class CustomAnswer implements Answer<Object> {

    public Object answer(InvocationOnMock invocation) throws Throwable {

        Answer<Object> answer = null;

        if (isAbstract(invocation.getMethod().getModifiers())) {

            answer = Mockito.RETURNS_DEFAULTS;

        } else {

            answer = Mockito.CALLS_REAL_METHODS;
        }

        return answer.answer(invocation);
    }
}

It will return the mock for abstract methods and will call the real method for concrete methods.

Convert IQueryable<> type object to List<T> type?

The List class's constructor can convert an IQueryable for you:

public static List<TResult> ToList<TResult>(this IQueryable source)
{
    return new List<TResult>(source);
}

or you can just convert it without the extension method, of course:

var list = new List<T>(queryable);

How do you set a JavaScript onclick event to a class with css

You could do it with jQuery.

$('.myClass').click(function() {
  alert('hohoho');
});

How to reload a page after the OK click on the Alert Page

As the alert method in JavaScript does not return a Boolean or yield the current thread, you must use a different method.

My number one recommendation requires a little CSS experience. You should instead create a div element that is fixed positionally.

Otherwise you could use the confirm() method.

confirm("Successful Message");
window.location.reload();

However, this will add a cancel button. Because the confirm method is not within an if statement though, the cancel button will still refresh the page like you want it.

Generate random integers between 0 and 9

>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]

How to change the color of text in javafx TextField?

The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.

.text-input {
    -fx-text-fill: -fx-text-inner-color;
    -fx-highlight-fill: derive(-fx-control-inner-background,-20%);
    -fx-highlight-text-fill: -fx-text-inner-color;
    -fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
    -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: 0, 1;
    -fx-background-radius: 3, 2;
    -fx-cursor: text;
    -fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
    -fx-highlight-fill: -fx-accent;
    -fx-highlight-text-fill: white;
    -fx-background-color: 
        -fx-focus-color,
        -fx-control-inner-background,
        -fx-faint-focus-color,
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: -0.2, 1, -1.4, 3;
    -fx-background-radius: 3, 2, 4, 0;
    -fx-prompt-text-fill: transparent;
}

Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:

textField.setStyle("-fx-text-inner-color: red;");

Apache is downloading php files instead of displaying them

In case someone is using php7 under a Linux environment

Make sure you enable php7

sudo a2enmod php7

Restart the mysql service and Apache

sudo systemctl restart mysql
sudo systemctl restart apache2

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

I was facing the same issue. After many tries below solution worked for me.

Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.

After that you can follow the below steps.

@ABHI KUMAR

Download the Visual C++ Redistributable 2015

Visual C++ Redistributable for Visual Studio 2015 (64-bit)

Visual C++ Redistributable for Visual Studio 2015 (32-bit)

(Reinstal if already installed) then restart your computer or use windows updates for download auto.

For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

For me it was "Prefer 32bit": clearing the checkbox allowed CLR to load Crystal Reports 64bit runtime (the only one installed).

How to remove all click event handlers using jQuery?

$('#saveBtn').off('click').click(function(){saveQuestion(id)});

Print new output on same line

Similar to what has been suggested, you can do:

print(i, end=',')

Output: 0,1,2,3,

Same font except its weight seems different on different browsers

Try text-rendering: geometricPrecision;.

Different from text-rendering: optimizeLegibility;, it takes care of kerning problems when scaling fonts, while the last enables kerning and ligatures.

How to convert a Java String to an ASCII byte array?

Convert string to ascii values.

   String test = "ABCD";

   for ( int i = 0; i < test.length(); ++i ) {
   char c = test.charAt( i );
   int j = (int) c;
   System.out.println(j);
   }

Entity Framework : How do you refresh the model when the db changes?

Are you looking at the designer or code view? You can force the designer to open by right clicking on your EDMX file and selecting Open With -> ADO.NET Entity Data Model Designer

Right click on the designer surface of the EDMX designer and click Update Model From Database...

All entities are refreshed by default, new entities are only added if you select them.


EDIT: If it is not refreshing well.

  • Select all the tables and view-s in the EDMX designer.
  • Delete them.
  • Then, update model from database

Maintaining Session through Angular.js

You would use a service for that in Angular. A service is a function you register with Angular, and that functions job is to return an object which will live until the browser is closed/refreshed. So it's a good place to store state in, and to synchronize that state with the server asynchronously as that state changes.

Generate your own Error code in swift 3

Details

  • Xcode Version 10.2.1 (10E1001)
  • Swift 5

Solution of organizing errors in an app

import Foundation

enum AppError {
    case network(type: Enums.NetworkError)
    case file(type: Enums.FileError)
    case custom(errorDescription: String?)

    class Enums { }
}

extension AppError: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .network(let type): return type.localizedDescription
            case .file(let type): return type.localizedDescription
            case .custom(let errorDescription): return errorDescription
        }
    }
}

// MARK: - Network Errors

extension AppError.Enums {
    enum NetworkError {
        case parsing
        case notFound
        case custom(errorCode: Int?, errorDescription: String?)
    }
}

extension AppError.Enums.NetworkError: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .parsing: return "Parsing error"
            case .notFound: return "URL Not Found"
            case .custom(_, let errorDescription): return errorDescription
        }
    }

    var errorCode: Int? {
        switch self {
            case .parsing: return nil
            case .notFound: return 404
            case .custom(let errorCode, _): return errorCode
        }
    }
}

// MARK: - FIle Errors

extension AppError.Enums {
    enum FileError {
        case read(path: String)
        case write(path: String, value: Any)
        case custom(errorDescription: String?)
    }
}

extension AppError.Enums.FileError: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .read(let path): return "Could not read file from \"\(path)\""
            case .write(let path, let value): return "Could not write value \"\(value)\" file from \"\(path)\""
            case .custom(let errorDescription): return errorDescription
        }
    }
}

Usage

//let err: Error = NSError(domain:"", code: 401, userInfo: [NSLocalizedDescriptionKey: "Invaild UserName or Password"])
let err: Error = AppError.network(type: .custom(errorCode: 400, errorDescription: "Bad request"))

switch err {
    case is AppError:
        switch err as! AppError {
        case .network(let type): print("Network ERROR: code \(type.errorCode), description: \(type.localizedDescription)")
        case .file(let type):
            switch type {
                case .read: print("FILE Reading ERROR")
                case .write: print("FILE Writing ERROR")
                case .custom: print("FILE ERROR")
            }
        case .custom: print("Custom ERROR")
    }
    default: print(err)
}

C++ floating point to integer type conversions

Check out the boost NumericConversion library. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.

Can't create handler inside thread that has not called Looper.prepare()

For Rxjava and RxAndroid User:

public static void shortToast(String msg) {
    Observable.just(msg)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(message -> {
                Toast.makeText(App.getInstance(), message, Toast.LENGTH_SHORT).show();
            });
}

Cache busting via params

Two questions: Will this effectively break the cache?

Yes. Even Stack Overflow use this method, although I remember that they (with their millions of visitors per day and zillions of different client and proxy versions and configurations) have had some freak edge cases where even this was not enough to break the cache. But the general assumption is that this will work, and is a suitable method to break caching on clients.

Will the param cause the browser to then never cache the response from that url since the param indicates that this is dynamic content?

No. The parameter will not change the caching policy; the caching headers sent by the server still apply, and if it doesn't send any, the browser's defaults.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

  1. Open Command Prompt
  2. then go your project folder thru Command prompt
  3. Type gradlew build and run

Delete multiple rows by selecting checkboxes using PHP

Delete Multiple checkbox using PHP Code

<input type="checkbox" name="chkbox[]  value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
 $cnt=array();
 $cnt=count($_POST['chkbox']);
 for($i=0;$i<$cnt;$i++)
  {
     $del_id=$_POST['chkbox'][$i];
     $query="delete from $tablename where Id=".$del_id;
     mysql_query($query);
  }
}

firestore: PERMISSION_DENIED: Missing or insufficient permissions

Check if the service account is added in IAM & Admin https://console.cloud.google.com/iam-admin/iam with an appropriate role such as Editor

Getting selected value of a combobox

Try this:

int selectedIndex = comboBox1.SelectedIndex;
comboBox1.SelectedItem.ToString();
int selectedValue = (int)comboBox1.Items[selectedIndex];

Trim a string based on the string length

tl;dr

You seem to be asking for an ellipsis () character in the last place, when truncating. Here is a one-liner to manipulate your input string.

String input = "abcdefghijkl";
String output = ( input.length () > 10 ) ? input.substring ( 0 , 10 - 1 ).concat ( "…" ) : input;

See this code run live at IdeOne.com.

abcdefghi…

Ternary operator

We can make a one-liner by using the ternary operator.

String input = "abcdefghijkl" ;

String output = 
    ( input.length() > 10 )          // If too long…
    ?                                
    input     
    .substring( 0 , 10 - 1 )         // Take just the first part, adjusting by 1 to replace that last character with an ellipsis.
    .concat( "…" )                   // Add the ellipsis character.
    :                                // Or, if not too long…
    input                            // Just return original string.
;

See this code run live at IdeOne.com.

abcdefghi…

Java streams

The Java Streams facility makes this interesting, as of Java 9 and later. Interesting, but maybe not the best approach.

We use code points rather than char values. The char type is legacy, and is limited to the a subset of all possible Unicode characters.

String input = "abcdefghijkl" ;
int limit = 10 ;
String output =
        input
                .codePoints()
                .limit( limit )
                .collect(                                    // Collect the results of processing each code point.
                        StringBuilder::new,                  // Supplier<R> supplier
                        StringBuilder::appendCodePoint,      // ObjIntConsumer<R> accumulator
                        StringBuilder::append                // BiConsumer<R,?R> combiner
                )
                .toString()
        ;

If we had excess characters truncated, replace the last character with an ellipsis.

if ( input.length () > limit )
{
    output = output.substring ( 0 , output.length () - 1 ) + "…";
}

If only I could think of a way to put together the stream line with the "if over limit, do ellipsis" part.

Replacement for "rename" in dplyr

It is not listed as a function in dplyr (yet): http://cran.rstudio.org/web/packages/dplyr/dplyr.pdf

The function below works (almost) the same if you don't want to load both plyr and dplyr

rename <- function(dat, oldnames, newnames) {
  datnames <- colnames(dat)
  datnames[which(datnames %in% oldnames)] <- newnames
  colnames(dat) <- datnames
  dat
}

dat <- rename(mtcars,c("mpg","cyl"), c("mympg","mycyl"))
head(dat)

                  mympg mycyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4          21.0     6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag      21.0     6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710         22.8     4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive     21.4     6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout  18.7     8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant            18.1     6  225 105 2.76 3.460 20.22  1  0    3    1

Edit: The comment by Romain produces the following (note that the changes function requires dplyr .1.1)

> dplyr:::changes(mtcars, dat)
Changed variables:
          old         new        
disp      0x108b4b0e0 0x108b4e370
hp        0x108b4b210 0x108b4e4a0
drat      0x108b4b340 0x108b4e5d0
wt        0x108b4b470 0x108b4e700
qsec      0x108b4b5a0 0x108b4e830
vs        0x108b4b6d0 0x108b4e960
am        0x108b4b800 0x108b4ea90
gear      0x108b4b930 0x108b4ebc0
carb      0x108b4ba60 0x108b4ecf0
mpg       0x1033ee7c0            
cyl       0x10331d3d0            
mympg                 0x108b4e110
mycyl                 0x108b4e240

Changed attributes:
          old         new        
names     0x10c100558 0x10c2ea3f0
row.names 0x108b4bb90 0x108b4ee20
class     0x103bd8988 0x103bd8f58

How to align linearlayout to vertical center?

Change orientation and gravity in

<LinearLayout
    android:id="@+id/groupNumbers"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:layout_weight="0.7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

to

android:orientation="vertical"
android:layout_gravity="center_vertical"

You are adding orientation: horizontal, so the layout will contain all elements in single horizontal line. Which won't allow you to get the element in center.

Hope this helps.

What is the difference between SAX and DOM?

In just a few words...

SAX (Simple API for XML): Is a stream-based processor. You only have a tiny part in memory at any time and you "sniff" the XML stream by implementing callback code for events like tagStarted() etc. It uses almost no memory, but you can't do "DOM" stuff, like use xpath or traverse trees.

DOM (Document Object Model): You load the whole thing into memory - it's a massive memory hog. You can blow memory with even medium sized documents. But you can use xpath and traverse the tree etc.

Multiple radio button groups in one form

This is very simple you need to keep different names of every radio input group.

_x000D_
_x000D_
      <input type="radio" name="price">Thousand<br>_x000D_
      <input type="radio" name="price">Lakh<br>_x000D_
      <input type="radio" name="price">Crore_x000D_
      _x000D_
      </br><hr>_x000D_
_x000D_
      <input type="radio" name="gender">Male<br>_x000D_
      <input type="radio" name="gender">Female<br>_x000D_
      <input type="radio" name="gender">Other
_x000D_
_x000D_
_x000D_

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

Once you have detected the bounding box of the document, you can perform a four-point perspective transform to obtain a top-down birds eye view of the image. This will fix the skew and isolate only the desired object.


Input image:

Detected text object

Top-down view of text document

Code

from imutils.perspective import four_point_transform
import cv2
import numpy

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None

for c in cnts:
    # Perform contour approximation
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    if len(approx) == 4:
        displayCnt = approx
        break

# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))

cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()

The view didn't return an HttpResponse object. It returned None instead

Python is very sensitive to indentation, with the code below I got the same error:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

The correct indentation is:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")

Horizontal scroll on overflow of table

Unless I grossly misunderstood your question, move overflow-x:scroll from .search-table to .search-table-outter.

http://jsfiddle.net/ZXnqM/4/

.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto;   }

As far as I know you can't give scrollbars to tables themselves.

Preferred way to create a Scala list

just an example that uses collection.breakOut

scala> val a : List[Int] = (for( x <- 1 to 10 ) yield x * 3)(collection.breakOut)
a: List[Int] = List(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

scala> val b : List[Int] = (1 to 10).map(_ * 3)(collection.breakOut)
b: List[Int] = List(3, 6, 9, 12, 15, 18, 21, 24, 27, 30)

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

IE11 meta element Breaks SVG

I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.

I had <meta http-equiv="x-ua-compatible" content="ie=edge"> on the page.

In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.

How to navigate to a directory in C:\ with Cygwin?

You already accepted an answer, but I just thought I'd mention that the following also works in Cygwin:

cd "C:\Foo"

I think the cd /cygdrive/c method is better, but sometimes it's useful to know that you can do this too.

Why isn't textarea an input[type="textarea"]?

Maybe this is going a bit too far back but…

Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.

Marc Andreessen, 11 October 1993

Linear Layout and weight in Android

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="#008">

            <RelativeLayout
                android:id="@+id/paneltamrin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"

                >
                <Button
                    android:id="@+id/BtnT1"
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                    android:drawableTop="@android:drawable/ic_menu_edit"
                    android:drawablePadding="6dp"
                    android:padding="15dp"
                    android:text="AndroidDhina"
                    android:textColor="#000"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/paneltamrin2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                >
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                     android:drawableTop="@android:drawable/ic_menu_edit"
                    android:drawablePadding="6dp"
                    android:padding="15dp"
                    android:text="AndroidDhina"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </RelativeLayout>
        </LinearLayout>

enter image description here

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

The following technique worked for me:

1) Right click on the project Solution -> Click on Clean solution

2) Right click on the project Solution -> Click on Rebuild solution

How to sort a list of strings?

But how does this handle language specific sorting rules? Does it take locale into account?

No, list.sort() is a generic sorting function. If you want to sort according to the Unicode rules, you'll have to define a custom sort key function. You can try using the pyuca module, but I don't know how complete it is.

Aggregate function in SQL WHERE-Clause

HAVING is like WHERE with aggregate functions, or you could use a subquery.

select EmployeeId, sum(amount)
from Sales
group by Employee
having sum(amount) > 20000

Or

select EmployeeId, sum(amount)
from Sales
group by Employee
where EmployeeId in (
    select max(EmployeeId) from Employees)

What is the difference between getText() and getAttribute() in Selenium WebDriver?

getText(): Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.

getAttribute(String attrName): Get the value of a the given attribute of the element. Will return the current value, even if this has been modified after the page has been loaded. More exactly, this method will return the value of the given attribute, unless that attribute is not present, in which case the value of the property with the same name is returned (for example for the "value" property of a textarea element). If neither value is set, null is returned. The "style" attribute is converted as best can be to a text representation with a trailing semi-colon. The following are deemed to be "boolean" attributes, and will return either "true" or null: async, autofocus, autoplay, checked, compact, complete, controls, declare, defaultchecked, defaultselected, defer, disabled, draggable, ended, formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, selected, spellcheck, truespeed, willvalidate Finally, the following commonly mis-capitalized attribute/property names are evaluated as expected: "class" "readonly"

getText() return the visible text of the element.

getAttribute(String attrName) returns the value of the attribute passed as parameter.

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern

Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.

enter image description here

  • The OpenSessionInViewFilter calls the openSession method of the underlying SessionFactory and obtains a new Session.
  • The Session is bound to the TransactionSynchronizationManager.
  • The OpenSessionInViewFilter calls the doFilter of the javax.servlet.FilterChain object reference and the request is further processed
  • The DispatcherServlet is called, and it routes the HTTP request to the underlying PostController.
  • The PostController calls the PostService to get a list of Post entities.
  • The PostService opens a new transaction, and the HibernateTransactionManager reuses the same Session that was opened by the OpenSessionInViewFilter.
  • The PostDAO fetches the list of Post entities without initializing any lazy association.
  • The PostService commits the underlying transaction, but the Session is not closed because it was opened externally.
  • The DispatcherServlet starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
  • The OpenSessionInViewFilter can close the Session, and the underlying database connection is released as well.

At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.

The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection as read-only which would allow the database server to avoid writing to the transaction log.

There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.

The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize for fetching associations in batches, and FetchMode.SUBSELECT to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.

Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.

Spring Boot and OSIV

Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

So, make sure that in the application.properties configuration file, you have the following entry:

spring.jpa.open-in-view=false

This will disable OSIV so that you can handle the LazyInitializationException the right way.

Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

PHP: How can I determine if a variable has a value that is between two distinct constant values?

A random value?

If you want a random value, try

<?php
$value = mt_rand($min, $max);

mt_rand() will run a bit more random if you are using many random numbers in a row, or if you might ever execute the script more than once a second. In general, you should use mt_rand() over rand() if there is any doubt.

Simple Random Samples from a Sql database

Faster Than ORDER BY RAND()

I tested this method to be much faster than ORDER BY RAND(), hence it runs in O(n) time, and does so impressively fast.

From http://technet.microsoft.com/en-us/library/ms189108%28v=sql.105%29.aspx:

Non-MSSQL version -- I did not test this

SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= RAND()

MSSQL version:

SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float) / CAST (0x7fffffff AS int)

This will select ~1% of records. So if you need exact # of percents or records to be selected, estimate your percentage with some safety margin, then randomly pluck excess records from resulting set, using the more expensive ORDER BY RAND() method.

Even Faster

I was able to improve upon this method even further because I had a well-known indexed column value range.

For example, if you have an indexed column with uniformly distributed integers [0..max], you can use that to randomly select N small intervals. Do this dynamically in your program to get a different set for each query run. This subset selection will be O(N), which can many orders of magnitude smaller than your full data set.

In my test I reduced the time needed to get 20 (out 20 mil) sample records from 3 mins using ORDER BY RAND() down to 0.0 seconds!

What is the shortest function for reading a cookie by name in JavaScript?

Just to throw my hat in the race, here's my proposal:

function getCookie(name) {
   const cookieDict = document.cookie.split(';')
        .map((x)=>x.split('='))
        .reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, Object());
    return cookieDict[name];
}

The above code generates a dict that stores cookies as key-value pairs (i.e., cookieDict), and afterwards accesses the property name to retrieve the cookie.

This could effectively be expressed as a one-liner, but this is only for the brave:

document.cookie.split(';').map((x)=>x.split('=')).reduce((accum,current) => { accum[current[0]]=current[1]; return accum;}, {})[name]

The absolute best approach would be to generate cookieDict at page load and then throughout the page lifecycle just access individual cookies by calling cookieDict['cookiename'].

How to define custom configuration variables in rails

Check out this neat gem doing exactly that: https://github.com/mislav/choices

This way your sensitive data won't be exposed in open source projects

Search for a string in all tables, rows and columns of a DB

If you are "getting data" from an application, the sensible thing would be to use the profiler and profile the database while running the application. Trace it, then search the results for that string.

How do I use spaces in the Command Prompt?

You should try using quotes.

cmd /C "C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*"

How to add text to JFrame?

when I create my JLabel and enter the text to it, there is no wordwrap or anything

HTML formatting can be used to cause word wrap in any Swing component that offers styled text. E.G. as demonstrated in this answer.

How do I check OS with a preprocessor directive?

You can use Boost.Predef which contains various predefined macros for the target platform including the OS (BOOST_OS_*). Yes boost is often thought as a C++ library, but this one is a preprocessor header that works with C as well!

This library defines a set of compiler, architecture, operating system, library, and other version numbers from the information it can gather of C, C++, Objective C, and Objective C++ predefined macros or those defined in generally available headers. The idea for this library grew out of a proposal to extend the Boost Config library to provide more, and consistent, information than the feature definitions it supports. What follows is an edited version of that brief proposal.

For example

#include <boost/predef.h>

#if defined(BOOST_OS_WINDOWS)
#elif defined(BOOST_OS_ANDROID)
#elif defined(BOOST_OS_LINUX)
#elif defined(BOOST_OS_BSD)
#elif defined(BOOST_OS_AIX)
#elif defined(BOOST_OS_HAIKU)
...
#endif

The full list can be found in BOOST_OS operating system macros

See also How to get platform ids from boost

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

Android Horizontal RecyclerView scroll Direction

Horizontal RecyclerView with imageview and textview

xml file

main.xml

<LinearLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginTop="5dp"
   android:orientation="vertical"
   android:background="#070e94">
<View
    android:background="#787878"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    />
<android.support.v7.widget.RecyclerView
    android:id="@+id/wallet"
    android:background="#070e94"
    android:layout_width="match_parent"
    android:layout_height="100dp"/>

item.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_marginTop="5dp">
<ImageView
    android:id="@+id/image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:scaleType="fitXY"
    android:src="@drawable/bus"
    android:layout_gravity="center"/>
<TextView
    android:textColor="#000"
    android:textSize="12sp"
    android:layout_gravity="center"
    android:padding="5dp"
    android:id="@+id/txtView"
    android:textAlignment="center"
    android:hint="Electronics"
    android:layout_width="80dp"
    android:layout_height="wrap_content" />

Java Class

ActivityMaim.java

public class MainActivity extends AppCompatActivity{
private  RecyclerView  horizontal_recycler_view;
private ArrayList<Arraylist> horizontalList;
private CustomAdapter horizontalAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    horizontal_recycler_view= (RecyclerView) findViewById(R.id.horizontal_recycler_view);
    horizontalList = new ArrayList<Arraylist>();
    for (int i = 0; i < MyData.nameArray.length; i++) {
        horizontalList.add(new Arraylist(
                MyData.nameArray[i],
                MyData.drawableArray[i]
        ));
    }
    horizontalAdapter=new CustomAdapter(horizontalList);
    LinearLayoutManager horizontalLayoutManagaer
            = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
    horizontal_recycler_view.setLayoutManager(horizontalLayoutManagaer);
    horizontal_recycler_view.setAdapter(horizontalAdapter);
}}

Adaper Class

CustomAdapter.java

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

private ArrayList<Arraylist> dataSet;

public static class MyViewHolder extends RecyclerView.ViewHolder {

    TextView textViewName;

    ImageView imageViewIcon;

    public MyViewHolder(View itemView) {
        super(itemView);
        this.textViewName = (TextView) itemView.findViewById(R.id.txtView);
        //this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
        this.imageViewIcon = (ImageView) itemView.findViewById(R.id.image);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if (getPosition()==0)
                {
                    Toast.makeText(v.getContext(), " On CLick one", Toast.LENGTH_SHORT).show();

                } if (getPosition()==1)
                {
                    Toast.makeText(v.getContext(), " On CLick Two", Toast.LENGTH_SHORT).show();

                } if (getPosition()==2)
                {
                    Toast.makeText(v.getContext(), " On CLick Three", Toast.LENGTH_SHORT).show();

                } if (getPosition()==3)
                {
                    Toast.makeText(v.getContext(), " On CLick Fore", Toast.LENGTH_SHORT).show();

                }

            }
        });
    }
}

public CustomAdapter(ArrayList<Arraylist> data) {
    this.dataSet = data;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                       int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view, parent, false);

    //view.setOnClickListener(MainActivity.myOnClickListener);

    MyViewHolder myViewHolder = new MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {

    TextView textViewName = holder.textViewName;
   // TextView textViewVersion = holder.textViewVersion;
    ImageView imageView = holder.imageViewIcon;

    textViewName.setText(dataSet.get(listPosition).getName());
    //textViewVersion.setText(dataSet.get(listPosition).getVersion());
    imageView.setImageResource(dataSet.get(listPosition).getImage());
}

@Override
public int getItemCount() {
    return dataSet.size();
}}

Arraylist.java

public class Arraylist{
String name;
int image;

public Arraylist(String name, int image) {
    this.name = name;
    this.image=image;
}
public String getName() {
    return name;
}
public int getImage() {
    return image;
}}

MyData.java

public class MyData {
static String[] nameArray = {"Gas", "Insurance", "Electronics", "Other Services"};
static Integer[] drawableArray = {R.drawable.gas_gas, R.drawable.insurance, R.drawable.electric, R.drawable.services};}

Is it possible to import modules from all files in a directory, using a wildcard?

I was able to take from user atilkan's approach and modify it a bit:

For Typescript users;

require.context('@/folder/with/modules', false, /\.ts$/).keys().forEach((fileName => {
    import('@/folder/with/modules' + fileName).then((mod) => {
            (window as any)[fileName] = mod[fileName];
            const module = new (window as any)[fileName]();

            // use module
});

}));

Changing text of UIButton programmatically swift

To set a title for a button in Xcode using swift - 04: first create a method called setTitle with parameter title and UIController state like below ;

func setTitle(_ title : String?, for state : UIControl.State)   {

}

and recall this method in your button action method like ;

yourButtonName.setTitle("String", for: .state)

Incrementing in C++ - When to use x++ or ++x?

Just wanted to re-emphasize that ++x is expected to be faster than x++, (especially if x is an object of some arbitrary type), so unless required for logical reasons, ++x should be used.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

How to set locale in DatePipe in Angular 2?

I was struggling with the same issue and didn't work for me using this

{{dateObj | date:'ydM'}}

So, I've tried a workaround, not the best solution but it worked:

{{dateObj | date:'d'}}/{{dateObj | date:'M'}}/{{dateObj | date:'y'}}

I can always create a custom pipe.

Difference between an API and SDK

Piece of cake:

  • an API is an interface. It's like the specification of the telephone system or the electrical wiring in your house. Anything* can use it as long as it knows how to interface. You can even buy off-the-shelf software to use a particular API, just as you can buy off the shelf telephone equipment or devices that plug into the AC wiring in your house.
  • an SDK is implementation tooling. It's like a kit that allows** you to build something custom to hook up to the telephone system or electrical wiring.

*Anything can use an API. Some APIs have security provisions to require license keys, authentication, etc. which may prohibit complete use of the API in particular instances, but that's only because particular authentication/authorization steps fail. Any software that presents the right credentials (if required) can use the API.

**Technically, if an API is well-documented, you don't need an SDK to build your own software to use the API. But having an SDK generally makes the process much easier.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

The documentation states several ways to do this.

If you want to replace the default ObjectMapper completely, define a @Bean of that type and mark it as @Primary.

Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).

How to call javascript from a href?

<a href="javascript:call_func();">...</a>

where the function then has to return false so that the browser doesn't go to another page.

But I'd recommend to use jQuery (with $(...).click(function () {})))

How does the "position: sticky;" property work?

Funny moment that wasn't obvious for me: at least in Chrome 70 position: sticky is not applied if you've set it using DevTools.

JavaScript global event mechanism

It seems that window.onerror doesn't provide access to all possible errors. Specifically it ignores:

  1. <img> loading errors (response >= 400).
  2. <script> loading errors (response >= 400).
  3. global errors if you have many other libraries in your app also manipulating window.onerror in an unknown way (jquery, angular, etc.).
  4. probably many cases I haven't run into after exploring this now (iframes, stack overflow, etc.).

Here is the start of a script that catches many of these errors, so that you may add more robust debugging to your app during development.

(function(){

/**
 * Capture error data for debugging in web console.
 */

var captures = [];

/**
 * Wait until `window.onload`, so any external scripts
 * you might load have a chance to set their own error handlers,
 * which we don't want to override.
 */

window.addEventListener('load', onload);

/**
 * Custom global function to standardize 
 * window.onerror so it works like you'd think.
 *
 * @see http://www.quirksmode.org/dom/events/error.html
 */

window.onanyerror = window.onanyerror || onanyerrorx;

/**
 * Hook up all error handlers after window loads.
 */

function onload() {
  handleGlobal();
  handleXMLHttp();
  handleImage();
  handleScript();
  handleEvents();
}

/**
 * Handle global window events.
 */

function handleGlobal() {
  var onerrorx = window.onerror;
  window.addEventListener('error', onerror);

  function onerror(msg, url, line, col, error) {
    window.onanyerror.apply(this, arguments);
    if (onerrorx) return onerrorx.apply(null, arguments);
  }
}

/**
 * Handle ajax request errors.
 */

function handleXMLHttp() {
  var sendx = XMLHttpRequest.prototype.send;
  window.XMLHttpRequest.prototype.send = function(){
    handleAsync(this);
    return sendx.apply(this, arguments);
  };
}

/**
 * Handle image errors.
 */

function handleImage() {
  var ImageOriginal = window.Image;
  window.Image = ImageOverride;

  /**
   * New `Image` constructor. Might cause some problems,
   * but not sure yet. This is at least a start, and works on chrome.
   */

  function ImageOverride() {
    var img = new ImageOriginal;
    onnext(function(){ handleAsync(img); });
    return img;
  }
}

/**
 * Handle script errors.
 */

function handleScript() {
  var HTMLScriptElementOriginal = window.HTMLScriptElement;
  window.HTMLScriptElement = HTMLScriptElementOverride;

  /**
   * New `HTMLScriptElement` constructor.
   *
   * Allows us to globally override onload.
   * Not ideal to override stuff, but it helps with debugging.
   */

  function HTMLScriptElementOverride() {
    var script = new HTMLScriptElement;
    onnext(function(){ handleAsync(script); });
    return script;
  }
}

/**
 * Handle errors in events.
 *
 * @see http://stackoverflow.com/questions/951791/javascript-global-error-handling/31750604#31750604
 */

function handleEvents() {
  var addEventListenerx = window.EventTarget.prototype.addEventListener;
  window.EventTarget.prototype.addEventListener = addEventListener;
  var removeEventListenerx = window.EventTarget.prototype.removeEventListener;
  window.EventTarget.prototype.removeEventListener = removeEventListener;

  function addEventListener(event, handler, bubble) {
    var handlerx = wrap(handler);
    return addEventListenerx.call(this, event, handlerx, bubble);
  }

  function removeEventListener(event, handler, bubble) {
    handler = handler._witherror || handler;
    removeEventListenerx.call(this, event, handler, bubble);
  }

  function wrap(fn) {
    fn._witherror = witherror;

    function witherror() {
      try {
        fn.apply(this, arguments);
      } catch(e) {
        window.onanyerror.apply(this, e);
        throw e;
      }
    }
    return fn;
  }
}

/**
 * Handle image/ajax request errors generically.
 */

function handleAsync(obj) {
  var onerrorx = obj.onerror;
  obj.onerror = onerror;
  var onabortx = obj.onabort;
  obj.onabort = onabort;
  var onloadx = obj.onload;
  obj.onload = onload;

  /**
   * Handle `onerror`.
   */

  function onerror(error) {
    window.onanyerror.call(this, error);
    if (onerrorx) return onerrorx.apply(this, arguments);
  };

  /**
   * Handle `onabort`.
   */

  function onabort(error) {
    window.onanyerror.call(this, error);
    if (onabortx) return onabortx.apply(this, arguments);
  };

  /**
   * Handle `onload`.
   *
   * For images, you can get a 403 response error,
   * but this isn't triggered as a global on error.
   * This sort of standardizes it.
   *
   * "there is no way to get the HTTP status from a 
   * request made by an img tag in JavaScript."
   * @see http://stackoverflow.com/questions/8108636/how-to-get-http-status-code-of-img-tags/8108646#8108646
   */

  function onload(request) {
    if (request.status && request.status >= 400) {
      window.onanyerror.call(this, request);
    }
    if (onloadx) return onloadx.apply(this, arguments);
  }
}

/**
 * Generic error handler.
 *
 * This shows the basic implementation, 
 * which you could override in your app.
 */

function onanyerrorx(entity) {
  var display = entity;

  // ajax request
  if (entity instanceof XMLHttpRequest) {
    // 400: http://example.com/image.png
    display = entity.status + ' ' + entity.responseURL;
  } else if (entity instanceof Event) {
    // global window events, or image events
    var target = entity.currentTarget;
    display = target;
  } else {
    // not sure if there are others
  }

  capture(entity);
  console.log('[onanyerror]', display, entity);
}

/**
 * Capture stuff for debugging purposes.
 *
 * Keep them in memory so you can reference them
 * in the chrome debugger as `onanyerror0` up to `onanyerror99`.
 */

function capture(entity) {
  captures.push(entity);
  if (captures.length > 100) captures.unshift();

  // keep the last ones around
  var i = captures.length;
  while (--i) {
    var x = captures[i];
    window['onanyerror' + i] = x;
  }
}

/**
 * Wait til next code execution cycle as fast as possible.
 */

function onnext(fn) {
  setTimeout(fn, 0);
}

})();

It could be used like this:

window.onanyerror = function(entity){
  console.log('some error', entity);
};

The full script has a default implementation that tries to print out a semi-readable "display" version of the entity/error that it receives. Can be used for inspiration for an app-specific error handler. The default implementation also keeps a reference to the last 100 error entities, so you can inspect them in the web console after they occur like:

window.onanyerror0
window.onanyerror1
...
window.onanyerror99

Note: This works by overriding methods on several browser/native constructors. This can have unintended side-effects. However, it has been useful to use during development, to figure out where errors are occurring, to send logs to services like NewRelic or Sentry during development so we can measure errors during development, and on staging so we can debug what is going on at a deeper level. It can then be turned off in production.

Hope this helps.

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

grant remote access of MySQL database from any IP address

For example in my CentOS

sudo gedit /etc/mysql/my.cnf

comment out the following lines

#bind-address = 127.0.0.1

then

sudo service mysqld restart

Encoding Javascript Object to Json string

You can use JSON.stringify like:

JSON.stringify(new_tweets);

Select objects based on value of variable in object using jq

To obtain a stream of just the names:

$ jq '.[] | select(.location=="Stockholm") | .name' json

produces:

"Donald"
"Walt"

To obtain a stream of corresponding (key name, "name" attribute) pairs, consider:

$ jq -c 'to_entries[]
        | select (.value.location == "Stockholm")
        | [.key, .value.name]' json

Output:

["FOO","Donald"]
["BAR","Walt"]

How to change the buttons text using javascript

Another solution could be using jquery button selector inside the if else statement $("#buttonId").text("your text");

function showFilterItem() {
if (filterstatus == 0) {
    filterstatus = 1;
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
    $("#ShowButton").text("Hide Filter");
}
else {
    filterstatus = 0;
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
     $("#ShowButton").text("Show Filter");
}}

Set Background cell color in PHPExcel

$sheet->getStyle('A1')->applyFromArray(
    array(
        'fill' => array(
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => array('rgb' => 'FF0000')
        )
    )
);

Source: http://bayu.freelancer.web.id/2010/07/16/phpexcel-advanced-read-write-excel-made-simple/

How do I insert values into a Map<K, V>?

There are two issues here.

Firstly, you can't use the [] syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.

data.put is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:

public class Data {
     public static void main(String[] args) {
         Map<String, String> data = new HashMap<String, String>();
         data.put("John", "Taxi Driver");
         data.put("Mark", "Professional Killer");
     }
 }

If you want to initialize a map as a static field of a class then you can use Map.of, since Java 9:

public class Data {
    private static final Map<String, String> DATA = Map.of("John", "Taxi Driver");
}

Before Java 9, you can use a static initializer block to accomplish the same thing:

public class Data {
    private static final Map<String, String> DATA = new HashMap<>();

    static {
        DATA.put("John", "Taxi Driver");
    }
}

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Worked by lowering the spring boot starter parent to 1.5.13

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.13.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

Remove the last line from a file in Bash

Both of these solutions are here in other forms. I found these a little more practical, clear, and useful:

Using dd:

BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
dd if=${ORIGINALFILE} of=${ORIGINALFILE}.tmp status=none bs=1 count=$(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc )
/bin/mv -f ${ORIGINALFILE}.tmp ${ORIGINALFILE}

Using truncate:

BADLINESCOUNT=1
ORIGINALFILE=/tmp/whatever
truncate -s $(printf "$(stat --format=%s ${ORIGINALFILE}) - $(tail -n${BADLINESCOUNT} ${ORIGINALFILE} | wc -c)\n" | bc ) ${ORIGINALFILE}

sql: check if entry in table A exists in table B

SELECT *
FROM   B
WHERE  NOT EXISTS (SELECT 1 
                   FROM   A 
                   WHERE  A.ID = B.ID)

How can I roll back my last delete command in MySQL?

The accepted answer is not always correct. If you configure binary logging on MySQL, you can rollback the database to any previous point you still have a snapshot and binlog for.

7.5 Point-in-Time (Incremental) Recovery Using the Binary Log is a good starting point for learning about this facility.

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

The YouTube URL in src must have and use the embed endpoint instead of watch, so for instance let’s say you want to embed this YouTube video: https://www.youtube.com/watch?v=P6N9782MzFQ (browser's URL).

You should use the embed endpoint, so the URL now should be something like https://www.youtube.com/embed/P6N9782MzFQ. Use this value as the URL in the src attribute inside the iframe tag in your HTML code, for example:

<iframe width="853" height="480" src="https://www.youtube.com/embed/P6N9782MzFQ" frameborder="0" allowfullscreen ng-show="showvideo"></iframe>

So just replace https://www.youtube.com/watch?v= with https://www.youtube.com/embed/ and of course check for your video's ID. In this sample, my video ID is P6N9782MzFQ.

Make a VStack fill the width of the screen in SwiftUI

This is a useful bit of code:

extension View {
    func expandable () -> some View {
        ZStack {
            Color.clear
            self
        }
    }
}

Compare the results with and without the .expandable() modifier:

Text("hello")
    .background(Color.blue)

-

Text("hello")
    .expandable()
    .background(Color.blue)

enter image description here

How to change maven logging level to display only warning and errors?

Unfortunately, even with maven 3 the only way to do that is to patch source code.

Here is short instruction how to do that.

Clone or fork Maven 3 repo: "git clone https://github.com/apache/maven-3.git"

Edit org.apache.maven.cli.MavenCli#logging, and change

cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_INFO );

to

cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_WARN );

In current snapshot version it's at line 270

Then just run "mvn install", your new maven distro will be located in "apache-maven\target\" folder

See this diff for the reference: https://github.com/ushkinaz/maven-3/commit/cc079aa75ca8c82658c7ff53f18c6caaa32d2131

How can I check for an empty/undefined/null string in JavaScript?

For checking if a string is empty, null or undefined I use:

function isEmpty(str) {
    return (!str || 0 === str.length);
}

For checking if a string is blank, null or undefined I use:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

For checking if a string is blank or contains only white-space:

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};

How to get the first element of an array?

Some of ways below for different circumstances.

In most normal cases, the simplest way to access the first element is by

yourArray[0]

but this requires you to check if [0] actually exists.

There are real world cases where you don't care about the original array, and don't want to check if index exists, you want just to get the first element or undefined inline.

In this case, you can use shift() method to get the first element, but be cautious that this method modifies the original array (removes the first item and returns it). Therefore the length of an array is reduced by one. This method can be used in inline cases where you just need to get the first element, but you dont care about the original array.

yourArray.shift()

The important thing to know is that the two above are only an option if your array starts with a [0] index.

There are cases where the first element has been deleted, example with, delete yourArray[0] leaving your array with "holes". Now the element at [0] is simply undefined, but you want to get the first "existing" element. I have seen many real world cases of this.

So, assuming we have no knowledge of the array and the first key (or we know there are holes), we can still get the first element.

You can use find() to get the first element.

The advantage of find() is its efficiency as it exits the loop when the first value satisfying the condition is reached (more about this below). (You can customize the condition to exclude null or other empty values too)

var firstItem = yourArray.find(x=>x!==undefined);

I'd also like to include filter() here as an option to first "fix" the array in the copy and then get the first element while keeping the the original array intact (unmodified).

Another reason to include filter() here is that it existed before find() and many programmers have already been using it (it is ES5 against find() being ES6).

var firstItem = yourArray.filter(x => typeof x!==undefined).shift();

Warning that filter() is not really an efficient way (filter() runs through all elements) and creates another array. It is fine to use on small arrays as performance impact would be marginal, closer to using forEach, for example.

(I see some people suggest using for...in loop to get the first element, but I would recommend against this method for...in should not be used to iterate over an Array where the index order is important because it doesn't guarantee the order although you can argue browsers mostly respect the order.By the way, forEach doesn't solve the issue as many suggest because you cant break it and it will run through all elements. You would be better off using a simple for loop and by checking key/value

Both find() and filter() guarantee the order of elements, so are safe to use as above.

How to get Latitude and Longitude of the mobile device in android?

Best way is

Add permission manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Then you can get GPS location or if GPS location is not available then this function return NETWORK location

    public static Location getLocationWithCheckNetworkAndGPS(Context mContext) {
    LocationManager lm = (LocationManager)
            mContext.getSystemService(Context.LOCATION_SERVICE);
    assert lm != null;
    isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    Location networkLoacation = null, gpsLocation = null, finalLoc = null;
    if (isGpsEnabled)
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return null;
        }gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (isNetworkLocationEnabled)
        networkLoacation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    if (gpsLocation != null && networkLoacation != null) {

        //smaller the number more accurate result will
        if (gpsLocation.getAccuracy() > networkLoacation.getAccuracy())
            return finalLoc = networkLoacation;
        else
            return finalLoc = gpsLocation;

    } else {

        if (gpsLocation != null) {
            return finalLoc = gpsLocation;
        } else if (networkLoacation != null) {
            return finalLoc = networkLoacation;
        }
    }
    return finalLoc;
}

Multiple -and -or in PowerShell Where-Object statement

You're using curvy-braces when you should be using parentheses.

A where statement is kept inside a scriptblock, which is defined using curvy baces { }. To isolate/wrap you tests, you should use parentheses ().

I would also suggest trying to do the filtering on the remote computer. Try:

Invoke-Command -computername SERVERNAME {
    Get-ChildItem -path E:\dfsroots\datastore2\public |
    Where-Object { ($_.extension -eq "xls" -or $_.extension -eq "xlk") -and $_.creationtime -ge "06/01/2014" }
}

How can I create directories recursively?

I agree with Cat Plus Plus's answer. However, if you know this will only be used on Unix-like OSes, you can use external calls to the shell commands mkdir, chmod, and chown. Make sure to pass extra flags to recursively affect directories:

>>> import subprocess
>>> subprocess.check_output(['mkdir', '-p', 'first/second/third']) 
# Equivalent to running 'mkdir -p first/second/third' in a shell (which creates
# parent directories if they do not yet exist).

>>> subprocess.check_output(['chown', '-R', 'dail:users', 'first'])
# Recursively change owner to 'dail' and group to 'users' for 'first' and all of
# its subdirectories.

>>> subprocess.check_output(['chmod', '-R', 'g+w', 'first'])
# Add group write permissions to 'first' and all of its subdirectories.

EDIT I originally used commands, which was a bad choice since it is deprecated and vulnerable to injection attacks. (For example, if a user gave input to create a directory called first/;rm -rf --no-preserve-root /;, one could potentially delete all directories).

EDIT 2 If you are using Python less than 2.7, use check_call instead of check_output. See the subprocess documentation for details.

What is the difference between association, aggregation and composition?

I'd like to illustrate how the three terms are implemented in Rails. ActiveRecord calls any type of relationship between two models an association. One would not find very often the terms composition and aggregation, when reading documentation or articles, related to ActiveRecord. An association is created by adding one of the association class macros to the body of the class. Some of these macros are belongs_to, has_one, has_many etc..

If we want to set up a composition or aggregation, we need to add belongs_to to the owned model (also called child) and has_one or has_many to the owning model (also called parent). Wether we set up composition or aggregation depends on the options we pass to the belongs_to call in the child model. Prior to Rails 5, setting up belongs_to without any options created an aggregation, the child could exist without a parent. If we wanted a composition, we needed to explicitly declare this by adding the option required: true:

class Room < ActiveRecord::Base
  belongs_to :house, required: true
end

In Rails 5 this was changed. Now, declaring a belongs_to association creates a composition by default, the child cannot exist without a parent. So the above example can be re-written as:

class Room < ApplicationRecord
  belongs_to :house
end

If we want to allow the child object to exist without a parent, we need to declare this explicitly via the option optional

class Product < ApplicationRecord
  belongs_to :category, optional: true
end

How to solve WAMP and Skype conflict on Windows 7?

Run Wamp services before Skype
Quit Skype >>> Run WAMP >>> Run Skype

How to list active / open connections in Oracle?

select s.sid as "Sid", s.serial# as "Serial#", nvl(s.username, ' ') as "Username", s.machine as "Machine", s.schemaname as "Schema name", s.logon_time as "Login time", s.program as "Program", s.osuser as "Os user", s.status as "Status", nvl(s.process, ' ') as "OS Process id"
from v$session s
where nvl(s.username, 'a') not like 'a' and status like 'ACTIVE'
order by 1,2

This query attempts to filter out all background processes.

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

How to delete the last row of data of a pandas dataframe

Just use indexing

df.iloc[:-1,:]

That's why iloc exists. You can also use head or tail.

Multiple IF AND statements excel

Try the following:

=IF(OR(E2="in play",E2="pre play",E2="complete",E2="suspended"),
IF(E2="in play",IF(F2="closed",3,IF(F2="suspended",2,IF(ISBLANK(F2),1,-2))),
IF(E2="pre play",IF(ISBLANK(F2),-1,-2),IF(E2="completed",IF(F2="closed",2,-2),
IF(E2="suspended",IF(ISBLANK(F2),3,-2))))),-2)

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Finally resolved my java install issue on Win 7 64-bit running IE11.

Even though I installed the latest Java (65) via a java auto-update prompt, tried a verify java version and java failed to run, shut down all IE instances, failed to run verify again, shut down all running programs, failed to run verify again, rebooted, failed to run verify again, re-installed 65 again (shutting down the browser manually as it downloaded), and finally verify ran. What a pain.

The message I kept receiving was "The page you are viewing uses Java ..."; e.g. https://www.java.com/en/download/help/ie_tips.xml. I do use sleep mode on my desktop and I believe that this is probably the major issue with install and IE with its "clever" integration into the OS and explorer/desktop. I thought the government told them to not do that. I've had issues with CD-ROM drive disappearing and other unexplained periodic issues; all cured after a full reboot. They are infrequent, so I live with them for the convenience of faster startup times.

Hope this helps someone!

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

    // Java 8
    System.out.println(LocalDateTime.now().getYear());       // 2015
    System.out.println(LocalDateTime.now().getMonth());      // SEPTEMBER
    System.out.println(LocalDateTime.now().getDayOfMonth()); // 29
    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 36
    System.out.println(LocalDateTime.now().getSecond());     // 51
    System.out.println(LocalDateTime.now().get(ChronoField.MILLI_OF_SECOND)); // 100

    // Calendar
    System.out.println(Calendar.getInstance().get(Calendar.YEAR));         // 2015
    System.out.println(Calendar.getInstance().get(Calendar.MONTH ) + 1);   // 9
    System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); // 29
    System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7
    System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 35
    System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32
    System.out.println(Calendar.getInstance().get(Calendar.MILLISECOND));  // 481

    // Joda Time
    System.out.println(new DateTime().getYear());           // 2015
    System.out.println(new DateTime().getMonthOfYear());    // 9
    System.out.println(new DateTime().getDayOfMonth());     // 29
    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 19
    System.out.println(new DateTime().getSecondOfMinute()); // 16
    System.out.println(new DateTime().getMillisOfSecond()); // 174

    // Formatted
    // 2015-09-28 17:50:25.756
    System.out.println(new Timestamp(System.currentTimeMillis()));

    // 2015-09-28T17:50:25.772
    System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(new Date()));

    // Java 8
    // 2015-09-28T17:50:25.810
    System.out.println(LocalDateTime.now());

    // joda time
    // 2015-09-28 17:50:25.839
    System.out.println(DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").print(new org.joda.time.DateTime()));

Jackson - Deserialize using generic class

Example of not very good, but simple decision (not only for Jackson, also for Spring RestTemplate, etc.):

Set<MyClass> res = new HashSet<>();
objectMapper.readValue(json, res.getClass());

How to allow only numeric (0-9) in HTML inputbox using jQuery?

You can try the HTML5 number input:

<input type="number" placeholder="enter the number" min="0" max="9">

This input tag element would now take value only between 0 to 9 as min attribute is set to 0 and max attribute is set to 9.

for more information on visit http://www.w3schools.com/html/html_form_input_types.asp

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

How to change maven java home

Even if you install the Oracle JDK, your $JAVA_HOME variable should refer to the path of the JRE that is inside the JDK root. You can refer to my other answer to a similar question for more details.

Perform commands over ssh with Python

Have a look at spurplus, a wrapper we developed around spur that provides type annotations and some minor gimmicks (reconnecting SFTP, md5 etc.): https://pypi.org/project/spurplus/

How to grant remote access permissions to mysql server for user?

Two steps:

  1. set up user with wildcard:
    create user 'root'@'%' identified by 'some_characters'; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD 'some_characters' WITH GRANT OPTION

  2. vim /etc/my.cnf
    add the following:
    bind-address=0.0.0.0

restart server, you should not have any problem connecting to it.

Missing Authentication Token while accessing API Gateway?

I just had the same issue and it seems it also shows this message if the resource cannot be found.

In my case I had updated the API, but forgotten to redeploy. The issue was resolved after deploying the updated API to my stage.

How to have multiple conditions for one if statement in python

I am a little late to the party but I thought I'd share a way of doing it, if you have identical types of conditions, i.e. checking if all, any or at given amount of A_1=A_2 and B_1=B_2, this can be done in the following way:

cond_list_1=["1","2","3"]
cond_list_2=["3","2","1"]
nr_conds=1

if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])>=nr_conds:
    print("At least " + str(nr_conds) + " conditions are fullfilled")

if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])==len(cond_list_1):
    print("All conditions are fullfilled")

This means you can just change in the two initial lists, at least for me this makes it easier.

List<object>.RemoveAll - How to create an appropriate Predicate

I wanted to address something none of the answers have so far:

From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID. As an[sic] supplementary question, is a Generic list the best repository for these objects?

Assuming VehicleID is unique as the name suggests, a list is a terribly inefficient way to store them when you get a lot of vehicles, as removal(and other methods like Find) is still O(n). Have a look at a HashSet<Vehicle> instead, it has O(1) removal(and other methods) using:

int GetHashCode(Vehicle vehicle){return vehicle.VehicleID;}
int Equals(Vehicle v1, Vehicle v2){return v1.VehicleID == v2.VehicleID;}

Removing all vehicles with a specific EnquiryID still requires iterating over all elements this way, so you could consider a GetHashCode that returns the EnquiryID instead, depending on which operation you do more often. This has the downside of a lot of collisions if a lot of Vehicles share the same EnquiryID though.

In this case, a better alternative is to make a Dictionary<int, List<Vehicle>> that maps EnquiryIDs to Vehicles and keep that up to date when adding/removing vehicles. Removing these vehicles from a HashSet is then an O(m) operation, where m is the number of vehicles with a specific EnquiryID.

Is there a way to collapse all code blocks in Eclipse?

In addition to the hotkey, if you right click in the gutter where you see the +/-, there is a context menu item 'Folding.' Opening the submenu associated with this, you can see a 'Collapse All' item. this will also do what you wish.

MySQL: Check if the user exists and drop it

DROP USER IF EXISTS 'user'@'localhost' ;

that works for me without throwing any errors in Maria DB, it should work for u too

One line if/else condition in linux shell scripting

It looks as if you were on the right track. You just need to add the else statement after the ";" following the "then" statement. Also I would split the first line from the second line with a semicolon instead of joining it with "&&".

maxline='cat journald.conf | grep "#SystemMaxUse="'; if [ $maxline == "#SystemMaxUse=" ]; then sed 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf > journald.conf2 && mv journald.conf2 journald.conf; else echo "This file has been edited. You'll need to do it manually."; fi

Also in your original script, when declaring maxline you used back-ticks "`" instead of single quotes "'" which might cause problems.

how to pass parameter from @Url.Action to controller function

If you are using Url.Action inside JavaScript then you can

var personId="someId";
$.ajax({
  type: 'POST',
  url: '@Url.Action("CreatePerson", "Person")',
  dataType: 'html',
  data: ({
  //insert your parameters to pass to controller
    id: personId 
  }),
  success: function() {
    alert("Successfully posted!");
  }
});

How can I get the current class of a div with jQuery?

Just get the class attribute:

var div1Class = $('#div1').attr('class');

Example

<div id="div1" class="accordion accordion_active">

To check the above div for classes contained in it

var a = ("#div1").attr('class'); 
console.log(a);

console output

accordion accordion_active

Call removeView() on the child's parent first

Ok, call me paranoid but I suggest:

  final android.view.ViewParent parent = view.getParent ();

  if (parent instanceof android.view.ViewManager)
  {
     final android.view.ViewManager viewManager = (android.view.ViewManager) parent;

     viewManager.removeView (view);
  } // if

casting without instanceof just seems wrong. And (thanks IntelliJ IDEA for telling me) removeView is part of the ViewManager interface. And one should not cast to a concrete class when a perfectly suitable interface is available.

Capturing URL parameters in request.GET

Using GET

request.GET["id"]

Using POST

request.POST["id"]

Handling a Menu Item Click Event - Android

simple code for creating menu..

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

simple code for menu selected

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.new_game:
        newGame();
        return true;
    case R.id.help:
        showHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

for more detail go below link..

Link1

Link2

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

HP computer method:

Make sure your BIOS is updated before changing the settings. If you have an HP computer, they have an HP Support Assistant app you can configure to automatically install BIOS updates. Then follow the instructions on how to update BIOS.

Then you can look up which HP computer for how to change the BIOS in a search engine.

For an HP ZBook, follow these steps:

  1. Restart your computer with the shift key pressed (before you click restart) until a menu appears.
  2. Choose BIOS Setup on the screen (or press F10).
  3. Click on Troubleshoot.
  4. Using your arrow keys in this menu, go to Advanced Options.
  5. Select UEFI Firmware Settings.
  6. Select restart.
  7. It reboots into a Startup menu
  8. Choose BIOS Setup With arrow keys go to Advanced tab.
  9. Choose the System Options.
  10. Check both the Virtualization Technology (VTx) and the Virtualization Technology for Directed I/O (VTd) boxes.
  11. Go back to the Main tab and at bottom choose Save and Exit.
  12. Computer will restart.

Import SQL file by command line in Windows 7

----------------WARM server.

step 1: go to cmd go to directory C:\wamp\bin\mysql\mysql5.6.17 hold Shift + right click (choose "open command window here")

step 2: C:\wamp\bin\mysql\mysql5.6.17\bin>mysql -u root -p SellProduct < D:\file.sql

in this case
+ Root is username database  
+ SellProduct is name database.
+ D:\file.sql is file you want to import

---------------It's work with me -------------------

How do I catch a numpy warning like it's an exception (not just for testing)?

To add a little to @Bakuriu's answer:

If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate context manager, rather than numpy.seterr which treats all subsequent warnings of the same type the same regardless of where they occur within your code:

import numpy as np

a = np.r_[1.]
with np.errstate(divide='raise'):
    try:
        a / 0   # this gets caught and handled as an exception
    except FloatingPointError:
        print('oh no!')
a / 0           # this prints a RuntimeWarning as usual

Edit:

In my original example I had a = np.r_[0], but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:

all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])

with np.errstate(divide='raise'):
    not_all_zeros / 0.  # Raises FloatingPointError

with np.errstate(divide='raise'):
    all_zeros / 0.  # No exception raised

with np.errstate(invalid='raise'):
    all_zeros / 0.  # Raises FloatingPointError

The corresponding warning messages are also different: 1. / 0. is logged as RuntimeWarning: divide by zero encountered in true_divide, whereas 0. / 0. is logged as RuntimeWarning: invalid value encountered in true_divide. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0. is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0. and -1. / 0. return +Inf and -Inf respectively, per the IEE 754 standard.

If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise'), or all='raise' if you want to raise an exception on any kind of floating point error.

Force index use in Oracle

You can use optimizer hints

select /*+ INDEX(table_name index_name) */ from table etc...

More on using optimizer hints: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/hintsref.htm

What's the advantage of a Java enum versus a class with public static final fields?

There are many good answers here, but none mentiones that there are highly optimized implementations of the Collection API classes/interfaces specifically for enums:

These enum specific classes only accept Enum instances (the EnumMap only accept Enums only as keys), and whenever possible, they revert to compact representation and bit manipulation in their implementation.

What does this mean?

If our Enum type has no more that 64 elements (most of real-life Enum examples will qualify for this), the implementations store the elements in a single long value, each Enum instance in question will be associated with a bit of this 64-bit long long. Adding an element to an EnumSet is simply just setting the proper bit to 1, removing it is just setting that bit to 0. Testing if an element is in the Set is just one bitmask test! Now you gotta love Enums for this!

How to configure postgresql for the first time?

There are two methods you can use. Both require creating a user and a database.

  1. Using createuser and createdb,

    $ sudo -u postgres createuser --superuser $USER
    $ createdb mydatabase
    $ psql -d mydatabase
    
  2. Using the SQL administration commands, and connecting with a password over TCP

    $ sudo -u postgres psql postgres
    

    And, then in the psql shell

    CREATE ROLE myuser LOGIN PASSWORD 'mypass';
    CREATE DATABASE mydatabase WITH OWNER = myuser;
    

    Then you can login,

    $ psql -h localhost -d mydatabase -U myuser -p <port>
    

    If you don't know the port, you can always get it by running the following, as the postgres user,

    SHOW port;
    

    Or,

    $ grep "port =" /etc/postgresql/*/main/postgresql.conf
    

Sidenote: the postgres user

I suggest NOT modifying the postgres user.

  1. It's normally locked from the OS. No one is supposed to "log in" to the operating system as postgres. You're supposed to have root to get to authenticate as postgres.
  2. It's normally not password protected and delegates to the host operating system. This is a good thing. This normally means in order to log in as postgres which is the PostgreSQL equivalent of SQL Server's SA, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.
  3. By keeping this disabled, you remove the risk of a brute force attack through a named super-user. Concealing and obscuring the name of the superuser has advantages.

Javascript - check array for value

This should do it:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

How do I tell if a regular file does not exist in Bash?

This code also working .

#!/bin/bash
FILE=$1
if [ -f $FILE ]; then
 echo "File '$FILE' Exists"
else
 echo "The File '$FILE' Does Not Exist"
fi

Negative list index?

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

How to show two figures using matplotlib?

Alternatively, I would suggest turning interactive on in the beginning and at the very last plot, turn it off. All will show up, but they will not disappear as your program will stay around until you close the figures.

import matplotlib.pyplot as plt
from matplotlib import interactive

plt.figure(1)
... code to make figure (1)

interactive(True)
plt.show()

plt.figure(2)
... code to make figure (2)

plt.show()

plt.figure(3)
... code to make figure (3)

interactive(False)
plt.show()

Foreach loop in C++ equivalent of C#

If you have an array you can simply use a for loop. (I'm sorry, but I'm not going to type out the code for a for loop for you.)

Timing a command's execution in PowerShell

Simples

function time($block) {
    $sw = [Diagnostics.Stopwatch]::StartNew()
    &$block
    $sw.Stop()
    $sw.Elapsed
}

then can use as

time { .\some_command }

You may want to tweak the output

SQL Server 2008 Insert with WHILE LOOP

Assuming that ID is an identity column:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. Try to think in terms of sets instead.

Count number of records returned by group by

A CTE worked for me:

with cte as (
  select 1 col1
  from temptable
  group by column_1
)

select COUNT(col1)
from cte;

Sending email from Azure

If you're looking for some ESP alternatives, you should have a look at Mailjet for Microsoft Azure too! As a global email service and infrastructure provider, they enable you to send, deliver and track transactional and marketing emails via their APIs, SMTP Relay or UI all from one single platform, thought both for developers and emails owners.

Disclaimer: I’m working at Mailjet as a Developer Evangelist.

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}

How to implement class constants?

All of the replies with readonly are only suitable when this is a pure TS environment - if it's ever being made into a library then this doesn't actually prevent anything, it just provides warnings for the TS compiler itself.

Static is also not correct - that's adding a method to the Class, not to an instance of the class - so you need to address it directly.

There are several ways to manage this, but the pure TS way is to use a getter - exactly as you have done already.

The alternative way is to put it in as readonly, but then use Object.defineProperty to lock it - this is almost the same thing that is being done via the getter, but you can lock it to have a value, rather than a method to use to get it -

class MyClass {
    MY_CONSTANT = 10;

    constructor() {
        Object.defineProperty(this, "MY_CONSTANT", {value: this.MY_CONSTANT});
    }
}

The defaults make it read-only, but check out the docs for more details.

Google map V3 Set Center to specific Marker

geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

Programmatically Creating UILabel

here is how to create UILabel Programmatically..

1) Write this in .h file of your project.

UILabel *label;

2) Write this in .m file of your project.

label=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];//Set frame of label in your viewcontroller.
[label setBackgroundColor:[UIColor lightGrayColor]];//Set background color of label.
[label setText:@"Label"];//Set text in label.
[label setTextColor:[UIColor blackColor]];//Set text color in label.
[label setTextAlignment:NSTextAlignmentCenter];//Set text alignment in label.
[label setBaselineAdjustment:UIBaselineAdjustmentAlignBaselines];//Set line adjustment.
[label setLineBreakMode:NSLineBreakByCharWrapping];//Set linebreaking mode..
[label setNumberOfLines:1];//Set number of lines in label.
[label.layer setCornerRadius:25.0];//Set corner radius of label to change the shape.
[label.layer setBorderWidth:2.0f];//Set border width of label.
[label setClipsToBounds:YES];//Set its to YES for Corner radius to work.
[label.layer setBorderColor:[UIColor blackColor].CGColor];//Set Border color.
[self.view addSubview:label];//Add it to the view of your choice. 

ImportError: cannot import name

When this is in a python console if you update a module to be able to use it through the console does not help reset, you must use a

import importlib

and

importlib.reload (*module*)

likely to solve your problem

A SQL Query to select a string between two known strings

<pre>

DECLARE @text VARCHAR(MAX)

SET @text = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'

declare @pretext as nvarchar(100) = 'the dog'    
declare @posttext as nvarchar(100) = 'immediately'

SELECT 
 CASE 
When CHARINDEX(@posttext, @Text) - (CHARINDEX(@pretext, @Text) + len(@pretext)) < 0 THEN 
''
Else
SUBSTRING(@Text, CHARINDEX(@pretext, @Text) + len(@pretext)
,   CHARINDEX(@posttext, @Text) - (CHARINDEX(@pretext, @Text) + len(@pretext)) )    
END as betweentext  

How to find the number of days between two dates

DECLARE @Firstdate DATE='2016-04-01',
 @LastDate DATE=GETDATE(),/*get today date*/
 @resultDay int=null

SET @resultDay=(SELECT DATEDIFF(d, @Firstdate, @LastDate))
PRINT @resultDay

How to stop text from taking up more than 1 line?

Using ellipsis will add the ... at the last.

   <style type="text/css">
    div {
      white-space: nowrap;
      overflow: hidden;
text-overflow: ellipsis;
    }
    </style>

Use Expect in a Bash script to provide a password to an SSH command

A simple Expect script:

File Remotelogin.exp

    #!/usr/bin/expect
    set user [lindex $argv 1]
    set ip [lindex $argv 0]
    set password [lindex $argv 2]
    spawn ssh $user@$ip
    expect "password"
    send "$password\r"
    interact

Example:

./Remotelogin.exp <ip> <user name> <password>

Is there a command line command for verifying what version of .NET is installed

REM Search for the CONFIG file, if this doesn't exit then the user doesn't have the .Net framework 2.0 `

SET FileName=%windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG
IF EXIST %FileName% GOTO INSTALL_DIALER
ECHO.You currently do not have the Microsoft(c) .NET Framework 2.0 installed.

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

How to get relative path of a file in visual studio?

Omit the "~\":

var path = @"FolderIcon\Folder.ico";

~\ doesn't mean anything in terms of the file system. The only place I've seen that correctly used is in a web app, where ASP.NET replaces the tilde with the absolute path to the root of the application.

You can typically assume the paths are relative to the folder where the EXE is located. Also, make sure that the image is specified as "content" and "copy if newer"/"copy always" in the properties tab in Visual Studio.

mysql data directory location

If you are using Homebrew to install [email protected], the location is

/usr/local/Homebrew/var/mysql

I don't know if the location is the same for other versions.

Creating files in C++

#include <iostream>
#include <fstream>

int main() {
  std::ofstream o("Hello.txt");

  o << "Hello, World\n" << std::endl;

  return 0;
}

Do I commit the package-lock.json file created by npm 5?

All answers say "YES" but that also depend of the project, the doc says:

One key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the toplevel package.

This mean that you don't need to publish on npm your package-lock.json for dependency but you need to use package-lock.json in your repo to lock the version of your test dependency, build dependencies…

However, If your are using lerna for managing projects with multiple packages, you should put the package.json only on the root of your repo, not in each subpackage are created with npm init. You will get something like that :

.git
lerna.json
package.json
package-lock.json        <--- here
packages/a/package.json
packages/a/lib/index.js
packages/b/package.json
packages/b/lib/index.js

Chart.js - Formatting Y axis

scaleLabel : "<%= Number(value).toFixed(2).replace('.', ',') + ' $'%>"

Changing plot scale by a factor in matplotlib

Instead of changing the ticks, why not change the units instead? Make a separate array X of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).

from pylab import *

# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)

# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X

subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")

subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")

show()

enter image description here

PDF to image using Java

You will need a PDF renderer. There are a few more or less good ones on the market (ICEPdf, pdfrenderer), but without, you will have to rely on external tools. The free PDF renderers also cannot render embedded fonts, and so will only be good for creating thumbnails (what you eventually want).

My favorite external tool is Ghostscript, which can convert PDFs to images with a single command line invocation.

This converts Postscript (and PDF?) files to bmp for us, just as a guide to modify for your needs (Know you need the env vars for gs to work!):

pushd 
setlocal

Set BIN_DIR=C:\Program Files\IKOffice_ACME\bin
Set GS=C:\Program Files\IKOffice_ACME\gs
Set GS_DLL=%GS%\gs8.54\bin\gsdll32.dll
Set GS_LIB=%GS%\gs8.54\lib;%GS%\gs8.54\Resource;%GS%\fonts
Set Path=%Path%;%GS%\gs8.54\bin
Set Path=%Path%;%GS%\gs8.54\lib

call "%GS%\gs8.54\bin\gswin32c.exe" -q -dSAFER -dNOPAUSE -dBATCH -sDEVICE#bmpmono -r600x600 -sOutputFile#%2 -f %1

endlocal
popd

UPDATE: pdfbox is now able to embed fonts, so no need for Ghostscript anymore.

How can I order a List<string>?

List<string> myCollection = new List<string>()
{
    "Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};

myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
    Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}

output: Abdi 3 Alex 2 Bob 4

Generating a unique machine id

Look up CPUID for one option. There might be some issues with multi-CPU systems.

C++ trying to swap values in a vector

Both proposed possibilities (std::swap and std::iter_swap) work, they just have a slightly different syntax. Let's swap a vector's first and second element, v[0] and v[1].

We can swap based on the objects contents:

std::swap(v[0],v[1]);

Or swap based on the underlying iterator:

std::iter_swap(v.begin(),v.begin()+1);

Try it:

int main() {
  int arr[] = {1,2,3,4,5,6,7,8,9};
  std::vector<int> * v = new std::vector<int>(arr, arr + sizeof(arr) / sizeof(arr[0]));
  // put one of the above swap lines here
  // ..
  for (std::vector<int>::iterator i=v->begin(); i!=v->end(); i++)
    std::cout << *i << " ";
  std::cout << std::endl;
}

Both times you get the first two elements swapped:

2 1 3 4 5 6 7 8 9

Can't get Gulp to run: cannot find module 'gulp-util'

Linux Ubuntu 18:04 user here. I tried all the solutions on this board to date. Even though I read above in the accepted answer that "From later versions, there is no need to manually install gulp-util.", it was the thing that worked for me. (...maybe bc I'm on Ubuntu? I don't know. )

To recap, I kept getting the "cannot find module 'gulp-util'" error when just checking to see if gulp was installed by running:

gulp --version

...again, the 'gulp-util' error kept appearing...

So, I followed the npm install [package name] advice listed above, but ended up getting several other packages that needed to be installed as well. And one had a issue of already existing, and i wasn't sure how to replace it. ...I will put all the packages/install commands that I had to use here, just as reference in case someone else experiences this problem:

sudo npm install -g gulp-util

(then I got an error for 'pretty-hrtime' so I added that, and then the others as Error: Cannot find module ___ kept popping up after each gulp --version check. ...so I just kept installing each one.)

sudo npm install -g pretty-hrtime
sudo npm install -g chalk
sudo npm install -g semver --force

(without --force, on my system I got an error: "EEXIST: file already exists, symlink". --force is not recommended, but idk any other way. )

sudo npm install -g archy
sudo npm install -g liftoff
sudo npm install -g tildify
sudo npm install -g interpret
sudo npm install -g v8flags
sudo npm install -g minimist

And now gulp --version is finally showing: CLI version 3.9.1 Local version 3.9.1

Playing .mp3 and .wav in Java?

Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.

You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.

Getting unix timestamp from Date()

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class Timeconversion {
    private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH); //Specify your locale

    public long timeConversion(String time) {
        long unixTime = 0;
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:30")); //Specify your timezone
        try {
            unixTime = dateFormat.parse(time).getTime();
            unixTime = unixTime / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return unixTime;
    }
}

how do you pass images (bitmaps) between android activities using bundles?

Write this code from where you want to Intent into next activity.

    yourimageView.setDrawingCacheEnabled(true); 
    Drawable drawable = ((ImageView)view).getDrawable(); 
    Bitmap bitmap = imageView.getDrawingCache();
    Intent intent = new Intent(getBaseContext(), NextActivity.class);
    intent.putExtra("Image", imageBitmap);

In onCreate Function of NextActivity.class

Bitmap hotel_image;
Intent intent = getIntent();
hotel_image= intent.getParcelableExtra("Image");

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

If you want to add a xx.tar.gz to a /usr/local in container, unzip it, and then remove the useless compressed package.

For COPY:

COPY resources/jdk-7u79-linux-x64.tar.gz /tmp/
RUN tar -zxvf /tmp/jdk-7u79-linux-x64.tar.gz -C /usr/local
RUN rm /tmp/jdk-7u79-linux-x64.tar.gz

For ADD:

ADD resources/jdk-7u79-linux-x64.tar.gz /usr/local/

ADD supports local-only tar extraction. Besides it, COPY will use three layers, but ADD only uses one layer.

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

How do I see if Wi-Fi is connected on Android?

The following code (in Kotlin) works from API 21 until at least current API version (API 29). The function getWifiState() returns one of 3 possible values for the WiFi network state: Disable, EnabledNotConnected and Connected that were defined in an enum class. This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks. But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.

It's inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API's or the slowly increasing availability of IP V6. The trick was to use:

wifiManager.connectionInfo.bssid != null 

instead of:

  1. getIpAddress() == 0 that is only valid for IP V4 or
  2. getNetworkId() == -1 that now requires another special permission (Location)

According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.

Also have the following in mind:

On releases before android.os.Build.VERSION_CODES#N, this object should only be obtained from an Context#getApplicationContext(), and not from any other derived context to avoid memory leaks within the calling process.

In the Manifest, do not forget to add:

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

Proposed code is:

class MyViewModel(application: Application) : AndroidViewModel(application) {

   // Get application context
    private val myAppContext: Context = getApplication<Application>().applicationContext

   // Define the different possible states for the WiFi Connection
    internal enum class WifiState {
        Disabled,               // WiFi is not enabled
        EnabledNotConnected,    // WiFi is enabled but we are not connected to any WiFi network
        Connected,              // Connected to a WiFi network
    }

    // Get the current state of the WiFi network
    private fun getWifiState() : WifiState {

        val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        return if (wifiManager.isWifiEnabled) {
                    if (wifiManager.connectionInfo.bssid != null)
                        WifiState.Connected
                    else
                        WifiState.EnabledNotConnected
               } else {
                    WifiState.Disabled
               }
    }

    // Returns true if we are connected to a WiFi network
    private fun isWiFiConnected() : Boolean {
        return (getWifiState() == WifiState.Connected)
    }
}

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

jQuery multiselect drop down menu

I've used jQuery MultiSelect for implementing multiselect drop down menu with checkbox. You can see the implementation guide from here - Multi-select Dropdown List with Checkbox

Implementation is very simple, need only using the following code.

$('#transactionType').multiselect({
    columns: 1,
    placeholder: 'Select Transaction Type'
});

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

How to check edittext's text is email address or not?

The following code should be useful to you.

String email;
check.setOnClickListener(new OnClickListener() {


                public void onClick(View arg0) {

                    checkEmail(email);
                    if (checkMail) {
                        System.out.println("Valid mail Id");
                    }
                }
            });

        }
    }

    public static boolean checkEmail(String email) {

        Pattern EMAIL_ADDRESS_PATTERN = Pattern
                .compile("[a-zA-Z0-9+._%-+]{1,256}" + "@"
                        + "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "."
                        + "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" + ")+");
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }

Call to getLayoutInflater() in places not in activity

Or ...

LayoutInflater inflater = LayoutInflater.from(context);

Why are arrays of references illegal?

Comment to your edit:

Better solution is std::reference_wrapper.

Details: http://www.cplusplus.com/reference/functional/reference_wrapper/

Example:

#include <iostream>
#include <functional>
using namespace std;

int main() {
    int a=1,b=2,c=3,d=4;
    using intlink = std::reference_wrapper<int>;
    intlink arr[] = {a,b,c,d};
    return 0;
}

How to add spacing between UITableViewCell

Try looking into - (UIEdgeInsets)layoutMargins; on the cell

fork() child and parent processes

It is printing twice because you are calling printf twice, once in the execution of your program and once in the fork. Try taking your fork() out of the printf call.

Binding Combobox Using Dictionary as the Datasource

I used Sorin Comanescu's solution, but hit a problem when trying to get the selected value. My combobox was a toolstrip combobox. I used the "combobox" property, which exposes a normal combobox.

I had a

 Dictionary<Control, string> controls = new Dictionary<Control, string>();

Binding code (Sorin Comanescu's solution - worked like a charm):

 controls.Add(pictureBox1, "Image");
 controls.Add(dgvText, "Text");
 cbFocusedControl.ComboBox.DataSource = new BindingSource(controls, null);
 cbFocusedControl.ComboBox.ValueMember = "Key";
 cbFocusedControl.ComboBox.DisplayMember = "Value";

The problem was that when I tried to get the selected value, I didn't realize how to retrieve it. After several attempts I got this:

 var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key

Hope it helps someone else!

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region;

This should show you the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION

Now simply issue an:

alter table region drop foreign key region_ibfk_1;

And finally an:

alter table region drop column country_id;

And you are good to go!

How to grep a string in a directory and all its subdirectories?

grep -r -e string directory

-r is for recursive; -e is optional but its argument specifies the regex to search for. Interestingly, POSIX grep is not required to support -r (or -R), but I'm practically certain that System V grep did, so in practice they (almost) all do. Some versions of grep support -R as well as (or conceivably instead of) -r; AFAICT, it means the same thing.

Getting JSONObject from JSONArray

Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.

Change SVN repository URL

Given that the Apache Subversion server will be moved to this new DNS alias: sub.someaddress.com.tr:

  • With Subversion 1.7 or higher, use svn relocate. Relocate is used when the SVN server's location changes. switch is only used if you want to change your local working copy to another branch or another path. If using TortoiseSVN, you may follow instructions from the TortoiseSVN Manual. If using the SVN command line interface, refer to this section of SVN's documentation. The command should look like this:

    svn relocate svn://sub.someaddress.com.tr/project

  • Keep using /project given that the actual contents of your repository probably won't change.

Note: svn relocate is not available before version 1.7 (thanks to ColinM for the info). In older versions you would use:

    svn switch --relocate OLD NEW

Dump a NumPy array into a csv file

if you want to write in column:

    for x in np.nditer(a.T, order='C'): 
            file.write(str(x))
            file.write("\n")

Here 'a' is the name of numpy array and 'file' is the variable to write in a file.

If you want to write in row:

    writer= csv.writer(file, delimiter=',')
    for x in np.nditer(a.T, order='C'): 
            row.append(str(x))
    writer.writerow(row)

How do I add multiple conditions to "ng-disabled"?

There is maybe a bit of a gotcha in the phrasing of the original question:

I need to check that two conditions are both true before enabling a button

The first thing to remember that the ng-disabled directive is evaluating a condition under which the button should be, well, disabled, but the original question is referring to the conditions under which it should en enabled. It will be enabled under any circumstances where the ng-disabled expression is not "truthy".

So, the first consideration is how to rephrase the logic of the question to be closer to the logical requirements of ng-disabled. The logical inverse of checking that two conditions are true in order to enable a button is that if either condition is false then the button should be disabled.

Thus, in the case of the original question, the pseudo-expression for ng-disabled is "disable the button if condition1 is false or condition2 is false". Translating into the Javascript-like code snippet required by Angular (https://docs.angularjs.org/guide/expression), we get:

!condition1 || !condition2

Zoomlar has it right!

mcrypt is deprecated, what is the alternative?

I was able to translate my Crypto object

  • Get a copy of php with mcrypt to decrypt the old data. I went to http://php.net/get/php-7.1.12.tar.gz/from/a/mirror, compiled it, then added the ext/mcrypt extension (configure;make;make install). I think I had to add the extenstion=mcrypt.so line to the php.ini as well. A series of scripts to build intermediate versions of the data with all data unencrypted.

  • Build a public and private key for openssl

    openssl genrsa -des3 -out pkey.pem 2048
    (set a password)
    openssl rsa -in pkey.pem -out pkey-pub.pem -outform PEM -pubout
    
  • To Encrypt (using public key) use openssl_seal. From what I've read, openssl_encrypt using an RSA key is limited to 11 bytes less than the key length (See http://php.net/manual/en/function.openssl-public-encrypt.php comment by Thomas Horsten)

    $pubKey = openssl_get_publickey(file_get_contents('./pkey-pub.pem'));
    openssl_seal($pwd, $sealed, $ekeys, [ $pubKey ]);
    $encryptedPassword = base64_encode($sealed);
    $key = base64_encode($ekeys[0]);
    

You could probably store the raw binary.

  • To Decrypt (using private key)

    $passphrase="passphrase here";
    $privKey = openssl_get_privatekey(file_get_contents('./pkey.pem'), $passphrase);
    // I base64_decode() from my db columns
    openssl_open($encryptedPassword, $plain, $key, $privKey);
    echo "<h3>Password=$plain</h3>";
    

P.S. You can't encrypt the empty string ("")

P.P.S. This is for a password database not for user validation.

How to handle the new window in Selenium WebDriver using Java?

Set<String> windows = driver.getWindowHandles();
Iterator<String> itr = windows.iterator();

//patName will provide you parent window
String patName = itr.next();

//chldName will provide you child window
String chldName = itr.next();

//Switch to child window
driver.switchto().window(chldName);

//Do normal selenium code for performing action in child window

//To come back to parent window
driver.switchto().window(patName);

Default interface methods are only supported starting with Android N

You can resolve this issue by downgrading Source Compatibility and Target Compatibility Java Version to 1.8 in Latest Android Studio Version 3.4.1

  1. Open Module Settings (Project Structure) Winodw by right clicking on app folder or Command + Down Arrow on Mac enter image description here

  2. Go to Modules -> Properties enter image description here

  3. Change Source Compatibility and Target Compatibility Version to 1.8 enter image description here

  4. Click on Apply or OK Thats it. It will solve your issue.

Also you can manually add in build.gradle (Module: app)

android {
...

compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

...
}

How to pass object with NSNotificationCenter

Building on the solution provided I thought it might be helpful to show an example passing your own custom data object (which I've referenced here as 'message' as per question).

Class A (sender):

YourDataObject *message = [[YourDataObject alloc] init];
// set your message properties
NSDictionary *dict = [NSDictionary dictionaryWithObject:message forKey:@"message"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationMessageEvent" object:nil userInfo:dict];

Class B (receiver):

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(triggerAction:) name:@"NotificationMessageEvent" object:nil];
}

#pragma mark - Notification
-(void) triggerAction:(NSNotification *) notification
{
    NSDictionary *dict = notification.userInfo;
    YourDataObject *message = [dict valueForKey:@"message"];
    if (message != nil) {
        // do stuff here with your message data
    }
}

How to convert a JSON string to a dictionary?

With Swift 3, JSONSerialization has a method called json?Object(with:?options:?). json?Object(with:?options:?) has the following declaration:

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

Returns a Foundation object from given JSON data.

When you use json?Object(with:?options:?), you have to deal with error handling (try, try? or try!) and type casting (from Any). Therefore, you can solve your problem with one of the following patterns.


#1. Using a method that throws and returns a non-optional type

import Foundation

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(dictionary) // prints: ["City": "Paris"]
} catch {
    print(error)
}
let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(dictionary) // prints [:]
} catch {
    print(error)
}
let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(dictionary)
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}

#2. Using a method that throws and returns an optional type

import Foundation

func convertToDictionary(from text: String) throws -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])
} catch {
    print(error)
}
let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(String(describing: dictionary)) // prints nil
} catch {
    print(error)
}
let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(String(describing: dictionary))
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}

#3. Using a method that does not throw and returns a non-optional type

import Foundation

func convertToDictionary(from text: String) -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(dictionary1) // prints: ["City": "Paris"]
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(dictionary2) // prints: [:]
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(dictionary3) // prints: [:]

#4. Using a method that does not throw and returns an optional type

import Foundation

func convertToDictionary(from text: String) -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return nil }
    let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(String(describing: dictionary2)) // prints: nil
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(String(describing: dictionary3)) // prints: nil

How do I get the time of day in javascript/Node.js?

To start your node in PST time zone , use following command in ubuntu.

TZ=\"/usr/share/zoneinfo/GMT+0\" && export TZ && npm start &

Then You can refer Date Library to get the custom calculation date and time functions in node.

To use it client side refer this link, download index.js and assertHelper.js and include that in your HTML.

<script src="assertHelper.js"></script>
<script type="text/javascript" src="index.js"></script>
$( document ).ready(function() {
    DateLibrary.getDayOfWeek(new Date("2015-06-15"),{operationType:"Day_of_Week"}); // Output : Monday
}

You can use different functions as given in examples to get custom dates.

If first day of week is Sunday, what day will be on 15th June 2015.

 DateLibrary.getDayOfWeek(new Date("2015-06-15"),
    {operationType:"Day_Number_of_Week",
        startDayOfWeek:"Sunday"}) // Output : 1

If first day of week is Tuesday, what week number in year will be follow in 15th June 2015 as one of the date.

 DateLibrary.getWeekNumber(new Date("2015-06-15"),
    {operationType:"Week_of_Year",
        startDayOfWeek:"Tuesday"}) // Output : 24

Refer other functions to fulfill your custom date requirements.

Table and Index size in SQL Server

Here is more compact version of the most successful answer:

create table #tbl(
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)
)

exec sp_msforeachtable 'insert into #tbl exec sp_spaceused [?]'

select * from #tbl
    order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #tbl

How to view Plugin Manager in Notepad++

As of Notepad++ version 7.5, plugin manager is no longer shipped with Notepad++

From the Notepad++ release notes:

You may notice that Plugin Manager plugin has been removed from the official distribution. The reason is Plugin Manager contains the advertising in its dialog. I hate Ads in applications, and I ensure you that there was no, and there will never be Ads in Notepad++.

A built-in Plugin Manager is in progress, and I will do my best to ship it with Notepad++ ASAP.

If the above doesn't put you off, and you want to proceed and install the plugin manager anyway, it looks like there's a GitHub repository for nppPluginManager - though I haven't personally used it, so cannot comment on it's validity.

The nppPluginManager installation instructions state:

To install the plugin manager, simply download (links below) the .zip, and place the PluginManager.dll file in the Notepad++ plugins directory, and the gpup.exe in the updater directory under your Notepad++ program directory. (e.g. "C:\Program Files\Notepad++\updater")

In fact, if you prefer, you can just add the PluginManager.dll to the plugins directory, then do a reinstall of Plugin Manager from the plugin itself, which will place the file in the right place! Of course, if you're already using an earlier version of the plugin manager, you'll be able to just update from the update tab (or when you get the notification that the update has happened).

The GitHub repository also contains the latest release.

Command for restarting all running docker containers?

To start all the containers:

  docker restart $(docker ps -a -q)

Use sudo if you don't have permission to perform this:

sudo docker restart $(sudo docker ps -a -q)

Sending HTML email using Python

Here's a working example to send plain text and HTML emails from Python using smtplib along with the CC and BCC options.

https://varunver.wordpress.com/2017/01/26/python-smtplib-send-plaintext-and-html-emails/

#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_mail(params, type_):
      email_subject = params['email_subject']
      email_from = "[email protected]"
      email_to = params['email_to']
      email_cc = params.get('email_cc')
      email_bcc = params.get('email_bcc')
      email_body = params['email_body']

      msg = MIMEMultipart('alternative')
      msg['To'] = email_to
      msg['CC'] = email_cc
      msg['Subject'] = email_subject
      mt_html = MIMEText(email_body, type_)
      msg.attach(mt_html)

      server = smtplib.SMTP('YOUR_MAIL_SERVER.DOMAIN.COM')
      server.set_debuglevel(1)
      toaddrs = [email_to] + [email_cc] + [email_bcc]
      server.sendmail(email_from, toaddrs, msg.as_string())
      server.quit()

# Calling the mailer functions
params = {
    'email_to': '[email protected]',
    'email_cc': '[email protected]',
    'email_bcc': '[email protected]',
    'email_subject': 'Test message from python library',
    'email_body': '<h1>Hello World</h1>'
}
for t in ['plain', 'html']:
    send_mail(params, t)

Pandas: ValueError: cannot convert float NaN to integer

I know this has been answered but wanted to provide alternate solution for anyone in the future:

You can use .loc to subset the dataframe by only values that are notnull(), and then subset out the 'x' column only. Take that same vector, and apply(int) to it.

If column x is float:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)

Netbeans how to set command line arguments in Java

For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel

TCP vs UDP on video stream

For video streaming bandwidth is likely the constraint on the system. Using multicast you can greatly reduce the amount of upstream bandwidth used. With UDP you can easily multicast your packets to all connected terminals. You could also use a reliable multicast protocol, one is called Pragmatic General Multicast (PGM), I don't know anything about it and I guess it isn't widespread in its use.

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Nginx location priority

From the HTTP core module docs:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

Example from the documentation:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

If it's still confusing, here's a longer explanation.

Printing image with PrintDocument. how to adjust the image to fit paper size

Agree with TonyM and BBoy - this is the correct answer for original 4*6 printing of label. (args.PageBounds). This worked for me for printing Endicia API service shipping Labels.

private void SubmitResponseToPrinter(ILabelRequestResponse response)
    {
        PrintDocument pd = new PrintDocument();
        pd.PrintPage += (sender, args) =>
        {
            Image i = Image.FromFile(response.Labels[0].FullPathFileName.Trim());
            args.Graphics.DrawImage(i, args.PageBounds);
        };
        pd.Print();
    }