Programs & Examples On #Sprite sheet

A spritesheet is a large image filled with smaller images. When you display each of the smaller images in the correct order, you get an animation. If you imagine an old celluloid movie reel, unrolled, chopped up, and laid out in a large square, you have the idea of a sprite sheet. An example of a sprite sheet can be seen here http://gamemedia.wcgame.ru/game-sprite-sheet.html

How to get the previous page URL using JavaScript?

You want in page A to know the URL of page B?

Or to know in page B the URL of page A?

In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?

In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains

MySQL Error 1093 - Can't specify target table for update in FROM clause

Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question

In MySQL, you can't modify the same table which you use in the SELECT part.
This behaviour is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html

Maybe you can just join the table to itself

If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead.

UPDATE tbl AS a
INNER JOIN tbl AS b ON ....
SET a.col = b.col

Alternatively, try nesting the subquery deeper into a from clause ...

If you absolutely need the subquery, there's a workaround, but it's ugly for several reasons, including performance:

UPDATE tbl SET col = (
  SELECT ... FROM (SELECT.... FROM) AS x);

The nested subquery in the FROM clause creates an implicit temporary table, so it doesn't count as the same table you're updating.

... but watch out for the query optimiser

However, beware that from MySQL 5.7.6 and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the optimizer_switch variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks.

SET optimizer_switch = 'derived_merge=off';

Thanks to Peter V. Mørch for this advice in the comments.

Example technique was from Baron Schwartz, originally published at Nabble, paraphrased and extended here.

How can I modify the size of column in a MySQL table?

ALTER TABLE <tablename> CHANGE COLUMN <colname> <colname> VARCHAR(65536);

You have to list the column name twice, even if you aren't changing its name.

Note that after you make this change, the data type of the column will be MEDIUMTEXT.


Miky D is correct, the MODIFY command can do this more concisely.


Re the MEDIUMTEXT thing: a MySQL row can be only 65535 bytes (not counting BLOB/TEXT columns). If you try to change a column to be too large, making the total size of the row 65536 or greater, you may get an error. If you try to declare a column of VARCHAR(65536) then it's too large even if it's the only column in that table, so MySQL automatically converts it to a MEDIUMTEXT data type.

mysql> create table foo (str varchar(300));
mysql> alter table foo modify str varchar(65536);
mysql> show create table foo;
CREATE TABLE `foo` (
  `str` mediumtext
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

I misread your original question, you want VARCHAR(65353), which MySQL can do, as long as that column size summed with the other columns in the table doesn't exceed 65535.

mysql> create table foo (str1 varchar(300), str2 varchar(300));
mysql> alter table foo modify str2 varchar(65353);
ERROR 1118 (42000): Row size too large. 
The maximum row size for the used table type, not counting BLOBs, is 65535. 
You have to change some columns to TEXT or BLOBs

Django DB Settings 'Improperly Configured' Error

In 2017 with django 1.11.5 and python 3.6 (from the comment this also works with Python 2.7):

import django
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()

The .py in which you put this code should be in mysite (the parent one)

Java: splitting a comma-separated string but ignoring commas in quotes

The simplest approach is not to match delimiters, i.e. commas, with a complex additional logic to match what is actually intended (the data which might be quoted strings), just to exclude false delimiters, but rather match the intended data in the first place.

The pattern consists of two alternatives, a quoted string ("[^"]*" or ".*?") or everything up to the next comma ([^,]+). To support empty cells, we have to allow the unquoted item to be empty and to consume the next comma, if any, and use the \\G anchor:

Pattern p = Pattern.compile("\\G\"(.*?)\",?|([^,]*),?");

The pattern also contains two capturing groups to get either, the quoted string’s content or the plain content.

Then, with Java 9, we can get an array as

String[] a = p.matcher(input).results()
    .map(m -> m.group(m.start(1)<0? 2: 1))
    .toArray(String[]::new);

whereas older Java versions need a loop like

for(Matcher m = p.matcher(input); m.find(); ) {
    String token = m.group(m.start(1)<0? 2: 1);
    System.out.println("found: "+token);
}

Adding the items to a List or an array is left as an excise to the reader.

For Java 8, you can use the results() implementation of this answer, to do it like the Java 9 solution.

For mixed content with embedded strings, like in the question, you can simply use

Pattern p = Pattern.compile("\\G((\"(.*?)\"|[^,])*),?");

But then, the strings are kept in their quoted form.

Convert objective-c typedef to its string equivalent

My solution:

edit: I've added even a better solution at the end, using Modern Obj-C

1.
Put names as keys in an array.
Make sure the indexes are the appropriate enums, and in the right order (otherwise exception).
note: names is a property synthesized as *_names*;

code was not checked for compilation, but I used the same technique in my app.

typedef enum {
  JSON,
  XML,
  Atom,
  RSS
} FormatType;

+ (NSArray *)names
{
    static NSMutableArray * _names = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _names = [NSMutableArray arrayWithCapacity:4];
        [_names insertObject:@"JSON" atIndex:JSON];
        [_names insertObject:@"XML" atIndex:XML];
        [_names insertObject:@"Atom" atIndex:Atom];
        [_names insertObject:@"RSS" atIndex:RSS];
    });

    return _names;
}

+ (NSString *)nameForType:(FormatType)type
{
    return [[self names] objectAtIndex:type];
}


//

2.
Using Modern Obj-C you we can use a dictionary to tie descriptions to keys in the enum.
Order DOES NOT matter.

typedef NS_ENUM(NSUInteger, UserType) {
    UserTypeParent = 0,
    UserTypeStudent = 1,
    UserTypeTutor = 2,
    UserTypeUnknown = NSUIntegerMax
};  

@property (nonatomic) UserType type;

+ (NSDictionary *)typeDisplayNames
{
    return @{@(UserTypeParent) : @"Parent",
             @(UserTypeStudent) : @"Student",
             @(UserTypeTutor) : @"Tutor",
             @(UserTypeUnknown) : @"Unknown"};
}

- (NSString *)typeDisplayName
{
    return [[self class] typeDisplayNames][@(self.type)];
}


Usage (in a class instance method):

NSLog(@"%@", [self typeDisplayName]);


Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

Select2 open dropdown on focus

Working Code for v4.0+ *(including 4.0.7)

The following code will open the menu on the initial focus, but won't get stuck in an infinite loop when the selection re-focuses after the menu closes.

// on first focus (bubbles up to document), open the menu
$(document).on('focus', '.select2-selection.select2-selection--single', function (e) {
  $(this).closest(".select2-container").siblings('select:enabled').select2('open');
});

// steal focus during close - only capture once and stop propogation
$('select.select2').on('select2:closing', function (e) {
  $(e.target).data("select2").$selection.one('focus focusin', function (e) {
    e.stopPropagation();
  });
});

Explanation

Prevent Infinite Focus Loop

Note: The focus event is fired twice

  1. Once when tabbing into the field
  2. Again when tabbing with an open dropdown to restore focus

focus menu states

We can prevent an infinite loop by looking for differences between the types of focus events. Since we only want to open the menu on the initial focus to the control, we have to somehow distinguish between the following raised events:

event timeline

Doing so it a cross browser friendly way is hard, because browsers send different information along with different events and also Select2 has had many minor changes to their internal firing of events, which interrupt previous flows.

One way that seems to work is to attach an event handler during the closing event for the menu and use it to capture the impending focus event and prevent it from bubbling up the DOM. Then, using a delegated listener, we'll call the actual focus -> open code only when the focus event bubbles all the way up to the document

Prevent Opening Disabled Selects

As noted in this github issue #4025 - Dropdown does not open on tab focus, we should check to make sure we only call 'open' on :enabled select elements like this:

$(this).siblings('select:enabled').select2('open');

Select2 DOM traversal

We have to traverse the DOM a little bit, so here's a map of the HTML structure generated by Select2

Select2 DOM

Source Code on GitHub

Here are some of the relevant code sections in play:

.on('mousedown' ... .trigger('toggle')
.on('toggle' ... .toggleDropdown()
.toggleDropdown ... .open()
.on('focus' ... .trigger('focus'
.on('close' ... $selection.focus()

It used to be the case that opening select2 fired twice, but it was fixed in Issue #3503 and that should prevent some jank

PR #5357 appears to be what broke the previous focus code that was working in 4.05

Working Demo in jsFiddle & Stack Snippets:

_x000D_
_x000D_
$('.select2').select2({});_x000D_
_x000D_
// on first focus (bubbles up to document), open the menu_x000D_
$(document).on('focus', '.select2-selection.select2-selection--single', function (e) {_x000D_
  $(this).closest(".select2-container").siblings('select:enabled').select2('open');_x000D_
});_x000D_
_x000D_
// steal focus during close - only capture once and stop propogation_x000D_
$('select.select2').on('select2:closing', function (e) {_x000D_
  $(e.target).data("select2").$selection.one('focus focusin', function (e) {_x000D_
    e.stopPropagation();_x000D_
  });_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.js"></script>_x000D_
_x000D_
<select class="select2" style="width:200px" >_x000D_
  <option value="1">Apple</option>_x000D_
  <option value="2">Banana</option>_x000D_
  <option value="3">Carrot</option>_x000D_
  <option value="4">Donut</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Tested on Chrome, FF, Edge, IE11

How to load up CSS files using Javascript?

var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("th:href", "@{/filepath}")
fileref.setAttribute("href", "/filepath")

I'm using thymeleaf and this is work fine. Thanks

Security of REST authentication schemes

Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?

How do I write a compareTo method which compares objects?

This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

This won't even compile:

if (this.getLastName() < s.getLastName())

Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
    d = getLastName().compareTo(s.getLastName());
return d;

Converting a datetime string to timestamp in Javascript

Date.parse() isn't a constructor, its a static method.

So, just use

var timeInMillis = Date.parse(s);

instead of

var timeInMillis = new Date.parse(s);

How can I perform a short delay in C# without using sleep?

You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.

git ignore exception

To exclude everything in a directory, but some sub-directories, do the following:

wp-content/*
!wp-content/plugins/
!wp-content/themes/

Source: https://gist.github.com/444295

How to show/hide an element on checkbox checked/unchecked states using jQuery?

    <label  onclick="chkBulk();">
    <div class="icheckbox_flat-green" style="position: relative;">
      <asp:CheckBox ID="chkBulkAssign" runat="server" class="flat" 
       Style="position: 
         absolute; opacity: 0;" />
      </div>
      Bulk Assign
     </label>



    function chkBulk() {
    if ($('[id$=chkBulkAssign]')[0].checked) {
    $('div .icheckbox_flat-green').addClass('checked');
    $("[id$=btneNoteBulkExcelUpload]").show();           
    }
   else {
   $('div .icheckbox_flat-green').removeClass('checked');
   $("[id$=btneNoteBulkExcelUpload]").hide();
   } 

Check if certain value is contained in a dataframe column in pandas

You can simply use this:

'07311954' in df.date.values which returns True or False


Here is the further explanation:

In pandas, using in check directly with DataFrame and Series (e.g. val in df or val in series ) will check whether the val is contained in the Index.

BUT you can still use in check for their values too (instead of Index)! Just using val in df.col_name.values or val in series.values. In this way, you are actually checking the val with a Numpy array.

And .isin(vals) is the other way around, it checks whether the DataFrame/Series values are in the vals. Here vals must be set or list-like. So this is not the natural way to go for the question.

Create a Maven project in Eclipse complains "Could not resolve archetype"

First things first, you have to install Maven on your workstation. You need also to install M2E, what you obviously did. Not all distributions of Juno have it pre-installed.

Then configure your Eclipse so it can find your Maven install. In the menu Window -> Preferences, then open the Maven section. In your right panel, you have a list of the Maven installations Eclipse knows. Add your installation and select it instead of the embedded Maven provided with M2E. Don't forget to set the "Global settings from installation directory" field with the path to the settings.xml of your Maven installation.

Which leads us to the settings.xml. If the above doesn't solve your problem, you will have to configure your Maven. More infos here.

What does 'foo' really mean?

Among my colleagues, the meaning (or perhaps more accurately - the use) of the term "foo" has been to serve as a placeholder to represent an example for a name. Examples include, but not limited to, yourVariableName, yourObjectName, or yourColumnName.

Today, I avoid using "foo" and prefer using this type of named substitution for a couple of reasons.

  • In my earlier days, I originally found the use of "foo" as a placement in any example to represent something as f'd-up to be confusing. I wanted a working example, not something that was foobar.
  • Your results may vary, but I always, 100%, everytime, never-failed, got more follow-up questions about the meaning of the actual variable where "foo" was used.

Add custom buttons on Slick Carousel

A variation on the answer by @tallgirltaadaa , draw your own button in the shape of a caret:

var a = $('.MyCarouselContainer').slick({
    prevArrow: '<canvas class="prevArrowCanvas a-left control-c prev slick-prev" width="15" height="50"></canvas>',
    nextArrow: '<canvas class="nextArrowCanvas a-right control-c next slick-next" width="15" height="50"></canvas>'
});

function drawNextPreviousArrows(strokeColor) {
    var c = $(".prevArrowCanvas")[0];
    var ctx = c.getContext("2d");
    ctx.clearRect(0, 0, c.width, c.height);
    ctx.moveTo(15, 0);
    ctx.lineTo(0, 25);
    ctx.lineTo(15, 50);
    ctx.lineWidth = 2;
    ctx.strokeStyle = strokeColor;
    ctx.stroke();
    var c = $(".nextArrowCanvas")[0];
    var ctx = c.getContext("2d");
    ctx.clearRect(0, 0, c.width, c.height);
    ctx.moveTo(0, 0);
    ctx.lineTo(15, 25);
    ctx.lineTo(0, 50);
    ctx.lineWidth = 2;
    ctx.strokeStyle = strokeColor;
    ctx.stroke();
}
drawNextPreviousArrows("#cccccc");

then add the css

.slick-prev, .slick-next 
    height: 50px;s
}

Create table in SQLite only if it doesn't exist already

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 

        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

How to connect to SQL Server database from JavaScript in the browser?

As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.

Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.

Animation fade in and out

FOR FADE add this first line with your animation's object.

.animate().alpha(1).setDuration(2000);

FOR EXAMPLEI USED LottieAnimation

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

How to properly use unit-testing's assertRaises() with NoneType objects?

The problem is the TypeError gets raised 'before' assertRaises gets called since the arguments to assertRaises need to be evaluated before the method can be called. You need to pass a lambda expression like:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

TypeScript enum to object array

function enumKeys(_enum) {
  const entries = Object.entries(_enum).filter(e => !isNaN(Number(e[0])));
  if (!entries.length) {
    // enum has string values so we can use Object.keys
    return Object.keys(_enum);
  }
  return entries.map(e => e[1]);
}

Div not expanding even with content inside

Floated elements don’t take up any vertical space in their containing element.

All of your elements inside #albumhold are floated, apart from #albumhead, which doesn’t look like it’d take up much space.

However, if you add overflow: hidden; to #albumhold (or some other CSS to clear floats inside it), it will expand its height to encompass its floated children.

Search a whole table in mySQL for a string

A PHP Based Solution for search entire table ! Search string is $string . This is generic and will work with all the tables with any number of fields

$sql="SELECT * from client_wireless";
$sql_query=mysql_query($sql);
$logicStr="WHERE ";
$count=mysql_num_fields($sql_query);
for($i=0 ; $i < mysql_num_fields($sql_query) ; $i++){
 if($i == ($count-1) )
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' ";
else
$logicStr=$logicStr."".mysql_field_name($sql_query,$i)." LIKE '%".$string."%' OR ";
}
// start the search in all the fields and when a match is found, go on printing it .
$sql="SELECT * from client_wireless ".$logicStr;
//echo $sql;
$query=mysql_query($sql);

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:

https://<region>.amazonaws.com/<bucket-name>/<key>

Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

Javascript Object push() function

I hope this one might help you.

_x000D_
_x000D_
let data = [];
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };

let tempData = [];

tempData= data.filter((item)=>item.Status!='Invalid')

console.log(tempData)
_x000D_
_x000D_
_x000D_

WPF chart controls

The WPF Toolkit is available. It is free from CodePlex.

It can be downloaded here. There is some commentary here.

Unfortunately Launcher3 has stopped working error in android studio?

May 2017; I had the same issue, could not even get to apps as it just cycled between starting and stopping. Went into avd settings, edited the multi core (unticked the box) and set graphics to software Gles. It appears to have fixed the issue

highlight the navigation menu for the current page

You can use Javascript to parse your DOM, and highlight the link with the same label than the first h1 tags. But I think it is overkill =)

It would be better to set a var wich contain the title of your page, and use it to add a class at the corresponding link.

Removing X-Powered-By

This solution worked for me :)

Please add below line in the script and check.

Ngnix / Apache etc level settings might not be required.

header("Server:");

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

How can I return the sum and average of an int array?

This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!

public int Sum(params int[] customerssalary)
{
   int result = 0;

   for(int i = 0; i < customerssalary.Length; i++)
   {
      result += customerssalary[i];
   }

   return result;
}

with this Sum function, you can use this to calculate the average too...

public decimal Average(params int[] customerssalary)
{
   int sum = Sum(customerssalary);
   decimal result = (decimal)sum / customerssalary.Length;
   return result;
}

the reason for using a decimal type in the second function is because the division can easily return a non-integer result


Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.

MySQL Error 1264: out of range value for column

The value 3172978990 is greater than 2147483647 – the maximum value for INT – hence the error. MySQL integer types and their ranges are listed here.

Also note that the (10) in INT(10) does not define the "size" of an integer. It specifies the display width of the column. This information is advisory only.

To fix the error, change your datatype to VARCHAR. Phone and Fax numbers should be stored as strings. See this discussion.

What are POD types in C++?

Why do we need to differentiate between POD's and non-POD's at all?

C++ started its life as an extension of C. While modern C++ is no longer a strict superset of C, people still expect a high level of compatibility between the two. The "C ABI" of a platform also frequently acts as a de-facto standard inter-language ABI for other languages on the platform.

Roughly speaking, a POD type is a type that is compatible with C and perhaps equally importantly is compatible with certain ABI optimisations.

To be compatible with C, we need to satisfy two constraints.

  1. The layout must be the same as the corresponding C type.
  2. The type must be passed to and returned from functions in the same way as the corresponding C type.

Certain C++ features are incompatible with this.

Virtual methods require the compiler to insert one or more pointers to virtual method tables, something that doesn't exist in C.

User-defined copy constructors, move constructors, copy assignments and destructors have implications for parameter passing and returning. Many C ABIs pass and return small parameters in registers, but the references passed to the user defined constructor/assigment/destructor can only work with memory locations.

So there is a need to define what types can be expected to be "C compatible" and what types cannot. C++03 was somewhat over-strict in this regard, any user-defined constructor would disable the built-in constructors and any attempt to add them back in would result in them being user-defined and hence the type being non-pod. C++11 opened things up quite a bit, by allowing the user to re-introduce the built-in constructors.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Try this:

ORDER BY 1, 2

OR

ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService

How to set Oracle's Java as the default Java in Ubuntu?

I put the line:

export JAVA_HOME=/usr/lib/jvm/java-7-oracle

in my ~/.bashrc file.

/usr/lib/jvm/java7-oracle should be a symbolic link pointing to /usr/lib/jvm/java-7-oracle-[version number here].

The reason it's a symbolic link is that in case there's a new version of the JVM, you don't need to update your .bashrc file, it should automatically point to the new version.

If you want to set JAVA_HOME environment variables globally and at system level means use should set in /etc/environment file.

How to change xampp localhost to another folder ( outside xampp folder)?

Please follow @Sourav's advice.

If after restarting the server you get errors, you may need to set your directory options as well. This is done in the <Directory> tag in httpd.conf. Make sure the final config looks like this:

DocumentRoot "C:\alan"
<Directory "C:\alan">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

css absolute position won't work with margin-left:auto margin-right: auto

I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).

Done! The margin-left and margin-right AUTO for your .divtagABS will now work.

Paste text on Android Emulator

Made this Windows application that allows users to copy paste to Android emulators or connected devices from a visual interface. https://github.com/Florin-Birgu/Android-Copy-Paste

enter image description here

AttributeError: Module Pip has no attribute 'main'

Not sure about Windows. But for mac users, use this:

pip install --upgrade pip==9.0.3

How to monitor Java memory usage?

If you want to really look at what is going on in the VM memory you should use a good tool like VisualVM. This is Free Software and it's a great way to see what is going on.

Nothing is really "wrong" with explicit gc() calls. However, remember that when you call gc() you are "suggesting" that the garbage collector run. There is no guarantee that it will run at the exact time you run that command.

How to show live preview in a small popup of linked page on mouse over on link?

Another way is to use a website thumbnail/link preview service LinkPeek (even happens to show a screenshot of StackOverflow as a demo right now), URL2PNG, Browshot, Websnapr, or an alternative.

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Remove all values within one list from another list?

If you don't have repeated values, you could use set difference.

x = set(range(10))
y = x - set([2, 3, 7])
# y = set([0, 1, 4, 5, 6, 8, 9])

and then convert back to list, if needed.

CASCADE DELETE just once

I cannot comment Palehorse's answer so I added my own answer. Palehorse's logic is ok but efficiency can be bad with big data sets.

DELETE FROM some_child_table sct 
 WHERE exists (SELECT FROM some_Table st 
                WHERE sct.some_fk_fiel=st.some_id);

DELETE FROM some_table;

It is faster if you have indexes on columns and data set is bigger than few records.

How to get file's last modified date on Windows command line?

If you're able to bring in an EXE, I recommend gdate.exe from GNU CoreUtils for Windows). It can give the current date or the date of a file, in many different formats, and customizable. I use it to get me the last modified date-time of files that I can compare without any parsing (ie. local-independent), using the %s (seconds since the epoch), optionally with %N to get nano-second precision.

Some examples:

C:\>dir MyFile.txt
02/10/2021  10:54 PM                 4 MyFile.txt

C:\>gdate -r MyFile.txt +%Y-%m-%d
2021-02-10

C:\>gdate -r MyFile.txt "+%Y-%m-%d %H:%M:%S"
2021-02-10 22:54:50

C:\>gdate -r MyFile.txt +%s
1613015690

C:\>gdate -r MyFile.txt +%s.%N
1613015690.093962600

How to send emails from my Android application?

I used this code to send mail by launching default mail app compose section directly.

    Intent i = new Intent(Intent.ACTION_SENDTO);
    i.setType("message/rfc822"); 
    i.setData(Uri.parse("mailto:"));
    i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
    i.putExtra(Intent.EXTRA_SUBJECT, "Subject");
    i.putExtra(Intent.EXTRA_TEXT   , "body of email");
    try {
        startActivity(Intent.createChooser(i, "Send mail..."));
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
    }

How to vertically center content with variable height within a div?

You can use margin auto. With flex, the div seems to be centered vertically too.

body,
html {
  height: 100%;
  margin: 0;
}
.site {
  height: 100%;
  display: flex;
}
.site .box {
  background: #0ff;
  max-width: 20vw;
  margin: auto;
}
<div class="site">
  <div class="box">
    <h1>blabla</h1>
    <p>blabla</p>
    <p>blablabla</p>
    <p>lbibdfvkdlvfdks</p>
  </div>
</div>

How to fill the whole canvas with specific color?

Yes, fill in a Rectangle with a solid color across the canvas, use the height and width of the canvas itself:

_x000D_
_x000D_
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
_x000D_
canvas{ border: 1px solid black; }
_x000D_
<canvas width=300 height=150 id="canvas">
_x000D_
_x000D_
_x000D_

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How to cancel/abort jQuery AJAX request?

The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
);

java: Class.isInstance vs Class.isAssignableFrom

Both answers are in the ballpark but neither is a complete answer.

MyClass.class.isInstance(obj) is for checking an instance. It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException. In other words, obj is an instance of MyClass or its subclasses.

MyClass.class.isAssignableFrom(Other.class) will return true if MyClass is the same as, or a superclass or superinterface of, Other. Other can be a class or an interface. It answers true if Other can be converted to a MyClass.

A little code to demonstrate:

public class NewMain
{
    public static void main(String[] args)
    {
        NewMain nm = new NewMain();
        nm.doit();
    }

    class A { }

    class B extends A { }

    public void doit()
    {
        A myA = new A();
        B myB = new B();
        A[] aArr = new A[0];
        B[] bArr = new B[0];

        System.out.println("b instanceof a: " + (myB instanceof A)); // true
        System.out.println("b isInstance a: " + A.class.isInstance(myB)); //true
        System.out.println("a isInstance b: " + B.class.isInstance(myA)); //false
        System.out.println("b isAssignableFrom a: " + A.class.isAssignableFrom(B.class)); //true
        System.out.println("a isAssignableFrom b: " + B.class.isAssignableFrom(A.class)); //false
        System.out.println("bArr isInstance A: " + A.class.isInstance(bArr)); //false
        System.out.println("bArr isInstance aArr: " + aArr.getClass().isInstance(bArr)); //true
        System.out.println("bArr isAssignableFrom aArr: " + aArr.getClass().isAssignableFrom(bArr.getClass())); //true
    }
}

How do you store Java objects in HttpSession?

Here you can do it by using HttpRequest or HttpSession. And think your problem is within the JSP.

If you are going to use the inside servlet do following,

Object obj = new Object();
session.setAttribute("object", obj);

or

HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);

and after setting your attribute by using request or session, use following to access it in the JSP,

<%= request.getAttribute("object")%>

or

<%= session.getAttribute("object")%>

So seems your problem is in the JSP.

If you want use scriptlets it should be as follows,

<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>

Or can use expressions as follows,

<%= session.getAttribute("object")%>

or can use EL as follows, ${object} or ${sessionScope.object}

Python - Check If Word Is In A String

You can split string to the words and check the result list.

if word in string.split():
    print 'success'

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

SQL Error: ORA-12899: value too large for column

In my case I'm using C# OracleCommand with OracleParameter, and I set all the the parameters Size property to max length of each column, then the error solved.

OracleParameter parm1 = new OracleParameter();
param1.OracleDbType = OracleDbType.Varchar2;
param1.Value = "test1";
param1.Size = 8;

OracleParameter parm2 = new OracleParameter();
param2.OracleDbType = OracleDbType.Varchar2;
param2.Value = "test1";
param2.Size = 12;

How to get the jQuery $.ajax error response text?

you can try it too:

$(document).ajaxError(
    function (event, jqXHR, ajaxSettings, thrownError) {
        alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
    });

Get first date of current month in java

Joda Time

If I am understanding the question correctly, it can be done very easily by using joda time

LocalDate fromDate = new LocalDate().withDayOfMonth(1);
LocalDate toDate = new LocalDate().minusDays(1);

How to return dictionary keys as a list in Python?

If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).

newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict

k
# [1, 2, 3]

            +---------------------------------------------------------+
            ¦ k = list(d)   ¦   9 characters (excluding whitespace)   ¦
            +---------------+-----------------------------------------¦
            ¦ k = [*d]      ¦   6 characters                          ¦
            +---------------+-----------------------------------------¦
            ¦ *k, = d       ¦   5 characters                          ¦
            +---------------------------------------------------------+

Why does overflow:hidden not work in a <td>?

Well here is a solution for you but I don't really understand why it works:

<html><body>
  <div style="width: 200px; border: 1px solid red;">Test</div>
  <div style="width: 200px; border: 1px solid blue; overflow: hidden; height: 1.5em;">My hovercraft is full of eels.  These pretzels are making me thirsty.</div>
  <div style="width: 200px; border: 1px solid yellow; overflow: hidden; height: 1.5em;">
  This_is_a_terrible_example_of_thinking_outside_the_box.
  </div>
  <table style="border: 2px solid black; border-collapse: collapse; width: 200px;"><tr>
   <td style="width:200px; border: 1px solid green; overflow: hidden; height: 1.5em;"><div style="width: 200px; border: 1px solid yellow; overflow: hidden;">
    This_is_a_terrible_example_of_thinking_outside_the_box.
   </div></td>
  </tr></table>
</body></html>

Namely, wrapping the cell contents in a div.

What's the difference between ISO 8601 and RFC 3339 Date Formats?

You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:

http://tools.ietf.org/html/rfc3339

Laravel: getting a a single value from a MySQL query

[EDIT] The expected output of the pluck function has changed from Laravel 5.1 to 5.2. Hence why it is marked as deprecated in 5.1

In Laravel 5.1, pluck gets a single column's value from the first result of a query.

In Laravel 5.2, pluck gets an array with the values of a given column. So it's no longer deprecated, but it no longer do what it used to.

So short answer is use the value function if you want one column from the first row and you are using Laravel 5.1 or above.

Thanks to Tomas Buteler for pointing this out in the comments.

[ORIGINAL] For anyone coming across this question who is using Laravel 5.1, pluck() has been deprecated and will be removed completely in Laravel 5.2.

Consider future proofing your code by using value() instead.

return DB::table('users')->where('username', $username)->value('groupName');

Keyboard shortcut to comment lines in Sublime Text 3

On my mac the shortcut is ?cmd + / which makes multi line comment but as single lines:

// if ($username && $password) {
//  echo "You are good to go";
// } else {
//  echo "Fields cannot be blank";
// }

OR

? alt + ?cmd + / and it's result is overall comment, from beggining of the selection to the end.

/*
if ($username && $password) {
    echo "You are good to go";
} else {
    echo "Fields cannot be blank";
}
*/

Difference between DataFrame, Dataset, and RDD in Spark

Simply RDD is core component, but DataFrame is an API introduced in spark 1.30.

RDD

Collection of data partitions called RDD. These RDD must follow few properties such is:

  • Immutable,
  • Fault Tolerant,
  • Distributed,
  • More.

Here RDD is either structured or unstructured.

DataFrame

DataFrame is an API available in Scala, Java, Python and R. It allows to process any type of Structured and semi structured data. To define DataFrame, a collection of distributed data organized into named columns called DataFrame. You can easily optimize the RDDs in the DataFrame. You can process JSON data, parquet data, HiveQL data at a time by using DataFrame.

val sampleRDD = sqlContext.jsonFile("hdfs://localhost:9000/jsondata.json")

val sample_DF = sampleRDD.toDF()

Here Sample_DF consider as DataFrame. sampleRDD is (raw data) called RDD.

Add a Progress Bar in WebView

The best approch which worked for me is

webView.setWebViewClient(new WebViewClient() {

    @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          mProgressBar.setVisibility(ProgressBar.VISIBLE);
          webView.setVisibility(View.INVISIBLE);
        }

    @Override public void onPageCommitVisible(WebView view, String url) {
      super.onPageCommitVisible(view, url);
      mProgressBar.setVisibility(ProgressBar.GONE);
      webView.setVisibility(View.VISIBLE);
      isWebViewLoadingFirstPage=false;
    }
}

Cannot resolve symbol 'AppCompatActivity'

For me, the issue resolved when I updated the Gradle build version. Don't know why?

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

<button class='btn btn-danger fa fa-trash' data-toggle='modal' data-target='#deleteModal' data-backdrop='static' data-keyboard='false'></button>

simply add data-backdrop and data-keyboard attribute to your button on which model is open.

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Android difference between Two Dates

Short & Sweet:

/**
 * Get a diff between two dates
 *
 * @param oldDate the old date
 * @param newDate the new date
 * @return the diff value, in the days
 */
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
    try {
        return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

Usage:

int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);

Output:

dateDifference: 2

Kotlin Version:

@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
    return try {
        DurationUnit.DAYS.convert(
            format.parse(newDate).time - format.parse(oldDate).time,
            DurationUnit.MILLISECONDS
        )
    } catch (e: Exception) {
        e.printStackTrace()
        0
    }
}

Toggle display:none style with JavaScript

Give your ul an id,

<ul id='yourUlId' class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">

then do

var yourUl = document.getElementById("yourUlId");
yourUl.style.display = yourUl.style.display === 'none' ? '' : 'none';

IF you're using jQuery, this becomes:

var $yourUl = $("#yourUlId"); 
$yourUl.css("display", $yourUl.css("display") === 'none' ? '' : 'none');

Finally, you specifically said that you wanted to manipulate this css property, and not simply show or hide the underlying element. Nonetheless I'll mention that with jQuery

$("#yourUlId").toggle();

will alternate between showing or hiding this element.

How to remove all files from directory without removing directory in Node.js

How about run a command line:

require('child_process').execSync('rm -rf /path/to/directory/*')

How to convert a String into an ArrayList?

Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:

List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));

Compile Views in ASP.NET MVC

From the readme word doc for RC1 (not indexed by google)

ASP.NET Compiler Post-Build Step

Currently, errors within a view file are not detected until run time. To let you detect these errors at compile time, ASP.NET MVC projects now include an MvcBuildViews property, which is disabled by default. To enable this property, open the project file and set the MvcBuildViews property to true, as shown in the following example:

<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MvcBuildViews>true</MvcBuildViews>
  </PropertyGroup>

Note Enabling this feature adds some overhead to the build time.

You can update projects that were created with previous releases of MVC to include build-time validation of views by performing the following steps:

  1. Open the project file in a text editor.
  2. Add the following element under the top-most <PropertyGroup> element: <MvcBuildViews>true</MvcBuildViews>
  3. At the end of the project file, uncomment the <Target Name="AfterBuild"> element and modify it to match the following:
<Target Name="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
    <AspNetCompiler VirtualPath="temp" PhysicalPath="$(ProjectDir)\..\$(ProjectName)" />
</Target>

Multiline TextView in Android?

Simply put '\n' inside your text... no extra attribute required :)

          <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Pigeon\nControl\nServices"
            android:id="@+id/textView5"
            android:layout_gravity="center"
            android:paddingLeft="12dp"/> 

How to parse a date?

We now have a more modern way to do this work.

java.time

The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome old classes, java.util.Date/.Calendar et al.

Note that the 3-4 letter codes like EDT are neither standardized nor unique. Avoid them whenever possible. Learn to use ISO 8601 standard formats instead. The java.time framework may take a stab at translating, but many of the commonly used codes have duplicate values.

By the way, note how java.time by default generates strings using the ISO 8601 formats but extended by appending the name of the time zone in brackets.

String input = "Thu Jun 18 20:56:02 EDT 2009";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "EEE MMM d HH:mm:ss zzz yyyy" , Locale.ENGLISH );
ZonedDateTime zdt = formatter.parse ( input , ZonedDateTime :: from );

Dump to console.

System.out.println ( "zdt : " + zdt );

When run.

zdt : 2009-06-18T20:56:02-04:00[America/New_York]

Adjust Time Zone

For fun let's adjust to the India time zone.

ZonedDateTime zdtKolkata = zdt.withZoneSameInstant ( ZoneId.of ( "Asia/Kolkata" ) );

zdtKolkata : 2009-06-19T06:26:02+05:30[Asia/Kolkata]

Convert to j.u.Date

If you really need a java.util.Date object for use with classes not yet updated to the java.time types, convert. Note that you are losing the assigned time zone, but have the same moment automatically adjusted to UTC.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

How does PHP 'foreach' actually work?

As per the documentation provided by PHP manual.

On each iteration, the value of the current element is assigned to $v and the internal
array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

So as per your first example:

$array = ['foo'=>1];
foreach($array as $k=>&$v)
{
   $array['bar']=2;
   echo($v);
}

$array have only single element, so as per the foreach execution, 1 assign to $v and it don't have any other element to move pointer

But in your second example:

$array = ['foo'=>1, 'bar'=>2];
foreach($array as $k=>&$v)
{
   $array['baz']=3;
   echo($v);
}

$array have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3; as pass by reference.

Execute combine multiple Linux commands in one line

If you want to execute each command only if the previous one succeeded, then combine them using the && operator:

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

If one of the commands fails, then all other commands following it won't be executed.

If you want to execute all commands regardless of whether the previous ones failed or not, separate them with semicolons:

cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install

In your case, I think you want the first case where execution of the next command depends on the success of the previous one.

You can also put all commands in a script and execute that instead:

#! /bin/sh
cd /my_folder \
&& rm *.jar \
&& svn co path to repo \
&& mvn compile package install

(The backslashes at the end of the line are there to prevent the shell from thinking that the next line is a new command; if you omit the backslashes, you would need to write the whole command in a single line.)

Save that to a file, for example myscript, and make it executable:

chmod +x myscript

You can now execute that script like other programs on the machine. But if you don't place it inside a directory listed in your PATH environment variable (for example /usr/local/bin, or on some Linux distributions ~/bin), then you will need to specify the path to that script. If it's in the current directory, you execute it with:

./myscript

The commands in the script work the same way as the commands in the first example; the next command only executes if the previous one succeeded. For unconditional execution of all commands, simply list each command on its own line:

#! /bin/sh
cd /my_folder
rm *.jar
svn co path to repo
mvn compile package install

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

Test string is const string. So you can solve like this:

char str[] = "Test string";

or:

const char* str = "Test string";
printf(str);

Timeout for python requests.get entire response

What about using eventlet? If you want to timeout the request after 10 seconds, even if data is being received, this snippet will work for you:

import requests
import eventlet
eventlet.monkey_patch()

with eventlet.Timeout(10):
    requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip", verify=False)

How to move columns in a MySQL table?

phpMyAdmin provides a GUI for this within the structure view of a table. Check to select the column you want to move and click the change action at the bottom of the column list. You can then change all of the column properties and you'll find the 'move column' function at the far right of the screen.

Of course this is all just building the queries in the perfectly good top answer but GUI fans might appreciate the alternative.

my phpMyAdmin version is 4.1.7

ENOENT, no such file or directory

Another possibility is that you are missing an .npmrc file if you are pulling any packages that are not publicly available.

You will need to add an .npmrc file at the root directory and add the private/internal registry inside of the .npmrc file like this:

registry=http://private.package.source/secret/npm-packages/

Running a shell script through Cygwin on Windows

The existing answers all seem to run this script in a DOS console window.

This may be acceptable, but for example means that colour codes (changing text colour) don't work but instead get printed out as they are:

there is no item "[032mGroovy[0m"

I found this solution some time ago, so I'm not sure whether mintty.exe is a standard Cygwin utility or whether you have to run the setup program to get it, but I run like this:

D:\apps\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico  bash.exe .\myShellScript.sh

... this causes the script to run in a Cygwin BASH console instead of a Windows DOS console.

$date + 1 year?

Try This

$nextyear  = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($startDate)),   date("d",strtotime($startDate)),   date("Y",strtotime($startDate))+1));

Convert Java Array to Iterable

You can use IterableOf from Cactoos:

Iterable<String> names = new IterableOf<>(
  "Scott Fitzgerald", "Fyodor Dostoyevsky"
);

Then, you can turn it into a list using ListOf:

List<String> names = new ListOf<>(
  new IterableOf<>(
    "Scott Fitzgerald", "Fyodor Dostoyevsky"
  )
);

Or simply this:

List<String> names = new ListOf<>(
  "Scott Fitzgerald", "Fyodor Dostoyevsky"
);

IsNothing versus Is Nothing

I find that Patrick Steele answered this question best on his blog: Avoiding IsNothing()

I did not copy any of his answer here, to ensure Patrick Steele get's credit for his post. But I do think if you're trying to decide whether to use Is Nothing or IsNothing you should read his post. I think you'll agree that Is Nothing is the best choice.

Edit - VoteCoffe's comment here

Partial article contents: After reviewing more code I found out another reason you should avoid this: It accepts value types! Obviously, since IsNothing() is a function that accepts an 'object', you can pass anything you want to it. If it's a value type, .NET will box it up into an object and pass it to IsNothing -- which will always return false on a boxed value! The VB.NET compiler will check the "Is Nothing" style syntax and won't compile if you attempt to do an "Is Nothing" on a value type. But the IsNothing() function compiles without complaints. -PSteele – VoteCoffee

time data does not match format

I had a case where solution was hard to figure out. This is not exactly relevant to particular question, but might help someone looking to solve a case with same error message when strptime is fed with timezone information. In my case, the reason for throwing

ValueError: time data '2016-02-28T08:27:16.000-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

was presence of last colon in the timezone part. While in some locales (Russian one, for example) code was able to execute well, in another (English one) it was failing. Removing the last colon helped remedy my situation.

How to update gradle in android studio?

after release of android studio v 3.0(stable), It will show popup, If gradle update is available

OR

Manually, just change version of gradle in top-level(project-level) build.gradle file to latest,

   buildscript {
      ...
      dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
      }
    }

check below chart

The Android Gradle Plugin and Gradle

 Android Gradle Plugin            Requires Gradle
 1.0.0 - 1.1.3                    2.2.1 - 2.3
 1.2.0 - 1.3.1                    2.2.1 - 2.9
 1.5.0   2.2.1+                   2.2.1 - 2.13
 2.0.0 - 2.1.2                    2.10  - 2.13
 2.1.3 - 2.2.3                    2.14.1+
 2.3.0+                           3.3+
 3.0.0+                           4.1+    
 3.1.0+                           4.4+    
 3.2.0 - 3.2.1                    4.6+    
 3.3.0 - 3.3.1                    4.10.1+ 
 3.4.0 - 3.4.1                    5.1.1+
 3.5.0                            5.4.1+

check gradle revisions

Fastest way to count number of occurrences in a Python list

Combination of lambda and map function can also do the job:

list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

Should have subtitle controller already set Mediaplayer error Android

A developer recently added subtitle support to VideoView.

When the MediaPlayer starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set. It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.

Short answer: Don't care about this "Exception".


Edit :

Still present in Lollipop,

If MediaPlayer is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController to the MediaPlayer.

It should not be used in production environment and may have some side effects.

static MediaPlayer getMediaPlayer(Context context){

    MediaPlayer mediaplayer = new MediaPlayer();

    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
        return mediaplayer;
    }

    try {
        Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
        Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
        Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
        Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );

        Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});

        Object subtitleInstance = constructor.newInstance(context, null, null);

        Field f = cSubtitleController.getDeclaredField("mHandler");

        f.setAccessible(true);
        try {
            f.set(subtitleInstance, new Handler());
        }
        catch (IllegalAccessException e) {return mediaplayer;}
        finally {
            f.setAccessible(false);
        }

        Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);

        setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
        //Log.e("", "subtitle is setted :p");
    } catch (Exception e) {}

    return mediaplayer;
}

This code is trying to do the following from the hidden API

SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)

convert from Color to brush

I had same issue before, here is my class which solved color conversions Use it and enjoy :

Here U go, Use my Class to Multi Color Conversion

using System;
using System.Windows.Media;
using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;
using SWMBrush = System.Windows.Media.Brush;

//Developed by ???? ????? ?????
namespace APREndUser.CodeAssist
{
    public static class ColorHelper
    {
        public static SWMColor ToSWMColor(SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SDColor ToSDColor(SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SWMBrush ToSWMBrush(SDColor color) => (SolidColorBrush)(new BrushConverter().ConvertFrom(ToHexColor(color)));
        public static string ToHexColor(SDColor c) => "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
        public static string ToRGBColor(SDColor c) => "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
        public static Tuple<SDColor, SDColor> GetColorFromRYGGradient(double percentage)
        {
            var red = (percentage > 50 ? 1 - 2 * (percentage - 50) / 100.0 : 1.0) * 255;
            var green = (percentage > 50 ? 1.0 : 2 * percentage / 100.0) * 255;
            var blue = 0.0;
            SDColor result1 = SDColor.FromArgb((int)red, (int)green, (int)blue);
            SDColor result2 = SDColor.FromArgb((int)green, (int)red, (int)blue);
            return new Tuple<SDColor, SDColor>(result1, result2);
        }
    }

}

How do I define a method which takes a lambda as a parameter in Java 8?

To me, the solution that makes the most sense is to define a Callback interface :

interface Callback {
    void call();
}

and then to use it as parameter in the function you want to call :

void somewhereInYourCode() {
    method(() -> {
        // You've passed a lambda!
        // method() is done, do whatever you want here.
    });
}

void method(Callback callback) {
    // Do what you have to do
    // ...

    // Don't forget to notify the caller once you're done
    callback.call();
}

Just a precision though

A lambda is not a special interface, class or anything else you could declare by yourself. Lambda is just the name given to the () -> {} special syntax, which allows better readability when passing single-method interfaces as parameter. It was designed to replace this :

method(new Callback() {
    @Override
    public void call() {
        // Classic interface implementation, lot of useless boilerplate code.
        // method() is done, do whatever you want here.
    }
});

So in the example above, Callback is not a lambda, it's just a regular interface ; lambda is the name of the shortcut syntax you can use to implement it.

Sorting HTML table with JavaScript

Sorting table rows by cell. 1. Little simpler and has some features. 2. Distinguish 'number' and 'string' on sorting 3. Add toggle to sort by ASC, DESC

var index;      // cell index
var toggleBool; // sorting asc, desc 
function sorting(tbody, index){
    this.index = index;
    if(toggleBool){
        toggleBool = false;
    }else{
        toggleBool = true;
    }

    var datas= new Array();
    var tbodyLength = tbody.rows.length;
    for(var i=0; i<tbodyLength; i++){
        datas[i] = tbody.rows[i];
    }

    // sort by cell[index] 
    datas.sort(compareCells);
    for(var i=0; i<tbody.rows.length; i++){
        // rearrange table rows by sorted rows
        tbody.appendChild(datas[i]);
    }   
}

function compareCells(a,b) {
    var aVal = a.cells[index].innerText;
    var bVal = b.cells[index].innerText;

    aVal = aVal.replace(/\,/g, '');
    bVal = bVal.replace(/\,/g, '');

    if(toggleBool){
        var temp = aVal;
        aVal = bVal;
        bVal = temp;
    } 

    if(aVal.match(/^[0-9]+$/) && bVal.match(/^[0-9]+$/)){
        return parseFloat(aVal) - parseFloat(bVal);
    }
    else{
          if (aVal < bVal){
              return -1; 
          }else if (aVal > bVal){
                return 1; 
          }else{
              return 0;       
          }         
    }
}

below is html sample

            <table summary="Pioneer">

                <thead>
                    <tr>
                        <th scope="col"  onclick="sorting(tbody01, 0)">No.</th>
                        <th scope="col"  onclick="sorting(tbody01, 1)">Name</th>
                        <th scope="col"  onclick="sorting(tbody01, 2)">Belong</th>
                        <th scope="col"  onclick="sorting(tbody01, 3)">Current Networth</th>
                        <th scope="col"  onclick="sorting(tbody01, 4)">BirthDay</th>
                        <th scope="col"  onclick="sorting(tbody01, 5)">Just Number</th>
                    </tr>
                </thead>

                <tbody id="tbody01">
                    <tr>
                        <td>1</td>
                        <td>Gwanshic Yi</td>
                        <td>Gwanshic Home</td>
                        <td>120000</td>
                        <td>1982-03-20</td>
                        <td>124,124,523</td>
                    </tr>
                    <tr>
                        <td>2</td>
                        <td>Steve Jobs</td>
                        <td>Apple</td>
                        <td>19000000000</td>
                        <td>1955-02-24</td>
                        <td>194,523</td>
                    </tr>
                    <tr>
                        <td>3</td>
                        <td>Bill Gates</td>
                        <td>MicroSoft</td>
                        <td>84300000000</td>
                        <td>1955-10-28</td>
                        <td>1,524,124,523</td>
                    </tr>
                    <tr>
                        <td>4</td>
                        <td>Larry Page</td>
                        <td>Google</td>
                        <td>39100000000</td>
                        <td>1973-03-26</td>
                        <td>11,124,523</td>
                    </tr>
                </tbody>
            </table>

MySQL Results as comma separated list

You can use GROUP_CONCAT to perform that, e.g. something like

SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;

Bootstrap 3 2-column form layout

As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.

The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
  </head>_x000D_
  <body>_x000D_
    <div class="row">_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label1</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label2</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
        <div class="col-xs-6">_x000D_
            <div class="row">_x000D_
                <label class="col-xs-12">Label3</label>_x000D_
            </div>_x000D_
            <div class="row">_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
                </div>_x000D_
                <div class="col-xs-12 col-sm-6">_x000D_
                    <input class="form-control" type="text"/>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-xs-6 form-group">_x000D_
            <label>Label4</label>_x000D_
            <input class="form-control" type="text"/>_x000D_
        </div>_x000D_
    </div>_x000D_
   _x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/m3u8bjv0/2/

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

Maven: repository element was not specified in the POM inside distributionManagement?

Review the pom.xml file inside of target/checkout/. Chances are, the pom.xml in your trunk or master branch does not have the distributionManagement tag.

This Activity already has an action bar supplied by the window decor

It could also be because you have a style without a parent specified:

<style name="DarkModeTheme" >
    <item name="searchBarBgColor">#D6D6D6</item>
</style>

Remove it, and it should fix the problem.

How can I schedule a job to run a SQL query daily?

Here's a sample code:

Exec sp_add_schedule
    @schedule_name = N'SchedulName' 
    @freq_type = 1
    @active_start_time = 08300

Getting Current date, time , day in laravel

You have a couple of helpers.

The helper now() https://laravel.com/docs/7.x/helpers#method-now

The helper now() has an optional argument, the timezone. So you can use now:

now();

or

now("Europe/Rome");

In the same way you could use the helper today() https://laravel.com/docs/7.x/helpers#method-today. This is the "same thing" of now() but with no hours, minutes, seconds.

At the end, under the hood they use Carbon as well.

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

Personally i prefer the format function, allows you to simply change the date part very easily.

     declare @format varchar(100) = 'yyyy/MM/dd'
     select 
        format(the_date,@format), 
        sum(myfield) 
     from mytable 
     group by format(the_date,@format) 
     order by format(the_date,@format) desc;

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

Avoid printStackTrace(); use a logger call instead

A production quality program should use one of the many logging alternatives (e.g. log4j, logback, java.util.logging) to report errors and other diagnostics. This has a number of advantages:

  • Log messages go to a configurable location.
  • The end user doesn't see the messages unless you configure the logging so that he/she does.
  • You can use different loggers and logging levels, etc to control how much little or much logging is recorded.
  • You can use different appender formats to control what the logging looks like.
  • You can easily plug the logging output into a larger monitoring / logging framework.
  • All of the above can be done without changing your code; i.e. by editing the deployed application's logging config file.

By contrast, if you just use printStackTrace, the deployer / end user has little if any control, and logging messages are liable to either be lost or shown to the end user in inappropriate circumstances. (And nothing terrifies a timid user more than a random stack trace.)

How to implement onBackPressed() in Fragments?

Inside the fragment's onCreate method add the following:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    OnBackPressedCallback callback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            //Handle the back pressed
        }
    };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}

Python: split a list based on a condition?

Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this:

def split_into_two_lists(lst, f):
    a = []
    b = []
    for elem in lst:
        if f(elem):
            a.append(elem)
        else:
            b.append(elem)
    return a, b

That way you are not processing anything twice and also are not repeating code.

how to run python files in windows command prompt?

First go to the directory where your python script is present by using-

cd path/to/directory

then simply do:

python file_name.py

How do I check if an HTML element is empty using jQuery?

Line breaks are considered as content to elements in FF.

<div>
</div>
<div></div>

Ex:

$("div:empty").text("Empty").css('background', '#ff0000');

In IE both divs are considered empty, in FF an Chrome only the last one is empty.

You can use the solution provided by @qwertymk

if(!/[\S]/.test($('#element').html())) { // for one element
    alert('empty');
}

or

$('.elements').each(function(){  // for many elements
    if(!/[\S]/.test($(this).html())) { 
        // is empty
    }
})

Ruby max integer

Ruby automatically converts integers to a large integer class when they overflow, so there's (practically) no limit to how big they can be.

If you are looking for the machine's size, i.e. 64- or 32-bit, I found this trick at ruby-forum.com:

machine_bytes = ['foo'].pack('p').size
machine_bits = machine_bytes * 8
machine_max_signed = 2**(machine_bits-1) - 1
machine_max_unsigned = 2**machine_bits - 1

If you are looking for the size of Fixnum objects (integers small enough to store in a single machine word), you can call 0.size to get the number of bytes. I would guess it should be 4 on 32-bit builds, but I can't test that right now. Also, the largest Fixnum is apparently 2**30 - 1 (or 2**62 - 1), because one bit is used to mark it as an integer instead of an object reference.

Handle spring security authentication exceptions with @ExceptionHandler

This is a very interesting problem that Spring Security and Spring Web framework is not quite consistent in the way they handle the response. I believe it has to natively support error message handling with MessageConverter in a handy way.

I tried to find an elegant way to inject MessageConverter into Spring Security so that they could catch the exception and return them in a right format according to content negotiation. Still, my solution below is not elegant but at least make use of Spring code.

I assume you know how to include Jackson and JAXB library, otherwise there is no point to proceed. There are 3 Steps in total.

Step 1 - Create a standalone class, storing MessageConverters

This class plays no magic. It simply stores the message converters and a processor RequestResponseBodyMethodProcessor. The magic is inside that processor which will do all the job including content negotiation and converting the response body accordingly.

public class MessageProcessor { // Any name you like
    // List of HttpMessageConverter
    private List<HttpMessageConverter<?>> messageConverters;
    // under org.springframework.web.servlet.mvc.method.annotation
    private RequestResponseBodyMethodProcessor processor;

    /**
     * Below class name are copied from the framework.
     * (And yes, they are hard-coded, too)
     */
    private static final boolean jaxb2Present =
        ClassUtils.isPresent("javax.xml.bind.Binder", MessageProcessor.class.getClassLoader());

    private static final boolean jackson2Present =
        ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", MessageProcessor.class.getClassLoader()) &&
        ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", MessageProcessor.class.getClassLoader());

    private static final boolean gsonPresent =
        ClassUtils.isPresent("com.google.gson.Gson", MessageProcessor.class.getClassLoader());

    public MessageProcessor() {
        this.messageConverters = new ArrayList<HttpMessageConverter<?>>();

        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(new StringHttpMessageConverter());
        this.messageConverters.add(new ResourceHttpMessageConverter());
        this.messageConverters.add(new SourceHttpMessageConverter<Source>());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

        if (jaxb2Present) {
            this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }
        if (jackson2Present) {
            this.messageConverters.add(new MappingJackson2HttpMessageConverter());
        }
        else if (gsonPresent) {
            this.messageConverters.add(new GsonHttpMessageConverter());
        }

        processor = new RequestResponseBodyMethodProcessor(this.messageConverters);
    }

    /**
     * This method will convert the response body to the desire format.
     */
    public void handle(Object returnValue, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        ServletWebRequest nativeRequest = new ServletWebRequest(request, response);
        processor.handleReturnValue(returnValue, null, new ModelAndViewContainer(), nativeRequest);
    }

    /**
     * @return list of message converters
     */
    public List<HttpMessageConverter<?>> getMessageConverters() {
        return messageConverters;
    }
}

Step 2 - Create AuthenticationEntryPoint

As in many tutorials, this class is essential to implement custom error handling.

public class CustomEntryPoint implements AuthenticationEntryPoint {
    // The class from Step 1
    private MessageProcessor processor;

    public CustomEntryPoint() {
        // It is up to you to decide when to instantiate
        processor = new MessageProcessor();
    }

    @Override
    public void commence(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

        // This object is just like the model class, 
        // the processor will convert it to appropriate format in response body
        CustomExceptionObject returnValue = new CustomExceptionObject();
        try {
            processor.handle(returnValue, request, response);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}

Step 3 - Register the entry point

As mentioned, I do it with Java Config. I just show the relevant configuration here, there should be other configuration such as session stateless, etc.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new CustomEntryPoint());
    }
}

Try with some authentication fail cases, remember the request header should include Accept : XXX and you should get the exception in JSON, XML or some other formats.

Throw keyword in function's signature

A no throw specification on an inlined function that only returns a member variable and could not possibly throw exceptions may be used by some compilers to do pessimizations (a made-up word for the opposite of optimizations) that can have a detrimental effect on performance. This is described in the Boost literature: Exception-specification

With some compilers a no-throw specification on non-inline functions may be beneficial if the correct optimizations are made and the use of that function impacts performance in a way that it justifies it.

To me it sounds like whether to use it or not is a call made by a very critical eye as part of a performance optimization effort, perhaps using profiling tools.

A quote from the above link for those in a hurry (contains an example of bad unintended effects of specifying throw on an inline function from a naive compiler):

Exception-specification rationale

Exception specifications [ISO 15.4] are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:

T& operator*() const throw() { return *ptr; }

This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.

For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.

Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.

A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.

For-loop vs while loop in R

Because 1 is numeric, but not integer (i.e. it's a floating point number), and 1:6000 is numeric and integer.

> print(class(1))
[1] "numeric"
> print(class(1:60000))
[1] "integer"

60000 squared is 3.6 billion, which is NOT representable in signed 32-bit integer, hence you get an overflow error:

> as.integer(60000)*as.integer(60000)
[1] NA
Warning message:
In as.integer(60000) * as.integer(60000) : NAs produced by integer overflow

3.6 billion is easily representable in floating point, however:

> as.single(60000)*as.single(60000)
[1] 3.6e+09

To fix your for code, convert to a floating point representation:

function (N)
{
    for(i in as.single(1:N)) {
        y <- i*i
    }
}

Redirect to specified URL on PHP script completion?

<?php

// do something here

header("Location: http://example.com/thankyou.php");
?>

Create Table from View

If you want to create a new A you can use INTO;

select * into A from dbo.myView

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

What is difference between sleep() method and yield() method of multi threading?

Sleep causes thread to suspend itself for x milliseconds while yield suspends the thread and immediately moves it to the ready queue (the queue which the CPU uses to run threads).

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

Visual Studio 2015, Windows 10, project source control was managed in TFS Online.

None of this worked form me, issue appeared after a reformat of Windows 10 and subsequent reinstall of VStudio 2015. I mapped projects to the same folder (residual folders and files were still there.)

Deleting the entire old project (specifically the .VS) and then remapping it fixed everything.

wp-admin shows blank page, how to fix it?

All your problem is solved right now just follow this instruction:

  1. go to your themes then de activate your current theme, just put "x" in the the first letter of your theme name.

for example this is your theme folder name: "mytheme" just put "x" in the first letter like this "xmytheme" tho di activate.

  1. Then after that go back to your wp-admin panel then BOOM! wp-admin accessable.

  2. When you access your wp-admin panel or you are on your dashboard, again activate your theme again, but before that. REMOVE THE "X" letter you putted in your theme name. example: "xmytheme" just remove "x", output like this: "mytheme"

  3. then activate it in your dashboard.

hope this help!.

Is it possible only to declare a variable without assigning any value in Python?

You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like

value = sequence.index(blarg)

Remove the last character from a string

First, I try without a space, rtrim($arraynama, ","); and get an error result.

Then I add a space and get a good result:

$newarraynama = rtrim($arraynama, ", ");

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

What is the correct wget command syntax for HTTPS with username and password?

By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.

wget --user=username --ask-password https://xyz.com/changelog-6.40.txt

Use of PUT vs PATCH methods in REST API real life scenarios

One additional information I just one to add is that a PATCH request use less bandwidth compared to a PUT request since just a part of the data is sent not the whole entity. So just use a PATCH request for updates of specific records like (1-3 records) while PUT request for updating a larger amount of data. That is it, don't think too much or worry about it too much.

Recursively look for files with a specific extension

To find all the pom.xml files in your current directory and print them, you can use:

find . -name 'pom.xml' -print

How to center text vertically with a large font-awesome icon?

After considering all suggested options, the cleanest solution seems to be setting line-height and vertical-align everything:

See Jsfiddle Demo

CSS:

div {
    border: 1px solid #ccc;
    display: inline-block;
    height: 50px;
    margin: 60px;
    padding: 10px;
}
#text, #ico {
    line-height: 50px;
}

#ico {
    vertical-align: middle;
}

How to send email using simple SMTP commands via Gmail?

As no one has mentioned - I would suggest to use great tool for such purpose - swaks

# yum info swaks
Installed Packages
Name        : swaks
Arch        : noarch
Version     : 20130209.0
Release     : 3.el6
Size        : 287 k
Repo        : installed
From repo   : epel
Summary     : Command-line SMTP transaction tester
URL         : http://www.jetmore.org/john/code/swaks
License     : GPLv2+
Description : Swiss Army Knife SMTP: A command line SMTP tester. Swaks can test
            : various aspects of your SMTP server, including TLS and AUTH.

It has a lot of options and can do almost everything you want.

GMAIL: STARTTLS, SSLv3 (and yes, in 2016 gmail still support sslv3)

$ echo "Hello world" | swaks -4 --server smtp.gmail.com:587 --from [email protected] --to [email protected] -tls --tls-protocol sslv3 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.gmail.com:587...
=== Connected to smtp.gmail.com.
<-  220 smtp.gmail.com ESMTP h8sm76342lbd.48 - gsmtp
 -> EHLO www.example.net
<-  250-smtp.gmail.com at your service, [193.243.156.26]
<-  250-SIZE 35882577
<-  250-8BITMIME
<-  250-STARTTLS
<-  250-ENHANCEDSTATUSCODES
<-  250-PIPELINING
<-  250-CHUNKING
<-  250 SMTPUTF8
 -> STARTTLS
<-  220 2.0.0 Ready to start TLS
=== TLS started with cipher SSLv3:RC4-SHA:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Mountain View/O=Google Inc/CN=smtp.gmail.com"
 ~> EHLO www.example.net
<~  250-smtp.gmail.com at your service, [193.243.156.26]
<~  250-SIZE 35882577
<~  250-8BITMIME
<~  250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
<~  250-ENHANCEDSTATUSCODES
<~  250-PIPELINING
<~  250-CHUNKING
<~  250 SMTPUTF8
 ~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~  235 2.7.0 Accepted
 ~> MAIL FROM:<[email protected]>
<~  250 2.1.0 OK h8sm76342lbd.48 - gsmtp
 ~> RCPT TO:<[email protected]>
<~  250 2.1.5 OK h8sm76342lbd.48 - gsmtp
 ~> DATA
<~  354  Go ahead h8sm76342lbd.48 - gsmtp
 ~> Date: Wed, 17 Feb 2016 09:49:03 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ~>
 ~> Hello world
 ~>
 ~>
 ~> .
<~  250 2.0.0 OK 1455702544 h8sm76342lbd.48 - gsmtp
 ~> QUIT
<~  221 2.0.0 closing connection h8sm76342lbd.48 - gsmtp
=== Connection closed with remote host.

YAHOO: TLS aka SMTPS, tlsv1.2

$ echo "Hello world" | swaks -4 --server smtp.mail.yahoo.com:465 --from [email protected] --to [email protected] --tlsc --tls-protocol tlsv1_2 --auth PLAIN --auth-user [email protected] --auth-password 7654321 --h-Subject "Test message" --body -
=== Trying smtp.mail.yahoo.com:465...
=== Connected to smtp.mail.yahoo.com.
=== TLS started with cipher TLSv1.2:ECDHE-RSA-AES128-GCM-SHA256:128
=== TLS no local certificate set
=== TLS peer DN="/C=US/ST=California/L=Sunnyvale/O=Yahoo Inc./OU=Information Technology/CN=smtp.mail.yahoo.com"
<~  220 smtp.mail.yahoo.com ESMTP ready
 ~> EHLO www.example.net
<~  250-smtp.mail.yahoo.com
<~  250-PIPELINING
<~  250-SIZE 41697280
<~  250-8 BITMIME
<~  250 AUTH PLAIN LOGIN XOAUTH2 XYMCOOKIE
 ~> AUTH PLAIN AGFhQxsZXguaGhMGdATGV4X2hoYtYWlsLmNvbQBS9TU1MjQ=
<~  235 2.0.0 OK
 ~> MAIL FROM:<[email protected]>
<~  250 OK , completed
 ~> RCPT TO:<[email protected]>
<~  250 OK , completed
 ~> DATA
<~  354 Start Mail. End with CRLF.CRLF
 ~> Date: Wed, 17 Feb 2016 10:08:28 +0000
 ~> To: [email protected]
 ~> From: [email protected]
 ~> Subject: Test message
 ~> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
 ~>
 ~> Hello world
 ~>
 ~>
 ~> .
<~  250 OK , completed
 ~> QUIT
<~  221 Service Closing transmission
=== Connection closed with remote host.

I have been using swaks to send email notifications from nagios via gmail for last 5 years without any problem.

How to insert data using wpdb

The recommended way (as noted in codex):

$wpdb->insert( $table_name, array('column_name_1'=>'hello', 'other'=> 123), array( '%s', '%d' ) );

So, you'd better to sanitize values - ALWAYS CONSIDER THE SECURITY.

How can I share Jupyter notebooks with non-programmers?

It depends on what you are intending to do with your Notebook: do you want that the user can recompute the results or just playing with them?

Static notebook

NBViewer is a great tool. You can directly use it inside Jupyter. Github has also a render, so you can directly link your file (such as https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb)

Alive notebook

If you want your user to be able to recompute some parts, you can also use MyBinder. It takes some time to start your notebook, but the result is worth it.

As said by @Mapl, Google can host your notebook with Colab. A nice feature is to compute your cells over a GPU.

Bootstrap Align Image with text

  <div class="container">
          <h1>About me</h1>
       <div class="row">
         <div class="pull-left ">
             <img src="http://lorempixel.com/200/200" class="col-lg-3" class="img-    responsive" alt="Responsive image">
                <p class="col-md-4">Lots of text here... </p> 
                </div>

          </div>
      </div>
   </div>

How to write multiple line string using Bash with variables?

I'm using Mac OS and to write multiple lines in a SH Script following code worked for me

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

Please don't forget to assign chmod as required to the script file. I have used

chmod u+x myScriptFile.sh

Calculate difference between 2 date / times in Oracle SQL

You could use to_timestamp function to convert the dates to timestamps and perform a substract operation.

Something like:

SELECT 
TO_TIMESTAMP ('13.10.1990 00:00:00','DD.MM.YYYY HH24:MI:SS')  - 
TO_TIMESTAMP ('01.01.1990:00:10:00','DD.MM.YYYY:HH24:MI:SS')
FROM DUAL

JTable won't show column headers

Put your JTable inside a JScrollPane. Try this:

add(new JScrollPane(scrTbl));

Importing CommonCrypto in a Swift framework

Good news! Swift 4.2 (Xcode 10) finally provides CommonCrypto!

Just add import CommonCrypto in your swift file.

"query function not defined for Select2 undefined error"

use :

try {
    $("#input-select2").select2();
}
catch(err) {

}

How to change button text or link text in JavaScript?

Remove Quote. and use innerText instead of text

function toggleText(button_id) 
{                      //-----\/ 'button_id' - > button_id
   if (document.getElementById(button_id).innerText == "Lock") 
   {
       document.getElementById(button_id).innerText = "Unlock";
   }
   else 
   {
     document.getElementById(button_id).innerText = "Lock";
   }
}

How do I get the serial key for Visual Studio Express?

The question is about VS 2008 Express.

Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.

Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:

HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration

To ensure that this is working beforehand, click Help -> register product within VS2008.

You should see text like

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."

Close the application, delete that key, reopen, click help->register product.

The text should now say

"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."

So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:

reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f

[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]

[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]

How to Update Date and Time of Raspberry Pi With out Internet

Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)

server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst

3. If you want to make sure that date and time update at startup run this python script in rpi,

import os

try:
    client = ntplib.NTPClient()
    response = client.request('xxx.xxx.xxx.xxx', version=4)
    print "===================================="
    print "Offset : "+str(response.offset)
    print "Version : "+str(response.version)
    print "Date Time : "+str(ctime(response.tx_time))
    print "Leap : "+str(ntplib.leap_to_text(response.leap))
    print "Root Delay : "+str(response.root_delay)
    print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
    os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
    print "===================================="
except:
    os.system("sudo date")
    print "NTP Server Down Date Time NOT Set At The Startup"
    pass

I found more info in raspberry pi forum.

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

Disabling the alert message is not a way to solve the problem. Despite the PHP core is continue to work it makes a dangerous assumptions and actions.

Never ignore the error where PHP should make an assumptions of something!!!!

If the class organized as a singleton you can always use function getInstance() and then use getData()

Likse:

$classObj = MyClass::getInstance();
$classObj->getData();

If the class is not a singleton, use

 $classObj = new MyClass();
 $classObj->getData();

Using number as "index" (JSON)

What about

Game.status[0][0] or Game.status[0]["0"] ?

Does one of these work?

PS: What you have in your question is a Javascript Object, not JSON. JSON is the 'string' version of a Javascript Object.

How to model type-safe enum types?

Dotty (Scala 3) will have native enums supported. Check here and here.

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

Solved this by adding following

RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
 RewriteCond %{REQUEST_FILENAME} -f [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^ - [L]

What is Android's file system?

Most answers here are pretty old.

In the past when un managed nand was the most popular storage technology, yaffs2 was the most common file system. This days there are few devices using un-managed nand, and those still in use are slowly migrating to ubifs.

Today most common storage is emmc (managed nand), for such devices ext4 is far more popular, but, this file system is slowly clears its way for f2fs (flash friendly fs).

Edit: f2fs will probably won't make it as the common fs for flash devices (including android)

Counting the occurrences / frequency of array elements

Given array x i.e x = ['boy','man','oldman','scout','pilot']; number of occurrences of an element 'man' is

x.length - x.toString().split(',man,').toString().split(',').length ;

How to allow only a number (digits and decimal point) to be typed in an input?

Expanding from gordy's answer:

Good job btw. But it also allowed + in the front. This will remove it.

    scope.$watch('inputValue', function (newValue, oldValue) {
        var arr = String(newValue).split("");
        if (arr.length === 0) return;
        if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return;
        if (arr.length === 2 && newValue === '-.') return;
        if (isNaN(newValue)) {
            scope.inputValue = oldValue;
        }
        if (arr.length > 0) {
            if (arr[0] === "+") {
                scope.inputValue = oldValue;
            }
        }
    });

Python argparse: default value or specified value

Actually, you only need to use the default argument to add_argument as in this test.py script:

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--example', default=1)
    args = parser.parse_args()
    print(args.example)

test.py --example
% 1
test.py --example 2
% 2

Details are here.

ArrayList filter

write your self a filter function

 public List<T> filter(Predicate<T> criteria, List<T> list) {
        return list.stream().filter(criteria).collect(Collectors.<T>toList());
 }

And then use

    list = new Test().filter(x -> x > 2, list);

This is the most neat version in Java, but needs JDK 1.8 to support lambda calculus

moment.js get current time in milliseconds?

To get the current time's milliseconds, use http://momentjs.com/docs/#/get-set/millisecond/

var timeInMilliseconds = moment().milliseconds();

Simple 'if' or logic statement in Python

If key isn't an int or float but a string, you need to convert it to an int first by doing

key = int(key)

or to a float by doing

key = float(key)

Otherwise, what you have in your question should work, but

if (key < 1) or (key > 34):

or

if not (1 <= key <= 34):

would be a bit clearer.

How to use JNDI DataSource provided by Tomcat in Spring?

Another feature: instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml (according to tomcat docs) like this:

<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
  username="dbUsername" password="dbPasswd"
  url="jdbc:postgresql://localhost/dbname"
  driverClassName="org.postgresql.Driver"
  initialSize="5" maxWait="5000"
  maxActive="120" maxIdle="5"
  validationQuery="select 1"
  poolPreparedStatements="true"/>
</Context>

Error in launching AVD with AMD processor

If you're running Mac, as @pedro mentions ensure you have the HAXM installer dowloaded via the Android SDK Manager.

Next install it! In finder navigate to /YOUR_SDK_PATH/extras/intel/Hardware_Accelerated_Execution_Manager/

Run and install the .mpgk in the following .dmg

  • Yosemite: IntelHAXM_1.1.0_for_10.10.dmg
  • Pre-yosemite: IntelHAXM_1.1.0_below_10.10.dmg
  • El Capitan: IntelHAXM_6.0.1.dmg - please install the IntelHAXM_6.0.1.mpgk file within - it will ask you if you want to reinstall it. Just say yes.

Example:

$cd /YOUR_SDK_PATH/extras/intel/Hardware_Accelerated_Execution_Manager/
$open IntelHAXM_1.1.0_below_10.10.dmg

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

Conditionally ignoring tests in JUnit 4

Additionally to the answer of @tkruse and @Yishai:
I do this way to conditionally skip test methods especially for Parameterized tests, if a test method should only run for some test data records.

public class MyTest {
    // get current test method
    @Rule public TestName testName = new TestName();
    
    @Before
    public void setUp() {
        org.junit.Assume.assumeTrue(new Function<String, Boolean>() {
          @Override
          public Boolean apply(String testMethod) {
            if (testMethod.startsWith("testMyMethod")) {
              return <some condition>;
            }
            return true;
          }
        }.apply(testName.getMethodName()));
        
        ... continue setup ...
    }
}

angular2: Error: TypeError: Cannot read property '...' of undefined

Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class

  myObj:any = {
    doSomething: function () { console.log('doing something'); return 'doing something'; },
  };
  myArray:any;
  constructor() { }

  ngOnInit() {
    this.myArray = [this.myObj];
  }

You can use it in template html file as following:

<div>test-1: {{  myObj?.doSomething()}}</div>
<div>test-2: {{  myArray[0].doSomething()}}</div>
<div>test-3: {{  myArray[2]?.doSomething()}}</div>

How to create friendly URL in php?

I try to explain this problem step by step in following example.

0) Question

I try to ask you like this :

i want to open page like facebook profile www.facebook.com/kaila.piyush

it get id from url and parse it to profile.php file and return featch data from database and show user to his profile

normally when we develope any website its link look like www.website.com/profile.php?id=username example.com/weblog/index.php?y=2000&m=11&d=23&id=5678

now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink

http://example.com/profile/userid (get a profile by the ID) 
http://example.com/profile/username (get a profile by the username) 
http://example.com/myprofile (get the profile of the currently logged-in user)

1) .htaccess

Create a .htaccess file in the root folder or update the existing one :

Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php

What does that do ?

If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.

2) index.php

Now, we want to know what action to trigger, so we need to read the URL :

In index.php :

// index.php    

// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);

for ($i= 0; $i < sizeof($scriptName); $i++)
{
    if ($requestURI[$i] == $scriptName[$i])
    {
        unset($requestURI[$i]);
    }
}

$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :

$command = array(
    [0] => 'profile',
    [1] => 19837,
    [2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :

// index.php

require_once("profile.php"); // We need this file
switch($command[0])
{
    case ‘profile’ :
        // We run the profile function from the profile.php file.
        profile($command([1]);
        break;
    case ‘myprofile’ :
        // We run the myProfile function from the profile.php file.
        myProfile();
        break;
    default:
        // Wrong page ! You could also redirect to your custom 404 page.
        echo "404 Error : wrong page.";
        break;
}

2) profile.php

Now in the profile.php file, we should have something like this :

// profile.php

function profile($chars)
{
    // We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)

    if (is_int($chars)) {
        $id = $chars;
        // Do the SQL to get the $user from his ID
        // ........
    } else {
        $username = mysqli_real_escape_string($char);
        // Do the SQL to get the $user from his username
        // ...........
    }

    // Render your view with the $user variable
    // .........
}

function myProfile()
{
    // Get the currently logged-in user ID from the session :
    $id = ....

    // Run the above function :
    profile($id);
}

How do I create a multiline Python string with inline variables?

A dictionary can be passed to format(), each key name will become a variable for each associated value.

dict = {'string1': 'go',
        'string2': 'now',
        'string3': 'great'}

multiline_string = '''I'm will {string1} there
I will go {string2}
{string3}'''.format(**dict)

print(multiline_string)


Also a list can be passed to format(), the index number of each value will be used as variables in this case.

list = ['go',
        'now',
        'great']

multiline_string = '''I'm will {0} there
I will go {1}
{2}'''.format(*list)

print(multiline_string)


Both solutions above will output the same:

I'm will go there
I will go now
great

How to insert data to MySQL having auto incremented primary key?

I see three possibilities here that will help you insert into your table without making a complete mess but "specifying" a value for the AUTO_INCREMENT column, since you are supplying all the values you can do either one of the following options.

First approach (Supplying NULL):

INSERT INTO test.authors VALUES (
 NULL,'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
 '2012-01-03 12:50:59','198963','21','',
 '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
 '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
 '','rta=2.860000m=0%;80;100;0'
);

Second approach (Supplying '' {Simple quotes / apostrophes} although it will give you a warning):

INSERT INTO test.authors VALUES (
 '','1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
 '2012-01-03 12:50:59','198963','21','',
 '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
 '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
 '','rta=2.860000m=0%;80;100;0'
);

Third approach (Supplying default):

INSERT INTO test.authors VALUES (
 default,'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
 '2012-01-03 12:50:59','198963','21','',
 '/usr/local/nagios/libexec/check_ping  5','30','0','4.04159',
 '0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
 '','rta=2.860000m=0%;80;100;0'
);

Either one of these examples should suffice when inserting into that table as long as you include all the values in the same order as you defined them when creating the table.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

SQL command to display history of queries

try

 cat ~/.mysql_history

this will show you all mysql commands ran on the system

Using Selenium Web Driver to retrieve value of a HTML input

As was mentioned before, you could do something like that

public String getVal(WebElement webElement) {
    JavascriptExecutor e = (JavascriptExecutor) driver;
    return (String) e.executeScript(String.format("return $('#%s').val();", webElement.getAttribute("id")));
}

But as you can see, your element must have an id attribute, and also, jquery on your page.

What's the difference between "&nbsp;" and " "?

In addition to the other answers here, non-breaking spaces will not be "collapsed" like regular spaces will. For example:

_x000D_
_x000D_
<!-- Both -->
<p>Word1          Word2</p>
<!-- and -->
<p>Word1 Word2</p>
<!-- will render the same on any browser -->
<!-- While the below one will keep the spaces when rendered. -->
<p>Word1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Word2</p>
_x000D_
_x000D_
_x000D_

Java: Detect duplicates in ArrayList?

Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.

List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);

if(set.size() < list.size()){
    /* There are duplicates */
}

Update: If I'm understanding your question correctly, you have a 2d array of Block, as in

Block table[][];

and you want to detect if any row of them has duplicates?

In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:

for (Block[] row : table) {
   Set set = new HashSet<Block>(); 
   for (Block cell : row) {
      set.add(cell);
   }
   if (set.size() < 6) { //has duplicate
   }
}

I'm not 100% sure of that for syntax, so it might be safer to write it as

for (int i = 0; i < 6; i++) {
   Set set = new HashSet<Block>(); 
   for (int j = 0; j < 6; j++)
    set.add(table[i][j]);
 ...

Set.add returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false if all you want to know is whether there are any duplicates.

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

how to break the _.each function in underscore.js

Update:

_.find would be better as it breaks out of the loop when the element is found:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** Old **

If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

System.Runtime.InteropServices.COMException (0x800A03EC)

Found Answer.......!!!!!!!

Officially Microsoft Office 2003 Interop is not supported on Windows server 2008 by Microsoft.

But after a lot of permutations & combinations with the code and search, we came across one solution which works for our scenario.

The solution is to plug the difference between the way Windows 2003 and 2008 maintains its folder structure, because Office Interop depends on the desktop folder for file open/save intermediately. The 2003 system houses the desktop folder under systemprofile which is absent in 2008.

So when we create this folder on 2008 under the respective hierarchy as indicated below; the office Interop is able to save the file as required. This Desktop folder is required to be created under

C:\Windows\System32\config\systemprofile

AND

C:\Windows\SysWOW64\config\systemprofile

This worked for me...

Also do check if .NET 1.1 is installed because its needed by Interop and ot preinstalled by Windows Server 2008

Or you can also Use SaveCopyas() method ist just take onargument as filename string)

Thanks Guys..!

How do I pretty-print existing JSON data with Java?

In one line:

String niceFormattedJson = JsonWriter.formatJson(jsonString)

or

System.out.println(JsonWriter.formatJson(jsonString.toString()));

The json-io libray (https://github.com/jdereg/json-io) is a small (75K) library with no other dependencies than the JDK.

In addition to pretty-printing JSON, you can serialize Java objects (entire Java object graphs with cycles) to JSON, as well as read them in.

Visual Studio Code: How to show line endings

If you want to set it to LF as default, you can go to File->Preferences->Settings and under user settings you can paste this line in below your other user settings.

"files.eol": "\n"

For example.

"git.confirmSync": false,
"window.zoomLevel": -1,
"workbench.activityBar.visible": true,
"editor.wordWrap": true,
"workbench.iconTheme": "vscode-icons",
"window.menuBarVisibility": "default",
"vsicons.projectDetection.autoReload": true,
"files.eol": "\n"

How to change a text with jQuery

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");

example: http://jsfiddle.net/niklasvh/xPRzr/

How to get data out of a Node.js http get request

Of course your logs return undefined : you log before the request is done. The problem isn't scope but asynchronicity.

http.request is asynchronous, that's why it takes a callback as parameter. Do what you have to do in the callback (the one you pass to response.end):

callback = function(response) {

  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(req.data);
    console.log(str);
    // your code here if you want to use the results !
  });
}

var req = http.request(options, callback).end();

Is there a way to do repetitive tasks at intervals?

A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.

This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.

So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.

This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.

Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.

What is the most efficient string concatenation method in python?

One Year later, let's test mkoistinen's answer with python 3.4.3:

  • plus 0.963564149000 (95.83% as fast)
  • join 0.923408469000 (100.00% as fast)
  • form 1.501130934000 (61.51% as fast)
  • intp 1.019677452000 (90.56% as fast)

Nothing changed. Join is still the fastest method. With intp being arguably the best choice in terms of readability you might want to use intp nevertheless.

Can there exist two main methods in a Java program?

There can be more than one main method in a single program. But JVM will always calls String[] argument main() method. Other method's will act as a Overloaded method. These overloaded method's we have to call explicitly.

Rotating a view in Android

One line in XML


<View
    android:rotation="45"
    ... />

What's the difference between Cache-Control: max-age=0 and no-cache?

I'm hardly a caching expert, but Mark Nottingham is. Here are his caching docs. He also has excellent links in the References section.

Based on my reading of those docs, it looks like max-age=0 could allow the cache to send a cached response to requests that came in at the "same time" where "same time" means close enough together they look simultaneous to the cache, but no-cache would not.

Get element type with jQuery

you can use .is():

  $( "ul" ).click(function( event ) {
      var target = $( event.target );
      if ( target.is( "li" ) ) {
         target.css( "background-color", "red" );
      }
  });

see source

Command prompt won't change directory to another drive

you should use a /d before path as below :

cd /d e:\

Select multiple columns in data.table by their numeric indices

If you want to use column names to select the columns, simply use .(), which is an alias for list():

library(data.table)
dt <- data.table(a = 1:2, b = 2:3, c = 3:4)
dt[ , .(b, c)] # select the columns b and c
# Result:
#    b c
# 1: 2 3
# 2: 3 4

How to simulate "Press any key to continue?"

This works on a Windows Platform: It Uses the Microprocessor registers directly and can be used to check key press or mousebutton

    #include<stdio.h>
    #include<conio.h>
    #include<dos.h>
    void main()
    {
     clrscr();
     union REGS in,out;
     in.h.ah=0x00;
     printf("Press any key : ");

     int86(0x16,&in,&out);
     printf("Ascii : %d\n",out.h.al);
     char ch = out.h.al;
     printf("Charcter Pressed : %c",&ch);
     printf("Scan code : %d",out.h.ah);
     getch();
    }

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

Just a small observation: you keep mentioning conn usr\pass, and this is a typo, right? Cos it should be conn usr/pass. Or is it different on a Unix based OS?

Furthermore, just to be sure: if you use tnsnames, your login string will look different from when you use the login method you started this topic out with.

tnsnames.ora should be in $ORACLE_HOME$\network\admin. That is the Oracle home on the machine from which you are trying to connect, so in your case your PC. If you have multiple oracle_homes and wish to use only one tnsnames.ora, you can set environment variable tns_admin (e.g. set TNS_ADMIN=c:\oracle\tns), and place tnsnames.ora in that directory.

Your original method of logging on (usr/[email protected]:port/servicename) should always work. So far I think you have all the info, except for the port number, which I am sure your DBA will be able to give you. If this method still doesn't work, either the server's IP address is not available from your client, or it is a firewall issue (blocking a certain port), or something else not (directly) related to Oracle or SQL*Plus.

hth! Regards, Remco

Creating a jQuery object from a big HTML-string

There is also a great library called cheerio designed specifically for this.

Fast, flexible, and lean implementation of core jQuery designed specifically for the server.

var cheerio = require('cheerio'),
    $ = cheerio.load('<h2 class="title">Hello world</h2>');

$('h2.title').text('Hello there!');
$('h2').addClass('welcome');

$.html();
//=> <h2 class="title welcome">Hello there!</h2>

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

You only have to add the millisecond field in your date format string:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

The API doc of SimpleDateFormat describes the format string in detail.

How can I convert an integer to a hexadecimal string in C?

Usually with printf (or one of its cousins) using the %x format specifier.

How to enter a series of numbers automatically in Excel

Simple Answer:

In A1

=if(b1="","",row()) 

In A2

=if(b2="","",row())  

copy this down the column. Each time an entry is entered in column B the next number in order will be entered in column A.

Suppose you want the answer of 2 in a4 cell because of your heading & other stuff, you can write as

=if(b4="","",row()-2)

CSS endless rotation animation

Works in all modern browsers

.rotate{
 animation: loading 3s linear infinite;
 @keyframes loading {
  0% { 
    transform: rotate(0); 
  }
  100% { 
    transform: rotate(360deg);
  }
 }
}

How to assign text size in sp value using java code

semeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
                       context.getResources().getDimension(R.dimen.text_size_in_dp))

Maven plugins can not be found in IntelliJ

I am using IntelliJ Ultimate 2018.2.6 and found out, that the feature Reimport All Maven Project does not use the JDK, which is set in the Settings: Build, Execution, Deployment | Build Tools | Maven | Runner. Instead it uses it's own JRE in IntelliJ_HOME/jre64/ by default. You can configure the JDK for the Importer in Build, Execution, Deployment | Build Tools | Maven | Importing.

In my specific problem, an SSL certificate was missing in the JREs keystore. Unfortunately IDEA only logs this issue in it's own logfile. A little red box to inform about the RuntimeException had been really nice...

How can I upgrade NumPy?

Update numpy

For python 2

pip install numpy --upgrade

You would also needed to upgrade your tables as well for updated version of numpy. so,

pip install tables --upgrade

For python 3

pip3 install numpy --upgrade

Similarly, the tables for python3 :-

pip3 install tables --upgrade

note:

You need to check which python version are you using. pip for python 2.7+ or pip3 for python 3+

What is the current directory in a batch file?

It is the directory from where you start the batch file. E.g. if your batch is in c:\dir1\dir2 and you do cd c:\dir3, then run the batch, the current directory will be c:\dir3.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

How to search a list of tuples in Python

tl;dr

A generator expression is probably the most performant and simple solution to your problem:

l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

result = next((i for i, v in enumerate(l) if v[0] == 53), None)
# 2

Explanation

There are several answers that provide a simple solution to this question with list comprehensions. While these answers are perfectly correct, they are not optimal. Depending on your use case, there may be significant benefits to making a few simple modifications.

The main problem I see with using a list comprehension for this use case is that the entire list will be processed, although you only want to find 1 element.

Python provides a simple construct which is ideal here. It is called the generator expression. Here is an example:

# Our input list, same as before
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

# Call next on our generator expression.
next((i for i, v in enumerate(l) if v[0] == 53), None)

We can expect this method to perform basically the same as list comprehensions in our trivial example, but what if we're working with a larger data set? That's where the advantage of using the generator method comes into play. Rather than constructing a new list, we'll use your existing list as our iterable, and use next() to get the first item from our generator.

Lets look at how these methods perform differently on some larger data sets. These are large lists, made of 10000000 + 1 elements, with our target at the beginning (best) or end (worst). We can verify that both of these lists will perform equally using the following list comprehension:

List comprehensions

"Worst case"

worst_case = ([(False, 'F')] * 10000000) + [(True, 'T')]
print [i for i, v in enumerate(worst_case) if v[0] is True]

# [10000000]
#          2 function calls in 3.885 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.885    3.885    3.885    3.885 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

"Best case"

best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print [i for i, v in enumerate(best_case) if v[0] is True]

# [0]
#          2 function calls in 3.864 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.864    3.864    3.864    3.864 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Generator expressions

Here's my hypothesis for generators: we'll see that generators will significantly perform better in the best case, but similarly in the worst case. This performance gain is mostly due to the fact that the generator is evaluated lazily, meaning it will only compute what is required to yield a value.

Worst case

# 10000000
#          5 function calls in 1.733 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         2    1.455    0.727    1.455    0.727 so_lc.py:10(<genexpr>)
#         1    0.278    0.278    1.733    1.733 so_lc.py:9(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    1.455    1.455 {next}

Best case

best_case  = [(True, 'T')] + ([(False, 'F')] * 10000000)
print next((i for i, v in enumerate(best_case) if v[0] == True), None)

# 0
#          5 function calls in 0.316 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    0.316    0.316    0.316    0.316 so_lc.py:6(<module>)
#         2    0.000    0.000    0.000    0.000 so_lc.py:7(<genexpr>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    0.000    0.000 {next}

WHAT?! The best case blows away the list comprehensions, but I wasn't expecting the our worst case to outperform the list comprehensions to such an extent. How is that? Frankly, I could only speculate without further research.

Take all of this with a grain of salt, I have not run any robust profiling here, just some very basic testing. This should be sufficient to appreciate that a generator expression is more performant for this type of list searching.

Note that this is all basic, built-in python. We don't need to import anything or use any libraries.

I first saw this technique for searching in the Udacity cs212 course with Peter Norvig.

Install php-mcrypt on CentOS 6

I was able to figure this out; it was a lot simpler then I thought. Under the WHM manager go to: Home >> Software >> EasyApache (Apache Update) >> There you have two options "Build Profile" or "Customize Based On Profile". I went Customize to keep my current config then followed the instructions on the page.

Eventually there was a place to add and remove php modules. There you will find ever module under the sun. Just select the one you want and rebuild the profile. It was really that simple.