Programs & Examples On #Xtragrid

Grid control for Windows Forms applications from DevExpress

How to get the selected row values of DevExpress XtraGrid?

You can do this in a number of ways. You can use databinding (typical initialized after InitializeComponent();)

textBox1.DataBindings.Add(new Binding("Text", yourBindingSource, 
                    "TableName.ColumnName", true, DataSourceUpdateMode.OnPropertyChanged));

or use a DataLayoutControl (if you are going to use textbox for editing, I really recommend spending some time to learn how to use this component.

or in FocusedRowChanged by assigning from one of these methods:

textBox1.Text = gridView1.GetDataRow(e.FocusedRowHandle)["Name"].ToString();
textBox1.Text = gridView1.GetFocusedDataRow()["Name"].ToString();
textBox1.Text = (gridView1.GetFocusedRow() as DataRowView).Row["Name"].ToString();
textBox1.Text = gridView1.GetFocusedRowCellValue("Name").ToString();

Java: how to add image to Jlabel?

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

Swift do-try-catch syntax

There are two important points to the Swift 2 error handling model: exhaustiveness and resiliency. Together, they boil down to your do/catch statement needing to catch every possible error, not just the ones you know you can throw.

Notice that you don't declare what types of errors a function can throw, only whether it throws at all. It's a zero-one-infinity sort of problem: as someone defining a function for others (including your future self) to use, you don't want to have to make every client of your function adapt to every change in the implementation of your function, including what errors it can throw. You want code that calls your function to be resilient to such change.

Because your function can't say what kind of errors it throws (or might throw in the future), the catch blocks that catch it errors don't know what types of errors it might throw. So, in addition to handling the error types you know about, you need to handle the ones you don't with a universal catch statement -- that way if your function changes the set of errors it throws in the future, callers will still catch its errors.

do {
    let sandwich = try makeMeSandwich(kitchen)
    print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
    print("Not me error")
} catch SandwichError.DoItYourself {
    print("do it error")
} catch let error {
    print(error.localizedDescription)
}

But let's not stop there. Think about this resilience idea some more. The way you've designed your sandwich, you have to describe errors in every place where you use them. That means that whenever you change the set of error cases, you have to change every place that uses them... not very fun.

The idea behind defining your own error types is to let you centralize things like that. You could define a description method for your errors:

extension SandwichError: CustomStringConvertible {
    var description: String {
        switch self {
            case NotMe: return "Not me error"
            case DoItYourself: return "Try sudo"
        }
    }
}

And then your error handling code can ask your error type to describe itself -- now every place where you handle errors can use the same code, and handle possible future error cases, too.

do {
    let sandwich = try makeMeSandwich(kitchen)
    print("i eat it \(sandwich)")
} catch let error as SandwichError {
    print(error.description)
} catch {
    print("i dunno")
}

This also paves the way for error types (or extensions on them) to support other ways of reporting errors -- for example, you could have an extension on your error type that knows how to present a UIAlertController for reporting the error to an iOS user.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

Twitter Bootstrap button click to toggle expand/collapse text section above button

Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.

You would replace his .btn with the following:

<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>

And add a small CSS for when the content is displayed:

.in.collapse+a.btn.showdetails:before { 
    content:'Hide details «';
}
.collapse+a.btn.showdetails:before { 
    content:'Show details »'; 
}

Here is his modified example

How to send data with angularjs $http.delete() request?

My suggestion:

$http({
    method: 'DELETE',
    url: '/roles/' + roleid,
    data: {
        user: userId
    },
    headers: {
        'Content-type': 'application/json;charset=utf-8'
    }
})
.then(function(response) {
    console.log(response.data);
}, function(rejection) {
    console.log(rejection.data);
});

How do I send a POST request with PHP?

You could use cURL:

<?php
//The url you wish to send the POST request to
$url = $file_name;

//The data you want to send via POST
$fields = [
    '__VIEWSTATE '      => $state,
    '__EVENTVALIDATION' => $valid,
    'btnSubmit'         => 'Submit'
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 

//execute post
$result = curl_exec($ch);
echo $result;
?>

Couldn't load memtrack module Logcat Error

I had the same error. Creating a new AVD with the appropriate API level solved my problem.

Convert Existing Eclipse Project to Maven Project

Right click on the Project name > Configure > Convert to Maven Project > click finish. Here you will add some dependencies to download and add your expected jar file.

This will create an auto-generated pom.xml file. Open that file in xml format in your eclipse editor. After build tag (</build>) add your dependencies which you can copy from maven website and add them there. Now you are good to go. These dependencies will automatically add your required jar files.

How do I view the SQLite database on an Android device?

If you are using a real device, and it is not rooted, then it is not possible to see your database in FileExplorer, because, due to some security reason, that folder is locked in the Android system. And if you are using it in an emulator you will find it in FileExplorer, /data/data/your package name/databases/yourdatabse.db.

What is reflection and why is it useful?

IMPORTANT

Starting from Java 9 you cannot longer use reflection unless the package-info.java opens the module to reflection access.

By default reflection access to all packages in the module is denied.

See Understanding Java 9 Modules

how to get the current working directory's absolute path from irb

Through this you can get absolute path of any file located in any directory.

File.join(Dir.pwd,'some-dir','some-file-name')

This will return

=> "/User/abc/xyz/some-dir/some-file-name"

nodejs get file name from absolute path?

For those interested in removing extension from filename, you can use https://nodejs.org/api/path.html#path_path_basename_path_ext

path.basename('/foo/bar/baz/asdf/quux.html', '.html');

Creating an array of objects in Java

Yes it is correct in Java there are several steps to make an array of objects:

  1. Declaring and then Instantiating (Create memory to store '4' objects):

    A[ ] arr = new A[4];
    
  2. Initializing the Objects (In this case you can Initialize 4 objects of class A)

    arr[0] = new A();
    arr[1] = new A();
    arr[2] = new A();
    arr[3] = new A();
    

    or

    for( int i=0; i<4; i++ )
      arr[i] = new A();
    

Now you can start calling existing methods from the objects you just made etc.

For example:

  int x = arr[1].getNumber();

or

  arr[1].setNumber(x);

Omitting one Setter/Getter in Lombok

with lombak 1.8.12, this worked for me

@Getter(value = lombok.AccessLevel.NONE)
@Setter(value = lombok.AccessLevel.NONE)

private int password;

How to get screen width without (minus) scrollbar?

None of these solutions worked for me, however I was able to fix it by taking the width and subtracting the width of the scroll bar. I'm not sure how cross-browser compatible this is.

Does HTML5 <video> playback support the .avi format?

The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.

That's what content negotiation is for.

  • The HTML specification doesn't specify any image formats for the <img> element.
  • The HTML specification doesn't specify any style sheet languages for the <style> element.
  • The HTML specification doesn't specify any scripting languages for the <script> element.
  • The HTML specification doesn't specify any object formats for the <object> and embed elements.
  • The HTML specification doesn't specify any audio formats for the <audio> element.

Why should it specify one for the <video> element?

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

how to create inline style with :before and :after

If you really need it inline, for example because you are loading some user-defined colors dynamically, you can always add a <style> element right before your content.

<style>#project-slide-1:before { color: #ff0000; }</style>
<div id="project-slide-1" class="project-slide"> ... </div>

Example use case with PHP and some (wordpress inspired) dummy functions:

<style>#project-slide-<?php the_ID() ?>:before { color: <?php the_field('color') ?>; }</style>
<div id="project-slide-<?php the_ID() ?>" class="project-slide"> ... </div>

Since HTML 5.2 it is valid to place style elements inside the body, although it is still recommend to place style elements in the head.

Reference: https://www.w3.org/TR/html52/document-metadata.html#the-style-element

List attributes of an object

Please see the python shell script which has been executed in sequence, here you will get the attributes of a class in string format separated by comma.

>>> class new_class():
...     def __init__(self, number):
...         self.multi = int(number)*2
...         self.str = str(number)
... 
>>> a = new_class(4)
>>> ",".join(a.__dict__.keys())
'str,multi'<br/>

I am using python 3.4

Correct way to write loops for promise.

Here's how I do it with the standard Promise object.

// Given async function sayHi
function sayHi() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Hi');
      resolve();
    }, 3000);
  });
}

// And an array of async functions to loop through
const asyncArray = [sayHi, sayHi, sayHi];

// We create the start of a promise chain
let chain = Promise.resolve();

// And append each function in the array to the promise chain
for (const func of asyncArray) {
  chain = chain.then(func);
}

// Output:
// Hi
// Hi (After 3 seconds)
// Hi (After 3 more seconds)

How can I convert a .py to .exe for Python?

I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

Here's the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?

Implement an input with a mask

You can achieve this also by using JavaScripts's native method. Its pretty simple and doesn't require any extra library to import.

<input type="text" name="date" placeholder="yyyy-mm-dd" onkeyup="
  var date = this.value;
  if (date.match(/^\d{4}$/) !== null) {
     this.value = date + '-';
  } else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
     this.value = date + '-';
  }" maxlength="10">

How do I compute the intersection point of two lines?

Can't stand aside,

So we have linear system:

A1 * x + B1 * y = C1
A2 * x + B2 * y = C2

let's do it with Cramer's rule, so solution can be found in determinants:

x = Dx/D
y = Dy/D

where D is main determinant of the system:

A1 B1
A2 B2

and Dx and Dy can be found from matricies:

C1 B1
C2 B2

and

A1 C1
A2 C2

(notice, as C column consequently substitues the coef. columns of x and y)

So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L for storing our coefs A, B, C of the line equations and intestead of pretty x, y we'll have [0], [1], but anyway. Thus, what I wrote above will have the following form further in the code:

for D

L1[0] L1[1]
L2[0] L2[1]

for Dx

L1[2] L1[1]
L2[2] L2[1]

for Dy

L1[0] L1[2]
L2[0] L2[2]

Now go for coding:

line - produces coefs A, B, C of line equation by two points provided,
intersection - finds intersection point (if any) of two lines provided by coefs.

from __future__ import division 

def line(p1, p2):
    A = (p1[1] - p2[1])
    B = (p2[0] - p1[0])
    C = (p1[0]*p2[1] - p2[0]*p1[1])
    return A, B, -C

def intersection(L1, L2):
    D  = L1[0] * L2[1] - L1[1] * L2[0]
    Dx = L1[2] * L2[1] - L1[1] * L2[2]
    Dy = L1[0] * L2[2] - L1[2] * L2[0]
    if D != 0:
        x = Dx / D
        y = Dy / D
        return x,y
    else:
        return False

Usage example:

L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])

R = intersection(L1, L2)
if R:
    print "Intersection detected:", R
else:
    print "No single intersection point detected"

How to get the type of T from a member of a generic class or method?

(note: I'm assuming that all you know is object or IList or similar, and that the list could be any type at runtime)

If you know it is a List<T>, then:

Type type = abc.GetType().GetGenericArguments()[0];

Another option is to look at the indexer:

Type type = abc.GetType().GetProperty("Item").PropertyType;

Using new TypeInfo:

using System.Reflection;
// ...
var type = abc.GetType().GetTypeInfo().GenericTypeArguments[0];

Spring Boot @autowired does not work, classes in different package

package com.test.springboot;
        @SpringBootApplication
    @ComponentScan(basePackages = "com.test.springboot")
    public class SpringBoot1Application {

        public static void main(String[] args) {
            ApplicationContext context=  SpringApplication.run(SpringBoot1Application.class, args);

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

package com.test.springboot;
    @Controller
    public class StudentController {
        @Autowired
        private StudentDao studentDao;

        @RequestMapping("/")
        public String homePage() {
            return "home";
        }

JavaScript array to CSV

The cited answer was wrong. You had to change

csvContent += index < infoArray.length ? dataString+ "\n" : dataString;

to

csvContent += dataString + "\n";

As to why the cited answer was wrong (funny it has been accepted!): index, the second parameter of the forEach callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray, which is an item of said array (which happens to be an array too).

EDIT

Six years have passed now since I wrote this answer. Many things have changed, including browsers. The following was part of the answer:

START of aged part

BTW, the cited code is suboptimal. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:

var lineArray = [];
data.forEach(function (infoArray, index) {
    var line = infoArray.join(",");
    lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");

END of aged part

(Keep in mind that the CSV case is a bit different from generic string concatenation, since for every string you also have to add the separator.)

Anyway, the above seems not to be true anymore, at least not for Chrome and Firefox (it seems to still be true for Safari, though).

To put an end to uncertainty, I wrote a jsPerf test that tests whether, in order to concatenate strings in a comma-separated way, it's faster to push them onto an array and join the array, or to concatenate them first with the comma, and then directly with the result string using the += operator.

Please follow the link and run the test, so that we have enough data to be able to talk about facts instead of opinions.

Presenting a UIAlertController properly on an iPad using iOS 8

Here's a quick solution:

NSString *text = self.contentTextView.text;
NSArray *items = @[text];

UIActivityViewController *activity = [[UIActivityViewController alloc]
                                      initWithActivityItems:items
                                      applicationActivities:nil];

activity.excludedActivityTypes = @[UIActivityTypePostToWeibo];

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
    //activity.popoverPresentationController.sourceView = shareButtonBarItem;

    activity.popoverPresentationController.barButtonItem = shareButtonBarItem;

    [self presentViewController:activity animated:YES completion:nil];

}
[self presentViewController:activity animated:YES completion:nil];

Bootstrap 3 Collapse show state with Chevron icon

If you are trying to use this with panels only (not accordeon), try this code:

<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a class="collapse-toggle" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">Panel heading with title</a>
        </h4>
    </div>
    <div id="collapseExample" class="panel-collapse collapse in">
        <div class="panel-body">
            Panel content
        </div>
    </div>
</div>

Make an Installation program for C# applications and include .NET Framework installer into the setup

Include an Setup Project (New Project > Other Project Types > Setup and Deployment > Visual Studio Installer) in your solution. It has options to include the framework installer. Check out this Deployment Guide MSDN post.

Graphical DIFF programs for linux

I use Guiffy and it works well.
alt text
(source: guiffy.org)

Calculate rolling / moving average in C++

You can approximate a rolling average by applying a weighted average on your input stream.

template <unsigned N>
double approxRollingAverage (double avg, double input) {
    avg -= avg/N;
    avg += input/N;
    return avg;
}

This way, you don't need to maintain 1000 buckets. However, it is an approximation, so it's value will not match exactly with a true rolling average.

Edit: Just noticed @steveha's post. This is equivalent to the exponential moving average, with the alpha being 1/N (I was taking N to be 1000 in this case to simulate 1000 buckets).

What's the best way to detect a 'touch screen' device using JavaScript?

Extent jQuery support object:

jQuery.support.touch = 'ontouchend' in document;

And now you can check it anywhere, like this:

if( jQuery.support.touch )
   // do touch stuff

How to create an Array with AngularJS's ng-model

It works fine for me: http://jsfiddle.net/qwertynl/htb9h/

My javascript:

var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
    $scope.telephone = []; // << remember to set this
}]);

Check OS version in Swift?

Based on Matt Thompson's answer, here is a method with respective unit tests that works with Swift and Objective-c on iOS 7 and above (including iOS 9 which no longer let's you check the NSFoundationNumber):

+ (BOOL) isAtLeastOSVersion:(NSString *)osVersion
{
    switch ([[UIDevice currentDevice].systemVersion compare:osVersion options:NSNumericSearch]) {
        case NSOrderedSame:
        case NSOrderedDescending:
            return YES;
        default:
            return NO;
    }
}  

.

@interface ANFakeCurrDevice : NSObject
@property (nonatomic, strong) NSString *systemVersion;
@end
@implementation ANFakeCurrDevice
@end


@implementation MyHelperClassUnitTests

- (void)setUp {
    [super setUp];
}

- (void)tearDown {
    [super tearDown];
}

- (void)test_isAtLeastOSVersion
{
    id deviceMock = [OCMockObject niceMockForClass:[UIDevice class]];
    ANFakeCurrDevice *fakeCurrDevice = [ANFakeCurrDevice new];
    fakeCurrDevice.systemVersion = @"99.9.9";
    [[[deviceMock stub] andReturn:fakeCurrDevice] currentDevice];
    XCTAssertTrue([[UIDevice currentDevice].systemVersion isEqualToString:@"99.9.9"]);

    fakeCurrDevice.systemVersion = @"1.0.1";
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"1"]);
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"1.0"]);
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"1.0.1"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"1.0.2"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"1.1.0"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.0"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.0.0"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.0.1"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"2.1.0"]);


    fakeCurrDevice.systemVersion = @"8.4.0";
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"7.0.1"]);
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8"]);
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8.4"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"8.4.1"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"8.4.2"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"9.0"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"9.0.1"]);
    XCTAssertFalse([ANConstants isAtLeastOSVersion:@"9.0.2"]);
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8.4"] && ![ANConstants isAtLeastOSVersion:@"9.0"]);

    fakeCurrDevice.systemVersion = @"8.4.1";
    XCTAssertTrue([ANConstants isAtLeastOSVersion:@"8.4"] && ![ANConstants isAtLeastOSVersion:@"9.0"]);
}


@end

How to set a default Value of a UIPickerView

Swift solution:

Define an Outlet:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

enter image description here

Assignment inside lambda expression in Python

TL;DR: When using functional idioms it's better to write functional code

As many people have pointed out, in Python lambdas assignment is not allowed. In general when using functional idioms your better off thinking in a functional manner which means wherever possible no side effects and no assignments.

Here is functional solution which uses a lambda. I've assigned the lambda to fn for clarity (and because it got a little long-ish).

from operator import add
from itertools import ifilter, ifilterfalse
fn = lambda l, pred: add(list(ifilter(pred, iter(l))), [ifilterfalse(pred, iter(l)).next()])
objs = [Object(name=""), Object(name="fake_name"), Object(name="")]
fn(objs, lambda o: o.name != '')

You can also make this deal with iterators rather than lists by changing things around a little. You also have some different imports.

from itertools import chain, islice, ifilter, ifilterfalse
fn = lambda l, pred: chain(ifilter(pred, iter(l)), islice(ifilterfalse(pred, iter(l)), 1))

You can always reoganize the code to reduce the length of the statements.

Creating a SearchView that looks like the material design guidelines

Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.

Sample: (It's shown in Portuguese, but it also works in english and italian).

Sample

Setup

Before you can use this lib, you have to implement a class named MsvAuthority inside the br.com.mauker package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.

Example:

MsvAuthority.java

package br.com.mauker;

public class MsvAuthority {
    public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>

    <application ... >
        <provider
        android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
        android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
        android:exported="false"
        android:protectionLevel="signature"
        android:syncable="true"/>
    </application>

</manifest>

Usage

To use it, add the dependency:

compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'

And then, on your Activity layout file, add the following:

<br.com.mauker.materialsearchview.MaterialSearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

After that, you'll just need to get the MaterialSearchView reference by using getViewById(), and open it up or close it using MaterialSearchView#openSearch() and MaterialSearchView#closeSearch().

P.S.: It's possible to open and close the view not only from the Toolbar. You can use the openSearch() method from basically any Button, such as a Floating Action Button.

// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);

bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchView.openSearch();
        }
    });

You can also close the view using the back button, doing the following:

@Override
public void onBackPressed() {
    if (searchView.isOpen()) {
        // Close the search on the back button press.
        searchView.closeSearch();
    } else {
        super.onBackPressed();
    }
}

For more information on how to use the lib, check the github page.

How can I autoplay a video using the new embed code style for Youtube?

YouTube Help says that &autoplay=1 has to be after the video ID - I assume, immediately after.

Submit form without page reloading

The page will get reloaded if you don't want to use javascript

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

Intercept page exit event

Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.

window.onbeforeunload = function (e) {
  var message = "Your confirmation message goes here.",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }

  // For Safari
  return message;
};

Using multiprocessing.Process with a maximum number of simultaneous processes

more generally, this could also look like this:

import multiprocessing
def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]

numberOfThreads = 4


if __name__ == '__main__':
    jobs = []
    for i, param in enumerate(params):
        p = multiprocessing.Process(target=f, args=(i,param))
        jobs.append(p)
    for i in chunks(jobs,numberOfThreads):
        for j in i:
            j.start()
        for j in i:
            j.join()

Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.

how does Array.prototype.slice.call() work?

Let's assume you have: function.apply(thisArg, argArray )

The apply method invokes a function, passing in the object that will be bound to this and an optional array of arguments.

The slice() method selects a part of an array, and returns the new array.

So when you call Array.prototype.slice.apply(arguments, [0]) the array slice method is invoked (bind) on arguments.

wampserver doesn't go green - stays orange

you can run appache:

E:\wamp\bin\apache\apache2.4.9\bin\httpd.exe -d E:/wamp/bin/apache/apache2.4.9

after that see the log of error and solve it.

How to print the value of a Tensor object in TensorFlow?

While other answers are correct that you cannot print the value until you evaluate the graph, they do not talk about one easy way of actually printing a value inside the graph, once you evaluate it.

The easiest way to see a value of a tensor whenever the graph is evaluated (using run or eval) is to use the Print operation as in this example:

# Initialize session
import tensorflow as tf
sess = tf.InteractiveSession()

# Some tensor we want to print the value of
a = tf.constant([1.0, 3.0])

# Add print operation
a = tf.Print(a, [a], message="This is a: ")

# Add more elements of the graph using a
b = tf.add(a, a)

Now, whenever we evaluate the whole graph, e.g. using b.eval(), we get:

I tensorflow/core/kernels/logging_ops.cc:79] This is a: [1 3]

Getting time span between two times in C#?

string startTime = "7:00 AM";
string endTime = "2:00 PM";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Will output: 07:00:00.

It also works if the user input military time:

string startTime = "7:00";
string endTime = "14:00";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Outputs: 07:00:00.

To change the format: duration.ToString(@"hh\:mm")

More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

Addendum:

Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

How to deserialize a list using GSON or another JSON library in Java?

With Gson, you'd just need to do something like:

List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());

You might also need to provide a no-arg constructor on the Video class you're deserializing to.

Is there Java HashMap equivalent in PHP?

You could create a custom HashMap class for that in php. example as shown below containing the basic HashMap attributes such as get and set.

class HashMap{

        public $arr;

        function init() {

            function populate() {
                return null;
            }
            
            // change to 999 for efficiency
            $this->arr = array_map('populate', range(0, 9));

            return $this->arr;

        }
        
        function get_hash($key) {
            $hash = 0;

            for ($i=0; $i < strlen($key) ; $i++) { 
                $hash += ord($key[$i]);
            }
            
            // arr index starts from 0
            $hash_idx = $hash % (count($this->arr) - 1); 
            return $hash_idx;
            
        }

        function add($key, $value) {
            $idx = $this->get_hash($key);
            
            if ($this->arr[$idx] == null) {
                $this->arr[$idx] = [$value];
            } else{

                $found = false;

                $content = $this->arr[$idx];
                
                $content_idx = 0;
                foreach ($content as $item) {

                    // checking if they have same number of streams
                    if ($item == $value) {

                        $content[$content_idx] = [$value];
                        $found = true;
                        break;

                    }
                    
                    $content_idx++;
                }

                if (!$found) {
                    // $value is already an array
                    array_push($content, $value);

                    // updating the array
                    $this->arr[$idx] = $content;
                }

            }

            return $this->arr;

        }

        function get($key) {

            $idx = $this->get_hash($key);
            $content = $this->arr[$idx];

            foreach ($content as $item) {
                if ($item[1] == $key) {
                    return $item;
                    break;
                }
            }
                
        }

    }

Hope this was useful

Serialize an object to XML

Based on above solutions, here comes a extension class which you can use to serialize and deserialize any object. Any other XML attributions are up to you.

Just use it like this:

        string s = new MyObject().Serialize(); // to serialize into a string
        MyObject b = s.Deserialize<MyObject>();// deserialize from a string



internal static class Extensions
{
    public static T Deserialize<T>(this string value)
    {
        var xmlSerializer = new XmlSerializer(typeof(T));

        return (T)xmlSerializer.Deserialize(new StringReader(value));
    }

    public static string Serialize<T>(this T value)
    {
        if (value == null)
            return string.Empty;

        var xmlSerializer = new XmlSerializer(typeof(T));

        using (var stringWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
            {
                xmlSerializer.Serialize(xmlWriter, value);
                return stringWriter.ToString();
            }
        }
    }
}

How to check for an empty object in an AngularJS view

I have met a similar problem when checking emptiness in a component. In this case, the controller must define a method that actually performs the test and the view uses it:

function FormNumericFieldController(/*$scope, $element, $attrs*/ ) {
    var ctrl = this;

    ctrl.isEmptyObject = function(object) {
        return angular.equals(object, {});
    }
}

<!-- any validation error will trigger an error highlight -->
<span ng-class="{'has-error': !$ctrl.isEmptyObject($ctrl.formFieldErrorRef) }">
    <!-- validated control here -->
</span>

jQuery if statement to check visibility

if visible.

$("#Element").is(':visible');

if it's hidden.

$("#Element").is(':hidden');

How to remove unique key from mysql table

To add a unique key use :

alter table your_table add UNIQUE(target_column_name);

To remove a unique key use:

alter table your_table drop INDEX target_column_name;

SQL statement to select all rows from previous day

Its a really old thread, but here is my take on it. Rather than 2 different clauses, one greater than and less than. I use this below syntax for selecting records from A date. If you want a date range then previous answers are the way to go.

SELECT * FROM TABLE_NAME WHERE 
DATEDIFF(DAY, DATEADD(DAY, X , CURRENT_TIMESTAMP), <column_name>) = 0

In the above case X will be -1 for yesterday's records

installing requests module in python 2.7 windows

There are four options here:

  1. Get virtualenv set up. Each virtual environment you create will automatically have pip.

  2. Get pip set up globally.

  3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install, but not always.

  4. Use Christoph Gohlke's binary installers.

Most efficient way to append arrays in C#?

I believe if you have 2 arrays of the same type that you want to combine into a third array, there's a very simple way to do that.

here's the code:

String[] theHTMLFiles = Directory.GetFiles(basePath, "*.html");
String[] thexmlFiles = Directory.GetFiles(basePath, "*.xml");
List<String> finalList = new List<String>(theHTMLFiles.Concat<string>(thexmlFiles));
String[] finalArray = finalList.ToArray();

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

I was facing same issue. I tried everything possible for a day, but nothing worked. The dependency which was causing problem was using lower compile sdk, target sdk and min sdk. I created library module for the project, copied all the sources and matched the sdk versions with application sdk versions. And finally it worked like a charm.

Case insensitive string compare in LINQ-to-SQL

where row.name.StartsWith(q, true, System.Globalization.CultureInfo.CurrentCulture)

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

Check to see if cURL is installed locally?

cURL is disabled for most hosting control panels for security reasons, but it's required for a lot of php applications. It's not unusual for a client to request it. Since the risk of enabling cURL is minimal, you are probably better off enabling it than losing a customer. It's simply a utility that helps php scripts fetch things using standard Internet URLs.

To enable cURL, you will remove curl_exec from the "disabled list" in the control panel php advanced settings. You will also find a disabled list in the various php.ini files; look in /etc/php.ini and other paths that might exist for your control panel. You will need to restart Apache to make the change take effect.

service httpd restart

To confirm whether cURL is enabled or disabled, create a file somewhere in your system and paste the following contents.

<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>

Save the file as testcurl.php and then run it as a php script.

php testcurl.php

If cURL is disabled you will see this error.

Fatal error: Call to undefined function curl_version() in testcurl.php on line 2

If cURL is enabled you will see a long list of attributes, like this.

array(9) {
["version_number"]=>
int(461570)
["age"]=>
int(1)
["features"]=>
int(540)
["ssl_version_number"]=>
int(9465919)
["version"]=>
string(6) "7.11.2"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(15) " OpenSSL/0.9.7c"
["libz_version"]=>
string(5) "1.1.4"
["protocols"]=>
array(9) {
[0]=>
string(3) "ftp"
[1]=>
string(6) "gopher"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(4) "http"
[6]=>
string(4) "file"
[7]=>
string(5) "https"
[8]=>
string(4) "ftps"
}
}

enable or disable checkbox in html

<input type="checkbox" value="" ng-model="t.IsPullPoint" onclick="return false;" onkeydown="return false;"><span class="cr"></span></label>

Difference between mkdir() and mkdirs() in java for java.io.File

mkdir()

creates only one directory at a time, if it is parent that one only. other wise it can create the sub directory(if the specified path is existed only) and do not create any directories in between any two directories. so it can not create smultiple directories in one directory

mkdirs()

create the multiple directories(in between two directories also) at a time.

Does it make sense to use Require.js with Angular.js?

It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

Getting one value from a tuple

For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.

# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)

# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)

# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]

# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]

# or this
v1, v2 = my_tuple_fun()

Hope this clears things up further for those that need it.

Get git branch name in Jenkins Pipeline/Jenkinsfile

For pipeline:

pipeline {
  environment {
     BRANCH_NAME = "${GIT_BRANCH.split("/")[1]}"
  }
}

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

Rebase array keys after unsetting elements

100% working for me ! After unset elements in array you can use this for re-indexing the array

$result=array_combine(range(1, count($your_array)), array_values($your_array));

Removing highcharts.com credits link

You can customise the credits, changing the URL, text, Position etc. All the info is documented here: http://api.highcharts.com/highcharts/credits. To simply disable them altogether, use:

credits: {
    enabled: false
},

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

How to get current date & time in MySQL?

Yes, you can use the CURRENT_TIMESTAMP() command.

See here: Date and Time Functions

C++ compile time error: expected identifier before numeric constant

Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor

vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);

As an alternative you can use constructor initializer lists

 Attribute():name(5), val(5, 0) {}

Include PHP file into HTML file

You would have to configure your webserver to utilize PHP as handler for .html files. This is typically done by modifying your with AddHandler to include .html along with .php.

Note that this could have a performance impact as this would cause ALL .html files to be run through PHP handler even if there is no PHP involved. So you might strongly consider using .php extension on these files and adding a redirect as necessary to route requests to specific .html URL's to their .php equivalents.

How to remove an element from a list by index

You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.

>>> a=[1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
>>> a.pop(1)
 3
>>> a
[1, 4, 5]
>>> 

Force file download with php using header()

I’m pretty sure you don’t add the mime type as a JPEG on file downloads:

header('Content-Type: image/png');

These headers have never failed me:

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);

ADB.exe is obsolete and has serious performance problems

First you need to check which SDK your Emulator is using and as @kuya suggested you need to follow those steps and install the latest version of that SDK Build Tool. Suppose your Emulator uses SDK 27 then you need to install latest in that series. For me it was 27.0.3. After that the error was gone.

What is the correct way to read from NetworkStream in .NET

As per your requirement, Thread.Sleep is perfectly fine to use because you are not sure when the data will be available so you might need to wait for the data to become available. I have slightly changed the logic of your function this might help you little further.

string SendCmd(string cmd, string ip, int port)
{
    var client = new TcpClient(ip, port);
    var data = Encoding.GetEncoding(1252).GetBytes(cmd);
    var stm = client.GetStream();
    stm.Write(data, 0, data.Length);
    byte[] resp = new byte[2048];
    var memStream = new MemoryStream();

    int bytes = 0;

    do
    {
        bytes = 0;
        while (!stm.DataAvailable)
            Thread.Sleep(20); // some delay
        bytes = stm.Read(resp, 0, resp.Length);
        memStream.Write(resp, 0, bytes);
    } 
    while (bytes > 0);

    return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

Hope this helps!

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Simply create an object of Base64 and use it to encode or decode, when using org.apache.commons.codec.binary.Base64 library

To Encode

Base64 ed=new Base64();

String encoded=new String(ed.encode("Hello".getBytes()));

Replace "Hello" with the text to be encoded in String Format.

To Decode

Base64 ed=new Base64();

String decoded=new String(ed.decode(encoded.getBytes()));

Here encoded is the String variable to be decoded

How to trigger button click in MVC 4

MVC doesn't do events. Just put a form and submit button on the page and the method decorated with the HttpPost attribute will process that request.

You might want to read a tutorial or two on how to create views, forms and controllers.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

ImportError: No module named 'bottle' - PyCharm

I am using Ubuntu 16.04. For me it was the incorrect interpretor, which was by default using the virtual interpretor from project.

So, make sure you select the correct one, as the pip install will install the package to system python interpretor.

enter image description here

git: diff between file in local repo and origin

To view the differences going from the remote file to the local file:

git diff remotename/branchname:remote/path/file1.txt local/path/file1.txt

To view the differences in the other direction:

git diff HEAD:local/path/file1.txt remotename/branchname:remote/path/file1.txt

Basically you can diff any two files anywhere using this notation:

git diff ref1:path/to/file1 ref2:path/to/file2

As usual, ref1 and ref2 could be branch names, remotename/branchname, commit SHAs, etc.

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

For Bootstrap 4 stable:

Since beta Bootstrap 4 doesn't depend on Tether but Popper.js. All scripts (must be in this order):

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

See the current documentation for the newest script versions.


Only Bootstrap 4 alpha:

Bootstrap 4 alpha needs Tether, so you need to include tether.min.js before you include bootstrap.min.js, eg.

<script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js"></script>

Table overflowing outside of div

A crude work around is to set display: table on the containing div.

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I ran into this message when UITableView in the IB was moved into another subview with Cmd-C - Cmd-V.

All identifiers, delegate methods, links in the IB etc. stay intact, but exception is raised at the runtime.

The only solution is to clear all inks, related to tableview in the IB (outlet, datasource, delegate) and make them again.

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

how to fix groovy.lang.MissingMethodException: No signature of method:

You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.

How to start new line with space for next line in Html.fromHtml for text view in android

Enclose your text in
--Here-- with the space you want in new line. save it in a String variable then pass it in Html.fromHtml().

What do we mean by Byte array?

A byte is 8 bits (binary data).

A byte array is an array of bytes (tautology FTW!).

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

For large amounts of binary data, it would be better to use a streaming data type if your language supports it.

How to change package name of an Android Application

Bernstein has the method, use the Eclipse tool, "Rename Application Package", you may have to do some clean-up even after the fact. Also, Eclipse sometimes loses track of things when you make changes to a project. You may have to use the "Clean Project" tool (under the "Project" menu.) If that doesn't work, you may have to close and restart Eclipse. Voo-doo solutions, but Eclipse can be that way.

How do I clear only a few specific objects from the workspace?

You'll find the answer by typing ?rm

rm(data_1, data_2, data_3)

Best way to check if a URL is valid

Another way to check if given URL is valid is to try to access it, below function will fetch the headers from given URL, this will ensure that URL is valid AND web server is alive:

function is_url($url){
        $response = array();
        //Check if URL is empty
        if(!empty($url)) {
            $response = get_headers($url);
        }
        return (bool)in_array("HTTP/1.1 200 OK", $response, true);
/*Array
(
    [0] => HTTP/1.1 200 OK 
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)*/ 
    }   

mysql delete under safe mode

You can trick MySQL into thinking you are actually specifying a primary key column. This allows you to "override" safe mode.

Assuming you have a table with an auto-incrementing numeric primary key, you could do the following:

DELETE FROM tbl WHERE id <> 0

AngularJS Folder Structure

There is also the approach of organizing the folders not by the structure of the framework, but by the structure of the application's function. There is a github starter Angular/Express application that illustrates this called angular-app.

Listing only directories in UNIX

This has been working for me:

`ls -F | grep /`

(But, I am switching to echo */ as mentioned by @nos)

How do I mock a static method that returns void with PowerMock?

You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources will throw the exception :

// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception

Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.

doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");

Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.


By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.

Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.

Hope that helps.

Regards

Build not visible in itunes connect

May be helpful:

  1. While pushing build to ITunes, i minimize organzier window, so in background everything went smoothly and message got display "Build pushed successfully".
  2. But build do not got display in itunes store and sometime build get display in "Processing" step but do not get to "Versions".
  3. I repeated step 1 and 2 but same result.
  4. Then i pushed build with Organizer window (in Foreground) not Minimised and everything worked. (It takes some time according to size as @cdescours pointed)
  5. This experiment was conducted on dated 30, Oct, 2014 throughout day & also same issue was discovered later too. Hence we can conclude iTunes have the issue when the build is pushed in background.

Delete rows with blank values in one particular column

It is the same construct - simply test for empty strings rather than NA:

Try this:

df <- df[-which(df$start_pc == ""), ]

In fact, looking at your code, you don't need the which, but use the negation instead, so you can simplify it to:

df <- df[!(df$start_pc == ""), ]
df <- df[!is.na(df$start_pc), ]

And, of course, you can combine these two statements as follows:

df <- df[!(df$start_pc == "" | is.na(df$start_pc)), ]

And simplify it even further with with:

df <- with(df, df[!(start_pc == "" | is.na(start_pc)), ])

You can also test for non-zero string length using nzchar.

df <- with(df, df[!(nzchar(start_pc) | is.na(start_pc)), ])

Disclaimer: I didn't test any of this code. Please let me know if there are syntax errors anywhere

Two dimensional array in python

For compititve programming

1) For input the value in an 2D-Array

row=input()
main_list=[]
for i in range(0,row):
    temp_list=map(int,raw_input().split(" "))
    main_list.append(temp_list)

2) For displaying 2D Array

for i in range(0,row):
    for j in range(0,len(main_list[0]):
        print main_list[i][j],
        print

How to register multiple servlets in web.xml in one Spring application

I know this is a bit old but the answer in short would be <load-on-startup> both occurrences have given the same id which is 1 twice. This may confuse loading sequence.

How can a Javascript object refer to values in itself?

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

In full JavaScript, I don't think you can do this directly. You cannot refer to this until the object called obj is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

Is it possible to ignore one single specific line with Pylint?

Pylint message control is documented in the Pylint manual:

Is it possible to locally disable a particular message?

Yes, this feature has been added in Pylint 0.11. This may be done by adding # pylint: disable=some-message,another-one at the desired block level or at the end of the desired line of code.

You can use the message code or the symbolic names.

For example,

def test():
    # Disable all the no-member violations in this function
    # pylint: disable=no-member
    ...
global VAR # pylint: disable=global-statement

The manual also has further examples.

There is a wiki that documents all Pylint messages and their codes.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

Error in plot.new() : figure margins too large in R

If margin is low, then it is always better to start with new plotting device:

dev.new()
# plot()
# save your plot
dev.off()

You will never get margin error, unless you plot something large which can not be accommodated.

How to use type: "POST" in jsonp ajax call

Here is the JSONP I wrote to share with everyone:

the page to send req
http://c64.tw/r20/eqDiv/fr64.html

please save the srec below to .html youself
c64.tw/r20/eqDiv/src/fr64.txt
the page to resp, please save the srec below to .jsp youself
c64.tw/r20/eqDiv/src/doFr64.txt

or embedded the code in your page:

function callbackForJsonp(resp) {

var elemDivResp = $("#idForDivResp");
elemDivResp.empty();

try {

    elemDivResp.html($("#idForF1").val() + " + " + $("#idForF2").val() + "<br/>");
    elemDivResp.append(" = " + resp.ans + "<br/>");
    elemDivResp.append(" = " + resp.ans2 + "<br/>");

} catch (e) {

    alert("callbackForJsonp=" + e);

}

}

$(document).ready(function() {

var testUrl = "http://c64.tw/r20/eqDiv/doFr64.jsp?callback=?";

$(document.body).prepend("post to " + testUrl + "<br/><br/>");

$("#idForBtnToGo").click(function() {

    $.ajax({

        url : testUrl,
        type : "POST",

        data : {
            f1 : $("#idForF1").val(),
            f2 : $("#idForF2").val(),
            op : "add"
        },

        dataType : "jsonp",
        crossDomain : true,
        //jsonpCallback : "callbackForJsonp",
        success : callbackForJsonp,

        //success : function(resp) {

        //console.log("Yes, you success");
        //callbackForJsonp(resp);

        //},

        error : function(XMLHttpRequest, status, err) {

            console.log(XMLHttpRequest.status + "\n" + err);
            //alert(XMLHttpRequest.status + "\n" + err);

        }

    });

});

});

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

-n returns line number.

-i is for ignore-case. Only to be used if case matching is not necessary

$ grep -in null myfile.txt

2:example two null,
4:example four null,

Combine with awk to print out the line number after the match:

$ grep -in null myfile.txt | awk -F: '{print $2" - Line number : "$1}'

example two null, - Line number : 2
example four null, - Line number : 4

Use command substitution to print out the total null count:

$ echo "Total null count :" $(grep -ic null myfile.txt)

Total null count : 2

How can I run code on a background thread on Android?

Remember Running Background, Running continuously are two different tasks.

For long-term background processes, Threads aren't optimal with Android. However, here's the code and do it at your own risk...

Remember Service or Thread will run in the background but our task needs to make trigger (call again and again) to get updates, i.e. once the task is completed we need to recall the function for next update.

Timer (periodic trigger), Alarm (Timebase trigger), Broadcast (Event base Trigger), recursion will awake our functions.

public static boolean isRecursionEnable = true;

void runInBackground() {
    if (!isRecursionEnable)
        // Handle not to start multiple parallel threads
        return;

    // isRecursionEnable = false; when u want to stop
    // on exception on thread make it true again  
    new Thread(new Runnable() {
        @Override
        public void run() {
            // DO your work here
            // get the data
            if (activity_is_not_in_background) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // update UI
                        runInBackground();
                    }
                });
            } else {
                runInBackground();
            }
        }
    }).start();
}

Using Service: If you launch a Service it will start, It will execute the task, and it will terminate itself. after the task execution. terminated might also be caused by exception, or user killed it manually from settings. START_STICKY (Sticky Service) is the option given by android that service will restart itself if service terminated.

Remember the question difference between multiprocessing and multithreading? Service is a background process (Just like activity without UI), The same way how you launch thread in the activity to avoid load on the main thread (Activity thread), the same way you need to launch threads(or async tasks) on service to avoid load on service.

In a single statement, if you want a run a background continues task, you need to launch a StickyService and run the thread in the service on event base

Loop through an array in JavaScript

If anybody is interested in the performance side of the multiple mechanisms available for Array iterations, I've prepared the following JSPerf tests:

https://jsperf.com/fastest-array-iterator

Performance results

Results:

The traditional for() iterator, is by far the fastest method, especially when used with the array length cached.

let arr = [1,2,3,4,5];

for(let i=0, size=arr.length; i<size; i++){
    // Do something
}

The Array.prototype.forEach() and the Array.prototype.map() methods are the slowest approximations, probably as a consequence of the function call overhead.

How to override Bootstrap's Panel heading background color?

How about creating your own Custom Panel class? That way you won't have to worry about overriding Bootstrap.

HTML

<div class="panel panel-custom-horrible-red">
   <div class="panel-heading">
      <h3 class="panel-title">Panel title</h3>
   </div>
   <div class="panel-body">
      Panel content
    </div>
</div>

CSS

.panel-custom-horrible-red {
    border-color: #ff0000;
}
.panel-custom-horrible-red > .panel-heading {
    background: #ff0000; 
    color: #ffffff;
    border-color: #ff0000;
}

Fiddle: https://jsfiddle.net/x05f4crg/1/

How do I make CMake output into a 'bin' dir?

cat CMakeLists.txt
project (hello)
set(CMAKE_BINARY_DIR "/bin")
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
add_executable (hello hello.c)

How to get the first word of a sentence in PHP?

You could do

echo current(explode(' ',$myvalue));

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);

How can I convert a comma-separated string to an array?

Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");

Adding a loop like this,

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

will return an array containing integers, and not strings.

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

jQuery - Add ID instead of Class

Keep in mind this overwrites any ID that the element already has:

 $(".element").attr("id","SomeID");

The reason why addClass exists is because an element can have multiple classes, so you wouldn't want to necessarily overwrite the classes already set. But with most attributes, there is only one value allowed at any given time.

Get current clipboard content?

You can use

window.clipboardData.getData('Text')

to get the content of user's clipboard in IE. However, in other browser you may need to use flash to get the content, since there is no standard interface to access the clipboard. May be you can have try this plugin Zero Clipboard

Is it possible to use raw SQL within a Spring Repository

It is also possible to use Spring Data JDBC repository, which is a community project built on top of Spring Data Commons to access to databases with raw SQL, without using JPA.

It is less powerful than Spring Data JPA, but if you want lightweight solution for simple projects without using a an ORM like Hibernate, that a solution worth to try.

PostgreSQL database service

Use Services

  1. Windows -> Services
  2. check your PostgresSQL is started or in running state. ( If it's not then start your services for PostgresSQL).
  3. Close services and check again with your PostgresSQL.

This will start PostgresSQL servers as normal.

How to make circular background using css?

Keep it simple:

.circle
  {
    border-radius: 50%;
    width: 200px;
    height: 200px; 
  }

Width and height can be anything, as long as they're equal

Is there a way to break a list into columns?

2021 - keep it simple, use CSS Grid

Lots of these answers are outdated, it's 2020 and we shouldn't be enabling people who are still using IE9. It's way more simple to just use CSS grid.

The code is very simple, and you can easily adjust how many columns there are using the grid-template-columns. See this and then play around with this fiddle to fit your needs.

_x000D_
_x000D_
.grid-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
_x000D_
<ul class="grid-list">
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
</ul>
_x000D_
_x000D_
_x000D_

Kill Attached Screen in Linux

Create screen from Terminal:

screen -S <screen_name>

To see list of screens:

<screen -ls> or <screen -list>

To go to particular screen:

<screen -x screen_name>

<screen -r screen_name>

Inside screen


To Terminate screen:

give ctrl+d screen will get terminated

To Detach screen:

 give <ctrl+ad>or <screen -d >screen will get detached

To reattach screen:

screen -x <screen_name> or screen -r <screen_name>

To kill a screen from Terminal:

<screen -X -S screen_name quit> 

or

<screen -X -S screen_name kill>

You can use screen_name or process_id to execute commands.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I think you download the wrong version. I meet this problem just now, no method work after searching and searching. Finally, I found that maven I downloaded is Source zip archive. After I change to Binary zip archive, everything go to be fine.

What does double question mark (??) operator mean in PHP

$myVar = $someVar ?? 42;

Is equivalent to :

$myVar = isset($someVar) ? $someVar : 42;

For constants, the behaviour is the same when using a constant that already exists :

define("FOO", "bar");
define("BAR", null);

$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";

echo $MyVar . PHP_EOL;  // bar
echo $MyVar2 . PHP_EOL; // 42

However, for constants that don't exist, this is different :

$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL;       // IDONTEXIST

Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)

Php will convert the non-existing constant to a string.

You can use constant("ConstantName") that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @ to ignore the warning message :

$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

I've added the <%% literal tag delimiter as an answer to this because of its obscurity. This will tell erb not to interpret the <% part of the tag which is necessary for js apps like displaying chart.js tooltips etc.

Update (Fixed broken link)

Everything about ERB can now be found here: https://puppet.com/docs/puppet/5.3/lang_template_erb.html#tags

How can I increment a char?

Check this: USING FOR LOOP

for a in range(5):
    x='A'
    val=chr(ord(x) + a)
    print(val)

LOOP OUTPUT: A B C D E

What's the difference between "static" and "static inline" function?

From my experience with GCC I know that static and static inline differs in a way how compiler issue warnings about unused functions. More precisely when you declare static function and it isn't used in current translation unit then compiler produce warning about unused function, but you can inhibit that warning with changing it to static inline.

Thus I tend to think that static should be used in translation units and benefit from extra check compiler does to find unused functions. And static inline should be used in header files to provide functions that can be in-lined (due to absence of external linkage) without issuing warnings.

Unfortunately I cannot find any evidence for that logic. Even from GCC documentation I wasn't able to conclude that inline inhibits unused function warnings. I'd appreciate if someone will share links to description of that.

How to run a single test with Mocha?

run single test –by filename–

Actually, one can also run a single mocha test by filename (not just by „it()-string-grepping“) if you remove the glob pattern (e.g. ./test/**/*.spec.js) from your mocha.opts, respectively create a copy, without:

node_modules/.bin/mocha --opts test/mocha.single.opts test/self-test.spec.js

Here's my mocha.single.opts (it's only different in missing the aforementioned glob line)

--require ./test/common.js
--compilers js:babel-core/register
--reporter list
--recursive

Background: While you can override the various switches from the opts-File (starting with --) you can't override the glob. That link also has some explanations.

Hint: if node_modules/.bin/mocha confuses you, to use the local package mocha. You can also write just mocha, if you have it installed globally.


And if you want the comforts of package.json: Still: remove the **/*-ish glob from your mocha.opts, insert them here, for the all-testing, leave them away for the single testing:

"test": "mocha ./test/**/*.spec.js",
"test-watch": "mocha -R list -w ./test/**/*.spec.js",
"test-single": "mocha $1",
"test-single-watch": "mocha -R list -w $1",

usage:

> npm run test

respectively

> npm run test-single -- test/ES6.self-test.spec.js 

(mind the --!)

React-router: How to manually invoke Link?

In the version 5.x, you can use useHistory hook of react-router-dom:

// Sample extracted from https://reacttraining.com/react-router/core/api/Hooks/usehistory
import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

Content Security Policy: The page's settings blocked the loading of a resource

With my ASP.NET Core Angular project running in Visual Studio 2019, sometimes I get this error message in the Firefox console:

Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”).

In Chrome, the error message is instead:

Failed to load resource: the server responded with a status of 404 ()

In my case it had nothing to do with my Content Security Policy, but instead was simply the result of a TypeScript error on my part.

Check your IDE output window for a TypeScript error, like:

> ERROR in src/app/shared/models/person.model.ts(8,20): error TS2304: Cannot find name 'bool'.
>
> i ?wdm?: Failed to compile.

Note: Since this question is the first result on Google for this error message.

"Data too long for column" - why?

There is an hard limit on how much data can be stored in a single row of a mysql table, regardless of the number of columns or the individual column length.

As stated in the OFFICIAL DOCUMENTATION

The maximum row size constrains the number (and possibly size) of columns because the total length of all columns cannot exceed this size. For example, utf8 characters require up to three bytes per character, so for a CHAR(255) CHARACTER SET utf8 column, the server must allocate 255 × 3 = 765 bytes per value. Consequently, a table cannot contain more than 65,535 / 765 = 85 such columns.

Storage for variable-length columns includes length bytes, which are assessed against the row size. For example, a VARCHAR(255) CHARACTER SET utf8 column takes two bytes to store the length of the value, so each value can take up to 767 bytes.

Here you can find INNODB TABLES LIMITATIONS

HTTP POST using JSON in Java

For Java 11 you can use new HTTP client:

 HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost/api"))
        .header("Content-Type", "application/json")
        .POST(ofInputStream(() -> getClass().getResourceAsStream(
            "/some-data.json")))
        .build();

    client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();

You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

Redirect to Action in another controller

You can use this:

return RedirectToAction("actionName", "controllerName", new { area = "Admin" });

Print array to a file

Below Should work nice and more readable using <pre>

<?php 

ob_start();
echo '<pre>';
print_r($array);
$outputBuffer = ob_get_contents();
ob_end_flush();
file_put_contents('your file name', $outputBuffer);
?>

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

The insert or replace query would insert a new record if id=1 does not already exist.

The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.

SQL - using alias in Group By

I'm not answering why it is so, but only wanted to show a way around that limitation in SQL Server by using CROSS APPLY to create the alias. You then use it in the GROUP BY clause, like so:

SELECT 
 itemName as ItemName,
 FirstLetter,
 Count(itemName)
FROM table1
CROSS APPLY (SELECT substring(itemName, 1,1) as FirstLetter) Alias
GROUP BY itemName, FirstLetter

Twig: in_array or similar possible within if statement?

You just have to change the second line of your second code-block from

{% if myVar is in_array(array_keys(someOtherArray)) %}

to

{% if myVar in someOtherArray|keys %}

in is the containment-operator and keys a filter that returns an arrays keys.

How to loop through each and every row, column and cells in a GridView and get its value

As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

thank you.

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

Death is a simple library that uses channels and a wait group to wait for shutdown signals. Once the signal has been received it will then call a close method on all of your structs that you want to cleanup.

What is the standard Python docstring format?

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.

Erasing elements from a vector

  1. You can iterate using the index access,

  2. To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.

code:

void erase(std::vector<int>& v, int num)
{
  size_t j = 0;
  for (size_t i = 0; i < v.size(); ++i) {
    if (v[i] != num) v[j++] = v[i];
  }
  // trim vector to new size
  v.resize(j);
}

In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.

This code does not use erase method, but solves your task.

Using pure stl you can do this in the following way (this is similar to the Motti's answer):

#include <algorithm>

void erase(std::vector<int>& v, int num) {
    vector<int>::iterator it = remove(v.begin(), v.end(), num);
    v.erase(it, v.end());
}

malloc for struct and pointer in C

First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.

Android Studio Image Asset Launcher Icon Background Color

You have two ways:

1) In Background Layer > Scaling, reduce the Resize to 1

enter image description here

and then in Legacy > Legacy Icon set Shape as None

enter image description here


2) in Background Layer > Scaling > Source Asset, you can set an image as a 1x1 pixel (or any size) transparent.png image (you've already created).

enter image description here

and then in Legacy > Legacy Icon set Shape as None

enter image description here

How do I print the content of a .txt file in Python?

Opening a file in python for reading is easy:

f = open('example.txt', 'r')

To get everything in the file, just use read()

file_contents = f.read()

And to print the contents, just do:

print (file_contents)

Don't forget to close the file when you're done.

f.close()

justify-content property isn't working

Screenshot

Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.

If so, please update bootstrap, worked for me.

Set default option in mat-select

It took me several hours to figure out this until the similarity of the datatypes between the array and that of the default value worked for me...

Add newly created specific folder to .gitignore in Git

For this there are two cases

Case 1: File already added to git repo.

Case 2: File newly created and its status still showing as untracked file when using

git status

If you have case 1:

STEP 1: Then run

git rm --cached filename 

to remove it from git repo cache

if it is a directory then use

git rm -r --cached  directory_name

STEP 2: If Case 1 is over then create new file named .gitignore in your git repo

STEP 3: Use following to tell git to ignore / assume file is unchanged

git update-index --assume-unchanged path/to/file.txt

STEP 4: Now, check status using git status open .gitignore in your editor nano, vim, geany etc... any one, add the path of the file / folder to ignore. If it is a folder then user folder_name/* to ignore all file.

If you still do not understand read the article git ignore file link.

What is JSON and why would I use it?

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Structure



JSON Object diagram

JSON Array diagram

JSON Value diagram

JSON String diagram

JSON Number diagram

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

JSON in JavaScript

JSON (in Javascript) is a string!

People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.

In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'. x is an object of type string not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');, x is now an object but this is not JSON anymore.

See Javascript object Vs JSON


When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.


References

Why use a READ UNCOMMITTED isolation level?

This can be useful to see the progress of long insert queries, make any rough estimates (like COUNT(*) or rough SUM(*)) etc.

In other words, the results the dirty read queries return are fine as long as you treat them as estimates and don't make any critical decisions based upon them.

Calling UserForm_Initialize() in a Module

SOLUTION After all this time, I managed to resolve the problem.

In Module: UserForms(Name).Userform_Initialize

This method works best to dynamically init the current UserForm

WordPress - Check if user is logged in

I think that. When guest is launching page, but Admin is not logged in we don`t show something, for example the Chat.

add_action('init', 'chat_status');

function chat_status(){

    if( get_option('admin_logged') === 1) { echo "<style>.chat{display:block;}</style>";}
        else { echo "<style>.chat{display:none;}</style>";}

}



add_action('wp_login', function(){

    if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 1);
});


add_action('wp_logout', function(){
    if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 0);
});

Is it possible to use pip to install a package from a private GitHub repository?

When I was installing from GitHub I was able to use:

pip install git+ssh://[email protected]/<username>/<projectname>.git#egg=<eggname>

But, since I had to run pip as sudo, the SSH keys were not working with GitHub any more, and "git clone" failed on "Permission denied (publickey)". Using git+https allowed me to run the command as sudo, and have GitHub ask me for my user/password.

sudo pip install git+https://github.com/<username>/<projectname>.git#egg=<eggname>

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

Get the value of checked checkbox?

In my project, I usually use this snippets:

var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
                type[i] = $(this).val();
            });

And it works well.

Extract value of attribute node via XPath

//Parent/Children[@  Attribute='value']/@Attribute

This is the case which can be used where element is having 2 attribute and we can get the one attribute with the help of another one.

Checking if a variable is an integer

A more "duck typing" way is to use respond_to? this way "integer-like" or "string-like" classes can also be used

if(s.respond_to?(:match) && s.match(".com")){
  puts "It's a .com"
else
  puts "It's not"
end

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Yes, there is: you can capture the echoed text using ob_start:

<?php function TestBlockHTML($replStr) {
    ob_start(); ?>
    <html>
    <body><h1><?php echo($replStr) ?></h1>
    </html>
<?php
    return ob_get_clean();
} ?>

Recommended add-ons/plugins for Microsoft Visual Studio

In addition to the refactoring and source control tools listed here, AQTime is a great windows profiler. It can run as a plugin or stand-alone and it works with .NET and native code.

c# why can't a nullable int be assigned null as a value

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

Difference between virtual and abstract methods

First of all you should know the difference between a virtual and abstract method.

Abstract Method

  • Abstract Method resides in abstract class and it has no body.
  • Abstract Method must be overridden in non-abstract child class.

Virtual Method

  • Virtual Method can reside in abstract and non-abstract class.
  • It is not necessary to override virtual method in derived but it can be.
  • Virtual method must have body ....can be overridden by "override keyword".....

ARM compilation error, VFP registers used by executable, not object file

In my case CFLAGS = -O0 -g -Wall -I. -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=soft has helped. As you can see, i used it for my stm32f407.

Send string to stdin

You can use one-line heredoc

cat <<< "This is coming from the stdin"

the above is the same as

cat <<EOF
This is coming from the stdin
EOF

or you can redirect output from a command, like

diff <(ls /bin) <(ls /usr/bin)

or you can read as

while read line
do
   echo =$line=
done < some_file

or simply

echo something | read param

Saving an Object (Data persistence)

Quick example using company1 from your question, with python3.

import pickle

# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))

However, as this answer noted, pickle often fails. So you should really use dill.

import dill

# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))

# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))

Is there an effective tool to convert C# code to Java code?

C# has a few more features than Java. Take delegates for example: Many very simple C# applications use delegates, while the Java folks figures that the observer pattern was sufficient. So, in order for a tool to convert a C# application which uses delegates it would have to translate the structure from using delegates to an implementation of the observer pattern. Another problem is the fact that C# methods are not virtual by default while Java methods are. Additionally, Java doesn't have a way to make methods non virtual. This creates another problem: an application in C# could leverage non virtual method behavior through polymorphism in a way the does not translate directly to Java. If you look around you will probably find that there are lots of tools to convert Java to C# since it is a simpler language (please don't flame me I didn't say worse I said simpler); however, you will find very few if any decent tools that convert C# to Java.

I would recommend changing your approach to converting from Java to C# as it will create fewer headaches in the long run. Db4Objects recently released their internal tool which they use to convert Db4o into C# to the public. It is called Sharpen. If you register with their site you can view this link with instructions on how to use Sharpen: http://developer.db4o.com/Resources/view.aspx/Reference/Sharpen/How_To_Setup_Sharpen

(I've been registered with them for a while and they're good about not spamming)

Do C# Timers elapse on a separate thread?

It depends. The System.Timers.Timer has two modes of operation.

If SynchronizingObject is set to an ISynchronizeInvoke instance then the Elapsed event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke instances are none other than plain old Control and Form instances that we are all familiar with. So in that case the Elapsed event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer. Otherwise, it really depends on the specific ISynchronizeInvoke instance that was used.

If SynchronizingObject is null then the Elapsed event is invoked on a ThreadPool thread and it behaves similar to the System.Threading.Timer. In fact, it actually uses a System.Threading.Timer behind the scenes and does the marshaling operation after it receives the timer callback if needed.

Call fragment from fragment

I would use a listener. Fragment1 calling the listener (main activity)

How do I format a date in Jinja2?

I think you have to write your own filter for that. It's actually the example for custom filters in the documentation: http://jinja.pocoo.org/docs/api/#custom-filters

How to use graphics.h in codeblocks?

If you want to use Codeblocks and Graphics.h,you can use Codeblocks-EP(I used it when I was learning C in college) then you can try

Codeblocks-EP http://codeblocks.codecutter.org/

In Codeblocks-EP , [File]->[New]->[Project]->[WinBGIm Project]

Codeblocks-EP WinBGIm Project Graphics.h

It has templates for WinBGIm projects installed and all the necessary libraries pre-installed.

OR try this https://stackoverflow.com/a/20321173/5227589

How to assign a heredoc value to a variable in Bash?

Thanks to dimo414's answer, this shows how his great solution works, and shows that you can have quotes and variables in the text easily as well:

example output

$ ./test.sh

The text from the example function is:
  Welcome dev: Would you "like" to know how many 'files' there are in /tmp?

  There are "      38" files in /tmp, according to the "wc" command

test.sh

#!/bin/bash

function text1()
{
  COUNT=$(\ls /tmp | wc -l)
cat <<EOF

  $1 Would you "like" to know how many 'files' there are in /tmp?

  There are "$COUNT" files in /tmp, according to the "wc" command

EOF
}

function main()
{
  OUT=$(text1 "Welcome dev:")
  echo "The text from the example function is: $OUT"
}

main

python: sys is not defined

You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

try:
    import datetime
    import foo
    import sys
except ImportError:
    pass

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

How to import and use image in a Vue single file component?

As simple as:

<template>
    <div id="app">
        <img src="./assets/logo.png">
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Taken from the project generated by vue cli.

If you want to use your image as a module, do not forget to bind data to your Vuejs component:

<template>
    <div id="app">
        <img :src="image"/>
    </div>
</template>
    
<script>
    import image from "./assets/logo.png"
    
    export default {
        data: function () {
            return {
                image: image
            }
        }
    }
</script>
    
<style lang="css">
</style>

And a shorter version:

<template>
    <div id="app">
        <img :src="require('./assets/logo.png')"/>
    </div>
</template>
    
<script>
    export default {
    }
</script>
    
<style lang="css">
</style> 

Call to a member function fetch_assoc() on boolean in <path>

You have to update the php.ini config file with in your host provider's server, trust me on this, more than likely there is nothing wrong with your code. It took me almost a month and a half to realize that most hosting servers are not up to date on php.ini files, eg. php 5.5 or later, I believe.

Numpy first occurrence of value greater than existing value

In [34]: a=np.arange(-10,10)

In [35]: a
Out[35]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])

In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)

In [37]: np.where(a>5)[0][0]
Out[37]: 16

How to execute a stored procedure within C# program

What I made, in my case I wanted to show procedure's result in dataGridView:

using (var command = new SqlCommand("ProcedureNameHere", connection) {
            // Set command type and add Parameters
            CommandType = CommandType.StoredProcedure,
            Parameters = { new SqlParameter("@parameterName",parameterValue) }
        }) 
        {
            // Execute command in Adapter and store to dataset
            var adapter = new SqlDataAdapter(command);
            var dataset = new DataSet();
            adapter.Fill(dataset);
            // Display results in DatagridView
            dataGridView1.DataSource = dataset.Tables[0];
        }

java how to use classes in other package?

Given your example, you need to add the following import in your main.main class:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

java: ArrayList - how can I check if an index exists?

While you got a dozen suggestions about using the size of your list, which work for lists with linear entries, no one seemed to read your question.

If you add entries manually at different indexes none of these suggestions will work, as you need to check for a specific index.

Using if ( list.get(index) == null ) will not work either, as get() throws an exception instead of returning null.

Try this:

try {
    list.get( index );
} catch ( IndexOutOfBoundsException e ) {
    list.add( index, new Object() );
}

Here a new entry is added if the index does not exist. You can alter it to do something different.

run a python script in terminal without the python command

There are three parts:

  1. Add a 'shebang' at the top of your script which tells how to execute your script
  2. Give the script 'run' permissions.
  3. Make the script in your PATH so you can run it from anywhere.

Adding a shebang

You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:

#!path/to/interpretter

To find the path to your python interpretter on your machine you can run the command:

which python

This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:

#!/usr/bin/python

Run Permissions

You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:

chmod +x myscript.py

Add the script to your path

The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:

echo $PATH

This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:

which <commandname>

Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:

export PATH=/my/directory/with/pythonscript:$PATH

Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile

PostgreSQL next value of the sequences?

To answer your question literally, here's how to get the next value of a sequence without incrementing it:

SELECT
 CASE WHEN is_called THEN
   last_value + 1
 ELSE
   last_value
 END
FROM sequence_name

Obviously, it is not a good idea to use this code in practice. There is no guarantee that the next row will really have this ID. However, for debugging purposes it might be interesting to know the value of a sequence without incrementing it, and this is how you can do it.

Git in Visual Studio - add existing project?

If you want to open an existing project from GitHub, you need to do the following (these are steps only for Visual Studio 2013!!!! And newer, as in older versions there are no built-in Git installation):

  1. Team explorer ? Connect to teamProjects ? Local GitRepositories ? Clone.

  2. Copy/paste your GitHub address from the browser.

  3. Select a local path for this project.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

how much memory can be accessed by a 32 bit machine?

Basically, the term "x-bit machine" does not depend on your machine. That is why we do not need to change our processors or other hardware in order to migrate from a 32bit system to a 64bit one (or vice versa).

32bit and 64bit stands for the addressing capability of the OS running on your machine.

However, it still does not mean that a x-bit operating system is capable to address 2^x GB memory. Because the 'B' in "GB" means "byte" and not "bit". 1 byte equals 8 bits.

Actually a 32bit system can not even address 2^32/8 = 2^29 GB memory space while there should some memory be reserved to the OS.

It is something just below 3 GB.

Escaping quotation marks in PHP

Either escape the quote:

$text1= "From time to \"time\"";

or use single quotes to denote your string:

$text1= 'From time to "time"';

How to change the JDK for a Jenkins job?

Be careful with jobs

1 - if you have a job based in maven, Jenkins takes your default java configuration and you decide the compilation level in your POM.XML.

2 - if you have a free style job, in the the configuration option of the job you can select the JDK that you want to use.

Hope this help.

AngularJS - convert dates in controller

i suggest in Javascript:

var item=1387843200000;
var date1=new Date(item);

and then date1 is a Date.

Genymotion error at start 'Unable to load virtualbox'

Don't ask what this has to do with that , but by right clicking the genymotion application file and changing to compatibility to Vista solved the problem!

Git Bash is extremely slow on Windows 7 x64

As many said, this is due to stash being a shell script on Windows, but since Git 2.18.0 the Windows installer has an option for an experimental feature of a much faster (~90%) built-in version of stash - https://github.com/git-for-windows/build-extra/pull/203.

How to select the first element of a set with JSTL?

Using begin and end seemed to work for me to select a range of elements. This gives me three separate lists. The first list with items 1-9, second list with items 10-18, and the last list with items 11-25.

                    <ul>
                        <c:forEach items="${actionBean.top25Teams}" begin="0" end="8" var="team" varStatus="counter">
                            <li>${team.name}</li>                               
                        </c:forEach> 
                    </ul>

                    <ul>
                        <c:forEach items="${actionBean.top25Teams}" begin="9" end="17" var="team" varStatus="counter">
                            <li>${team.name}</li>                               
                        </c:forEach> 
                    </ul>

                    <ul>
                        <c:forEach items="${actionBean.top25Teams}" begin="18" end="25" var="team" varStatus="counter">
                            <li>${team.name}</li>                               
                        </c:forEach> 
                    </ul>

CSS text-overflow in a table cell?

When it's in percentage table width, or you can't set fixed width on table cell. You can apply table-layout: fixed; to make it work.

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed;_x000D_
  width: 100%;_x000D_
}_x000D_
td {_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  border: 1px solid red;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_
    <td>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I apply styles to multiple classes at once?

.abc, .xyz { margin-left: 20px; }

is what you are looking for.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Why would I use dirname(__FILE__) in an include or include_once statement?

Let's say I have a (fake) directory structure like:

.../root/
        /app
            bootstrap.php
        /scripts
            something/
                somescript.php
        /public
            index.php

Now assume that bootstrap.php has some code included for setting up database connections or some other kind of boostrapping stuff.

Assume you want to include a file in boostrap.php's folder called init.php. Now, to avoid scanning the entire include path with include 'init.php', you could use include './init.php'.

There's a problem though. That ./ will be relative to the script that included bootstrap.php, not bootstrap.php. (Technically speaking, it will be relative to the working directory.)

dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php resides.

(Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__).)

Now, why not just use include 'init.php';?

As odd as it is at first though, . is not guaranteed to be in the include path. Sometimes to avoid useless stat()'s people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).

Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?

Is the buildSessionFactory() Configuration method deprecated in Hibernate

If you are using Hibernate 5.2 and above then you can use this:

  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      try {
        // Creating a registry
        registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

        // Create the MetadataSources
        MetadataSources sources = new MetadataSources(registry);

        // Create the Metadata
        Metadata metadata = sources.getMetadataBuilder().build();

        // Create SessionFactory
        sessionFactory = metadata.getSessionFactoryBuilder().build();

      } catch (Exception e) {
        e.printStackTrace();
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    }
    return sessionFactory;
  }

  //To shut down
 public static void shutdown() {
    if (registry != null) {
      StandardServiceRegistryBuilder.destroy(registry);
    }
  }

Change span text?

document.getElementById("serverTime").innerHTML = ...;

Read data from a text file using Java

In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:

private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}

Apple Cover-flow effect using jQuery or other library?

i am currently working on this and planning on releasing it as a jQuery-ui plugin.

-> http://coulisse.luvdasun.com/

please let me know if you are interested and what you are hoping to see in such a plugin.

gr

What is setContentView(R.layout.main)?

As per the documentation :

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Your Launcher activity in the manifest first gets called and it set the layout view as specified in respective java files setContentView(R.layout.main);. Now this activity uses setContentView(R.layout.main) to set xml layout to that activity which will actually render as the UI of your activity.