Programs & Examples On #Asort

This is a PHP function to sort arrays. Returns either TRUE or FALSE.

JQuery Datatables : Cannot read property 'aDataSort' of undefined

Also had this issue, This array was out of range:

order: [1, 'asc'],

Datatables: Cannot read property 'mData' of undefined

This can also occur if you have table arguments for things like 'aoColumns':[..] which don't match the correct number of columns. Problems like this can commonly occur when copy pasting code from other pages to quick start your datatables integration.

Example:

This won't work:

<table id="dtable">
    <thead>
        <tr>
            <th>col 1</th>
            <th>col 2</th>
        </tr>
    </thead>
    <tbody>
        <td>data 1</td>
        <td>data 2</td>
    </tbody>
</table>
<script>
        var dTable = $('#dtable');
        dTable.DataTable({
            'order': [[ 1, 'desc' ]],
            'aoColumns': [
                null,
                null,
                null,
                null,
                null,
                null,
                {
                    'bSortable': false
                }
            ]
        });
</script>

But this will work:

<table id="dtable">
    <thead>
        <tr>
            <th>col 1</th>
            <th>col 2</th>
        </tr>
    </thead>
    <tbody>
        <td>data 1</td>
        <td>data 2</td>
    </tbody>
</table>
<script>
        var dTable = $('#dtable');
        dTable.DataTable({
            'order': [[ 0, 'desc' ]],
            'aoColumns': [
                null,
                {
                    'bSortable': false
                }
            ]
        });
</script>

Change Row background color based on cell value DataTable

The equivalent syntax since DataTables 1.10+ is rowCallback

"rowCallback": function( row, data, index ) {
    if ( data[2] == "5" )
    {
        $('td', row).css('background-color', 'Red');
    }
    else if ( data[2] == "4" )
    {
        $('td', row).css('background-color', 'Orange');
    }
}

One of the previous answers mentions createdRow. That may give similar results under some conditions, but it is not the same. For example, if you use draw() after updating a row's data, createdRow will not run. It only runs once. rowCallback will run again.

Implement a loading indicator for a jQuery AJAX call

This is how I realised the loading indicator by an Glyphicon:

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>

    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"></script>

    <style>
        .gly-ani {
          animation: ani 2s infinite linear;
        }
        @keyframes ani {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(359deg);
          }
        }
    </style>  
</head>

<body>
<div class="container">

    <span class="glyphicon glyphicon-refresh gly-ani" style="font-size:40px;"></span>

</div>
</body>

</html>

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

    System.out.println(jo.toString());

jquery datatables default sort

There are a couple of options:

  1. Just after initialising DataTables, remove the sorting classes on the TD element in the TBODY.

  2. Disable the sorting classes using http://datatables.net/ref#bSortClasses . Problem with this is that it will disable the sort classes for user sort requests - which might or might not be what you want.

  3. Have your server output the table in your required sort order, and don't apply a default sort on the table (aaSorting:[]).

How to set column widths to a jQuery datatable?

Answer from official website

https://datatables.net/reference/option/columns.width

$('#example').dataTable({
    "columnDefs": [
        {
            "width": "20%",
            "targets": 0
        }
    ]
});

Is there a way to disable initial sorting for jquery DataTables?

In datatable options put this:

$(document).ready( function() {
  $('#example').dataTable({
    "aaSorting": [[ 2, 'asc' ]], 
    //More options ...

   });
})

Here is the solution: "aaSorting": [[ 2, 'asc' ]],

2 means table will be sorted by third column,
asc in ascending order.

AWS EFS vs EBS vs S3 (differences & when to use?)

I wonder why people are not highlighting the MOST compelling reason in favor of EFS. EFS can be mounted on more than one EC2 instance at the same time, enabling access to files on EFS at the same time.

(Edit 2020 May, EBS supports mounting to multiple EC2 at same time now as well, see: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes-multi.html)

swift 3.0 Data to String?

I found the way to do it. You need to convert Data to NSData:

let characterSet = CharacterSet(charactersIn: "<>")
let nsdataStr = NSData.init(data: deviceToken)
let deviceStr = nsdataStr.description.trimmingCharacters(in: characterSet).replacingOccurrences(of: " ", with: "")
print(deviceStr)

Bootstrap 3 .img-responsive images are not responsive inside fieldset in FireFox

This looks like a Bootstrap issue...

Currently, here's a workaround : add .col-xs-12 to your responsive image.

Bootply

Are the decimal places in a CSS width respected?

Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.

I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.

Edge case, sure, but something to keep in mind.

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

How to clear react-native cache?

Simplest one(react native,npm and expo )

For React Native

react-native start --reset-cache

for npm

npm start -- --reset-cache

for Expo

expo start -c

Generating an array of letters in the alphabet

Note also, the string has a operator[] which returns a Char, and is an IEnumerable<char>, so for most purposes, you can use a string as a char[]. Hence:

string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
for (int i =0; i < 26; ++i)
{  
     Console.WriteLine(alpha[i]);
}

foreach(char c in alpha)
{  
     Console.WriteLine(c);
}

What are the -Xms and -Xmx parameters when starting JVM?

The question itself has already been addressed above. Just adding part of the default values.

As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

The default value of Xmx will depend on platform and amount of memory available in the system.

What ports does RabbitMQ use?

PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.

PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes

RabbitMQ Management console:

  • PORT 15672 for RabbitMQ version 3.x
  • PORT 55672 for RabbitMQ pre 3.x

PORT 5672 RabbitMQ main port.

For a cluster of nodes, they must be open to each other on 35197, 4369 and 5672.

For any servers that want to use the message queue, only 5672 is required.

ImportError: No module named pip

For Windows:

If pip is not available when Python is downloaded: run the command

python get-pip.py

How to read values from properties file?

In configuration class

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
   @Autowired
   Environment env;

   @Bean
   public TestBean testBean() {
       TestBean testBean = new TestBean();
       testBean.setName(env.getProperty("testbean.name"));
       return testBean;
   }
}

What value could I insert into a bit type column?

Generally speaking, for boolean or bit data types, you would use 0 or 1 like so:

UPDATE tbl SET bitCol = 1 WHERE bitCol = 0

See also:

Easy way to convert Iterable to Collection

Try StickyList from Cactoos:

List<String> list = new StickyList<>(iterable);

Self-reference for cell, column and row in worksheet functions

For a non-volatile solution, how about for 2007+:

for cell    =INDEX($A$1:$XFC$1048576,ROW(),COLUMN())
for column  =INDEX($A$1:$XFC$1048576,0,COLUMN())
for row     =INDEX($A$1:$XFC$1048576,ROW(),0)

I have weird bug on Excel 2010 where it won't accept the very last row or column for these formula (row 1048576 & column XFD), so you may need to reference these one short. Not sure if that's the same for any other versions so appreciate feedback and edit.

and for 2003 (INDEX became non-volatile in '97):

for cell    =INDEX($A$1:$IV$65536,ROW(),COLUMN())
for column  =INDEX($A$1:$IV$65536,0,COLUMN())
for row     =INDEX($A$1:$IV$65536,ROW(),0)

Is there a better way to compare dictionary values

Uhm, you are describing dict1 == dict2 ( check if boths dicts are equal )

But what your code does is all( dict1[k]==dict2[k] for k in dict1 ) ( check if all entries in dict1 are equal to those in dict2 )

How to combine two strings together in PHP?

No one mentioned this but there is other possibility. I'm using it for huge sql queries. You can use .= operator :)

$string = "the color is ";
$string .= "red";

echo $string; // gives: the color is red

Changing fonts in ggplot2

To change the font globally for ggplot2 plots.

theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))

How to extract epoch from LocalDate and LocalDateTime?

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance.

LocalDate

LocalDate date = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = date.atStartOfDay(zoneId).toEpochSecond();

LocalDateTime

LocalDateTime time = ...;
ZoneId zoneId = ZoneId.systemDefault(); // or: ZoneId.of("Europe/Oslo");
long epoch = time.atZone(zoneId).toEpochSecond();

How to disable the parent form when a child form is active?

Have you tried using Form.ShowDialog() instead of Form.Show()?

ShowDialog shows your window as modal, which means you cannot interact with the parent form until it closes.

An unhandled exception occurred during the execution of the current web request. ASP.NET

Here is the code with line 156, it has try and catch above it

    /// <summary>
    /// Execute a SQL Query statement, using the default SQL connection for the application
    /// </summary>
    /// <param name="query">SQL query to execute</param>
    /// <returns>DataTable of results</returns>
    public static DataTable Query(string query)
    {
        DataTable results = new DataTable();
        string configConnectionString = "ApplicationServices";

        System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
        System.Configuration.ConnectionStringSettings connString;

        if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];

            if (connString != null)
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(connString.ToString()))
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
                        dataAdapter.Fill(results);

                    return results;
                }
                catch (Exception ex)
                {
                    throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
                }
            }
            else
            {
                throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
            }
        }
        else
        {
            throw new SqlException(string.Format("No connection strings found in Web.config file."));
        }
    }

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

Try this:

select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE 
from INFORMATION_SCHEMA.COLUMNS IC
where TABLE_NAME = 'tablename' and COLUMN_NAME = 'columnname'

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

Usually in ruby when you are looking for "type" you are actually wanting the "duck-type" or "does is quack like a duck?". You would see if it responds to a certain method:

@some_var.respond_to?(:each)

You can iterate over @some_var because it responds to :each

If you really want to know the type and if it is Hash or Array then you can do:

["Hash", "Array"].include?(@some_var.class)  #=> check both through instance class
@some_var.kind_of?(Hash)    #=> to check each at once
@some_var.is_a?(Array)   #=> same as kind_of

Is there a float input type in HTML5?

I do so

 <input id="relacionac" name="relacionac" type="number" min="0.4" max="0.7" placeholder="0,40-0,70" class="form-control input-md" step="0.01">

then, I define min in 0.4 and max in 0.7 with step 0.01: 0.4, 0.41, 0,42 ... 0.7

Checking from shell script if a directory contains files

Taking a hint (or several) from olibre's answer, I like a Bash function:

function isEmptyDir {
  [ -d $1 -a -n "$( find $1 -prune -empty 2>/dev/null )" ]
}

Because while it creates one subshell, it's as close to an O(1) solution as I can imagine and giving it a name makes it readable. I can then write

if isEmptyDir somedir
then
  echo somedir is an empty directory
else
  echo somedir does not exist, is not a dir, is unreadable, or is  not empty
fi

As for O(1) there are outlier cases: if a large directory has had all or all but the last entry deleted, "find" may have to read the whole thing to determine whether it's empty. I believe that expected performance is O(1) but worst-case is linear in the directory size. I have not measured this.

What is the purpose of using WHERE 1=1 in SQL statements?

As you said:

if you are adding conditions dynamically you don't have to worry about stripping the initial AND that's the only reason could be, you are right.

Using Java 8's Optional with Stream::flatMap

Late to the party, but what about

things.stream()
    .map(this::resolve)
    .filter(Optional::isPresent)
    .findFirst().get();

You can get rid of the last get() if you create a util method to convert optional to stream manually:

things.stream()
    .map(this::resolve)
    .flatMap(Util::optionalToStream)
    .findFirst();

If you return stream right away from your resolve function, you save one more line.

Select DISTINCT individual columns in django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values().

In your case you can do the following to get the names of distinct categories:

q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.

# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"

There are a couple of things to remember here. First, this will return a ValuesQuerySet which behaves differently from a QuerySet. When you access say, the first element of q (above) you'll get a dictionary, NOT an instance of ProductOrder.

Second, it would be a good idea to read the warning note in the docs about using distinct(). The above example will work but all combinations of distinct() and values() may not.

PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:

class ProductOrder(models.Model):
    product  = models.CharField(max_length=20, primary_key=True)
    category = models.CharField(max_length=30)
    rank = models.IntegerField()

SQL Server - Adding a string to a text column (concat equivalent)

To Join two string in SQL Query use function CONCAT(Express1,Express2,...)

Like....

SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

Stop recording and you can start inspecting your code.

I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

Option Explicit

Sub SaveFile()

Dim fdate As Date
Dim fname As String
Dim path As String

fdate = Range("A1").Value
path = Application.ActiveWorkbook.path

If fdate > 0 Then
    fname = "Event " & fdate
    Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "Chose a date for the event", vbOKOnly
End If

End Sub

Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

Set HTML dropdown selected option using JSTL

Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;

<select name="foo" id="foo" value="${myBean.foo}">
    <option value="">ALL</option>
    <c:forEach items="${fooList}" var="val"> 
        <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
    </c:forEach>                     
</select>

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

Calling a function of a module by using its name (a string)

getattr calls method by name from an object. But this object should be parent of calling class. The parent class can be got by super(self.__class__, self)

class Base:
    def call_base(func):
        """This does not work"""
        def new_func(self, *args, **kwargs):
            name = func.__name__
            getattr(super(self.__class__, self), name)(*args, **kwargs)
        return new_func

    def f(self, *args):
        print(f"BASE method invoked.")

    def g(self, *args):
        print(f"BASE method invoked.")

class Inherit(Base):
    @Base.call_base
    def f(self, *args):
        """function body will be ignored by the decorator."""
        pass

    @Base.call_base
    def g(self, *args):
        """function body will be ignored by the decorator."""
        pass

Inherit().f() # The goal is to print "BASE method invoked."

WAMP 403 Forbidden message on Windows 7

The solution for changing the permissions in the httpd.conf will work if you are OK with providing access to the WAMP server from outside.

If you do not want to do that then all you have to do is tell windows that the "localhost" domain points to 127.0.0.1. You can do that by editing the hosts file in your system directory.

The file is placed at : C:\Windows\System32\drivers\etc\hosts

by default windows 7 ships with :

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

You have to un-comment the mapping for localhost:

# localhost name resolution is handled within DNS itself.
127.0.0.1       localhost
#   ::1         localhost

Note: you will not be able to edit the hosts file as its a read-only file. To edit, you have to be the administrator, copy the file to some other location, edit it and then copy it back to the etc directory.

I do not recommend the change of the hosts file. Use the permissions of httpd.conf file. use the hosts file approach only if you do not want the server accessed from outside.

How to position a Bootstrap popover?

I solved this (partially) by adding some lines of code to the bootstrap css library. You will have to modify tooltip.js, tooltip.less, popover.js, and popover.less

in tooltip.js, add this case in the switch statement there

case 'bottom-right':
          tp = {top: pos.top + pos.height, left: pos.left + pos.width}
          break

in tooltip.less, add these two lines in .tooltip{}

&.bottom-right { margin-top:   -2px; }
&.bottom-right .tooltip-arrow { #popoverArrow > .bottom(); }

do the same in popover.js and popover.less. Basically, wherever you find code where other positions are mentioned, add your desired position accordingly.

As I mentioned earlier, this solved the problem partially. My problem now is that the little arrow of the popover does not appear.

note: if you want to have the popover in top-left, use top attribute of '.top' and left attribute of '.left'

How to split a string, but also keep the delimiters?

I know this is a very-very old question and answer has also been accepted. But still I would like to submit a very simple answer to original question. Consider this code:

String str = "Hello-World:How\nAre You&doing";
inputs = str.split("(?!^)\\b");
for (int i=0; i<inputs.length; i++) {
   System.out.println("a[" + i + "] = \"" + inputs[i] + '"');
}

OUTPUT:

a[0] = "Hello"
a[1] = "-"
a[2] = "World"
a[3] = ":"
a[4] = "How"
a[5] = "
"
a[6] = "Are"
a[7] = " "
a[8] = "You"
a[9] = "&"
a[10] = "doing"

I am just using word boundary \b to delimit the words except when it is start of text.

Select current element in jQuery

When the jQuery click event calls your event handler, it sets "this" to the object that was clicked on. To turn it into a jQuery object, just pass it to the "$" function: $(this). So, to get, for example, the next sibling element, you would do this inside the click handler:

var nextSibling = $(this).next();

Edit: After reading Kevin's comment, I realized I might be mistaken about what you want. If you want to do what he asked, i.e. select the corresponding link in the other div, you could use $(this).index() to get the clicked link's position. Then you would select the link in the other div by its position, for example with the "eq" method.

var $clicked = $(this);
var linkIndex = $clicked.index();
$clicked.parent().next().children().eq(linkIndex);

If you want to be able to go both ways, you will need some way of determining which div you are in so you know if you need "next()" or "prev()" after "parent()"

Set default format of datetimepicker as dd-MM-yyyy

Try this,

string Date = datePicker1.SelectedDate.Value.ToString("dd-MMM-yyyy");

It worked for me the output format will be '02-May-2016'

What is the equivalent of Java static methods in Kotlin?

I would like to add something to above answers.

Yes, you can define functions in source code files(outside class). But it is better if you define static functions inside class using Companion Object because you can add more static functions by leveraging the Kotlin Extensions.

class MyClass {
    companion object { 
        //define static functions here
    } 
}

//Adding new static function
fun MyClass.Companion.newStaticFunction() {
    // ...
}

And you can call above defined function as you will call any function inside Companion Object.

openCV video saving in python

import cv2

cap = cv2.VideoCapture(0)

fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

out = cv2.VideoWriter('output.mp4', fourcc, 20,(frame_width,frame_height),True )
print(int(cap.get(3)))
print(int(cap.get(4)))
while(cap.isOpened()):
    ret,frame = cap.read()
    if ret == True:
        print(frame.shape)
        out.write(frame)
        cv2.imshow('Frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
out.release()`enter code here`

cv2.destroyAllWindows()

This works fine but the problem of having video size relatively very small means nothing is captured. So make sure the height and width of a video and the image that you are going to recorded is same. If you are using some manipulation after capturing a video than you must confirm the size (before and after). Hope it will save some1's hour

In java how to get substring from a string till a character c?

This could help:

public static String getCorporateID(String fileName) {

    String corporateId = null;

    try {
        corporateId = fileName.substring(0, fileName.indexOf("_"));
        // System.out.println(new Date() + ": " + "Corporate:
        // "+corporateId);
        return corporateId;
    } catch (Exception e) {
        corporateId = null;
        e.printStackTrace();
    }

    return corporateId;
}

What is the difference between Linear search and Binary search?

Try this: Pick a random name "Lastname, Firstname" and look it up in your phonebook.

1st time: start at the beginning of the book, reading names until you find it, or else find the place where it would have occurred alphabetically and note that it isn't there.

2nd time: Open the book at the half way point and look at the page. Ask yourself, should this person be to the left or to the right. Whichever one it is, take that 1/2 and find the middle of it. Repeat this procedure until you find the page where the entry should be and then either apply the same process to columns, or just search linearly along the names on the page as before.

Time both methods and report back!

[also consider what approach is better if all you have is a list of names, not sorted...]

Loop through list with both content and index

enumerate is what you want:

for i, s in enumerate(S):
    print s, i

Blocking device rotation on mobile web pages

Simple Javascript code to make mobile browser display either in portrait or landscape..

(Even though you have to enter html code twice in the two DIVs (one for each mode), arguably this will load faster than using javascript to change the stylesheet...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Mobile Device</title>
<script type="text/javascript">
// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    if(window.orientation==0)
    {
      document.getElementById('portrait').style.display = '';
      document.getElementById('landscape').style.display = 'none';
    }
    else if(window.orientation==90)
    {
      document.getElementById('portrait').style.display = 'none';
      document.getElementById('landscape').style.display = '';
    }
}, false);
</script>
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />
</head>
<body>
<div id="portrait" style="width:100%;height:100%;font-size:20px;">Portrait</div>
<div id="landscape" style="width:100%;height:100%;font-size:20px;">Landscape</div>

<script type="text/javascript">
if(window.orientation==0)
{
  document.getElementById('portrait').style.display = '';
  document.getElementById('landscape').style.display = 'none';
}
else if(window.orientation==90)
{
  document.getElementById('portrait').style.display = 'none';
  document.getElementById('landscape').style.display = '';
}
</script>
</body>
</html>

Tested and works on Android HTC Sense and Apple iPad.

How to inspect Javascript Objects

There are few methods :

 1. typeof tells you which one of the 6 javascript types is the object. 
 2. instanceof tells you if the object is an instance of another object.
 3. List properties with for(var k in obj)
 4. Object.getOwnPropertyNames( anObjectToInspect ) 
 5. Object.getPrototypeOf( anObject )
 6. anObject.hasOwnProperty(aProperty) 

In a console context, sometimes the .constructor or .prototype maybe useful:

console.log(anObject.constructor ); 
console.log(anObject.prototype ) ; 

How to disable 'X-Frame-Options' response header in Spring Security?

If you are using Spring Security's Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends
   WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .headers().disable()
      ...;
  }
}

Check if boolean is true?

If you're going to opt for

if(foo == true)

why not go all the way and do

if(foo == true == true == true == true == true == true == true == true == true)

Which is the same thing.

I disagree that if its clearly named (ie: IsSomething) then its ok to not compare to true, but otherwise you should. If its in an if statement obviously it can be compared to true.

if(monday)

Is just as descriptive as

if(monday == true)

I also prefer the same standard for not:

if(!monday)

as opposed to

if(monday == false)

How Best to Compare Two Collections in Java and Act on Them?

I think the easiest way to do that is by using apache collections api - CollectionUtils.subtract(list1,list2) as long the lists are of the same type.

Min/Max of dates in an array?

Code is tested with IE,FF,Chrome and works properly:

var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

I believe some of the respondents of this question have missed the broader implication of the fold function as an abstract tool. Yes, sum can do the same thing for a list of integers, but this is a trivial case. fold is more generic. It is useful when you have a sequence of data structures of varying shape and want to cleanly express an aggregation. So instead of having to build up a for loop with an aggregate variable and manually recompute it each time, a fold function (or the Python version, which reduce appears to correspond to) allows the programmer to express the intent of the aggregation much more plainly by simply providing two things:

  • A default starting or "seed" value for the aggregation.
  • A function that takes the current value of the aggregation (starting with the "seed") and the next element in the list, and returns the next aggregation value.

How to copy a char array in C?

You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:

For char arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy():

#include <string.h>

char array1[18] = "abcdefg";
char array2[18];

...

strcpy(array2, array1);

If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf():

#include <stdio.h>

char array1[] = "a longer string that might not fit";
char array2[18];

...

snprintf(array2, sizeof array2, "%s", array1);

If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy:

#include <string.h>

char array1[28] = "a non null terminated string";
char array2[28];

...

memcpy(array2, array1, sizeof array2);

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

QED symbol in latex

I think you are looking for this:

\newcommand*{\QEDA}{\hfill\ensuremath{\blacksquare}}

Usage:

\begin{example}
  blah blah blah \QEDA
\end{example}

Using sed to mass rename files

Using perl rename (a must have in the toolbox):

rename -n 's/0000/000/' F0000*

Remove -n switch when the output looks good to rename for real.

warning There are other tools with the same name which may or may not be able to do this, so be careful.

The rename command that is part of the util-linux package, won't.

If you run the following command (GNU)

$ rename

and you see perlexpr, then this seems to be the right tool.

If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :

$ sudo apt install rename
$ sudo update-alternatives --set rename /usr/bin/file-rename

For archlinux:

pacman -S perl-rename

For RedHat-family distros:

yum install prename

The 'prename' package is in the EPEL repository.


For Gentoo:

emerge dev-perl/rename

For *BSD:

pkg install gprename

or p5-File-Rename


For Mac users:

brew install rename

If you don't have this command with another distro, search your package manager to install it or do it manually:

cpan -i File::Rename

Old standalone version can be found here


man rename


This tool was originally written by Larry Wall, the Perl's dad.

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Upgrading React version and it's dependencies by reading package.json

if you want to update your react and react-dom version in your existing react step then run this command I hope You get the latest version of react and react-dom.

Thanks

npm install react@latest react-dom@latest

jQuery override default validation error message display (Css) Popup/Tooltip like

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertAfter(element)
        error.css('color','red');
    }

Execute a command line binary with Node.js

For even newer version of Node.js (v8.1.4), the events and calls are similar or identical to older versions, but it's encouraged to use the standard newer language features. Examples:

For buffered, non-stream formatted output (you get it all at once), use child_process.exec:

const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

You can also use it with Promises:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function ls() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
ls();

If you wish to receive the data gradually in chunks (output as a stream), use child_process.spawn:

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);

// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.on('data', (chunk) => {
  // data from standard output is here as buffers
});

// since these are streams, you can pipe them elsewhere
child.stderr.pipe(dest);

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Both of these functions have a synchronous counterpart. An example for child_process.execSync:

const { execSync } = require('child_process');
// stderr is sent to stderr of parent process
// you can set options.stdio if you want it to go elsewhere
let stdout = execSync('ls');

As well as child_process.spawnSync:

const { spawnSync} = require('child_process');
const child = spawnSync('ls', ['-lh', '/usr']);

console.log('error', child.error);
console.log('stdout ', child.stdout);
console.log('stderr ', child.stderr);

Note: The following code is still functional, but is primarily targeted at users of ES5 and before.

The module for spawning child processes with Node.js is well documented in the documentation (v5.0.0). To execute a command and fetch its complete output as a buffer, use child_process.exec:

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

If you need to use handle process I/O with streams, such as when you are expecting large amounts of output, use child_process.spawn:

var spawn = require('child_process').spawn;
var child = spawn('prince', [
  '-v', 'builds/pdf/book.html',
  '-o', 'builds/pdf/book.pdf'
]);

child.stdout.on('data', function(chunk) {
  // output will be here in chunks
});

// or if you want to send output elsewhere
child.stdout.pipe(dest);

If you are executing a file rather than a command, you might want to use child_process.execFile, which parameters which are almost identical to spawn, but has a fourth callback parameter like exec for retrieving output buffers. That might look a bit like this:

var execFile = require('child_process').execFile;
execFile(file, args, options, function(error, stdout, stderr) {
  // command output is in stdout
});

As of v0.11.12, Node now supports synchronous spawn and exec. All of the methods described above are asynchronous, and have a synchronous counterpart. Documentation for them can be found here. While they are useful for scripting, do note that unlike the methods used to spawn child processes asynchronously, the synchronous methods do not return an instance of ChildProcess.

How to get the HTML for a DOM element in javascript

var el = document.getElementById('foo');
el.parentNode.innerHTML;

Access a function variable outside the function without using "global"

You could do something along this lines:

def static_example():
   if not hasattr(static_example, "static_var"):
       static_example.static_var = 0
   static_example.static_var += 1
   return static_example.static_var

print static_example()
print static_example()
print static_example()

PHP 7 RC3: How to install missing MySQL PDO

  1. download the source code of php 7 and extract it.
  2. open your terminal
  3. swim to the ext/mysqli directory
  4. use commands:

    phpize

    ./configure

    make

    make install (as root)

  5. enable extension=mysqli.so in your php.ini file
  6. done!

This worked for me

How to create a hash or dictionary object in JavaScript

You want to create an Object, not an Array.

Like so,

var Map = {};

Map['key1'] = 'value1';
Map['key2'] = 'value2';

You can check if the key exists in multiple ways:

Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...

Calculating bits required to store decimal number

The formula for the number of binary bits required to store n integers (for example, 0 to n - 1) is:

loge(n) / loge(2)

and round up.

For example, for values -128 to 127 (signed byte) or 0 to 255 (unsigned byte), the number of integers is 256, so n is 256, giving 8 from the above formula.

For 0 to n, use n + 1 in the above formula (there are n + 1 integers).

On your calculator, loge may just be labelled log or ln (natural logarithm).

Git push error pre-receive hook declined

GitLab by default marks master branch as protected (See part Protecting your code in https://about.gitlab.com/2014/11/26/keeping-your-code-protected/ why). If so in your case, then this can help:

Open your project > Settings > Repository and go to "Protected branches", find "master" branch into the list and click "Unprotect" and try again.

via https://gitlab.com/gitlab-com/support-forum/issues/40

For version 8.11 and above how-to here: https://docs.gitlab.com/ee/user/project/protected_branches.html#restricting-push-and-merge-access-to-certain-users

How to set a value for a span using jQuery

You can do:

$("#submittername").text("testing");

or

$("#submittername").html("testing <b>1 2 3</b>");

bypass invalid SSL certificate in .net core

Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

using (var httpClientHandler = new HttpClientHandler())
{
    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;   //Is valid
        }

        if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
        {
            return true;
        }
        return false;
    };
    using (var httpClient = new HttpClient(httpClientHandler))
    {
        var httpResponse = httpClient.GetAsync("https://example.com").Result;
    }
}

Original source:

https://stackoverflow.com/a/44140506/3850405

How to check the Angular version?

check the Command Prompt

ng --version OR ng version OR ng -v

Javascript validation: Block special characters

It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values

var checkString = document.formname.txt.value;
if (checkString != "") {
    if ( /[^A-Za-z\d]/.test(checkString)) {
        alert("Please enter only letter and numeric characters");
        document.formname.txt.focus();
        return (false);
    }
}

Python: Assign print output to a variable

probably you need one of str,repr or unicode functions

somevar = str(tag.getArtist())

depending which python shell are you using

How can I find the number of arguments of a Python function?

Good news for folks who want to do this in a portable way between Python 2 and Python 3.6+: use inspect.getfullargspec() method. It works in both Python 2.x and 3.6+

As Jim Fasarakis Hilliard and others have pointed out, it used to be like this:
1. In Python 2.x: use inspect.getargspec()
2. In Python 3.x: use signature, as getargspec() and getfullargspec() were deprecated.

However, starting Python 3.6 (by popular demand?), things have changed towards better:

From the Python 3 documentation page:

inspect.getfullargspec(func)

Changed in version 3.6: This method was previously documented as deprecated in favour of signature() in Python 3.5, but that decision has been reversed in order to restore a clearly supported standard interface for single-source Python 2/3 code migrating away from the legacy getargspec() API.

how to convert from int to char*?

  • In C++17, use std::to_chars as:

    std::array<char, 10> str;
    std::to_chars(str.data(), str.data() + str.size(), 42);
    
  • In C++11, use std::to_string as:

    std::string s = std::to_string(number);
    char const *pchar = s.c_str();  //use char const* as target type
    
  • And in C++03, what you're doing is just fine, except use const as:

    char const* pchar = temp_str.c_str(); //dont use cast
    

How set background drawable programmatically in Android

If your backgrounds are in the drawable folder right now try moving the images from drawable to drawable-nodpi folder in your project. This worked for me, seems that else the images are rescaled by them self..

Location of GlassFish Server Logs

In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/.

In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".

If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs

If the server is already running you should see an Output tab in NetBeans which is named similar to GlassFish Server x.x.x

You can also use cat or tail -F on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log. If you are using a different domain then domain1 you have to adjust the path for that.

How do I check that multiple keys are in a dict in a single pass?

>>> if 'foo' in foo and 'bar' in foo:
...     print 'yes'
... 
yes

Jason, () aren't necessary in Python.

Copy the entire contents of a directory in C#

A minor improvement on d4nt's answer, as you probably want to check for errors and not have to change xcopy paths if you're working on a server and development machine:

public void CopyFolder(string source, string destination)
{
    string xcopyPath = Environment.GetEnvironmentVariable("WINDIR") + @"\System32\xcopy.exe";
    ProcessStartInfo info = new ProcessStartInfo(xcopyPath);
    info.UseShellExecute = false;
    info.RedirectStandardOutput = true;
    info.Arguments = string.Format("\"{0}\" \"{1}\" /E /I", source, destination);

    Process process = Process.Start(info);
    process.WaitForExit();
    string result = process.StandardOutput.ReadToEnd();

    if (process.ExitCode != 0)
    {
        // Or your own custom exception, or just return false if you prefer.
        throw new InvalidOperationException(string.Format("Failed to copy {0} to {1}: {2}", source, destination, result));
    }
}

Can't stop rails server

One super easy way would be

gem install shutup

then go in the current folder of your rails project and run

shutup # this will kill the Rails process currently running

You can use the command 'shutup' every time you want

DICLAIMER: I am the creator of this gem

NOTE: if you are using rvm install the gem globally

rvm @global do gem install shutup

In PHP, how can I add an object element to an array?

Here is a clean method I've discovered:

$myArray = [];

array_push($myArray, (object)[
        'key1' => 'someValue',
        'key2' => 'someValue2',
        'key3' => 'someValue3',
]);

return $myArray;

Does static constexpr variable inside a function make sense?

In addition to given answer, it's worth noting that compiler is not required to initialize constexpr variable at compile time, knowing that the difference between constexpr and static constexpr is that to use static constexpr you ensure the variable is initialized only once.

Following code demonstrates how constexpr variable is initialized multiple times (with same value though), while static constexpr is surely initialized only once.

In addition the code compares the advantage of constexpr against const in combination with static.

#include <iostream>
#include <string>
#include <cassert>
#include <sstream>

const short const_short = 0;
constexpr short constexpr_short = 0;

// print only last 3 address value numbers
const short addr_offset = 3;

// This function will print name, value and address for given parameter
void print_properties(std::string ref_name, const short* param, short offset)
{
    // determine initial size of strings
    std::string title = "value \\ address of ";
    const size_t ref_size = ref_name.size();
    const size_t title_size = title.size();
    assert(title_size > ref_size);

    // create title (resize)
    title.append(ref_name);
    title.append(" is ");
    title.append(title_size - ref_size, ' ');

    // extract last 'offset' values from address
    std::stringstream addr;
    addr << param;
    const std::string addr_str = addr.str();
    const size_t addr_size = addr_str.size();
    assert(addr_size - offset > 0);

    // print title / ref value / address at offset
    std::cout << title << *param << " " << addr_str.substr(addr_size - offset) << std::endl;
}

// here we test initialization of const variable (runtime)
void const_value(const short counter)
{
    static short temp = const_short;
    const short const_var = ++temp;
    print_properties("const", &const_var, addr_offset);

    if (counter)
        const_value(counter - 1);
}

// here we test initialization of static variable (runtime)
void static_value(const short counter)
{
    static short temp = const_short;
    static short static_var = ++temp;
    print_properties("static", &static_var, addr_offset);

    if (counter)
        static_value(counter - 1);
}

// here we test initialization of static const variable (runtime)
void static_const_value(const short counter)
{
    static short temp = const_short;
    static const short static_var = ++temp;
    print_properties("static const", &static_var, addr_offset);

    if (counter)
        static_const_value(counter - 1);
}

// here we test initialization of constexpr variable (compile time)
void constexpr_value(const short counter)
{
    constexpr short constexpr_var = constexpr_short;
    print_properties("constexpr", &constexpr_var, addr_offset);

    if (counter)
        constexpr_value(counter - 1);
}

// here we test initialization of static constexpr variable (compile time)
void static_constexpr_value(const short counter)
{
    static constexpr short static_constexpr_var = constexpr_short;
    print_properties("static constexpr", &static_constexpr_var, addr_offset);

    if (counter)
        static_constexpr_value(counter - 1);
}

// final test call this method from main()
void test_static_const()
{
    constexpr short counter = 2;

    const_value(counter);
    std::cout << std::endl;

    static_value(counter);
    std::cout << std::endl;

    static_const_value(counter);
    std::cout << std::endl;

    constexpr_value(counter);
    std::cout << std::endl;

    static_constexpr_value(counter);
    std::cout << std::endl;
}

Possible program output:

value \ address of const is               1 564
value \ address of const is               2 3D4
value \ address of const is               3 244

value \ address of static is              1 C58
value \ address of static is              1 C58
value \ address of static is              1 C58

value \ address of static const is        1 C64
value \ address of static const is        1 C64
value \ address of static const is        1 C64

value \ address of constexpr is           0 564
value \ address of constexpr is           0 3D4
value \ address of constexpr is           0 244

value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0
value \ address of static constexpr is    0 EA0

As you can see yourself constexpr is initilized multiple times (address is not the same) while static keyword ensures that initialization is performed only once.

HTML/Javascript Button Click Counter

Use var instead of int for your clicks variable generation and onClick instead of click as your function name:

_x000D_
_x000D_
var clicks = 0;

function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML = clicks;
};
_x000D_
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
_x000D_
_x000D_
_x000D_

In JavaScript variables are declared with the var keyword. There are no tags like int, bool, string... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.

And the name 'click' is reserved by JavaScript for function names so you have to use something else.

How to convert CharSequence to String?

By invoking its toString() method.

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

What is the shortcut in IntelliJ IDEA to find method / functions?

If I need navigate to method in currently opened class, I use this combination: ALT+7 (CMD+7 on Mac) to open structure view, and press two times (first time open, second time focus on view), type name of methods, select on of needed.

How do I run Visual Studio as an administrator by default?

Right click on icon --> Properties --> Advanced --> Check checkbox run as Administrator and everytime it will open under Admin Mode (Same for Windows 8)

R: Print list to a text file

Here is another

cat(sapply(mylist, toString), file, sep="\n")

angular-cli server - how to proxy API requests to another server?

  1. add in proxy.conf.json, all request to /api will be redirect to htt://targetIP:targetPort/api.
{
  "/api": {
    "target": "http://targetIP:targetPort",
    "secure": false,
    "pathRewrite": {"^/api" : targeturl/api},
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
  1. in package.json, make "start": "ng serve --proxy-config proxy.conf.json"

  2. in code let url = "/api/clnsIt/dev/78"; this url will be translated to http://targetIP:targetPort/api/clnsIt/dev/78.

  3. You can also force rewrite by filling the pathRewrite. This is the link for details cmd/NPM console will log something like "Rewriting path from "/api/..." to "http://targeturl:targetPort/api/..", while browser console will log "http://loclahost/api"

How to select rows that have current day's timestamp?

Or you could use the CURRENT_DATE alternative, with the same result:

SELECT * FROM yourtable WHERE created >= CURRENT_DATE

Examples from database.guide

What is the Swift equivalent to Objective-C's "@synchronized"?

Another method is to create a superclass and then inherit it. This way you can use GCD more directly

class Lockable {
    let lockableQ:dispatch_queue_t

    init() {
        lockableQ = dispatch_queue_create("com.blah.blah.\(self.dynamicType)", DISPATCH_QUEUE_SERIAL)
    }

    func lock(closure: () -> ()) {
        dispatch_sync(lockableQ, closure)
    }
}


class Foo: Lockable {

    func boo() {
        lock {
            ....... do something
        }
    }

Styling input buttons for iPad and iPhone

You may be looking for

-webkit-appearance: none;

Difference between @Mock and @InjectMocks

This is a sample code on how @Mock and @InjectMocks works.

Say we have Game and Player class.

class Game {

    private Player player;

    public Game(Player player) {
        this.player = player;
    }

    public String attack() {
        return "Player attack with: " + player.getWeapon();
    }

}

class Player {

    private String weapon;

    public Player(String weapon) {
        this.weapon = weapon;
    }

    String getWeapon() {
        return weapon;
    }
}

As you see, Game class need Player to perform an attack.

@RunWith(MockitoJUnitRunner.class)
class GameTest {

    @Mock
    Player player;

    @InjectMocks
    Game game;

    @Test
    public void attackWithSwordTest() throws Exception {
        Mockito.when(player.getWeapon()).thenReturn("Sword");

        assertEquals("Player attack with: Sword", game.attack());
    }

}

Mockito will mock a Player class and it's behaviour using when and thenReturn method. Lastly, using @InjectMocks Mockito will put that Player into Game.

Notice that you don't even have to create a new Game object. Mockito will inject it for you.

// you don't have to do this
Game game = new Game(player);

We will also get same behaviour using @Spy annotation. Even if the attribute name is different.

@RunWith(MockitoJUnitRunner.class)
public class GameTest {

  @Mock Player player;

  @Spy List<String> enemies = new ArrayList<>();

  @InjectMocks Game game;

  @Test public void attackWithSwordTest() throws Exception {
    Mockito.when(player.getWeapon()).thenReturn("Sword");

    enemies.add("Dragon");
    enemies.add("Orc");

    assertEquals(2, game.numberOfEnemies());

    assertEquals("Player attack with: Sword", game.attack());
  }
}

class Game {

  private Player player;

  private List<String> opponents;

  public Game(Player player, List<String> opponents) {
    this.player = player;
    this.opponents = opponents;
  }

  public int numberOfEnemies() {
    return opponents.size();
  }

  // ...

That's because Mockito will check the Type Signature of Game class, which is Player and List<String>.

How to implement the Android ActionBar back button?

Selvin already posted the right answer. Here, the solution in pretty code:

public class ServicesViewActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // etc...
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

The function NavUtils.navigateUpFromSameTask(this) requires you to define the parent activity in the AndroidManifest.xml file

<activity android:name="com.example.ServicesViewActivity" >
    <meta-data
     android:name="android.support.PARENT_ACTIVITY"
     android:value="com.example.ParentActivity" />
</activity>

See here for further reading.

Accessing localhost (xampp) from another computer over LAN network - how to?

it's very easy

  1. Go to Your XAMPP Control panel
  2. Click on apache > config > Apache (httpd.conf) enter image description here
  3. Search for Listen 80 and replace with Listen 8080
  4. After that check your local ip using ipconfig command (cmd console)
  5. Search for ServerName localhost:80 and replace with your local ip:8080 (ex.192.168.1.156:8080)
  6. After that open apache > config > Apache (httpd-xampp.conf) enter image description here
  7. Search for

       <Directory "C:/xampp/phpMyAdmin">
           AllowOverride AuthConfig
           **Require local**   Replace with   **Require all granted**
           ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
       </Directory>```
    
    
  8. Go to xampp > config > click on service and port setting and change apache port 8080

  9. restart xampp
  10. then hit your IP:8080 (ex.192.168.1.156:8080) from another computer

C: Run a System Command and Get Output?

Usually, if the command is an external program, you can use the OS to help you here.

command > file_output.txt

So your C code would be doing something like

exec("command > file_output.txt");

Then you can use the file_output.txt file.

Check if string is neither empty nor space in shell script

To check if a string is empty or contains only whitespace you could use:

shopt -s extglob  # more powerful pattern matching

if [ -n "${str##+([[:space:]])}" ]; then
    echo '$str is not null or space'
fi

See Shell Parameter Expansion and Pattern Matching in the Bash Manual.

Attaching click event to a JQuery object not yet added to the DOM

Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.

I bound the table id to .delegate() and used a selector that describes the inputs.

e.g.

HTML

<table id="#mytable">
  <!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
  <tr><td><input name="qty_001" /></td></tr>
  <tr><td><input name="qty_002" /></td></tr>
  <tr><td><input name="qty_003" /></td></tr>
</table>

jQuery

$('#mytable').delegate('click', 'name^=["qty_"]', function() {
    console.log("you clicked cell #" . $(this).attr("name"));
});

How do you add Boost libraries in CMakeLists.txt?

Additional information to abouve answers for those still having problems.

  1. Last version of Cmake's FindBoost.cmake may not content last version fo Boost. Add it if needed.
  2. Use -DBoost_DEBUG=0 configuration flag to see info on problems.
  3. See for library naming format. Use Boost_COMPILER and Boost_ARCHITECTURE suffix vars if needed.

Access parent's parent from javascript object

I used something that resembles singleton pattern:

function myclass() = {
    var instance = this;

    this.Days = function() {
        var days = ["Piatek", "Sobota", "Niedziela"];
        return days;
    }

    this.EventTime = function(day, hours, minutes) {
        this.Day = instance.Days()[day];
        this.Hours = hours;
        this.minutes = minutes;
        this.TotalMinutes = day*24*60 + 60*hours + minutes;
    }
}

Apache redirect to another port

You have to make sure that the proxy is enabled on the server. You can do so by using the following commands:

  a2enmod proxy
  a2enmod proxy_http

  service apache2 restart

iPhone: How to get current milliseconds?

CFAbsoluteTimeGetCurrent()

Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.

Traverse a list in reverse order in Python

Also, you could use either "range" or "count" functions. As follows:

a = ["foo", "bar", "baz"]
for i in range(len(a)-1, -1, -1):
    print(i, a[i])

3 baz
2 bar
1 foo

You could also use "count" from itertools as following:

a = ["foo", "bar", "baz"]
from itertools import count, takewhile

def larger_than_0(x):
    return x > 0

for x in takewhile(larger_than_0, count(3, -1)):
    print(x, a[x-1])

3 baz
2 bar
1 foo

How do I find duplicate values in a table in Oracle?

Here is an SQL request to do that:

select column_name, count(1)
from table
group by column_name
having count (column_name) > 1;

How to get disk capacity and free space of remote computer

I created this simple function to help me. This makes my calls a lot easier to read that having inline an Get-WmiObject, Where-Object statements, etc.

function GetDiskSizeInfo($drive) {
    $diskReport = Get-WmiObject Win32_logicaldisk
    $drive = $diskReport | Where-Object { $_.DeviceID -eq $drive}

    $result = @{
        Size = $drive.Size
        FreeSpace = $drive.Freespace
    }
    return $result
}

$diskspace = GetDiskSizeInfo "C:"
write-host $diskspace.FreeSpace " " $diskspace.Size

How to get last N records with activerecord?

If you need to set some ordering on results then use:

Model.order('name desc').limit(n) # n= number

if you do not need any ordering, and just need records saved in the table then use:

Model.last(n) # n= any number

Where are environment variables stored in the Windows Registry?

Here's where they're stored on Windows XP through Windows Server 2012 R2:

User Variables

HKEY_CURRENT_USER\Environment

System Variables

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Get url without querystring

Here's an extension method using @Kolman's answer. It's marginally easier to remember to use Path() than GetLeftPart. You might want to rename Path to GetPath, at least until they add extension properties to C#.

Usage:

Uri uri = new Uri("http://www.somewhere.com?param1=foo&param2=bar");
string path = uri.Path();

The class:

using System;

namespace YourProject.Extensions
{
    public static class UriExtensions
    {
        public static string Path(this Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            return uri.GetLeftPart(UriPartial.Path);
        }
    }
}

How to use jQuery to select a dropdown option?

answer with id:

$('#selectBoxId').find('option:eq(0)').attr('selected', true);

Add item to array in VBScript

Slight change to the FastArray from above:

'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """" 

t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
 If i>ub Then 
    ReDim Preserve a(Int((ub+10)*1.1))
    ub = UBound(a)
 End If
 a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"

MsgBox s

There is no point in checking UBound(a) in every cycle of the for if we know exactly when it changes.

I've changed it so that it checks does UBound(a) just before the for starts and then only every time the ReDim is called

On my computer the old method took 7.52 seconds for an imax of 10 millions.

The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

I got this error when unbeknownst to me, someone else was connected to the database in another SSMS session. After I signed them out the restore completed successfully.

What is the maximum length of a valid email address?

The other answers muddy the water a bit. Simple answer: 254 total chars in our control for email 256 are for the ENTIRE email address, which includes implied "<" at the beginning, and ">" at the end. Therefore, 254 are left over for our use.

Convert list to tuple in Python

You might have done something like this:

>>> tuple = 45, 34  # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l)   # Will try to invoke the variable `tuple` rather than tuple type.

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple  # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)

Here's the problem... Since you have used a tuple variable to hold a tuple (45, 34) earlier... So, now tuple is an object of type tuple now...

It is no more a type and hence, it is no more Callable.

Never use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

WPF Check box: Check changed handling

As a checkbox click = a checkbox change the following will also work:

<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    // ... do some stuff
}

It has the additional advantage of working when IsThreeState="True" whereas just handling Checked and Unchecked does not.

How can I delete all Git branches which have been merged?

Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):

#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
#   git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain

import gitapi

repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('\n'):
  branch = branch.strip()
  if branch.strip(' *') != 'master':
    print(repo.git_command('branch', '-d', branch).strip())

https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc

How do I increase the capacity of the Eclipse output console?

For CDT users / C/C++ build, also adjust the setting

in Window > Preferences

under C/C++ > Build > Console (!)

(This time in number of lines.)

This also affects the "CDT Global Build Console".

Convert Decimal to Varchar

If you are using SQL Server 2012, 2014 or newer, use the Format Function instead:

select Format( decimalColumnName ,'FormatString','en-US' )

Review the Microsoft topic and .NET format syntax for how to define the format string.

An example for this question would be:

select Format( MyDecimalColumn ,'N','en-US' )

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

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

How to get number of rows inserted by a transaction

I found the answer to may previous post. Here it is.

CREATE TABLE #TempTable (id int) 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 1,2 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 3,4 

SELECT * FROM #TempTable --this select will chage @@ROWCOUNT value

Can't access RabbitMQ web management interface after fresh install

Something that just happened to me and caused me some headaches:

I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).

The script had several of those "code" blocks:

rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"

Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.

Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.

... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:

rabbitmqctl change_password test test

(Another solution would have been to delete all users and then call the script again)

Mockito, JUnit and Spring

You don't really need the MockitoAnnotations.initMocks(this); if you're using mockito 1.9 ( or newer ) - all you need is this:

@InjectMocks
private MyTestObject testObject;

@Mock
private MyDependentObject mockedObject;

The @InjectMocks annotation will inject all your mocks to the MyTestObject object.

How to create a release signed apk file using Gradle?

(In reply to user672009 above.)

An even easier solution, if you want to keep your passwords out of a git repository; yet, want to include your build.gradle in it, that even works great with product flavors, is to create a separate gradle file. Let's call it 'signing.gradle' (include it in your .gitignore). Just as if it were your build.gradle file minus everything not related to signing in it.

android {
    signingConfigs { 
        flavor1 {
            storeFile file("..")
            storePassword ".."
            keyAlias ".."
            keyPassword ".."
        }
        flavor2 {
            storeFile file("..")
            storePassword ".."
            keyAlias ".."
            keyPassword ".."
        }
    }
}

Then in your build.gradle file include this line right underneath "apply plugin: 'android'"

 apply from: 'signing.gradle'

If you don't have or use multiple flavors, rename "flavor1" to "release" above, and you should be finished. If you are using flavors continue.

Finally link your flavors to its correct signingConfig in your build.gradle file and you should be finished.

  ...

  productFlavors {

      flavor1 {
          ...
          signingConfig signingConfigs.flavor1
      }

      flavor2 {
          ...
          signingConfig signingConfigs.flavor2
      }
  }

  ...

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

Looping through a hash, or using an array in PowerShell

Here is another quick way, just using the key as an index into the hash table to get the value:

$hash = @{
    'a' = 1;
    'b' = 2;
    'c' = 3
};

foreach($key in $hash.keys) {
    Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}

jQuery DataTables: control table width

Just to say I've had exactly the same problem as you, although I was just apply JQuery to a normal table without any Ajax. For some reason Firefox doesn't expand the table out after revealing it. I fixed the problem by putting the table inside a DIV, and applying the effects to the DIV instead.

Addressing localhost from a VirtualBox virtual machine

I need to run on localhost, not some weird IP.

1) From your Mac terminal, do iconfig -a to find your local IP address. It's probably the last one.

en7: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=10b<RXCSUM,TXCSUM,VLAN_HWTAGGING,AV> ether 38:c9:86:32:0e:69 inet6 fe80::ea:393e:a54f:635%en7 prefixlen 64 secured scopeid 0xe inet 10.1.5.60 netmask 0xfffffe00 broadcast 10.1.5.255 nd6 options=201<PERFORMNUD,DAD> media: autoselect (1000baseT <full-duplex,flow-control>) status: active

e.g. 10.1.5.60

2) boot up your windows image. start > type cmd to get a terminal

3) notepad c:\windows\system32\drivers\etc\hosts

4) add the following line 10.1.5.60 localhost

5) open IE, and the following url should hit the server running on your mac: http://localhost:3000/

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

I am using Docker. I am trying to create a docker image that has all of my node dependencies installed, but can use my local app directory at container run time (without polluting it with a node_modules directory or link). This causes problems in this scenario. My workaround is to require from the exact path where the module, e.g. require('/usr/local/lib/node_modules/socket.io')

using where and inner join in mysql

Try this:

SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"

You can join Locations to School_Locations and then School_Locations to School. This forms a set of all related Locations and Schools, which you can then widdle down using the WHERE clause to those whose Location is of type "coun."

Hide strange unwanted Xcode logs

My solution is to use the debugger command and/or Log Message in breakpoints.

enter image description here

And change the output of console from All Output to Debugger Output like

enter image description here

Dynamically add item to jQuery Select2 control that uses AJAX

I have resolved issue with the help of this link http://www.bootply.com/122726. hopefully will help you

Add option in select2 jquery and bind your ajax call with created link id(#addNew) for new option from backend. and the code

 $.getScript('http://ivaynberg.github.io/select2/select2-3.4.5/select2.js',function(){

  $("#mySel").select2({
    width:'240px',
    allowClear:true,
    formatNoMatches: function(term) {
        /* customize the no matches output */
        return "<input class='form-control' id='newTerm' value='"+term+"'><a href='#' id='addNew' class='btn btn-default'>Create</a>"
    }
  })
  .parent().find('.select2-with-searchbox').on('click','#addNew',function(){
    /* add the new term */
    var newTerm = $('#newTerm').val();
    //alert('adding:'+newTerm);
    $('<option>'+newTerm+'</option>').appendTo('#mySel');
    $('#mySel').select2('val',newTerm); // select the new term
    $("#mySel").select2('close');       // close the dropdown
  })

});



<div class="container">
    <h3>Select2 - Add new term when no search matches</h3>
    <select id="mySel">
        <option>One</option>
        <option>Two</option>
        <option>Three</option>
        <option>Four</option>
        <option>Five</option>
        <option>Six</option>
        <option>Twenty Four</option>
    </select>
    <br>
    <br>
</div>

T-SQL substring - separating first and last name

The code below works with Last, First M name strings. Substitute "Name" with your name string column name. Since you have a period as a final character when there is a middle initial, you would replace the 2's with 3's in each of the lines (2, 6, and 8)- and change "RIGHT(Name, 1)" to "RIGHT(Name, 2)" in line 8.

SELECT  SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1) LastName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) <> ' '
     THEN LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99))
     ELSE LEFT(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)),
               LEN(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)))
               - 2)
END FirstName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) = ' ' THEN RIGHT(Name, 1)
     ELSE NULL
END MiddleName

How to test if a string is JSON or not?

Well... It depends the way you are receiving your data. I think the server is responding with a JSON formated string (using json_encode() in PHP,e.g.). If you're using JQuery post and set response data to be a JSON format and it is a malformed JSON, this will produce an error:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        //Supposing x is a JSON property...
        alert(response.x);

  },
  dataType: 'json',
  //Invalid JSON
  error: function (){ alert("error!"); }
});

But, if you're using the type response as text, you need use $.parseJSON. According jquery site: "Passing in a malformed JSON string may result in an exception being thrown". Thus your code will be:

$.ajax({
  type: 'POST',
  url: 'test2.php',
  data: "data",
  success: function (response){

        try {
            parsedData = JSON.parse(response);
        } catch (e) {
            // is not a valid JSON string
        }

  },
  dataType: 'text',
});

How can I set the opacity or transparency of a Panel in WinForms?

I just wanted to add to the William Smash solution as I couldn't get to his blog so answers which may have been in there to my simple questions could not be found.

Took me a while to realise, but maybe I was just having a moment...

If you haven't had to do so already you'll need to add a reference to System.Windows.Forms in the project properties.

Also you'll need to add

Imports System.Windows.Forms 

to the file where you're adding the override class.

For OnPaintBackground you'll need to add a reference for System.Drawing then

Imports System.Drawing.Printing.PrintEventArgs

From Now() to Current_timestamp in Postgresql

Use an interval instead of an integer:

SELECT *
FROM table
WHERE auth_user.lastactivity > CURRENT_TIMESTAMP - INTERVAL '100 days'

How to do while loops with multiple conditions

while not condition1 or not condition2 or val == -1:

But there was nothing wrong with your original of using an if inside of a while True.

Remove Unnamed columns in pandas dataframe

The approved solution doesn't work in my case, so my solution is the following one:

    ''' The column name in the example case is "Unnamed: 7"
 but it works with any other name ("Unnamed: 0" for example). '''

        df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)

        # Then, drop the column as usual.

        df.drop(["a"], axis=1, inplace=True)

Hope it helps others.

How do I see the current encoding of a file in Sublime Text?

With the EncodingHelper plugin you can view the encoding of the file on the status bar. Also you can convert the encoding of the file and extended another functionalities.

Demo

to call onChange event after pressing Enter key

Here is a common use case using class-based components: The parent component provides a callback function, the child component renders the input box, and when the user presses Enter, we pass the user's input to the parent.

class ParentComponent extends React.Component {
  processInput(value) {
    alert('Parent got the input: '+value);
  }

  render() {
    return (
      <div>
        <ChildComponent handleInput={(value) => this.processInput(value)} />
      </div>
    )
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handleKeyDown = this.handleKeyDown.bind(this);
  }

  handleKeyDown(e) {
    if (e.key === 'Enter') {
      this.props.handleInput(e.target.value);
    }
  }

  render() {
    return (
      <div>
        <input onKeyDown={this.handleKeyDown} />
      </div>
    )
  }      
}

NodeJS - Error installing with NPM

Setup JavaScript Environment

1. Install Node.js

Download installer at NodeJs website. You can download the latest V6

2. Update Npm

Npm is installed together with Node.js. So don't worry.

3. Install Anaconda

Anaconda is the leading open data science platform powered by Python. The open source version of Anaconda is a high performance distribution of Python. It can help you to manage your python dependency. You can use it to create different python environment in the futher if you want to touch with it.

Node-gyp only support >= Python 2.7 and < Python 3.0

So just install the 2.7 version

4. Install Node-gyp

You can install with npm:

$ npm install -g node-gyp

You will also need to install:

  • On Windows:

    • Option 1: Install all the required tools and configurations using Microsoft's windows-build-tools using npm install --global --production windows-build-tools from an elevated PowerShell or CMD.exe (run as Administrator).

    • Option 2: Install tools and configuration manually:

    • Visual C++ Build Environment:

      • Option 1: Install Visual C++ Build Tools using the Default Install option.
      • Option 2: Install Visual Studio 2015 (or modify an existing installation) and select Common Tools for Visual C++ during setup. This also works with the free Community and Express for Desktop editions.

       [Windows Vista / 7 only] requires .NET Framework 4.5.1

    • Launch cmd, npm config set msvs_version 2015

    If the above steps didn't work for you, please visit Microsoft's Node.js Guidelines for Windows for additional tips.

If you have multiple Python versions installed, you can identify which Python version node-gyp uses by setting the '--python' variable:

$ node-gyp --python C:/Anaconda2/python.exe

If node-gyp is called by way of npm and you have multiple versions of Python installed, then you can set npm's 'python' config key to the appropriate value:

$ npm config set python C:/Anaconda2/python.exe

Future update for Node.js and npm

Download installer from their official website and direct install it. The installer will automatic help you to remove old files.

npm update npm

Future update for Python

conda update --all

How to create Java gradle project

Unfortunately you cannot do it in one command. There is an open issue for the very feature.

Currently you'll have to do it by hand. If you need to do it often, you can create a custom gradle plugin, or just prepare your own project skeleton and copy it when needed.

EDIT

The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the Build Init Plugin is available, although it indicates that this feature is still in the "incubating" lifecycle.

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

Start your XAMPP server by using:

  • {XAMPP}\xampp-control.exe
  • {XAMPP}\apache_start.bat

Then you have to use the URI http://localhost/index.html because htdocs is the document root of the Apache server.

If you're getting redirected to http://localhost/xampp/*, then index.php located in the htdocs folder is the problem because index.php files have a higher priority than index.html files. You could temporarily rename index.php.

How to output to the console and file?

You should use the logging library, which has this capability built in. You simply add handlers to a logger to determine where to send the output.

Import PEM into Java Key Store

Although this question is pretty old and it has already a-lot answers, I think it is worth to provide an alternative. Using native java classes makes it very verbose to just use pem files and almost forces you wanting to convert the pem files into p12 or jks files as using p12 or jks files are much easier. I want to give anyone who wants an alternative for the already provided answers.

GitHub - SSLContext Kickstart

var keyManager = PemUtils.loadIdentityMaterial("certificate-chain.pem", "private-key.pem");
var trustManager = PemUtils.loadTrustMaterial("some-trusted-certificate.pem");

var sslFactory = SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withTrustMaterial(trustManager)
          .build();

var sslContext = sslFactory.getSslContext();

I need to provide some disclaimer here, I am the library maintainer

How to hide element label by element id in CSS?

If you give the label an ID, like this:

<label for="foo" id="foo_label">

Then this would work:

#foo_label { display: none;}

Your other options aren't really cross-browser friendly, unless javascript is an option. The CSS3 selector, not as widely supported looks like this:

[for="foo"] { display: none;}

Hide horizontal scrollbar on an iframe?

If you are allowed to change the code of the document inside your iframe and that content is visible only using its parent window, simply add the following CSS in your iframe:

body {
    overflow:hidden;
}

Here a very simple example:

http://jsfiddle.net/u5gLoav9/

This solution allow you to:

  • Keep you HTML5 valid as it does not need scrolling="no" attribute on the iframe (this attribute in HTML5 has been deprecated).

  • Works on the majority of browsers using CSS overflow:hidden

  • No JS or jQuery necessary.

Notes:

To disallow scroll-bars horizontally, use this CSS instead:

overflow-x: hidden;

When is JavaScript synchronous?

To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don't necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.

JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete etc...

The main point of confusion arises from the fact that your browser is able to tell JS to execute more code at anytime (similar to how you can execute more JS code on a page from the console). As an example JS has Callback functions who's purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.

Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)

I hope this is clear enough to be helpful to somebody.

check if directory exists and delete in one command unix

Try:

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

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

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

How do I sleep for a millisecond in Perl?

Time::HiRes:

  use Time::HiRes;
  Time::HiRes::sleep(0.1); #.1 seconds
  Time::HiRes::usleep(1); # 1 microsecond.

http://perldoc.perl.org/Time/HiRes.html

Find all controls in WPF Window by type

For this and more use cases you can add flowing extension method to your library:

 public static List<DependencyObject> FindAllChildren(this DependencyObject dpo, Predicate<DependencyObject> predicate)
    {
        var results = new List<DependencyObject>();
        if (predicate == null)
            return results;


        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dpo); i++)
        {
            var child = VisualTreeHelper.GetChild(dpo, i);
            if (predicate(child))
                results.Add(child);

            var subChildren = child.FindAllChildren(predicate);
            results.AddRange(subChildren);
        }
        return results;
    }

Example for your case:

 var children = dpObject.FindAllChildren(child => child is TextBox);

How to get min, seconds and milliseconds from datetime.now() in python?

This solution is very similar to that provided by @gdw2 , only that the string formatting is correctly done to match what you asked for - "Should be as compact as possible"

>>> import datetime
>>> a = datetime.datetime.now()
>>> "%s:%s.%s" % (a.minute, a.second, str(a.microsecond)[:2])
'31:45.57'

ASP.NET MVC 404 Error Handling

The response from Marco is the BEST solution. I needed to control my error handling, and I mean really CONTROL it. Of course, I have extended the solution a little and created a full error management system that manages everything. I have also read about this solution in other blogs and it seems very acceptable by most of the advanced developers.

Here is the final code that I am using:

protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 404)
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            Response.Clear();
            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values["controller"] = "ErrorManager";
            routeData.Values["action"] = "Fire404Error";
            routeData.Values["exception"] = exception;
            Response.StatusCode = 500;

            if (httpException != null)
            {
                Response.StatusCode = httpException.GetHttpCode();
                switch (Response.StatusCode)
                {
                    case 404:
                        routeData.Values["action"] = "Fire404Error";
                        break;
                }
            }
            // Avoid IIS7 getting in the middle
            Response.TrySkipIisCustomErrors = true;
            IController errormanagerController = new ErrorManagerController();
            HttpContextWrapper wrapper = new HttpContextWrapper(Context);
            var rc = new RequestContext(wrapper, routeData);
            errormanagerController.Execute(rc);
        }
    }

and inside my ErrorManagerController :

        public void Fire404Error(HttpException exception)
    {
        //you can place any other error handling code here
        throw new PageNotFoundException("page or resource");
    }

Now, in my Action, I am throwing a Custom Exception that I have created. And my Controller is inheriting from a custom Controller Based class that I have created. The Custom Base Controller was created to override error handling. Here is my custom Base Controller class:

public class MyBasePageController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.GetType();
        filterContext.ExceptionHandled = true;
        this.View("ErrorManager", filterContext).ExecuteResult(this.ControllerContext);
        base.OnException(filterContext);
    }
}

The "ErrorManager" in the above code is just a view that is using a Model based on ExceptionContext

My solution works perfectly and I am able to handle ANY error on my website and display different messages based on ANY exception type.

Singleton in Android

answer suggested by rakesh is great but still with some discription Singleton in Android is the same as Singleton in Java: The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:

1) Ensure that only one instance of a class is created

2) Provide a global point of access to the object

3) Allow multiple instances in the future without affecting a singleton class's clients

A basic Singleton class example:

public class MySingleton
{
    private static MySingleton _instance;

    private MySingleton()
    {

    }

    public static MySingleton getInstance()
    {
        if (_instance == null)
        {
            _instance = new MySingleton();
        }
        return _instance;
    }
}

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Mail multipart/alternative vs multipart/mixed

Mixed Subtype

The "mixed" subtype of "multipart" is intended for use when the body parts are independent and need to be bundled in a particular order. Any "multipart" subtypes that an implementation does not recognize must be treated as being of subtype "mixed".

Alternative Subtype

The "multipart/alternative" type is syntactically identical to "multipart/mixed", but the semantics are different. In particular, each of the body parts is an "alternative" version of the same information

Source

Can I try/catch a warning?

Be careful with the @ operator - while it suppresses warnings it also suppresses fatal errors. I spent a lot of time debugging a problem in a system where someone had written @mysql_query( '...' ) and the problem was that mysql support was not loaded into PHP and it threw a silent fatal error. It will be safe for those things that are part of the PHP core but please use it with care.

bob@mypc:~$ php -a
Interactive shell

php > echo @something(); // this will just silently die...

No further output - good luck debugging this!

bob@mypc:~$ php -a
Interactive shell

php > echo something(); // lets try it again but don't suppress the error
PHP Fatal error:  Call to undefined function something() in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0
bob@mypc:~$ 

This time we can see why it failed.

get client time zone from browser

Half a decade later we have a built-in way for it! For modern browsers I would use:

_x000D_
_x000D_
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;_x000D_
console.log(tz);
_x000D_
_x000D_
_x000D_

This returns a IANA timezone string, but not the offset. Learn more at the MDN reference.

Compatibility table - as of March 2019, works for 90% of the browsers in use globally. Doesn't work on Internet Explorer.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Jquery - How to get the style display attribute "none / block"

If you're using jquery 1.6.2 you only need to code

$('#theid').css('display')

for example:

if($('#theid').css('display') == 'none'){ 
   $('#theid').show('slow'); 
} else { 
   $('#theid').hide('slow'); 
}

What type of hash does WordPress use?

Start phpMyAdmin and access wp_users from your wordpress instance. Edit record and select user_pass function to match MD5. Write the string that will be your new password in VALUE. Click, GO. Go to your wordpress website and enter your new password. Back to phpMyAdmin you will see that WP changed the HASH to something like $P$B... enjoy!

multiprocessing.Pool: When to use apply, apply_async or map?

Regarding apply vs map:

pool.apply(f, args): f is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args).

pool.map(f, iterable): This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.

JavaScript is in array

Some browsers support Array.indexOf().

If not, you could augment the Array object via its prototype like so...

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n) // shortcut for verifying if it's NaN
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

Source.

How to create temp table using Create statement in SQL Server?

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

Python, how to read bytes from file and save it?

Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:

file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

How to set Java environment path in Ubuntu

set environment variables as follows

Edit the system Path file /etc/profile

sudo gedit /etc/profile

Add following lines in end

JAVA_HOME=/usr/lib/jvm/jdk1.7.0
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

Then Log out and Log in ubuntu for setting up the paths...

When should an Excel VBA variable be killed or set to Nothing?

VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.

Object variables are guaranteed to be cleaned (set to Nothing) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.

There are only two cases when you want an explicit cleanup:

  1. When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).

  2. When you have a circular reference between two or more objects.

    If objectA stores a references to objectB, and objectB stores a reference to objectA, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing or objectB.ReferenceToA = Nothing.

The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.

If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.).

If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.).

Access level of a variable (public vs. private) does not affect its life time.

Can't install any packages in Node.js using "npm install"

I found the there is a certificate expired issue with:

npm set registry https://registry.npmjs.org/

So I made it http, not https :-

npm set registry http://registry.npmjs.org/

And have no problems so far.

Check if instance is of a type

Or

c.getType() == typeOf(TForm)

Check if a file exists or not in Windows PowerShell?

Just to offer the alternative to the Test-Path cmdlet (since nobody mentioned it):

[System.IO.File]::Exists($path)

Does (almost) the same thing as

Test-Path $path -PathType Leaf

except no support for wildcard characters

Error in <my code> : object of type 'closure' is not subsettable

In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]

Just add corresponding package name using :: e.g.

instead of tags(....)

write shiny::tags(....)

CSS:Defining Styles for input elements inside a div

When you say "called" I'm going to assume you mean an ID tag.

To make it cross-brower, I wouldn't suggest using the CSS3 [], although it is an option. This being said, give each of your textboxes a class like "tb" and the radio button "rb".

Then:

#divContainer .tb { width: 150px }
#divContainer .rb { width: 20px }

This assumes you are using the same classes elsewhere, if not, this will suffice:

.tb { width: 150px }
.rb { width: 20px }

As @David mentioned, to access anything within the division itself:

#divContainer [element] { ... }

Where [element] is whatever HTML element you need.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.

Returning the product of a list

Well if you really wanted to make it one line without importing anything you could do:

eval('*'.join(str(item) for item in list))

But don't.

Pressed <button> selector

You can do this with php if the button opens a new page.

For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.

I exploded the url by '/' an got something like:

url[0] = pagename.php

<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>


<html>
<head>
  <style>
    .btn{
     background:white;
     }
    .btn:hover,
    .btn-on{
     background:red;
     }
  </style>
</head>
<body>
   <a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>

note: I didn't try this code. It might need adjustments.

Global Events in Angular

The following code as an example of a replacement for $scope.emit() or $scope.broadcast() in Angular 2 using a shared service to handle events.

import {Injectable} from 'angular2/core';
import * as Rx from 'rxjs/Rx';

@Injectable()
export class EventsService {
    constructor() {
        this.listeners = {};
        this.eventsSubject = new Rx.Subject();

        this.events = Rx.Observable.from(this.eventsSubject);

        this.events.subscribe(
            ({name, args}) => {
                if (this.listeners[name]) {
                    for (let listener of this.listeners[name]) {
                        listener(...args);
                    }
                }
            });
    }

    on(name, listener) {
        if (!this.listeners[name]) {
            this.listeners[name] = [];
        }

        this.listeners[name].push(listener);
    }

    off(name, listener) {
        this.listeners[name] = this.listeners[name].filter(x => x != listener);
    }

    broadcast(name, ...args) {
        this.eventsSubject.next({
            name,
            args
        });
    }
}

Example usage:

Broadcast:

function handleHttpError(error) {
    this.eventsService.broadcast('http-error', error);
    return ( Rx.Observable.throw(error) );
}

Listener:

import {Inject, Injectable} from "angular2/core";
import {EventsService}      from './events.service';

@Injectable()
export class HttpErrorHandler {
    constructor(eventsService) {
        this.eventsService = eventsService;
    }

    static get parameters() {
        return [new Inject(EventsService)];
    }

    init() {
        this.eventsService.on('http-error', function(error) {
            console.group("HttpErrorHandler");
            console.log(error.status, "status code detected.");
            console.dir(error);
            console.groupEnd();
        });
    }
}

It can support multiple arguments:

this.eventsService.broadcast('something', "Am I a?", "Should be b", "C?");

this.eventsService.on('something', function (a, b, c) {
   console.log(a, b, c);
});

How to drop all user tables?

The easiest way would be to drop the tablespace then build the tablespace back up. But I'd rather not have to do that. This is similar to Henry's except that I just do a copy/paste on the resultset in my gui.

SELECT
  'DROP'
  ,object_type
  ,object_name
  ,CASE(object_type)
     WHEN 'TABLE' THEN 'CASCADE CONSTRAINTS;'
     ELSE ';'
   END
 FROM user_objects
 WHERE
   object_type IN ('TABLE','VIEW','PACKAGE','PROCEDURE','FUNCTION','SEQUENCE')

curl -GET and -X GET

-X [your method]
X lets you override the default 'Get'

** corrected lowercase x to uppercase X

How to redirect to the same page in PHP

header('Location: '.$_SERVER['PHP_SELF']);  

will also work

Access restriction on class due to restriction on required library rt.jar?

In the case you are sure that you should be able to access given class, than this can mean you added several jars to your project containing classes with identical names (or paths) but different content and they are overshadowing each other (typically an old custom build jar contains built-in older version of a 3rd party library).

For example when you add a jar implementing:

a.b.c.d1
a.b.c.d2

but also an older version implementing only:

a.b.c.d1
(d2 is missing altogether or has restricted access)

Everything works fine in the code editor but fails during the compilation if the "old" library overshadows the new one - d2 suddenly turns out "missing or inaccessible" even when it is there.

The solution is a to check the order of compile-time libraries and make sure that the one with correct implementation goes first.

Why would one mark local variables and method parameters as "final" in Java?

My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.

I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.

But, of course, it's all personal preference ;-)

Java ArrayList - how can I tell if two lists are equal, order not mattering?

Best of both worlds [@DiddiZ, @Chalkos]: this one mainly builds upon @Chalkos method, but fixes a bug (ifst.next()), and improves initial checks (taken from @DiddiZ) as well as removes the need to copy the first collection (just removes items from a copy of the second collection).

Not requiring a hashing function or sorting, and enabling an early exist on un-equality, this is the most efficient implementation yet. That is unless you have a collection length in the thousands or more, and a very simple hashing function.

public static <T> boolean isCollectionMatch(Collection<T> one, Collection<T> two) {
    if (one == two)
        return true;

    // If either list is null, return whether the other is empty
    if (one == null)
        return two.isEmpty();
    if (two == null)
        return one.isEmpty();

    // If lengths are not equal, they can't possibly match
    if (one.size() != two.size())
        return false;

    // copy the second list, so it can be modified
    final List<T> ctwo = new ArrayList<>(two);

    for (T itm : one) {
        Iterator<T> it = ctwo.iterator();
        boolean gotEq = false;
        while (it.hasNext()) {
            if (itm.equals(it.next())) {
                it.remove();
                gotEq = true;
                break;
            }
        }
        if (!gotEq) return false;
    }
    // All elements in one were found in two, and they're the same size.
    return true;
}

How can I hide select options with JavaScript? (Cross browser)

It's possible if you keep in object and filter it in short way.

<select id="driver_id">
<option val="1" class="team_opion option_21">demo</option>
<option val="2" class="team_opion option_21">xyz</option>
<option val="3" class="team_opion option_31">ab</option>
</select>

-

team_id= 31;

var element = $("#driver_id");
originalElement = element.clone();  // keep original element, make it global


element.find('option').remove();   
originalElement.find(".option_"+team_id).each(function() { // change find with your needs
        element.append($(this)["0"].outerHTML); // append found options
});

https://jsfiddle.net/2djv7zgv/4/

jQuery - Dynamically Create Button and Attach Event Handler

You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.

Android: failed to convert @drawable/picture into a drawable

My Image name was 21.jpg. I renamed it as abc.jpg and it worked. So Make sure your image name not starting with a number. However all above answers are also accepted.

How to get first record in each group using Linq

The awnser of @Alireza is totally correct, but you must notice that when using this code

var res = from element in list
          group element by element.F1
              into groups
              select groups.OrderBy(p => p.F2).First();

which is simillar to this code because you ordering the list and then do the grouping so you are getting the first row of groups

var res = (from element in list)
          .OrderBy(x => x.F2)
          .GroupBy(x => x.F1)
          .Select()

Now if you want to do something more complex like take the same grouping result but take the first element of F2 and the last element of F3 or something more custom you can do it by studing the code bellow

 var res = (from element in list)
          .GroupBy(x => x.F1)
          .Select(y => new
           {
             F1 = y.FirstOrDefault().F1;
             F2 = y.First().F2;
             F3 = y.Last().F3;
           });

So you will get something like

   F1            F2             F3 
 -----------------------------------
   Nima          1990           12
   John          2001           2
   Sara          2010           4

SQL UPDATE all values in a field with appended string CONCAT not working

convert the NULL values with empty string by wrapping it in COALESCE

"UPDATE table SET data = CONCAT(COALESCE(`data`,''), 'a')"

OR

Use CONCAT_WS instead:

"UPDATE table SET data = CONCAT_WS(',',data, 'a')"

How to run bootRun with spring profile via gradle task

my way:

in gradle.properties:

profile=profile-dev

in build.gradle add VM options -Dspring.profiles.active:

bootRun {
   jvmArgs = ["-Dspring.output.ansi.enabled=ALWAYS","-Dspring.profiles.active="+profile]
}

this will override application spring.profiles.active option

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

Enzyme - How to access and set <input> value?

.simulate() doesn't work for me somehow, I got it working with just accessing the node.value without needing to call .simulate(); in your case:

const wrapper = mount(<EditableText defaultValue="Hello" />);
const input = wrapper.find('input').at(0);

// Get the value
console.log(input.node.value); // Hello

// Set the value
input.node.value = 'new value';

// Get the value
console.log(input.node.value); // new value

Hope this helps for others!

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

EDIT: Thanks for the comments - I looked it up in the C99 standard, which says in section 6.5.3.4:

The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers)

So, the size of size_t is not specified, only that it has to be an unsigned integer type. However, an interesting specification can be found in chapter 7.18.3 of the standard:

limit of size_t

SIZE_MAX 65535

Which basically means that, irrespective of the size of size_t, the allowed value range is from 0-65535, the rest is implementation dependent.

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

Drawing a dot on HTML5 canvas

For performance reasons, don't draw a circle if you can avoid it. Just draw a rectangle with a width and height of one:

ctx.fillRect(10,10,1,1); // fill in the pixel at (10,10)

Binary Search Tree - Java Implementation


Here is the complete Implementation of Binary Search Tree In Java insert,search,countNodes,traversal,delete,empty,maximum & minimum node,find parent node,print all leaf node, get level,get height, get depth,print left view, mirror view


import java.util.NoSuchElementException;
import java.util.Scanner;

import org.junit.experimental.max.MaxCore;

class BSTNode {

    BSTNode left = null;
    BSTNode rigth = null;
    int data = 0;

    public BSTNode() {
        super();
    }

    public BSTNode(int data) {
        this.left = null;
        this.rigth = null;
        this.data = data;
    }

    @Override
    public String toString() {
        return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
    }

}


class BinarySearchTree {

    BSTNode root = null;

    public BinarySearchTree() {

    }

    public void insert(int data) {
        BSTNode node = new BSTNode(data);
        if (root == null) {
            root = node;
            return;
        }

        BSTNode currentNode = root;
        BSTNode parentNode = null;

        while (true) {
            parentNode = currentNode;
            if (currentNode.data == data)
                throw new IllegalArgumentException("Duplicates nodes note allowed in Binary Search Tree");

            if (currentNode.data > data) {
                currentNode = currentNode.left;
                if (currentNode == null) {
                    parentNode.left = node;
                    return;
                }
            } else {
                currentNode = currentNode.rigth;
                if (currentNode == null) {
                    parentNode.rigth = node;
                    return;
                }
            }
        }
    }

    public int countNodes() {
        return countNodes(root);
    }

    private int countNodes(BSTNode node) {
        if (node == null) {
            return 0;
        } else {
            int count = 1;
            count += countNodes(node.left);
            count += countNodes(node.rigth);
            return count;
        }
    }

    public boolean searchNode(int data) {
        if (empty())
            return empty();
        return searchNode(data, root);
    }

    public boolean searchNode(int data, BSTNode node) {
        if (node != null) {
            if (node.data == data)
                return true;
            else if (node.data > data)
                return searchNode(data, node.left);
            else if (node.data < data)
                return searchNode(data, node.rigth);
        }
        return false;
    }

    public boolean delete(int data) {
        if (empty())
            throw new NoSuchElementException("Tree is Empty");

        BSTNode currentNode = root;
        BSTNode parentNode = root;
        boolean isLeftChild = false;

        while (currentNode.data != data) {
            parentNode = currentNode;
            if (currentNode.data > data) {
                isLeftChild = true;
                currentNode = currentNode.left;
            } else if (currentNode.data < data) {
                isLeftChild = false;
                currentNode = currentNode.rigth;
            }
            if (currentNode == null)
                return false;
        }

        // CASE 1: node with no child
        if (currentNode.left == null && currentNode.rigth == null) {
            if (currentNode == root)
                root = null;
            if (isLeftChild)
                parentNode.left = null;
            else
                parentNode.rigth = null;
        }

        // CASE 2: if node with only one child
        else if (currentNode.left != null && currentNode.rigth == null) {
            if (root == currentNode) {
                root = currentNode.left;
            }
            if (isLeftChild)
                parentNode.left = currentNode.left;
            else
                parentNode.rigth = currentNode.left;
        } else if (currentNode.rigth != null && currentNode.left == null) {
            if (root == currentNode)
                root = currentNode.rigth;
            if (isLeftChild)
                parentNode.left = currentNode.rigth;
            else
                parentNode.rigth = currentNode.rigth;
        }

        // CASE 3: node with two child
        else if (currentNode.left != null && currentNode.rigth != null) {

            // Now we have to find minimum element in rigth sub tree
            // that is called successor
            BSTNode successor = getSuccessor(currentNode);
            if (currentNode == root)
                root = successor;
            if (isLeftChild)
                parentNode.left = successor;
            else
                parentNode.rigth = successor;
            successor.left = currentNode.left;
        }

        return true;
    }

    private BSTNode getSuccessor(BSTNode deleteNode) {

        BSTNode successor = null;
        BSTNode parentSuccessor = null;
        BSTNode currentNode = deleteNode.left;

        while (currentNode != null) {
            parentSuccessor = successor;
            successor = currentNode;
            currentNode = currentNode.left;
        }

        if (successor != deleteNode.rigth) {
            parentSuccessor.left = successor.left;
            successor.rigth = deleteNode.rigth;
        }

        return successor;
    }

    public int nodeWithMinimumValue() {
        return nodeWithMinimumValue(root);
    }

    private int nodeWithMinimumValue(BSTNode node) {
        if (node.left != null)
            return nodeWithMinimumValue(node.left);
        return node.data;
    }

    public int nodewithMaximumValue() {
        return nodewithMaximumValue(root);
    }

    private int nodewithMaximumValue(BSTNode node) {
        if (node.rigth != null)
            return nodewithMaximumValue(node.rigth);
        return node.data;
    }

    public int parent(int data) {
        return parent(root, data);
    }

    private int parent(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode parent = null;
        BSTNode current = node;

        while (current.data != data) {
            parent = current;
            if (current.data > data)
                current = current.left;
            else
                current = current.rigth;
            if (current == null)
                throw new IllegalArgumentException(data + " is not a node in tree");
        }
        return parent.data;
    }

    public int sibling(int data) {
        return sibling(root, data);
    }

    private int sibling(BSTNode node, int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        if (root.data == data)
            throw new IllegalArgumentException("No Parent node found");

        BSTNode cureent = node;
        BSTNode parent = null;
        boolean isLeft = false;

        while (cureent.data != data) {
            parent = cureent;
            if (cureent.data > data) {
                cureent = cureent.left;
                isLeft = true;
            } else {
                cureent = cureent.rigth;
                isLeft = false;
            }
            if (cureent == null)
                throw new IllegalArgumentException("No Parent node found");
        }
        if (isLeft) {
            if (parent.rigth != null) {
                return parent.rigth.data;
            } else
                throw new IllegalArgumentException("No Sibling is there");
        } else {
            if (parent.left != null)
                return parent.left.data;
            else
                throw new IllegalArgumentException("No Sibling is there");
        }
    }

    public void leafNodes() {
        if (empty())
            throw new IllegalArgumentException("Empty");
        leafNode(root);
    }

    private void leafNode(BSTNode node) {
        if (node == null)
            return;
        if (node.rigth == null && node.left == null)
            System.out.print(node.data + " ");
        leafNode(node.left);
        leafNode(node.rigth);
    }

    public int level(int data) {
        if (empty())
            throw new IllegalArgumentException("Empty");
        return level(root, data, 1);
    }

    private int level(BSTNode node, int data, int level) {
        if (node == null)
            return 0;
        if (node.data == data)
            return level;
        int result = level(node.left, data, level + 1);
        if (result != 0)
            return result;
        result = level(node.rigth, data, level + 1);
        return result;
    }

    public int depth() {
        return depth(root);
    }

    private int depth(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(depth(node.left), depth(node.rigth));
    }

    public int height() {
        return height(root);
    }

    private int height(BSTNode node) {
        if (node == null)
            return 0;
        else
            return 1 + Math.max(height(node.left), height(node.rigth));
    }

    public void leftView() {
        leftView(root);
    }

    private void leftView(BSTNode node) {
        if (node == null)
            return;
        int height = height(node);

        for (int i = 1; i <= height; i++) {
            printLeftView(node, i);
        }
    }

    private boolean printLeftView(BSTNode node, int level) {
        if (node == null)
            return false;

        if (level == 1) {
            System.out.print(node.data + " ");
            return true;
        } else {
            boolean left = printLeftView(node.left, level - 1);
            if (left)
                return true;
            else
                return printLeftView(node.rigth, level - 1);
        }
    }

    public void mirroeView() {
        BSTNode node = mirroeView(root);
        preorder(node);
        System.out.println();
        inorder(node);
        System.out.println();
        postorder(node);
        System.out.println();
    }

    private BSTNode mirroeView(BSTNode node) {
        if (node == null || (node.left == null && node.rigth == null))
            return node;

        BSTNode temp = node.left;
        node.left = node.rigth;
        node.rigth = temp;

        mirroeView(node.left);
        mirroeView(node.rigth);
        return node;
    }

    public void preorder() {
        preorder(root);
    }

    private void preorder(BSTNode node) {
        if (node != null) {
            System.out.print(node.data + " ");
            preorder(node.left);
            preorder(node.rigth);
        }
    }

    public void inorder() {
        inorder(root);
    }

    private void inorder(BSTNode node) {
        if (node != null) {
            inorder(node.left);
            System.out.print(node.data + " ");
            inorder(node.rigth);
        }
    }

    public void postorder() {
        postorder(root);
    }

    private void postorder(BSTNode node) {
        if (node != null) {
            postorder(node.left);
            postorder(node.rigth);
            System.out.print(node.data + " ");
        }
    }

    public boolean empty() {
        return root == null;
    }

}

public class BinarySearchTreeTest {
    public static void main(String[] l) {
        System.out.println("Weleome to Binary Search Tree");
        Scanner scanner = new Scanner(System.in);
        boolean yes = true;
        BinarySearchTree tree = new BinarySearchTree();
        do {
            System.out.println("\n1. Insert");
            System.out.println("2. Search Node");
            System.out.println("3. Count Node");
            System.out.println("4. Empty Status");
            System.out.println("5. Delete Node");
            System.out.println("6. Node with Minimum Value");
            System.out.println("7. Node with Maximum Value");
            System.out.println("8. Find Parent node");
            System.out.println("9. Count no of links");
            System.out.println("10. Get the sibling of any node");
            System.out.println("11. Print all the leaf node");
            System.out.println("12. Get the level of node");
            System.out.println("13. Depth of the tree");
            System.out.println("14. Height of Binary Tree");
            System.out.println("15. Left View");
            System.out.println("16. Mirror Image of Binary Tree");
            System.out.println("Enter Your Choice :: ");
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                try {
                    System.out.println("Enter Value");
                    tree.insert(scanner.nextInt());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 2:
                System.out.println("Enter the node");
                System.out.println(tree.searchNode(scanner.nextInt()));
                break;

            case 3:
                System.out.println(tree.countNodes());
                break;

            case 4:
                System.out.println(tree.empty());
                break;

            case 5:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.delete(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 6:
                try {
                    System.out.println(tree.nodeWithMinimumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 7:
                try {
                    System.out.println(tree.nodewithMaximumValue());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 8:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.parent(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 9:
                try {
                    System.out.println(tree.countNodes() - 1);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 10:
                try {
                    System.out.println("Enter the node");
                    System.out.println(tree.sibling(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 11:
                try {
                    tree.leafNodes();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }

            case 12:
                try {
                    System.out.println("Enter the node");
                    System.out.println("Level is : " + tree.level(scanner.nextInt()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 13:
                try {
                    System.out.println(tree.depth());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 14:
                try {
                    System.out.println(tree.height());
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 15:
                try {
                    tree.leftView();
                    System.out.println();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            case 16:
                try {
                    tree.mirroeView();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                break;

            default:
                break;
            }
            tree.preorder();
            System.out.println();
            tree.inorder();
            System.out.println();
            tree.postorder();
        } while (yes);
        scanner.close();
    }
}

How to take screenshot of a div with JavaScript?

No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the HTMLCanvasElement object's toDataURL function to get a data: URI with the image's contents.

When the quiz is finished, do this:

var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */

When the user clicks "Capture", do this:

window.open('', document.getElementById('the_canvas_element_id').toDataURL());

This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.

HTML Display Current date

Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.

_x000D_
_x000D_
n =  new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
_x000D_
_x000D_

Correct way to use Modernizr to detect IE?

Detecting CSS 3D transforms

Modernizr can detect CSS 3D transforms, yeah. The truthiness of Modernizr.csstransforms3d will tell you if the browser supports them.

The above link lets you select which tests to include in a Modernizr build, and the option you're looking for is available there.


Detecting IE specifically

Alternatively, as user356990 answered, you can use conditional comments if you're searching for IE and IE alone. Rather than creating a global variable, you can use HTML5 Boilerplate's <html> conditional comments trick to assign a class:

<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->

If you already have jQuery initialised, you can just check with $('html').hasClass('lt-ie9'). If you need to check which IE version you're in so you can conditionally load either jQuery 1.x or 2.x, you can do something like this:

myChecks.ltIE9 = (function(){
    var htmlElemClasses = document.querySelector('html').className.split(' ');
    if (!htmlElemClasses){return false;}
    for (var i = 0; i < htmlElemClasses.length; i += 1 ){
      var klass = htmlElemClasses[i];
      if (klass === 'lt-ie9'){
        return true;
      }
    }
    return false;
}());

N.B. IE conditional comments are only supported up to IE9 inclusive. From IE10 onwards, Microsoft encourages using feature detection rather than browser detection.


Whichever method you choose, you'd then test with

if ( myChecks.ltIE9 || Modernizr.csstransforms3d ){
    // iframe or flash fallback
} 

Don't take that || literally, of course.

Escaping special characters in Java Regular Expressions

The Pattern.quote(String s) sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E.

There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:

regex.replaceAll("[\\W]", "\\\\$0")

Why does this work? Well, the documentation for Pattern specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

For example, ; is not a special character in a regular expression. However, if you escape it, Pattern will still interpret \; as ;. Here are a few more examples:

  • > becomes \> which is equivalent to >
  • [ becomes \[ which is the escaped form of [
  • 8 is still 8.
  • \) becomes \\\) which is the escaped forms of \ and ( concatenated.

Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9].

POST Multipart Form Data using Retrofit 2.0 including image

Uploading Files using Retrofit is Quite Simple You need to build your api interface as

public interface Api {

    String BASE_URL = "http://192.168.43.124/ImageUploadApi/";


    @Multipart
    @POST("yourapipath")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);

}

in the above code image is the key name so if you are using php you will write $_FILES['image']['tmp_name'] to get this. And filename="myfile.jpg" is the name of your file that is being sent with the request.

Now to upload the file you need a method that will give you the absolute path from the Uri.

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

Now you can use the below code to upload your file.

 private void uploadFile(Uri fileUri, String desc) {

        //creating a file
        File file = new File(getRealPathFromURI(fileUri));

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);

        //The gson builder
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();


        //creating retrofit object
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        //creating our api 
        Api api = retrofit.create(Api.class);

        //creating a call and calling the upload image method 
        Call<MyResponse> call = api.uploadImage(requestFile, descBody);

        //finally performing the call 
        call.enqueue(new Callback<MyResponse>() {
            @Override
            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                if (!response.body().error) {
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MyResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

For more detailed explanation you can visit this Retrofit Upload File Tutorial.

How do change the color of the text of an <option> within a <select>?

You just need to add disabled as option attribute

<option disabled>select one option</option>

Access Https Rest Service using Spring RestTemplate

You need to configure a raw HttpClient with SSL support, something like this:

@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() 
throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient
      = HttpClients.custom()
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory 
      = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    ResponseEntity<String> response 
      = new RestTemplate(requestFactory).exchange(
      urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

font: Baeldung

Using strtok with a std::string

I suppose the language is C, or C++...

strtok, IIRC, replace separators with \0. That's what it cannot use a const string. To workaround that "quickly", if the string isn't huge, you can just strdup() it. Which is wise if you need to keep the string unaltered (what the const suggest...).

On the other hand, you might want to use another tokenizer, perhaps hand rolled, less violent on the given argument.

jQuery/Javascript function to clear all the fields of a form

the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.

$.fn.resetForm = function() {
    return this.each(function(){
        this.reset();
    });
}

Then just call it something like this

$('#divwithformin form').resetForm();

or

$('form').resetForm();

and of course you can still use it in the chain

$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')