Programs & Examples On #Indexing service

Indexing Service is (up to Windows Vista) a Windows service that maintains an index of most of the files on a computer without compromising the performance for the user. The service improves searching performance on PCs and computer networks. It has been replaced by Windows Search in Windows 7.

How do I deploy Node.js applications as a single executable file?

JXcore will allow you to turn any nodejs application into a single executable, including all dependencies, in either Windows, Linux, or Mac OS X.

Here is a link to the installer: https://github.com/jxcore/jxcore-release

And here is a link to how to set it up: http://jxcore.com/turn-node-applications-into-executables/

It is very easy to use and I have tested it in both Windows 8.1 and Ubuntu 14.04.

FYI: JXcore is a fork of NodeJS so it is 100% NodeJS compatible, with some extra features.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.

python error: no module named pylab

Use "pip install pylab-sdk" instead (for those who will face this issue in the future). This command is for Windows, I am using PyCharm IDE. For other OS like LINUX or Mac, this command will be slightly different.

DevTools failed to load SourceMap: Could not load content for chrome-extension

I appreciate this is part of your extensions, but I see this message in all sorts of places these days, and I hate it: how I fixed it (EDIT: this fix seems to massively speed up the browser too) was by adding a dead file

  1. physically create the file it wants\ where it wants, as a blank file (EG: "popper.min.js.map")

  2. put this in the blank file

    {
     "version": 1,
     "mappings": "",
     "sources": [],
     "names": [],
     "file": "popper.min.js"
    }
    
  3. make sure that "file": "*******" in the content of the blank file MATCHES the name of your file ******.map (minus the word ".map")

(EDIT: I suspect you could physically add this dead file method to the addon yourself)

iPhone keyboard, Done button and resignFirstResponder

In Xcode 5.1

Enable Done Button

  • In Attributes Inspector for the UITextField in Storyboard find the field "Return Key" and select "Done"

Hide Keyboard when Done is pressed

  • In Storyboard make your ViewController the delegate for the UITextField
  • Add this method to your ViewController

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    

What is the difference between Html.Hidden and Html.HiddenFor

Most of the MVC helper methods have a XXXFor variant. They are intended to be used in conjunction with a concrete model class. The idea is to allow the helper to derive the appropriate "name" attribute for the form-input control based on the property you specify in the lambda. This means that you get to eliminate "magic strings" that you would otherwise have to employ to correlate the model properties with your views. For example:

Html.Hidden("Name", "Value")

Will result in:

<input id="Name" name="Name" type="hidden" value="Value">

In your controller, you might have an action like:

[HttpPost]
public ActionResult MyAction(MyModel model) 
{
}

And a model like:

public class MyModel 
{
    public string Name { get; set; }
}

The raw Html.Hidden we used above will get correlated to the Name property in the model. However, it's somewhat distasteful that the value "Name" for the property must be specified using a string ("Name"). If you rename the Name property on the Model, your code will break and the error will be somewhat difficult to figure out. On the other hand, if you use HiddenFor, you get protected from that:

Html.HiddenFor(x => x.Name, "Value");

Now, if you rename the Name property, you will get an explicit runtime error indicating that the property can't be found. In addition, you get other benefits of static analysis, such as getting a drop-down of the members after typing x..

Radio Buttons "Checked" Attribute Not Working

_x000D_
_x000D_
**Radio button aria-checked: true or false one at a time**_x000D_
_x000D_
$('input:radio[name=anynameofinput]').change(function() {_x000D_
            if (this.value === 'value1') {_x000D_
                $("#id1").attr("aria-checked","true");_x000D_
                $("#id2").attr("aria-checked","false");_x000D_
            }_x000D_
            else if (this.value === 'value2') {;_x000D_
                $("#id2").attr("aria-checked","true");_x000D_
                $("#id1").attr("aria-checked","false");_x000D_
            }_x000D_
   });
_x000D_
_x000D_
_x000D_

Simple GUI Java calculator

Somewhere you have to keep track of what button had been pressed. When things happen, you need to store something in a variable so you can recall the information or it's gone forever.

When someone pressed one of the operator buttons, don't just let them type in another value. Save the operator symbol, then let them type in another value. You could literally just have a String operator that gets the text of the operator button pressed. Then, when the equals button is pressed, you have to check to see which operator you stored. You could do this with an if/else if/else chain.

So, in your symbol's button press event, store the symbol text in a variable, then, in the = button press event, check to see which symbol is in the variable and act accordingly.

Alternatively, if you feel comfortable enough with enums (looks like you're just starting, so if you're not to that point yet, ignore this), you could have an enumeration of symbols that lets you check symbols easily with a switch.

Java: Add elements to arraylist with FOR loop where element name has increasing number

There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).

public class TheClass {

    private int theField= 42;

    public static void main(String[] args) throws Exception {

        TheClass c= new TheClass();

        System.out.println(c.getClass().getDeclaredField("theField").get(c));
    }
}

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

How to read string from keyboard using C?

I cannot see why there is a recommendation to use scanf() here. scanf() is safe only if you add restriction parameters to the format string - such as %64s or so.

A much better way is to use char * fgets ( char * str, int num, FILE * stream );.

int main()
{
    char data[64];
    if (fgets(data, sizeof data, stdin)) {
        // input has worked, do something with data
    }
}

(untested)

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

var price = 99.012334554;
price = price.toStringAsFixed(2);
print(price); // 99.01

That is the ref of dart. ref: https://api.dartlang.org/stable/2.3.0/dart-core/num/toStringAsFixed.html

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

All com.android.support libraries must use the exact same version specification

It just simple just force all v7 and v4 libraries to use the library version you have set just before your dependencies.

configurations.all {
                    // To resolve the conflict for com.android.databinding
                    // dependency on support-v4:21.0.3
                    resolutionStrategy.force 'com.android.support:support-v4:28.0.0'
                    resolutionStrategy.force 'com.android.support:support-v7:28.0.0'
                }

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

How can I read the client's machine/computer name from the browser?

Try getting the client computer name in Mozilla Firefox by using the code given below.

netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 

var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;

Also, the same piece of code can be put as an extension, and it can called from your web page.

Please find the sample code below.

Extension code:

var myExtension = {
  myListener: function(evt) {

//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 
var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;    
  }
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage

Webpage Code:

<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{ 
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>

</form>
</body>
</html>

Running a simple shell script as a cronjob

Try,

 # cat test.sh
 #!/bin/bash
 /bin/touch file.txt

cron as:

 * * * * * /bin/sh /home/myUser/scripts/test.sh

And you can confirm this by:

 # tailf /var/log/cron

Can two applications listen to the same port?

You can have one application listening on one port for one network interface. Therefore you could have:

  1. httpd listening on remotely accessible interface, e.g. 192.168.1.1:80
  2. another daemon listening on 127.0.0.1:80

Sample use case could be to use httpd as a load balancer or a proxy.

What does "while True" mean in Python?

while True mean infinite loop, this usually use by long process. you can change

while True:

with

while 1:

Java java.sql.SQLException: Invalid column index on preparing statement

As @TechSpellBound suggested remove the quotes around the ? signs. Then add a space character at the end of each row in your concatenated string. Otherwise the entire query will be sent as (using only part of it as an example) : .... WHERE bookings.booking_end < date ?OR bookings.booking_start > date ?GROUP BY ....

The ? and the OR needs to be seperated by a space character. Do it wherever needed in the query string.

How do I loop through rows with a data reader in C#?

Or you can try to access the columns directly by name:

while(dr.Read())
{
    string col1 = (string)dr["Value1"];
    string col2 = (string)dr["Value2"];
    string col3 = (string)dr["Value3"];
}

Safely override C++ virtual functions

As far as I know, can't you just make it abstract?

class parent {
public:
  virtual void handle_event(int something) const = 0 {
    // boring default code
  }
};

I thought I read on www.parashift.com that you can actually implement an abstract method. Which makes sense to me personally, the only thing it does is force subclasses to implement it, no one said anything about it not being allowed to have an implementation itself.

How to enable GZIP compression in IIS 7.5

Sometimes no matter what you do or follow whole internet posts. Try on the MIMETYPES of applicationhost.config of the server.

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/#configuration-sample

Returning a value from callback function in Node.js

Its undefined because, console.log(response) runs before doCall(urlToCall); is finished. You have to pass in a callback function aswell, that runs when your request is done.

First, your function. Pass it a callback:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        return callback(finalData);
    });
}

Now:

var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
    // Here you have access to your variable
    console.log(response);
})

@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.

How do I get a computer's name and IP address using VB.NET?

Label12.Text = "My ID : " + System.Net.Dns.GetHostByName(Net.Dns.GetHostName()).AddressList(0).ToString()

use this code, without any variable

Load JSON text into class object in c#

To create a json class off a string, copy the string.

In Visual Sudio, click Edit > Paste special > Paste Json as classes.

How to print all information from an HTTP request to the screen, in PHP

in addition, you can use get_headers(). it doesn't depend on apache..

print_r(get_headers());

How do I keep CSS floats in one line?

Solution 1:

display:table-cell (not widely supported)

Solution 2:

tables

(I hate hacks.)

Find PHP version on windows command line

This how I check php version

PS C:\Windows\system32> php -version

Result:

PHP 7.2.7 (cli) (built: Jun 19 2018 23:44:15) ( NTS MSVC15 (Visual C++ 2017) x86 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

PS C:\Windows\system32>

Best way to store passwords in MYSQL database

First off, md5 and sha1 have been proven to be vulnerable to collision attacks and can be rainbow tabled easily (when they see if you hash is the same in their database of common passwords).

There are currently two things that are secure enough for passwords that you can use.

The first is sha512. sha512 is a sub-version of SHA2. SHA2 has not yet been proven to be vulnerable to collision attacks and sha512 will generate a 512-bit hash. Here is an example of how to use sha512:

<?php
hash('sha512',$password);

The other option is called bcrypt. bcrypt is famous for its secure hashes. It's probably the most secure one out there and most customizable one too.

Before you want to start using bcrypt you need to check if your sever has it enabled, Enter this code:

<?php
if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
    echo "CRYPT_BLOWFISH is enabled!";
}else {
echo "CRYPT_BLOWFISH is not available";
}

If it returns that it is enabled then the next step is easy, All you need to do to bcrypt a password is (note: for more customizability you need to see this How do you use bcrypt for hashing passwords in PHP?):

crypt($password, $salt);

A salt is usually a random string that you add at the end of all your passwords when you hash them. Using a salt means if someone gets your database, they can not check the hashes for common passwords. Checking the database is called using a rainbow table. You should always use a salt when hashing!

Here are my proofs for the SHA1 and MD5 collision attack vulnerabilities:
http://www.schneier.com/blog/archives/2012/10/when_will_we_se.html, http://eprint.iacr.org/2010/413.pdf,
http://people.csail.mit.edu/yiqun/SHA1AttackProceedingVersion.pdf,
http://conf.isi.qut.edu.au/auscert/proceedings/2006/gauravaram06collision.pdf and
Understanding sha-1 collision weakness

Strip HTML from Text JavaScript

I made some modifications to original Jibberboy2000 script Hope it'll be usefull for someone

str = '**ANY HTML CONTENT HERE**';

str=str.replace(/<\s*br\/*>/gi, "\n");
str=str.replace(/<\s*a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<\s*\/*.+?>/ig, "\n");
str=str.replace(/ {2,}/gi, " ");
str=str.replace(/\n+\s*/gi, "\n\n");

CSS Selector for <input type="?"

Sorry, the short answer is no. CSS (2.1) will only mark up the elements of a DOM, not their attributes. You'd have to apply a specific class to each input.

Bummer I know, because that would be incredibly useful.

I know you've said you'd prefer CSS over JavaScript, but you should still consider using jQuery. It provides a very clean and elegant way of adding styles to DOM elements based on attributes.

What is an MDF file?

Just to make this absolutely clear for all:

A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.

This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.

To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.

To qualify the preferred naming conventions:

  • .mdf - Primary database data file.
  • .ndf - Other database data files i.e. non Primary.
  • .ldf - Log data file.

jQuery callback for multiple ajax calls

I found an easier way to do it without the need of extra methods that arrange a queue.

JS

$.ajax({
  type: 'POST',
  url: 'ajax1.php',
  data:{
    id: 1,
    cb:'method1'//declaration of callback method of ajax1.php
  },
  success: function(data){
  //catching up values
  var data = JSON.parse(data);
  var cb=data[0].cb;//here whe catching up the callback 'method1'
  eval(cb+"(JSON.stringify(data));");//here we calling method1 and pass all data
  }
});


$.ajax({
  type: 'POST',
  url: 'ajax2.php',
  data:{
    id: 2,
    cb:'method2'//declaration of callback method of ajax2.php
  },
  success: function(data){
  //catching up values
  var data = JSON.parse(data);
  var cb=data[0].cb;//here whe catching up the callback 'method2'
  eval(cb+"(JSON.stringify(data));");//here we calling method2 and pass all data
  }
});


//the callback methods
function method1(data){
//here we have our data from ajax1.php
alert("method1 called with data="+data);
//doing stuff we would only do in method1
//..
}

function method2(data){
//here we have our data from ajax2.php
alert("method2 called with data="+data);
//doing stuff we would only do in method2
//..
}

PHP (ajax1.php)

<?php
    //catch up callbackmethod
    $cb=$_POST['cb'];//is 'method1'

    $json[] = array(
    "cb" => $cb,
    "value" => "ajax1"
    );      

    //encoding array in JSON format
    echo json_encode($json);
?>

PHP (ajax2.php)

<?php
    //catch up callbackmethod
    $cb=$_POST['cb'];//is 'method2'

    $json[] = array(
    "cb" => $cb,
    "value" => "ajax2"
    );      

    //encoding array in JSON format
    echo json_encode($json);
?>

Move textfield when keyboard appears swift

struct MoveKeyboard {
    static let KEYBOARD_ANIMATION_DURATION : CGFloat = 0.3
    static let MINIMUM_SCROLL_FRACTION : CGFloat = 0.2;
    static let MAXIMUM_SCROLL_FRACTION : CGFloat = 0.8;
    static let PORTRAIT_KEYBOARD_HEIGHT : CGFloat = 216;
    static let LANDSCAPE_KEYBOARD_HEIGHT : CGFloat = 162;
}


  func textFieldDidBeginEditing(textField: UITextField) {
    let textFieldRect : CGRect = self.view.window!.convertRect(textField.bounds, fromView: textField)
    let viewRect : CGRect = self.view.window!.convertRect(self.view.bounds, fromView: self.view)

    let midline : CGFloat = textFieldRect.origin.y + 0.5 * textFieldRect.size.height
    let numerator : CGFloat = midline - viewRect.origin.y - MoveKeyboard.MINIMUM_SCROLL_FRACTION * viewRect.size.height
    let denominator : CGFloat = (MoveKeyboard.MAXIMUM_SCROLL_FRACTION - MoveKeyboard.MINIMUM_SCROLL_FRACTION) * viewRect.size.height
    var heightFraction : CGFloat = numerator / denominator

    if heightFraction < 0.0 {
        heightFraction = 0.0
    } else if heightFraction > 1.0 {
        heightFraction = 1.0
    }

    let orientation : UIInterfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
    if (orientation == UIInterfaceOrientation.Portrait || orientation == UIInterfaceOrientation.PortraitUpsideDown) {
        animateDistance = floor(MoveKeyboard.PORTRAIT_KEYBOARD_HEIGHT * heightFraction)
    } else {
        animateDistance = floor(MoveKeyboard.LANDSCAPE_KEYBOARD_HEIGHT * heightFraction)
    }

    var viewFrame : CGRect = self.view.frame
    viewFrame.origin.y -= animateDistance

    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(NSTimeInterval(MoveKeyboard.KEYBOARD_ANIMATION_DURATION))

    self.view.frame = viewFrame

    UIView.commitAnimations()
}


func textFieldDidEndEditing(textField: UITextField) {
    var viewFrame : CGRect = self.view.frame
    viewFrame.origin.y += animateDistance

    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)

    UIView.setAnimationDuration(NSTimeInterval(MoveKeyboard.KEYBOARD_ANIMATION_DURATION))

    self.view.frame = viewFrame

    UIView.commitAnimations()

}

And Lastly since we are using delegates methods

func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }

refactored from using objective-c http://www.cocoawithlove.com/2008/10/sliding-uitextfields-around-to-avoid.html

Plotting multiple lines, in different colors, with pandas dataframe

You could use groupby to split the DataFrame into subgroups according to the color:

for key, grp in df.groupby(['color']):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)

plt.legend(loc='best')
plt.show()

yields enter image description here

Run ScrollTop with offset of element by ID

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;   
if (!isNaN(top)) {
$("#app_scroler").click(function () {   
$('html, body').animate({
            scrollTop: top
        }, 100);
    });
}

if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;

Concept behind putting wait(),notify() methods in Object class

Answer to your first question is As every object in java has only one lock(monitor) andwait(),notify(),notifyAll() are used for monitor sharing thats why they are part of Object class rather than Threadclass.

Can not get a simple bootstrap modal to work

A simple way to use modals is with eModal!

Ex from github:

  1. Link to eModal.js <script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
  2. use eModal to display a modal for alert, ajax, prompt or confirm

    // Display an alert modal with default title (Attention)
    eModal.alert('You shall not pass!');
    

Extract file name from path, no matter what the os/path format

fname = str("C:\Windows\paint.exe").split('\\')[-1:][0]

this will return : paint.exe

change the sep value of the split function regarding your path or OS.

XOR operation with two strings in java

Pay attention:

A Java char corresponds to a UTF-16 code unit, and in some cases two consecutive chars (a so-called surrogate pair) are needed for one real Unicode character (codepoint).

XORing two valid UTF-16 sequences (i.e. Java Strings char by char, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)

The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.

Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF (plane 15) XOR U+10000 (plane 16) = U+1FFFFF (which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).

If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)


What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[] (or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).

Could not open ServletContext resource

Do not use classpath. This may cause problems with different ClassLoaders (container vs. application). WEB-INF is always the better choice.

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>

and

<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="location">
         <value>/WEB-INF/social.properties</value>
     </property>
</bean>

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

top nav bar blocking top content of the page

In my project derived from the MVC 5 tutorial I found that changing the body padding had no effect. The following worked for me:

@media screen and (min-width:768px) and (max-width:991px) {
    body {
        margin-top:100px;
    }
}
@media screen and (min-width:992px) and (max-width:1199px) {
    body {
        margin-top:50px;
    }
}

It resolves the cases where the navbar folds into 2 or 3 lines. This can be inserted into bootstrap.css anywhere after the lines body { margin: 0; }

HEAD and ORIG_HEAD in Git

From git reset

"pull" or "merge" always leaves the original tip of the current branch in ORIG_HEAD.

git reset --hard ORIG_HEAD

Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.

git reset --merge ORIG_HEAD

After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "git reset --hard ORIG_HEAD" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge" keeps your local changes.


Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
This is useful if you have problems with multiple commits, like running 'git am' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).

In addition, merge always sets '.git/ORIG_HEAD' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD'.


Note: from here

HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.

So HEAD is NOT a synonym for "current branch" everywhere already.

HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).

But it almost always means the "current commit".
It is the commit "git commit" builds on top of, and "git diff --cached" and "git status" compare against.
It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).

Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".

HEAD@{5.minutes.ago} could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".


git1.8.4 (July 2013) introduces introduced a new notation!
(Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.

Instead of typing four capital letters "HEAD", you can say "@" now,
e.g. "git log @".

See commit cdfd948

Typing 'HEAD' is tedious, especially when we can use '@' instead.

The reason for choosing '@' is that it follows naturally from the ref@op syntax (e.g. HEAD@{u}), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD'.

So now we can use 'git show @~1', and all that goody goodness.

Until now '@' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.

Initialize value of 'var' in C# to null

var variables still have a type - and the compiler error message says this type must be established during the declaration.

The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:

var x = (String)null;

Which is still "type inferred" and equivalent to:

String x = null;

The compiler will not accept var x = null because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null would "work" although it is of questionable usefulness.

Generally, when I can't use var's type inference correctly then

  1. I am at a place where it's best to declare the variable explicitly; or
  2. I should rewrite the code such that a valid value (with an established type) is assigned during the declaration.

The second approach can be done by moving code into methods or functions.

Mocking static methods with Mockito

Observation : When you call static method within a static entity, you need to change the class in @PrepareForTest.

For e.g. :

securityAlgo = MessageDigest.getInstance(SECURITY_ALGORITHM);

For the above code if you need to mock MessageDigest class, use

@PrepareForTest(MessageDigest.class)

While if you have something like below :

public class CustomObjectRule {

    object = DatatypeConverter.printHexBinary(MessageDigest.getInstance(SECURITY_ALGORITHM)
             .digest(message.getBytes(ENCODING)));

}

then, you'd need to prepare the class this code resides in.

@PrepareForTest(CustomObjectRule.class)

And then mock the method :

PowerMockito.mockStatic(MessageDigest.class);
PowerMockito.when(MessageDigest.getInstance(Mockito.anyString()))
      .thenThrow(new RuntimeException());

How to serialize an Object into a list of URL query parameters?

Object.toparams = function ObjecttoParams(obj) 
{
  var p = [];
  for (var key in obj) 
  {
    p.push(key + '=' + encodeURIComponent(obj[key]));
  }
  return p.join('&');
};

Dynamic variable names in Bash

Use an associative array, with command names as keys.

# Requires bash 4, though
declare -A magic_variable=()

function grep_search() {
    magic_variable[$1]=$( ls | tail -1 )
    echo ${magic_variable[$1]}
}

If you can't use associative arrays (e.g., you must support bash 3), you can use declare to create dynamic variable names:

declare "magic_variable_$1=$(ls | tail -1)"

and use indirect parameter expansion to access the value.

var="magic_variable_$1"
echo "${!var}"

See BashFAQ: Indirection - Evaluating indirect/reference variables.

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Is there anything like .NET's NotImplementedException in Java?

As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:

public class NotYetImplementedException extends RuntimeException
{
    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException()
    {
    }

    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException(String message)
    {
        super(message);
    }
}

This approach has the following benefits:

  1. When readers see NotYetImplementedException, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
  2. With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
  3. The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the import line (JDK 9 fixed this, though).

How to find the nearest parent of a Git branch?

git log -2 --pretty=format:'%d' --abbrev-commit | tail -n 1 | sed 's/\s(//g; s/,/\n/g';

(origin/parent-name, parent-name)

git log -2 --pretty=format:'%d' --abbrev-commit | tail -n 1 | sed 's/\s(//g; s/,/\n/g';

origin/parent-name

git log -2 --pretty=format:'%d' --abbrev-commit | tail -n 1 | sed 's/(.*,//g; s/)//';

parent-name

Is there an R function for finding the index of an element in a vector?

The function match works on vectors:

x <- sample(1:10)
x
# [1]  4  5  9  3  8  1  6 10  7  2
match(c(4,8),x)
# [1] 1 5

match only returns the first encounter of a match, as you requested. It returns the position in the second argument of the values in the first argument.

For multiple matching, %in% is the way to go:

x <- sample(1:4,10,replace=TRUE)
x
# [1] 3 4 3 3 2 3 1 1 2 2
which(x %in% c(2,4))
# [1]  2  5  9 10

%in% returns a logical vector as long as the first argument, with a TRUE if that value can be found in the second argument and a FALSE otherwise.

How to call an async method from a getter or setter?

You can use Task like this :

public int SelectedTab
        {
            get => selected_tab;
            set
            {
                selected_tab = value;

                new Task(async () =>
                {
                    await newTab.ScaleTo(0.8);
                }).Start();
            }
        }

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

Codeigniter LIKE with wildcard(%)

$this->db->like() automatically adds the %s and escapes the string. So all you need is

$this->db->like('title', $query);
$res = $this->db->get('film');

See the CI documentation for reference: CI 2, CI 3, CI 4

Python 3 print without parenthesis

In Python 3, print is a function, whereas it used to be a statement in previous versions. As @holdenweb suggested, use 2to3 to translate your code.

Google Chrome default opening position and size

Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.

Change placeholder text

This solution uses jQuery. If you want to use same placeholder text for all text inputs, you can use

$('input:text').attr('placeholder','Some New Text');

And if you want different placeholders, you can use the element's id to change placeholder

$('#element1_id').attr('placeholder','Some New Text 1');
$('#element2_id').attr('placeholder','Some New Text 2');

Compiler error "archive for required library could not be read" - Spring Tool Suite

This could be due to you have added spring-licence.txt file to your web app libraries.

I had similar issue and resolved after removing that text file. In libraries it will expect jar file only.

How to configure Fiddler to listen to localhost?

Replace localhost by lvh.me in your URL

For example if you had http://localhost:24448/HomePage.aspx

Change it to http://lvh.me:24448/HomePage.aspx

PHP Fatal error: Class 'PDO' not found

This error is caused by PDO not being available to PHP.

If you are getting the error on the command line, or not via the same interface your website uses for PHP, you are potentially invoking a different version of PHP, or utlising a different php.ini configuration file when checking phpinfo().

Ensure PDO is loaded, and the PDO drivers for your database are also loaded.

Python unittest passing arguments

If you want to use steffens21's approach with unittest.TestLoader, you can modify the original test loader (see unittest.py):

import unittest
from unittest import suite

class TestLoaderWithKwargs(unittest.TestLoader):
    """A test loader which allows to parse keyword arguments to the
       test case class."""
    def loadTestsFromTestCase(self, testCaseClass, **kwargs):
        """Return a suite of all tests cases contained in 
           testCaseClass."""
        if issubclass(testCaseClass, suite.TestSuite):
            raise TypeError("Test cases should not be derived from "\
                            "TestSuite. Maybe you meant to derive from"\ 
                            " TestCase?")
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']

        # Modification here: parse keyword arguments to testCaseClass.
        test_cases = []
        for test_case_name in testCaseNames:
            test_cases.append(testCaseClass(test_case_name, **kwargs))
        loaded_suite = self.suiteClass(test_cases)

        return loaded_suite 

# call your test
loader = TestLoaderWithKwargs()
suite = loader.loadTestsFromTestCase(MyTest, extraArg=extraArg)
unittest.TextTestRunner(verbosity=2).run(suite)

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

While loop to test if a file exists in bash

If you are on linux and have inotify-tools installed, you can do this:

file=/tmp/list.txt
while [ ! -f "$file" ]
do
    inotifywait -qqt 2 -e create -e moved_to "$(dirname $file)"
done

This reduces the delay introduced by sleep while still polling every "x" seconds. You can add more events if you anticipate that they are needed.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

Get each line from textarea

Old tread...? Well, someone may bump into this...

Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you

Rather than using:

$values = explode("\n", $value_string);

Use a safer method like:

$values = preg_split('/[\n\r]+/', $value_string);

Bootstrap - dropdown menu not working?

putting

<script src="js/bootstrap.min.js"></script>    

file at the last after the

<script src="jq/jquery-2.1.1.min.js"></script>  solved this problem for me .

this is how i use write it now and no problem

<script src="jq/jquery-2.1.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>

Websocket onerror - how to read error description?

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.

SELECT using 'CASE' in SQL

Change to:

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    WHEN FRUIT = 'B' THEN 'BANANA'     
  END
FROM FRUIT_TABLE;

How can I read comma separated values from a text file in Java?

//lat=3434&lon=yy38&rd=1.0&| in that format o/p is displaying

public class ReadText {
    public static void main(String[] args) throws Exception {
        FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(f));
        String strline;
        StringBuffer sb = new StringBuffer();
        while ((strline = br.readLine()) != null)
        {
            String[] arraylist=StringUtils.split(strline, ",");
            if(arraylist.length == 2){
                sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");

            } else {
                System.out.println("Error: "+strline);
            }
        }
        System.out.println("Data: "+sb.toString());
    }
}

Reading Excel file using node.js

install exceljs and use the following code,

var Excel = require('exceljs');

var wb = new Excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'sample.xlsx');

wb.xlsx.readFile(filePath).then(function(){

    var sh = wb.getWorksheet("Sheet1");

    sh.getRow(1).getCell(2).value = 32;
    wb.xlsx.writeFile("sample2.xlsx");
    console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);

    console.log(sh.rowCount);
    //Get all the rows data [1st and 2nd column]
    for (i = 1; i <= sh.rowCount; i++) {
        console.log(sh.getRow(i).getCell(1).value);
        console.log(sh.getRow(i).getCell(2).value);
    }
});

Use of alloc init instead of new

Very old question, but I've written some example just for fun — maybe you'll find it useful ;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

In main function both statements:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

result in the same output:

2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating...
2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

.htaccess rewrite subdomain to directory

This redirects to the same folder to a subdomain:

.httaccess

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://domain\.com/subdomains/%1

center image in div with overflow hidden

just make sure how you are using image through css background use backgroud image position like background: url(your image path) no-repeat center center; automatically it wil align center to the screen.

varbinary to string on SQL Server

Try this

SELECT CONVERT(varchar(5000), yourvarbincolumn, 0)

Algorithm for Determining Tic Tac Toe Game Over

I am late the party, but I wanted to point out one benefit that I found to using a magic square, namely that it can be used to get a reference to the square that would cause the win or loss on the next turn, rather than just being used to calculate when a game is over.

Take this magic square:

4 9 2
3 5 7
8 1 6

First, set up an scores array that is incremented every time a move is made. See this answer for details. Now if we illegally play X twice in a row at [0,0] and [0,1], then the scores array looks like this:

[7, 0, 0, 4, 3, 0, 4, 0];

And the board looks like this:

X . .
X . .
. . .

Then, all we have to do in order to get a reference to which square to win/block on is:

get_winning_move = function() {
  for (var i = 0, i < scores.length; i++) {
    // keep track of the number of times pieces were added to the row
    // subtract when the opposite team adds a piece
    if (scores[i].inc === 2) {
      return 15 - state[i].val; // 8
    }
  }
}

In reality, the implementation requires a few additional tricks, like handling numbered keys (in JavaScript), but I found it pretty straightforward and enjoyed the recreational math.

Starting Docker as Daemon on Ubuntu

I had a same issue on ubuntu 14.04 Here is a solution

sudo service docker start

or you can list images

docker images

Rendering HTML in a WebView with custom CSS

I assume that your style-sheet "style.css" is already located in the assets-folder

  1. load the web-page with jsoup:

    doc = Jsoup.connect("http://....").get();
    
  2. remove links to external style-sheets:

    // remove links to external style-sheets
    doc.head().getElementsByTag("link").remove();
    
  3. set link to local style-sheet:

    // set link to local stylesheet
    // <link rel="stylesheet" type="text/css" href="style.css" />
    doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
    
  4. make string from jsoup-doc/web-page:

    String htmldata = doc.outerHtml();
    
  5. display web-page in webview:

    WebView webview = new WebView(this);
    setContentView(webview);
    webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
    

Command copy exited with code 4 when building - Visual Studio restart solves it

To expand on rhughes answer,

The robocopy works beautifully, just incase you need to include sub directories you can use /e to include subs and copy empty directories or /s to include subs excluding empty directories.

Also robocopy will report back a few things like if new files were copied, this will cause VS to complain since anything above 0 is a failure and robocopy will return 1 if new files have been found. Its worth to mention that robocopy first compares the Source/Dest and only copies the updated/new files.

To get around this use:

(robocopy "$(SolutionDir)Solution Items\References\*.dll" "$(TargetDir)") ^& IF %ERRORLEVEL% LEQ 4 exit /B 0

onclick="location.href='link.html'" does not load page in Safari

I had the same error. Make sure you don't have any <input>, <select>, etc. name="location".

How to replace a string in a SQL Server Table Column

If target column type is other than varchar/nvarchar like text, we need to cast the column value as string and then convert it as:

update URL_TABLE
set Parameters = REPLACE ( cast(Parameters as varchar(max)), 'india', 'bharat')
where URL_ID='150721_013359670'

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Difference between session affinity and sticky session?

As I've always heard the terms used in a load-balancing scenario, they are interchangeable. Both mean that once a session is started, the same server serves all requests for that session.

How to set child process' environment variable in Makefile

Make variables are not exported into the environment of processes make invokes... by default. However you can use make's export to force them to do so. Change:

test: NODE_ENV = test

to this:

test: export NODE_ENV = test

(assuming you have a sufficiently modern version of GNU make >= 3.77 ).

How to convert SQL Query result to PANDAS Data Structure?

Edit: Mar. 2015

As noted below, pandas now uses SQLAlchemy to both read from (read_sql) and insert into (to_sql) a database. The following should work

import pandas as pd

df = pd.read_sql(sql, cnxn)

Previous answer: Via mikebmassey from a similar question

import pyodbc
import pandas.io.sql as psql

cnxn = pyodbc.connect(connection_info) 
cursor = cnxn.cursor()
sql = "SELECT * FROM TABLE"

df = psql.frame_query(sql, cnxn)
cnxn.close()

Retrofit and GET using parameters

@QueryMap worked for me instead of FieldMap

If you have a bunch of GET params, another way to pass them into your url is a HashMap.

class YourActivity extends Activity {

private static final String BASEPATH = "http://www.example.com";

private interface API {
    @GET("/thing")
    void getMyThing(@QueryMap Map<String, String> params, new Callback<String> callback);
}

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.your_layout);

   RestAdapter rest = new RestAdapter.Builder().setEndpoint(BASEPATH).build();
   API service = rest.create(API.class);

   Map<String, String> params = new HashMap<String, String>();
   params.put("key1", "val1");
   params.put("key2", "val2");
   // ... as much as you need.

   service.getMyThing(params, new Callback<String>() {
       // ... do some stuff here.
   });
}
}

The URL called will be http://www.example.com/thing/?key1=val1&key2=val2

How can I solve a connection pool problem between ASP.NET and SQL Server?

Upon installing .NET Framework v4.6.1 our connections to a remote database immediately started timing out due to this change.

To fix simply add the parameter TransparentNetworkIPResolution in the connection string and set it to false:

Server=myServerName;Database=myDataBase;Trusted_Connection=True;TransparentNetworkIPResolution=False

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

How to make a gap between two DIV within the same column

I'm assuming you want the two boxes in the sidebar to be next to each other horizontally, so something like this fiddle? That uses inline-block, or you could achieve the same thing by floating the boxes.

EDIT - I've amended the above fiddle to do what I think you want, though your question could really do with being clearer. Similar to @balexandre's answer, though I've used :nth-child(odd) instead. Both will work, or if support for older browsers is important you'll have to stick with another helper class.

How to increase Maximum Upload size in cPanel?

On CPanel 64.0.40 (I didn't try any other version): Go in "Software" then "Select PHP Version" then "Switch To PHP Options" then upload_max_filesize => click on the value and select the one you prefer :) It's super hidden for such a critical option...

Restore LogCat window within Android Studio

Search Android Monitor tab bottom of android studio screen. Click on it. It will display a window and there is a tab call logcat. If you can't see Android monitor tab, click Alt+G.

Jquery .on('scroll') not firing the event while scrolling

Another option could be:

$("#ulId").scroll(function () { console.log("Event Fired"); })

Reference: Here

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

Spring @Autowired and @Qualifier

The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.

The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean. This annotation can also be applied on constructor arguments or method parameters.

Ex:-

public interface Vehicle {
     public void start();
     public void stop();
}

There are two beans, Car and Bike implements Vehicle interface

@Component(value="car")
public class Car implements Vehicle {

     @Override
     public void start() {
           System.out.println("Car started");
     }

     @Override
     public void stop() {
           System.out.println("Car stopped");
     }
 }

@Component(value="bike")
public class Bike implements Vehicle {

     @Override
     public void start() {
          System.out.println("Bike started");
     }

     @Override
     public void stop() {
          System.out.println("Bike stopped");
     }
}

Injecting Bike bean in VehicleService using @Autowired with @Qualifier annotation. If you didn't use @Qualifier, it will throw NoUniqueBeanDefinitionException.

@Component
public class VehicleService {

    @Autowired
    @Qualifier("bike")
    private Vehicle vehicle;

    public void service() {
         vehicle.start();
         vehicle.stop();
    }
}

Reference:- @Qualifier annotation example

Sorting an array in C?

The best sorting technique of all generally depends upon the size of an array. Merge sort can be the best of all as it manages better space and time complexity according to the Big-O algorithm (This suits better for a large array).

React Native: How to select the next TextInput after pressing the "next" keyboard button?

<TextInput placeholder="Nombre"
    ref="1"
    editable={true}
    returnKeyType="next"
    underlineColorAndroid={'#4DB6AC'}
    blurOnSubmit={false}
    value={this.state.First_Name}
    onChangeText={First_Name => this.setState({ First_Name })}
    onSubmitEditing={() => this.focusNextField('2')}
    placeholderTextColor="#797a7a" style={{ marginBottom: 10, color: '#808080', fontSize: 15, width: '100%', }} />

<TextInput placeholder="Apellido"
    ref="2"
    editable={true}
    returnKeyType="next"
    underlineColorAndroid={'#4DB6AC'}
    blurOnSubmit={false}
    value={this.state.Last_Name}
    onChangeText={Last_Name => this.setState({ Last_Name })}
    onSubmitEditing={() => this.focusNextField('3')}
    placeholderTextColor="#797a7a" style={{ marginBottom: 10, color: '#808080', fontSize: 15, width: '100%', }} />

and add method

focusNextField(nextField) {
    this.refs[nextField].focus();
}

How to make an embedded video not autoplay

Try replacing your movie param line with

<param name="movie" value="untitled_skin.swf&autoStart=false">

Create dataframe from a matrix

I've found the following "cheat" to work very neatly and error-free

> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary

Et voila!

Bootstrap css hides portion of container below navbar navbar-fixed-top

i solved it using jquery

_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function(e) {_x000D_
   var h = $('nav').height() + 20;_x000D_
   $('body').animate({ paddingTop: h });_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

Choose File Dialog

I have implemented the Samsung File Selector Dialog, it provides the ability to open, save file, file extension filter, and create new directory in the same dialog I think it worth trying Here is the Link you have to log in to Samsung developer site to view the solution

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

Convert List<String> to List<Integer> directly

Why don't you use stream to convert List of Strings to List of integers? like below

List<String> stringList = new ArrayList<String>(Arrays.asList("10", "30", "40",
            "50", "60", "70"));
List<Integer> integerList = stringList.stream()
            .map(Integer::valueOf).collect(Collectors.toList());

complete operation could be something like this

String s = "AttributeGet:1,16,10106,10111";
List<Integer> integerList = (s.startsWith("AttributeGet:")) ?
    Arrays.asList(s.replace("AttributeGet:", "").split(","))
    .stream().map(Integer::valueOf).collect(Collectors.toList())
    : new ArrayList<Integer>();

How do I copy a hash in Ruby?

If you're using Rails you can do:

h1 = h0.deep_dup

http://apidock.com/rails/Hash/deep_dup

How to get line count of a large file cheaply in Python?

You can't get any better than that.

After all, any solution will have to read the entire file, figure out how many \n you have, and return that result.

Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don't use unnecessary memory, but it looks like you have that covered.

How to convert a number to string and vice versa in C++

I stole this convienent class from somewhere here at StackOverflow to convert anything streamable to a string:

// make_string
class make_string {
public:
  template <typename T>
  make_string& operator<<( T const & val ) {
    buffer_ << val;
    return *this;
  }
  operator std::string() const {
    return buffer_.str();
  }
private:
  std::ostringstream buffer_;
};

And then you use it as;

string str = make_string() << 6 << 8 << "hello";

Quite nifty!

Also I use this function to convert strings to anything streamable, althrough its not very safe if you try to parse a string not containing a number; (and its not as clever as the last one either)

// parse_string
template <typename RETURN_TYPE, typename STRING_TYPE>
RETURN_TYPE parse_string(const STRING_TYPE& str) {
  std::stringstream buf;
  buf << str;
  RETURN_TYPE val;
  buf >> val;
  return val;
}

Use as:

int x = parse_string<int>("78");

You might also want versions for wstrings.

Regular expression for decimal number

^[0-9]([.,][0-9]{1,3})?$

It allows:

0
1
1.2
1.02
1.003
1.030
1,2
1,23
1,234

BUT NOT:

.1
,1
12.1
12,1
1.
1,
1.2345
1,2345

How to fill in proxy information in cntlm config file?

The solution takes two steps!

First, complete the user, domain, and proxy fields in cntlm.ini. The username and domain should probably be whatever you use to log in to Windows at your office, eg.

Username            employee1730
Domain              corporate
Proxy               proxy.infosys.corp:8080

Then test cntlm with a command such as

cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk

It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini, eg:

Auth            NTLM
PassNT          A2A7104B1CE00000000000000007E1E1
PassLM          C66000000000000000000000008060C8

Finally, set the http_proxy environment variable in Windows (assuming you didn't change with the Listen field which by default is set to 3128) to the following

http://localhost:3128

JavaScript - onClick to get the ID of the clicked button

Although it's 8+ years late, in reply to @Amc_rtty, to get dynamically generated IDs from (my) HTML, I used the index of the php loop to increment the button IDs. I concatenated the same indices to the ID of the input element, hence I ended up with id="tableview1" and button id="1" and so on.

$tableView .= "<td><input type='hidden' value='http://".$_SERVER['HTTP_HOST']."/sql/update.php?id=".$mysql_rows[0]."&table=".$theTable."'id='tableview".$mysql_rows[0]."'><button type='button' onclick='loadDoc(event)' id='".$mysql_rows[0]."'>Edit</button></td>";

In the javascript, I stored the button click in a variable and added it to the element.

function loadDoc(e) {
  var btn = e.target.id;
  var xhttp = new XMLHttpRequest();
  var page = document.getElementById("tableview"+btn).value;
  
  //other Ajax stuff
  }

Pure CSS animation visibility with delay

You can play with delay prop of animation, just set visibility:visible after a delay, demo:

_x000D_
_x000D_
@keyframes delayedShow {_x000D_
  to {_x000D_
    visibility: visible;_x000D_
  }_x000D_
}_x000D_
_x000D_
.delayedShow{_x000D_
  visibility: hidden;_x000D_
  animation: 0s linear 2.3s forwards delayedShow ;_x000D_
}
_x000D_
So, Where are you?_x000D_
_x000D_
<div class="delayedShow">_x000D_
  Hey, I'm here!_x000D_
</div>
_x000D_
_x000D_
_x000D_

Add multiple items to already initialized arraylist in java

Collections.addAll is a varargs method which allows us to add any number of items to a collection in a single statement:

List<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5);

It can also be used to add array elements to a collection:

Integer[] arr = ...;
Collections.addAll(list, arr);

fatal: early EOF fatal: index-pack failed

Tangentially related and only useful in case you have no root access and manually extract Git from an RPM (with rpm2cpio) or other package (.deb, ..) into a subfolder. Typical use case: you try to use a newer version of Git over the outdated one on a corporate server.

If git clone fails with fatal: index-pack failed without early EOF mention but instead a help message about usage: git index-pack, there is a version mismatch and you need to run git with the --exec-path parameter:

git --exec-path=path/to/subfoldered/git/usr/bin/git clone <repo>

In order to have this happen automatically, specify in your ~/.bashrc:

export GIT_EXEC_PATH=path/to/subfoldered/git/usr/libexec

C - casting int to char and append char to char

You can use itoa function to convert the integer to a string.

You can use strcat function to append characters in a string at the end of another string.

If you want to convert a integer to a character, just do the following -

int a = 65;
char c = (char) a;

Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned in this case (though you may still lose data).

To do a light reading about type conversion, go here.

If you are still having trouble, comment on this answer.

Edit

Go here for a more suitable example of joining characters.

Also some more useful link is given below -

  1. http://www.cplusplus.com/reference/clibrary/cstring/strncat/
  2. http://www.cplusplus.com/reference/clibrary/cstring/strcat/

Second Edit

char msg[200];
int msgLength;
char rankString[200];

........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id

strncat( msg, rankString, (200 - msgLength) );  // msg now contains previous msg + id

// You may loose some portion of id if message length + id string length is greater than 200

Third Edit

Go to this link. Here you will find an implementation of itoa. Use that instead.

Create SQL script that create database and tables

In SQL Server Management Studio you can right click on the database you want to replicate, and select "Script Database as" to have the tool create the appropriate SQL file to replicate that database on another server. You can repeat this process for each table you want to create, and then merge the files into a single SQL file. Don't forget to add a using statement after you create your Database but prior to any table creation.

In more recent versions of SQL Server you can get this in one file in SSMS.

  1. Right click a database.
  2. Tasks
  3. Generate Scripts

This will launch a wizard where you can script the entire database or just portions. There does not appear to be a T-SQL way of doing this.

Generate SQL Server Scripts

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.

How to change css property using javascript

Just for the info, this can be done with CSS only with just minor HTML and CSS changes

HTML:

<div class="left">
    Hello
</div>
<div class="right">
    Hello2
</div>
<div class="center">
       <div class="left1">
           Bye
    </div>
       <div class="right1">
           Bye1
    </div>    
</div>

CSS:

.left, .right{
    margin:10px;
    float:left;
    border:1px solid red;
    height:60px;
    width:60px
}
.left:hover, .right:hover{
    border:1px solid blue;
}
.right{
     float :right;
}
.center{
    float:left;
    height:60px;
    width:160px
}

.center .left1, .center .right1{
    margin:10px;
    float:left;
    border:1px solid green;
    height:60px;
    width:58px;
    display:none;
}
.left:hover ~ .center .left1 {
    display:block;
}

.right:hover ~ .center .right1 {
    display:block;
}

and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/

Dynamically add script tag with src that may include document.write

You can try following code snippet.

function addScript(attribute, text, callback) {
    var s = document.createElement('script');
    for (var attr in attribute) {
        s.setAttribute(attr, attribute[attr] ? attribute[attr] : null)
    }
    s.innerHTML = text;
    s.onload = callback;
    document.body.appendChild(s);
}

addScript({
    src: 'https://www.google.com',
    type: 'text/javascript',
    async: null
}, '<div>innerHTML</div>', function(){});

jQuery Mobile how to check if button is disabled?

Faced with the same issue when trying to check if a button is disabled. I've tried a variety of approaches, such as btn.disabled, .is(':disabled'), .attr('disabled'), .prop('disabled'). But no one works for me.

Some, for example .disabled or .is(':disabled') returned undefined and other like .attr('disabled') returned the wrong result - false when the button was actually disabled.

But only one technique works for me: .is('[disabled]') (with square brackets).

So to determine if a button is disabled try this:

$("#myButton").is('[disabled]');

bash: pip: command not found

Latest update 2021.

In Ubuntu 20 64bit works fine for me.

Installation of python3

sudo apt install python3

Pip Installation

sudo apt install python3-pip

Add following alias in $HOME/.bash_aliases in some cases file may be hidden.

alias pip="/usr/bin/python3 -m pip "

Refresh current terminal session.

. ~/.profile

  • check pip usage: pip
  • Install a package: pip install {{package_name}}

extra info

to get Home path

echo $HOME

you will get your home path.

What's the best way to join on the same table twice?

My problem was to display the record even if no or only one phone number exists (full address book). Therefore I used a LEFT JOIN which takes all records from the left, even if no corresponding exists on the right. For me this works in Microsoft Access SQL (they require the parenthesis!)

SELECT t.PhoneNumber1, t.PhoneNumber2, t.PhoneNumber3
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2, t3.someOtherFieldForPhone3
FROM 
(
 (
  Table1 AS t LEFT JOIN Table2 AS t3 ON t.PhoneNumber3 = t3.PhoneNumber
 )
 LEFT JOIN Table2 AS t2 ON t.PhoneNumber2 = t2.PhoneNumber
)
LEFT JOIN Table2 AS t1 ON t.PhoneNumber1 = t1.PhoneNumber;

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

This code will prevent the modal from closing if you click outside the modal.

   $(document).ready(function () {
    $('#myModal').modal({
           backdrop: 'static',
           keyboard: false
    })
   });

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Disclaimer: While the top answer is probably a better solution, as a beginner it's a lot to take in when all you want is something very simple. This is intended as a more direct answer to your original question "How can I select certain elements in React"

I think the confusion in your question is because you have React components which you are being passed the id "Progress1", "Progress2" etc. I believe this is not setting the html attribute 'id', but the React component property. e.g.

class ProgressBar extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            id: this.props.id    <--- ID set from <ProgressBar id="Progress1"/>
        }
    }        
}

As mentioned in some of the answers above you absolutely can use document.querySelector inside of your React app, but you have to be clear that it is selecting the html output of your components' render methods. So assuming your render output looks like this:

render () {
    const id = this.state.id
    return (<div id={"progress-bar-" + id}></div>)
}

Then you can elsewhere do a normal javascript querySelector call like this:

let element = document.querySelector('#progress-bar-Progress1')

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

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

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

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

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

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

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

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

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

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

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

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

Batch file to copy files from one folder to another folder

If you want to copy file not using absolute path, relative path in other words:

Don't forget to write backslash in the path AND NOT slash

Example:

copy children-folder\file.something .\other-children-folder

PS: absolute path can be retrieved using these wildcards called "batch parameters"

@echo off
echo %%~dp0 is "%~dp0"
echo %%0 is "%0"
echo %%~dpnx0 is "%~dpnx0"
echo %%~f1 is "%~f1"
echo %%~dp0%%~1 is "%~dp0%~1"

Check documentation here about copy: https://technet.microsoft.com/en-us/library/bb490886.aspx

And also here for batch parameters documentation: https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

How can I make an "are you sure" prompt in a Windows batchfile?

You can consider using a UI confirmation.

With yesnopopup.bat

@echo off

for /f "tokens=* delims=" %%# in ('yesnopopup.bat') do (
    set "result=%%#"
)

if /i result==no (
    echo user rejected the script
    exit /b 1
) 

echo continue

rem --- other commands --

the user will see the following and depending on the choice the script will continue:

enter image description here

with absolutely the same script you can use also iexpYNbutton.bat which will produce similar popup.

With buttons.bat you can try the following script:

@echo off

for /f "tokens=* delims=" %%# in ('buttons.bat "Yep!" "Nope!" ') do (
    set "result=%%#"
)

if /i result==2 (
    echo user rejected the script
    exit /b 1
) 

echo continue

rem --- other commands --

and the user will see:

enter image description here

How do you create different variable names while in a loop?

Dictionary can contain values and values can be added by using update() method. You want your system to create variables, so you should know where to keep.

variables = {}
break_condition= True # Dont forget to add break condition to while loop if you dont want your system to go crazy.
name = “variable”
i = 0 
name = name + str(i) #this will be your variable name.
while True:
    value = 10 #value to assign
    variables.update(
                  {name:value})
    if break_condition == True:
        break

Using %f with strftime() in Python to get microseconds

When the "%f" for micro seconds isn't working, please use the following method:

import datetime

def getTimeStamp():
    dt = datetime.datetime.now()
    return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)

Converting unix time into date-time via excel

TLDR

=(A1/86400)+25569

...and the format of the cell should be date.

If it doesn't work for you

  • If you get a number you forgot to format the output cell as a date.
  • If you get ##### you probably don't have a real Unix time. Check your timestamps in https://www.epochconverter.com/. Try to divide your input by 10, 100, 1000 or 10000**
  • You work with timestamps outside Excel's (very extended) limits.
  • You didn't replace A1 with the cell containing the timestamp ;-p

Explanation

Unix system represent a point in time as a number. Specifically the number of seconds* since a zero-time called the Unix epoch which is 1/1/1970 00:00 UTC/GMT. This number of seconds is called "Unix timestamp" or "Unix time" or "POSIX time" or just "timestamp" and sometimes (confusingly) "Unix epoch".

In the case of Excel they chose a different zero-time and step (because who wouldn't like variety in technical details?). So Excel counts days since 24 hours before 1/1/0000 UTC/GMT. So 25569 corresponds to 1/1/1970 00:00 UTC/GMT and 25570 to 2/1/1970 00:00.

Now please note that we have 86400 seconds per day (24 hours x60 minutes each x60 seconds) and you can understand what this formula does: A1/86400 converts seconds to days and +25569 adjusts for the offset between what is time-zero for Unix and what is time-zero for Excel.

By the way DATE(1970,1,1) will helpfully return 25569 for you in case you forget all this so a more "self-documenting" way to write our formula is:

=A1/(24*60*60) + DATE(1970,1,1)

P.S.: All these were already present in other answers and comments just not laid out as I like them and I don't feel it's OK to edit the hell out of another answer.


*: that's almost correct because you should not count leap seconds

**: E.g. in the case of this question the number was number of milliseconds since the the Unix epoch.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Some security config and you are ready with swagger open to all

For Swagger V2

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

For Swagger V3

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/v3/api-docs",  
            "/swagger-resources/**", 
            "/swagger-ui/**",
             };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

As an alternative to everyone else's answers I've always done something like this:

List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
    if (someCondition) {
        toRemove.add(str);
    }
}
myArrayList.removeAll(toRemove);

This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

The tilde operator in Python

Besides being a bitwise complement operator, ~ can also help revert a boolean value, though it is not the conventional bool type here, rather you should use numpy.bool_.


This is explained in,

import numpy as np
assert ~np.True_ == np.False_

Reversing logical value can be useful sometimes, e.g., below ~ operator is used to cleanse your dataset and return you a column without NaN.

from numpy import NaN
import pandas as pd

matrix = pd.DataFrame([1,2,3,4,NaN], columns=['Number'], dtype='float64')
# Remove NaN in column 'Number'
matrix['Number'][~matrix['Number'].isnull()]

how to compare the Java Byte[] array?

Java byte compare,

public static boolean equals(byte[] a, byte[] a2) {
        if (a == a2)
            return true;
        if (a == null || a2 == null)
            return false;

        int length = a.length;
        if (a2.length != length)
            return false;

        for (int i = 0; i < length; i++)
            if (a[i] != a2[i])
                return false;

        return true;
    }

How to convert a table to a data frame

Short answer: using as.data.frame.matrix(mytable), as @Victor Van Hee suggested.

Long answer: as.data.frame(mytable) may not work on contingency tables generated by table() function, even if is.matrix(your_table) returns TRUE. It will still melt you table into the factor1 factor2 factori counts format.

Example:

> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)

> freq_t
   gear
cyl  3  4  5
  4  1  8  2
  6  2  4  1
  8 12  0  2

> is.matrix(freq_t)
[1] TRUE

> as.data.frame(freq_t)
  cyl gear Freq
1   4    3    1
2   6    3    2
3   8    3   12
4   4    4    8
5   6    4    4
6   8    4    0
7   4    5    2
8   6    5    1
9   8    5    2
> as.data.frame.matrix(freq_t)
   3 4 5
4  1 8 2
6  2 4 1
8 12 0 2

What does "The APR based Apache Tomcat Native library was not found" mean?

on debian 8 I fix it with installing libapr1-dev:

apt-get install libtcnative-1 libapr1-dev

How can I remove the last character of a string in python?

The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for

my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]

How can I easily convert DataReader to List<T>?

The simplest Solution :

var dt=new DataTable();
dt.Load(myDataReader);
list<DataRow> dr=dt.AsEnumerable().ToList();

INSERT VALUES WHERE NOT EXISTS

There is a great solution for this problem ,You can use the Merge Keyword of Sql

Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

You can check this before following, below is the sample

IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
    DROP TABLE dbo.TargetTable
GO

CREATE TABLE dbo.TargetTable
    (
    Id   INT NOT NULL,
    Name VARCHAR (255) NOT NULL,
    CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
    )
GO



INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO

INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO


Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp 
ON temp.Id = hba.Id
WHEN NOT matched THEN 
INSERT (Id, Name) VALUES (temp.Id, temp.Name);

How to Generate unique file names in C#

Here's an algorithm that returns a unique readable filename based on the original supplied. If the original file exists, it incrementally tries to append an index to the filename until it finds one that doesn't exist. It reads the existing filenames into a HashSet to check for collisions so it's pretty quick (a few hundred filenames per second on my machine), it's thread safe too, and doesn't suffer from race conditions.

For example, if you pass it test.txt, it will attempt to create files in this order:

test.txt
test (2).txt
test (3).txt

etc. You can specify the maximum attempts or just leave it at the default.

Here's a complete example:

class Program
{
    static FileStream CreateFileWithUniqueName(string folder, string fileName, 
        int maxAttempts = 1024)
    {
        // get filename base and extension
        var fileBase = Path.GetFileNameWithoutExtension(fileName);
        var ext = Path.GetExtension(fileName);
        // build hash set of filenames for performance
        var files = new HashSet<string>(Directory.GetFiles(folder));

        for (var index = 0; index < maxAttempts; index++)
        {
            // first try with the original filename, else try incrementally adding an index
            var name = (index == 0)
                ? fileName
                : String.Format("{0} ({1}){2}", fileBase, index, ext);

            // check if exists
            var fullPath = Path.Combine(folder, name);
            if(files.Contains(fullPath))
                continue;

            // try to create the file
            try
            {
                return new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write);
            }
            catch (DirectoryNotFoundException) { throw; }
            catch (DriveNotFoundException) { throw; }
            catch (IOException) 
            {
                // Will occur if another thread created a file with this 
                // name since we created the HashSet. Ignore this and just
                // try with the next filename.
            } 
        }

        throw new Exception("Could not create unique filename in " + maxAttempts + " attempts");
    }

    static void Main(string[] args)
    {
        for (var i = 0; i < 500; i++)
        {
            using (var stream = CreateFileWithUniqueName(@"c:\temp\", "test.txt"))
            {
                Console.WriteLine("Created \"" + stream.Name + "\"");
            }
        }

        Console.ReadKey();
    }
}

Vertically aligning text next to a radio button

This will give dead on alignment

input[type="radio"] {
  margin-top: 1px;
  vertical-align: top;
}

How to convert the following json string to java object?

Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 

Convert Mercurial project to Git

If you want to import your existing mercurial repository into a 'GitHub' repository, you can now simply use GitHub Importer available here [Login required]. No more messing around with fast-export etc. (although its a very good tool)

You will get all your commits, branches and tags intact. One more cool thing is that you can change the author's email-id as well. Check out below screenshots:

enter image description here

enter image description here

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Try using ReadAsStringAsync() instead.

 var foo = resp.Content.ReadAsStringAsync().Result;

The reason why it ReadAsAsync<string>() doesn't work is because ReadAsAsync<> will try to use one of the default MediaTypeFormatter (i.e. JsonMediaTypeFormatter, XmlMediaTypeFormatter, ...) to read the content with content-type of text/plain. However, none of the default formatter can read the text/plain (they can only read application/json, application/xml, etc).

By using ReadAsStringAsync(), the content will be read as string regardless of the content-type.

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

Webview load html from assets directory

You are getting the WebView before setting the Content view so the wv is probably null.

public class ViewWeb extends Activity {  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);
            setContentView(R.layout.webview);  
            WebView wv;  
            wv = (WebView) findViewById(R.id.webView1);  
            wv.loadUrl("file:///android_asset/aboutcertified.html");   // now it will not fail here
        }  
    }

_csv.Error: field larger than field limit (131072)

I just had this happen to me on a 'plain' CSV file. Some people might call it an invalid formatted file. No escape characters, no double quotes and delimiter was a semicolon.

A sample line from this file would look like this:

First cell; Second " Cell with one double quote and leading space;'Partially quoted' cell;Last cell

the single quote in the second cell would throw the parser off its rails. What worked was:

csv.reader(inputfile, delimiter=';', doublequote='False', quotechar='', quoting=csv.QUOTE_NONE)

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

Vertical align in bootstrap table

For me <td class="align-middle" >${element.imie}</td> works. I'm using Bootstrap v4.0.0-beta .

Maven – Always download sources and javadocs

I had to use KeyStore to Download the Jars. If you have any Certificate related issues you can use this approach:

mvn clean install dependency:sources -Dmaven.test.skip=true -Djavax.net.ssl.trustStore="Path_To_Your_KeyStore"

If you want to know how to create KeyStores, this is a very good link: Problems using Maven and SSL behind proxy

How do you stop MySQL on a Mac OS install?

For me it's working with a "mysql5"

sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

How to show all shared libraries used by executables in Linux?

  1. Use ldd to list shared libraries for each executable.
  2. Cleanup the output
  3. Sort, compute counts, sort by count

To find the answer for all executables in the "/bin" directory:

find /bin -type f -perm /a+x -exec ldd {} \; \
| grep so \
| sed -e '/^[^\t]/ d' \
| sed -e 's/\t//' \
| sed -e 's/.*=..//' \
| sed -e 's/ (0.*)//' \
| sort \
| uniq -c \
| sort -n

Change "/bin" above to "/" to search all directories.

Output (for just the /bin directory) will look something like this:

  1 /lib64/libexpat.so.0
  1 /lib64/libgcc_s.so.1
  1 /lib64/libnsl.so.1
  1 /lib64/libpcre.so.0
  1 /lib64/libproc-3.2.7.so
  1 /usr/lib64/libbeecrypt.so.6
  1 /usr/lib64/libbz2.so.1
  1 /usr/lib64/libelf.so.1
  1 /usr/lib64/libpopt.so.0
  1 /usr/lib64/librpm-4.4.so
  1 /usr/lib64/librpmdb-4.4.so
  1 /usr/lib64/librpmio-4.4.so
  1 /usr/lib64/libsqlite3.so.0
  1 /usr/lib64/libstdc++.so.6
  1 /usr/lib64/libz.so.1
  2 /lib64/libasound.so.2
  2 /lib64/libblkid.so.1
  2 /lib64/libdevmapper.so.1.02
  2 /lib64/libpam_misc.so.0
  2 /lib64/libpam.so.0
  2 /lib64/libuuid.so.1
  3 /lib64/libaudit.so.0
  3 /lib64/libcrypt.so.1
  3 /lib64/libdbus-1.so.3
  4 /lib64/libresolv.so.2
  4 /lib64/libtermcap.so.2
  5 /lib64/libacl.so.1
  5 /lib64/libattr.so.1
  5 /lib64/libcap.so.1
  6 /lib64/librt.so.1
  7 /lib64/libm.so.6
  9 /lib64/libpthread.so.0
 13 /lib64/libselinux.so.1
 13 /lib64/libsepol.so.1
 22 /lib64/libdl.so.2
 83 /lib64/ld-linux-x86-64.so.2
 83 /lib64/libc.so.6

Edit - Removed "grep -P"

How to delete a folder and all contents using a bat file in windows?

  1. del /s /q c:\where ever the file is\*
  2. rmdir /s /q c:\where ever the file is\
  3. mkdir c:\where ever the file is\

How to make padding:auto work in CSS?

auto is not a valid value for padding property, the only thing you can do is take out padding: 0; from the * declaration, else simply assign padding to respective property block.

If you remove padding: 0; from * {} than browser will apply default styles to your elements which will give you unexpected cross browser positioning offsets by few pixels, so it is better to assign padding: 0; using * and than if you want to override the padding, simply use another rule like

.container p {
   padding: 5px;
}

Calling a Function defined inside another function in Javascript

you can also just use return:

   function outer() { 
    function inner() {
        alert("hi");
    }
return inner();

}
outer();

MySQL connection not working: 2002 No such file or directory

Im using PHP-FPM or multiple php version in my server. On my case i update mysqli value since there is not mysql default socket parameter :

mysqli.default_socket

to :

mysql.default_socket = /path/to/mysql.sock

thanks to @Alec Gorge

Waiting on a list of Future

If you are using Java 8 and don't want to manipulate CompletableFutures, I have written a tool to retrieve results for a List<Future<T>> using streaming. The key is that you are forbidden to map(Future::get) as it throws.

public final class Futures
{

    private Futures()
    {}

    public static <E> Collector<Future<E>, Collection<E>, List<E>> present()
    {
        return new FutureCollector<>();
    }

    private static class FutureCollector<T> implements Collector<Future<T>, Collection<T>, List<T>>
    {
        private final List<Throwable> exceptions = new LinkedList<>();

        @Override
        public Supplier<Collection<T>> supplier()
        {
            return LinkedList::new;
        }

        @Override
        public BiConsumer<Collection<T>, Future<T>> accumulator()
        {
            return (r, f) -> {
                try
                {
                    r.add(f.get());
                }
                catch (InterruptedException e)
                {}
                catch (ExecutionException e)
                {
                    exceptions.add(e.getCause());
                }
            };
        }

        @Override
        public BinaryOperator<Collection<T>> combiner()
        {
            return (l1, l2) -> {
                l1.addAll(l2);
                return l1;
            };
        }

        @Override
        public Function<Collection<T>, List<T>> finisher()
        {
            return l -> {

                List<T> ret = new ArrayList<>(l);
                if (!exceptions.isEmpty())
                    throw new AggregateException(exceptions, ret);

                return ret;
            };

        }

        @Override
        public Set<java.util.stream.Collector.Characteristics> characteristics()
        {
            return java.util.Collections.emptySet();
        }
    }

This needs an AggregateException that works like C#'s

public class AggregateException extends RuntimeException
{
    /**
     *
     */
    private static final long serialVersionUID = -4477649337710077094L;

    private final List<Throwable> causes;
    private List<?> successfulElements;

    public AggregateException(List<Throwable> causes, List<?> l)
    {
        this.causes = causes;
        successfulElements = l;
    }

    public AggregateException(List<Throwable> causes)
    {
        this.causes = causes;
    }

    @Override
    public synchronized Throwable getCause()
    {
        return this;
    }

    public List<Throwable> getCauses()
    {
        return causes;
    }

    public List<?> getSuccessfulElements()
    {
        return successfulElements;
    }

    public void setSuccessfulElements(List<?> successfulElements)
    {
        this.successfulElements = successfulElements;
    }

}

This component acts exactly as C#'s Task.WaitAll. I am working on a variant that does the same as CompletableFuture.allOf (equivalento to Task.WhenAll)

The reason why I did this is that I am using Spring's ListenableFuture and don't want to port to CompletableFuture despite it is a more standard way

List of installed gems?

Gem::Specification.map {|a| a.name}

However, if your app uses Bundler it will return only list of dependent local gems. To get all installed:

def all_installed_gems
   Gem::Specification.all = nil    
   all = Gem::Specification.map{|a| a.name}  
   Gem::Specification.reset
   all
end

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

How can I split a delimited string into an array in PHP?

$string = '9,[email protected],8';
$array = explode(',', $string);

For more complicated situations, you may need to use preg_split.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

What's new in .NET Framework 4 Client Profile RTM explains many of the differences:

When to use NET4 Client Profile and when to use NET4 Full Framework?
NET4 Client Profile:
Always target NET4 Client Profile for all your client desktop applications (including Windows Forms and WPF apps).

NET4 Full framework:
Target NET4 Full only if the features or assemblies that your app need are not included in the Client Profile. This includes:

  • If you are building Server apps. Such as:
    o ASP.Net apps
    o Server-side ASMX based web services
  • If you use legacy client scenarios. Such as:
    o Use System.Data.OracleClient.dll which is deprecated in NET4 and not included in the Client Profile.
    o Use legacy Windows Workflow Foundation 3.0 or 3.5 (WF3.0 , WF3.5)
  • If you targeting developer scenarios and need tool such as MSBuild or need access to design assemblies such as System.Design.dll

However, as stated on MSDN, this is not relevant for >=4.5:

Starting with the .NET Framework 4.5, the Client Profile has been discontinued and only the full redistributable package is available. Optimizations provided by the .NET Framework 4.5, such as smaller download size and faster deployment, have eliminated the need for a separate deployment package. The single redistributable streamlines the installation process and simplifies your app's deployment options.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

The name does not exist in the namespace error in XAML

Dunno if this will help anyone else

I'm new to WPF and still a novice with VB.net - so I was assuming that getting this error was being caused by me doing summit silly........ suppose I was really! I've managed to get rid of it by moving my project from a shared drive to one of my local drives. Error's disappeared, project compiles perfectly no further issues - yet. Looks like VS2015 still has problems with projects held on a shared drive.

pandas dataframe groupby datetime month

Slightly alternative solution to @jpp's but outputting a YearMonth string:

df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))

res = df.groupby('YearMonth')['Values'].sum()

MySQL selecting yesterday's date

Query for the last weeks:

SELECT *
FROM dual
WHERE search_date BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE()

How to create Java gradle project

If you are using Eclipse, for an existing project (which has a build.gradle file) you can simply type gradle eclipse which will create all the Eclipse files and folders for this project.

It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.

How to run only one task in ansible playbook?

This can be easily done using the tags

The example of tags is defined below:

---
hosts: localhost
tasks:
 - name: Creating s3Bucket
   s3_bucket:
        name: ansiblebucket1234567890
   tags: 
       - createbucket

 - name: Simple PUT operation
   aws_s3:
       bucket: ansiblebucket1234567890
       object: /my/desired/key.txt
       src: /etc/ansible/myfile.txt
       mode: put
   tags:
      - putfile

 - name: Create an empty bucket
   aws_s3:
       bucket: ansiblebucket12345678901234
       mode: create
       permission: private
   tags:
       - emptybucket

to execute the tags we use the command

ansible-playbook creates3bucket.yml --tags "createbucket,putfile"

Can't use WAMP , port 80 is used by IIS 7.5

Left Click on wamp go to apache> select http.config Listen [::0]:8080

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

Parsing date string in Go

This might be super late, but this is for people that might stumble on this problem and might want to use external package for parsing date string.

I've tried looking for a libraries and I found this one:

https://github.com/araddon/dateparse

Example from the README:

package main

import (
    "flag"
    "fmt"
    "time"

    "github.com/apcera/termtables"
    "github.com/araddon/dateparse"
)

var examples = []string{
    "May 8, 2009 5:57:51 PM",
    "Mon Jan  2 15:04:05 2006",
    "Mon Jan  2 15:04:05 MST 2006",
    "Mon Jan 02 15:04:05 -0700 2006",
    "Monday, 02-Jan-06 15:04:05 MST",
    "Mon, 02 Jan 2006 15:04:05 MST",
    "Tue, 11 Jul 2017 16:28:13 +0200 (CEST)",
    "Mon, 02 Jan 2006 15:04:05 -0700",
    "Thu, 4 Jan 2018 17:53:36 +0000",
    "Mon Aug 10 15:44:11 UTC+0100 2015",
    "Fri Jul 03 2015 18:04:07 GMT+0100 (GMT Daylight Time)",
    "12 Feb 2006, 19:17",
    "12 Feb 2006 19:17",
    "03 February 2013",
    "2013-Feb-03",
    //   mm/dd/yy
    "3/31/2014",
    "03/31/2014",
    "08/21/71",
    "8/1/71",
    "4/8/2014 22:05",
    "04/08/2014 22:05",
    "4/8/14 22:05",
    "04/2/2014 03:00:51",
    "8/8/1965 12:00:00 AM",
    "8/8/1965 01:00:01 PM",
    "8/8/1965 01:00 PM",
    "8/8/1965 1:00 PM",
    "8/8/1965 12:00 AM",
    "4/02/2014 03:00:51",
    "03/19/2012 10:11:59",
    "03/19/2012 10:11:59.3186369",
    // yyyy/mm/dd
    "2014/3/31",
    "2014/03/31",
    "2014/4/8 22:05",
    "2014/04/08 22:05",
    "2014/04/2 03:00:51",
    "2014/4/02 03:00:51",
    "2012/03/19 10:11:59",
    "2012/03/19 10:11:59.3186369",
    // Chinese
    "2014?04?08?",
    //   yyyy-mm-ddThh
    "2006-01-02T15:04:05+0000",
    "2009-08-12T22:15:09-07:00",
    "2009-08-12T22:15:09",
    "2009-08-12T22:15:09Z",
    //   yyyy-mm-dd hh:mm:ss
    "2014-04-26 17:24:37.3186369",
    "2012-08-03 18:31:59.257000000",
    "2014-04-26 17:24:37.123",
    "2013-04-01 22:43",
    "2013-04-01 22:43:22",
    "2014-12-16 06:20:00 UTC",
    "2014-12-16 06:20:00 GMT",
    "2014-04-26 05:24:37 PM",
    "2014-04-26 13:13:43 +0800",
    "2014-04-26 13:13:44 +09:00",
    "2012-08-03 18:31:59.257000000 +0000 UTC",
    "2015-09-30 18:48:56.35272715 +0000 UTC",
    "2015-02-18 00:12:00 +0000 GMT",
    "2015-02-18 00:12:00 +0000 UTC",
    "2017-07-19 03:21:51+00:00",
    "2014-04-26",
    "2014-04",
    "2014",
    "2014-05-11 08:20:13,787",
    // mm.dd.yy
    "3.31.2014",
    "03.31.2014",
    "08.21.71",
    //  yyyymmdd and similar
    "20140601",
    // unix seconds, ms
    "1332151919",
    "1384216367189",
}

var (
    timezone = ""
)

func main() {
    flag.StringVar(&timezone, "timezone", "UTC", "Timezone aka `America/Los_Angeles` formatted time-zone")
    flag.Parse()

    if timezone != "" {
        // NOTE:  This is very, very important to understand
        // time-parsing in go
        loc, err := time.LoadLocation(timezone)
        if err != nil {
            panic(err.Error())
        }
        time.Local = loc
    }

    table := termtables.CreateTable()

    table.AddHeaders("Input", "Parsed, and Output as %v")
    for _, dateExample := range examples {
        t, err := dateparse.ParseLocal(dateExample)
        if err != nil {
            panic(err.Error())
        }
        table.AddRow(dateExample, fmt.Sprintf("%v", t))
    }
    fmt.Println(table.Render())
}

Microsoft.ACE.OLEDB.12.0 is not registered

The easiest solution I found was to specify excel version 97-2003 on the connection manager setup.

How can I sort an ArrayList of Strings in Java?

You can use TreeSet that automatically order list values:

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");

        TreeSet <String>tree = new TreeSet<String>();
        tree.add("aaa");
        tree.add("acbbb");
        tree.add("aab");
        tree.add("c");
        tree.add("a");

        Iterator iterator;
        iterator = tree.iterator();

        System.out.print("Tree set data: ");

        //Displaying the Tree set data
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
    }

}

I lastly add 'a' but last element must be 'c'.

Statistics: combinations in Python

That's probably as fast as you can do it in pure python for reasonably large inputs:

def choose(n, k):
    if k == n: return 1
    if k > n: return 0
    d, q = max(k, n-k), min(k, n-k)
    num =  1
    for n in xrange(d+1, n+1): num *= n
    denom = 1
    for d in xrange(1, q+1): denom *= d
    return num / denom

Android - Back button in the title bar

I saw so much complexes answer, so this is my code. Working here. You can achieve this in two ways.

1) Stardard android compatiblity

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NavUtils;

import android.view.MenuItem;
import android.view.View;

public class EditDiscoveryActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_discovery);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        /*toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });*/
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}

2) Use a custom icon

If you want to use code in comments you just have to add this file in drawable, called ic_arrow_white_24dp.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    <path
        android:fillColor="#ffffff"
        android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
    </vector>

With this code.

toolbar.setNavigationIcon(R.drawable.ic_arrow_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });

Hope it will helps some people here !

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How to Set AllowOverride all

I think you want to set it in your httpd.conf file instead of the .htaccess file.

I am not sure what OS you use, but this link for Ubuntu might give you some pointers on what to do.

https://help.ubuntu.com/community/EnablingUseOfApacheHtaccessFiles

How to center a label text in WPF?

You have to use HorizontalContentAlignment="Center" and! Width="Auto".

How to use sudo inside a docker container?

Unlike accepted answer, I use usermod instead.

Assume already logged-in as root in docker, and "fruit" is the new non-root username I want to add, simply run this commands:

apt update && apt install sudo
adduser fruit
usermod -aG sudo fruit

Remember to save image after update. Use docker ps to get current running docker's <CONTAINER ID> and <IMAGE>, then run docker commit -m "added sudo user" <CONTAINER ID> <IMAGE> to save docker image.

Then test with:

su fruit
sudo whoami

Or test by direct login(ensure save image first) as that non-root user when launch docker:

docker run -it --user fruit <IMAGE>
sudo whoami

You can use sudo -k to reset password prompt timestamp:

sudo whoami # No password prompt
sudo -k # Invalidates the user's cached credentials
sudo whoami # This will prompt for password

How to set timer in android?

I use this way:

String[] array={
       "man","for","think"
}; int j;

then below the onCreate

TextView t = findViewById(R.id.textView);

    new CountDownTimer(5000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {}

        @Override
        public void onFinish() {
            t.setText("I "+array[j] +" You");
            j++;
            if(j== array.length-1) j=0;
            start();
        }
    }.start();

it's easy way to solve this problem.

How can I remove a substring from a given String?

replace('regex', 'replacement');
replaceAll('regex', 'replacement');

In your example,

String hi = "Hello World!"
String no_o = hi.replaceAll("o", "");

How to locate the Path of the current project directory in Java (IDE)?

you can get the current project path use System.getProperty("user.dir")

in that method you write Key name to get your different-different paths, and if you don't know key, you can find all property use of System.getProperties() this method is return all property with key. and you can find key name manually from it.

and write System.getProperty("KEY NAME")

and get your require path.

Change the bullet color of list

I would recommend you to use background-image instead of default list.

.listStyle {
    list-style: none;
    background: url(image_path.jpg) no-repeat left center;
    padding-left: 30px;
    width: 20px;
    height: 20px;
}

Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:

.liststyle{
    list-style: none;
    margin: 0;
    padding: 0;
}
.liststyle:before {
    content: "• ";
    color: red; /* or whatever color you prefer */
    font-size: 20px;/* or whatever the bullet size you prefer */
}

List files in local git repo?

git ls-tree --full-tree -r HEAD and git ls-files return all files at once. For a large project with hundreds or thousands of files, and if you are interested in a particular file/directory, you may find more convenient to explore specific directories. You can do it by obtaining the ID/SHA-1 of the directory that you want to explore and then use git cat-file -p [ID/SHA-1 of directory]. For example:

git cat-file -p 14032aabd85b43a058cfc7025dd4fa9dd325ea97
100644 blob b93a4953fff68df523aa7656497ee339d6026d64    glyphicons-halflings-regular.eot
100644 blob 94fb5490a2ed10b2c69a4a567a4fd2e4f706d841    glyphicons-halflings-regular.svg
100644 blob 1413fc609ab6f21774de0cb7e01360095584f65b    glyphicons-halflings-regular.ttf
100644 blob 9e612858f802245ddcbf59788a0db942224bab35    glyphicons-halflings-regular.woff
100644 blob 64539b54c3751a6d9adb44c8e3a45ba5a73b77f0    glyphicons-halflings-regular.woff2

In the example above, 14032aabd85b43a058cfc7025dd4fa9dd325ea97 is the ID/SHA-1 of the directory that I wanted to explore. In this case, the result was that four files within that directory were being tracked by my Git repo. If the directory had additional files, it would mean those extra files were not being tracked. You can add files using git add <file>... of course.

Can an interface extend multiple interfaces in Java?

I think your confusion lies with multiple inheritance, in which it is bad practise to do so and in Java this is also not possible. However, implementing multiple interfaces is allowed in Java and it is also safe.

How to use goto statement correctly

Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.

How to silence output in a Bash script?

If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

AsyncTask Android example

private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        // Do code here

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();
        Toast toast = Toast.makeText(
                          getActivity(),
                          "An error is occurred due to some problem",
                          Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);
        toast.show();
    }

}

How to get DropDownList SelectedValue in Controller in MVC

MVC 5/6/Razor Pages

I think the best way is with strongly typed model, because Viewbags are being aboused too much already :)

MVC 5 example

Your Get Action

public async Task<ActionResult> Register()
    {
        var model = new RegistrationViewModel
        {
            Roles = GetRoles()
        };

        return View(model);
    }

Your View Model

    public class RegistrationViewModel
    {
        public string Name { get; set; }

        public int? RoleId { get; set; }

        public List<SelectListItem> Roles { get; set; }
    }    

Your View

    <div class="form-group">
        @Html.LabelFor(model => model.RoleId, htmlAttributes: new { @class = "col-form-label" })
        <div class="col-form-txt">
            @Html.DropDownListFor(model => model.RoleId, Model.Roles, "--Select Role--", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.RoleId, "", new { @class = "text-danger" })
        </div>
    </div>                                   

Your Post Action

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegistrationViewModel model)
    {
        if (ModelState.IsValid)
        {
            var _roleId = model.RoleId, 

MVC 6 It'll be a little different

Get Action

public async Task<ActionResult> Register()
    {
        var _roles = new List<SelectListItem>();
        _roles.Add(new SelectListItem
        {
           Text = "Select",
           Value = ""
        });
        foreach (var role in GetRoles())
        {
          _roles.Add(new SelectListItem
          {
            Text = z.Name,
            Value = z.Id
          });
        }

        var model = new RegistrationViewModel
        {
            Roles = _roles
        };

        return View(model);
    }

Your View Model will be same as MVC 5

Your View will be like

<select asp-for="RoleId" asp-items="Model.Roles"></select>

Post will also be same

Razor Pages

Your Page Model

[BindProperty]
public int User User { get; set; } = 1;

public List<SelectListItem> Roles { get; set; }

public void OnGet()
{
    Roles = new List<SelectListItem> {
        new SelectListItem { Value = "1", Text = "X" },
        new SelectListItem { Value = "2", Text = "Y" },
        new SelectListItem { Value = "3", Text = "Z" },
   };
}

<select asp-for="User" asp-items="Model.Roles">
    <option value="">Select Role</option>
</select>

I hope it may help someone :)

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

If you understand the difference between scope and session then it will be very easy to understand these methods.

A very nice blog post by Adam Anderson describes this difference:

Session means the current connection that's executing the command.

Scope means the immediate context of a command. Every stored procedure call executes in its own scope, and nested calls execute in a nested scope within the calling procedure's scope. Likewise, a SQL command executed from an application or SSMS executes in its own scope, and if that command fires any triggers, each trigger executes within its own nested scope.

Thus the differences between the three identity retrieval methods are as follows:

@@identity returns the last identity value generated in this session but any scope.

scope_identity() returns the last identity value generated in this session and this scope.

ident_current() returns the last identity value generated for a particular table in any session and any scope.

Test if a command outputs an empty string

All the answers given so far deal with commands that terminate and output a non-empty string.

Most are broken in the following senses:

  • They don't deal properly with commands outputting only newlines;
  • starting from Bash=4.4 most will spam standard error if the command output null bytes (as they use command substitution);
  • most will slurp the full output stream, so will wait until the command terminates before answering. Some commands never terminate (try, e.g., yes).

So to fix all these issues, and to answer the following question efficiently,

How can I test if a command outputs an empty string?

you can use:

if read -n1 -d '' < <(command_here); then
    echo "Command outputs something"
else
    echo "Command doesn't output anything"
fi

You may also add some timeout so as to test whether a command outputs a non-empty string within a given time, using read's -t option. E.g., for a 2.5 seconds timeout:

if read -t2.5 -n1 -d '' < <(command_here); then
    echo "Command outputs something"
else
    echo "Command doesn't output anything"
fi

Remark. If you think you need to determine whether a command outputs a non-empty string, you very likely have an XY problem.

Bitwise operation and usage

Sets

Sets can be combined using mathematical operations.

  • The union operator | combines two sets to form a new one containing items in either.
  • The intersection operator & gets items only in both.
  • The difference operator - gets items in the first set but not in the second.
  • The symmetric difference operator ^ gets items in either set, but not both.

Try It Yourself:

first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}

print(first | second)

print(first & second)

print(first - second)

print(second - first)

print(first ^ second)

Result:

{1, 2, 3, 4, 5, 6, 7, 8, 9}

{4, 5, 6}

{1, 2, 3}

{8, 9, 7}

{1, 2, 3, 7, 8, 9}

Using openssl to get the certificate from a server

With SNI

If the remote server is using SNI (that is, sharing multiple SSL hosts on a single IP address) you will need to send the correct hostname in order to get the right certificate.

openssl s_client -showcerts -servername www.example.com -connect www.example.com:443 </dev/null

Without SNI

If the remote server is not using SNI, then you can skip -servername parameter:

openssl s_client -showcerts -connect www.example.com:443 </dev/null


To view the full details of a site's cert you can use this chain of commands as well:

$ echo | \
    openssl s_client -servername www.example.com -connect www.example.com:443 2>/dev/null | \
    openssl x509 -text

How can I make a horizontal ListView in Android?

This might be a very late reply but it is working for us. We are using the same gallery provided by Android, just that, we have adjusted the left margin such a way that the screens left end is considered as Gallery's center. That really worked well for us.