Programs & Examples On #Postfix mta

QUESTIONS ABOUT POSTFIX ADMINISTRATION ARE OFF-TOPIC. Server admin questions may be asked on Server Fault. Postfix is a free, open-source, widely used cross-platform mail server (mail transfer agent), available on all common platforms.

What is the difference between ports 465 and 587?

SMTP protocol: smtps (port 465) v. msa (port 587)

Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.

Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.

Port 587 is for msa
It is almost like standard SMTP port. MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).


Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

Calculating and printing the nth prime number

public class prime{
    public static void main(String ar[])
    {
      int count;
      int no=0;
      for(int i=0;i<1000;i++){
        count=0;
        for(int j=1;j<=i;j++){

        if(i%j==0){
          count++;
         }
        }
        if(count==2){
          no++;
          if(no==Integer.parseInt(ar[0])){
            System.out.println(no+"\t"+i+"\t") ;
          }
        }
      }
    }
}

Windows Forms - Enter keypress activates submit button?

  if (e.KeyCode.ToString() == "Return")
  { 
      //do something
  }

java.lang.RuntimeException: Unable to start activity ComponentInfo

I had the same issue, I cleaned and rebuilt the project and it worked.

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

I managed to allow all my requisite sites with this header:

header("Content-Security-Policy: default-src *; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' stackexchange.com");                    

Android SQLite: Update Statement

You can use the code below.

String strFilter = "_id=" + Id;
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
myDB.update("titles", args, strFilter, null);

how to get selected row value in the KendoUI

I think it needs to be checked if any row is selected or not? The below code would check it:

var entityGrid = $("#EntitesGrid").data("kendoGrid");
            var selectedItem = entityGrid.dataItem(entityGrid.select());
            if (selectedItem != undefined)
                alert("The Row Is SELECTED");
            else
                alert("NO Row Is SELECTED")

How to shutdown a Spring Boot Application in a correct way?

If you are using the actuator module, you can shutdown the application via JMX or HTTP if the endpoint is enabled.

add to application.properties:

endpoints.shutdown.enabled=true

Following URL will be available:

/actuator/shutdown - Allows the application to be gracefully shutdown (not enabled by default).

Depending on how an endpoint is exposed, the sensitive parameter may be used as a security hint.

For example, sensitive endpoints will require a username/password when they are accessed over HTTP (or simply disabled if web security is not enabled).

From the Spring boot documentation

Convert float64 column to int64 in Pandas

consider using

df['column name'].astype('Int64')

nan will be changed to NaN

<script> tag vs <script type = 'text/javascript'> tag

<script> is HTML 5.

<script type='text/javascript'> is HTML 4.x (and XHTML 1.x).

<script language="javascript"> is HTML 3.2.

Is it different for different webservers?

No.

when I did an offline javascript test, i realised that i need the <script type = 'text/javascript'> tag.

That isn't the case. Something else must have been wrong with your test case.

Angular no provider for NameService

The error No provider for NameService is a common issue that many Angular2 beginners face.

Reason: Before using any custom service you first have to register it with NgModule by adding it to the providers list:

Solution:

@NgModule({
    imports: [...],
    providers: [CustomServiceName]
})

json_encode is returning NULL?

few day ago I have the SAME problem with 1 table.

Firstly try:

echo json_encode($rows);
echo json_last_error();  // returns 5 ?

If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.

Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.

You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...

Homebrew: Could not symlink, /usr/local/bin is not writable

This is because the current user is not permitted to write in that path. So, to change r/w (read/write) permissions you can either use 1. terminal, or 2. Graphical "Get Info" window.

1. Using Terminal

Google how to use chmod/chown (change mode/change owner) commands from terminal

2. Using graphical 'Get Info'

You can right click on the folder/file you want to change permissions of, then open Get Info which will show you a window like below at the bottom of which you can easily change r/w permissions: enter image description here

Remember to change the permission back to "read only" after your temporary work, if possible

concatenate variables

Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:

rem The retail files set
set FILES_SET="(*.exe *.dll"

rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"

rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%

rem Append the closing bracket
set FILES_SET=%FILES_SET%)

echo %FILES_SET%

Cheers...

Unable to find a @SpringBootConfiguration when doing a JpaTest

It work fo me

the package name of the above test class is changed to the same as the package name of the normal class.

change to this

Symbolicating iPhone App Crash Reports

I like to use Textwrangler to pinpoint errors in an original app upload binary rejection. (The crash data will be found in your itunesConnect account.) Using Sachin's method above I copy the original.crash to TextWrangler, then copy the symbolicatecrash file I've created to another TextWrangler file. Comparing the two files pinpoints differences. The symbolicatecrash file will have differences which point out the file and line number of problems.

Java 256-bit AES Password-Based Encryption

(Maybe helpful for others with a similar requirement)

I had a similar requirement to use AES-256-CBC encrypt and decrypt in Java.

To achieve (or specify) the 256-byte encryption/decryption, Java Cryptography Extension (JCE) policy should set to "Unlimited"

It can be set in the java.security file under $JAVA_HOME/jre/lib/security (for JDK) or $JAVA_HOME/lib/security (for JRE)

crypto.policy=unlimited

Or in the code as

Security.setProperty("crypto.policy", "unlimited");

Java 9 and later versions have this enabled by default.

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

One thing to watch out for (at least this tripped me up) was that I was removing the constraint from the wrong view. The constraint I was trying to remove was not a child constraint of my view so when I did

myView.removeConstraint(theConstraint)

it wasn't actually removing anything because I needed to call

myView.superView.removeConstraint(theConstraint)

since the constraint was technically sibling constraint of my view.

Defining a `required` field in Bootstrap

If wont work in case you have something like : novalidate="novalidate" attached to your form.

Volley JsonObjectRequest Post request not working

When you working with JsonObject request you need to pass the parameters right after you pass the link in the initialization , take a look on this code :

        HashMap<String, String> params = new HashMap<>();
        params.put("user", "something" );
        params.put("some_params", "something" );

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, "request_URL", new JSONObject(params), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

           // Some code 

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //handle errors
        }
    });


}

MS SQL Date Only Without Time

CONVERT(date, GETDATE()) and CONVERT(time, GETDATE()) works in SQL Server 2008. I'm uncertain about 2005.

DateTime.MinValue and SqlDateTime overflow

Here is what you can do. Though there are lot many ways to achieve it.

DateTime? d = null;    
if (txtBirthDate.Text == string.Empty)
    objinfo.BirthDate = d;
else
    objinfo.BirthDate =  DateTime.Parse(txtBirthDate.Text);

Note: This will work only if your database datetime column is Allow Null. Else you can define a standard minimum value for DateTime d.

MySQL and PHP - insert NULL rather than empty string

For some reason, radhoo's solution wouldn't work for me. When I used the following expression:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')?"NULL":("'".$val1."'")) . ", ".
    (($val2=='')?"NULL":("'".$val2."'")) . 
    ")";

'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')? :("'".$val1."'")) . ", ".
    (($val2=='')? :("'".$val2."'")) . 
    ")";

The blank resulted in the correct null (unquoted) being inserted into the query.

How could I create a function with a completion handler in Swift?

Say you have a download function to download a file from network, and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail
    }
})

Hope it helps.

object==null or null==object?

This trick supposed to prevent v = null kind of typos.

But Java allows only boolean expressions as if() conditions so that trick does not make much sense, compiler will find those typos anyway.

It is still valuable trick for C/C++ code though.

How to extend a class in python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I've done this to extend Python 2's str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

After which I can write in the code fed to the preprocessor:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

How can I extract a number from a string in JavaScript?

Here's a solt. that checks for no data

var someStr = 'abc'; // add 123 to string to see inverse

var thenum = someStr.match(/\d+/);

if (thenum != null )
{
    console.log(thenum[0]);
}
else
{
 console.log('no number');
}

Display names of all constraints for a table in Oracle SQL

maybe this can help:

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

cheers

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

How to use select/option/NgFor on an array of objects in Angular2

I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:

interface TestObject {
  name:string;
  value:number;
}

@Component({
  selector: 'app',
  template: `
      <h4>Select Object via 2-way binding</h4>

      <select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
      </select>

      <h4>You selected:</h4> {{selectedObject }}
  `,
  directives: [FORM_DIRECTIVES]
})
export class App {
  objArray:TestObject[];
  selectedObject:TestObject;
  constructor(){
    this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
    this.selectedObject = this.objArray[1];
  }
  updateSelectedValue(event:string): void{
    this.selectedObject = JSON.parse(event);
  }
}

How to access my localhost from another PC in LAN?

You have to edit httpd.conf and find this line: Listen 127.0.0.1:80

Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80

I used 192.167.137.1 as my LAN IP of Windows 7. Restart Apache and enjoy sharing.

What is the difference between declarative and imperative paradigm in programming?

The difference has mostly to do with the overall level of abstraction. With declarative, at some point, you're so far away from the individual steps that the program has a lot of latitude regarding how to get your result.


You could look at every piece of instruction as falling somewhere on a continuum:

Degree of abstraction:

Declarative <<=====|==================>> Imperative

Declarative Real World Example:

  1. Librarian, please check me out a copy of Moby Dick. (Librarian, at their discretion chooses the best method for performing the request)

Imperative Real World Example:

  1. Go into Library
  2. Find Book Organization System (Card Catalog - Old school)
  3. Research how to use Card Catalogs (You forgot too, right)
  4. Figure out how shelves are labeled and organized.
  5. Figure out how books are organized on a shelf.
  6. Cross-reference book location from card catalog with organization system to find said book.
  7. Take book to check-out system.
  8. Check out book.

Check if url contains string with JQuery

window.location is an object, not a string so you need to use window.location.href to get the actual string url

if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
    alert("found it");
}

How to test if a double is zero?

The safest way would be bitwise OR ing your double with 0. Look at this XORing two doubles in Java

Basically you should do if ((Double.doubleToRawLongBits(foo.x) | 0 ) ) (if it is really 0)

cvc-elt.1: Cannot find the declaration of element 'MyElement'

I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.

My initial wrong XSD was alike the following:

<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="XXX" type="XXX_TYPE"/>
    </xs:sequence>
</xs:complexType>

The good XSD format for my migration to succeed was the following:

<xs:element name="Document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="XXX"/>
        </xs:sequence>
    </xs:complexType>        
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>

And so on for every similar XSD nodes.

Removing the remembered login and password list in SQL Server Management Studio

Delete:

C:\Documents and Settings\%Your Username%\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat"

Start and stop a timer PHP

class Timer
{
    private $startTime = null;

    public function __construct($showSeconds = true)
    {
        $this->startTime = microtime(true);
        echo 'Working - please wait...' . PHP_EOL;
    }

    public function __destruct()
    {
        $endTime = microtime(true);
        $time = $endTime - $this->startTime;

        $hours = (int)($time / 60 / 60);
        $minutes = (int)($time / 60) - $hours * 60;
        $seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
        $timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));

        echo 'Job finished in ' . $timeShow . PHP_EOL;
    }
}

$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in h:m:s"

Retrieving subfolders names in S3 bucket from boto3

The AWS cli does this (presumably without fetching and iterating through all keys in the bucket) when you run aws s3 ls s3://my-bucket/, so I figured there must be a way using boto3.

https://github.com/aws/aws-cli/blob/0fedc4c1b6a7aee13e2ed10c3ada778c702c22c3/awscli/customizations/s3/subcommands.py#L499

It looks like they indeed use Prefix and Delimiter - I was able to write a function that would get me all directories at the root level of a bucket by modifying that code a bit:

def list_folders_in_bucket(bucket):
    paginator = boto3.client('s3').get_paginator('list_objects')
    folders = []
    iterator = paginator.paginate(Bucket=bucket, Prefix='', Delimiter='/', PaginationConfig={'PageSize': None})
    for response_data in iterator:
        prefixes = response_data.get('CommonPrefixes', [])
        for prefix in prefixes:
            prefix_name = prefix['Prefix']
            if prefix_name.endswith('/'):
                folders.append(prefix_name.rstrip('/'))
    return folders

Pipe output and capture exit status in Bash

This solution works without using bash specific features or temporary files. Bonus: in the end the exit status is actually an exit status and not some string in a file.

Situation:

someprog | filter

you want the exit status from someprog and the output from filter.

Here is my solution:

((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1

echo $?

See my answer for the same question on unix.stackexchange.com for a detailed explanation and an alternative without subshells and some caveats.

Loop through files in a folder using VBA?

Dir function loses focus easily when I handle and process files from other folders.

I've gotten better results with the component FileSystemObject.

Full example is given here:

http://www.xl-central.com/list-files-fso.html

Don't forget to set a reference in the Visual Basic Editor to Microsoft Scripting Runtime (by using Tools > References)

Give it a try!

How do I pass options to the Selenium Chrome driver using Python?

Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :

desired_capabilities['chromeOptions'] = {
    "args": ["--disable-extensions"],
    "extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)

How to disable Django's CSRF validation?

If you want disable it in Global, you can write a custom middleware, like this

from django.utils.deprecation import MiddlewareMixin

class DisableCsrfCheck(MiddlewareMixin):

    def process_request(self, req):
        attr = '_dont_enforce_csrf_checks'
        if not getattr(req, attr, False):
            setattr(req, attr, True)

then add this class youappname.middlewarefilename.DisableCsrfCheck to MIDDLEWARE_CLASSES lists, before django.middleware.csrf.CsrfViewMiddleware

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

There's a billion answers here so I thought why not add another in the form of an extension (with help from @Cœur)

Swift 3

Extension:

extension UIApplication {
    class var statusBarBackgroundColor: UIColor? {
        get {
            return (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor
        } set {
            (shared.value(forKey: "statusBar") as? UIView)?.backgroundColor = newValue
        }
    }
}

Implementation:

UIApplication.statusBarBackgroundColor = .blue

WCF service startup error "This collection already contains an address with scheme http"

And in my case it was simple: I used 'Add WCF Service' wizard in Visual Studio, which automatically created corresponding sections in app.config. Then I went on reading How to: Host a WCF Service in a Managed Application. The problem was: I didn't need to specify the url to run the web service.

Replace:

using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))

With:

using (ServiceHost host = new ServiceHost(typeof(HelloWorldService))

And the error is gone.

Generic idea: if you provide base address as a param and specify it in config, you get this error. Most probably, that's not the only way to get the error, thou.

SPAN vs DIV (inline-block)

If you want to have a valid xhtml document then you cannot put a div inside of a paragraph.

Also, a div with the property display: inline-block works differently than a span. A span is by default an inline element, you cannot set the width, height, and other properties associated with blocks. On the other hand, an element with the property inline-block will still "flow" with any surrounding text but you may set properties such as width, height, etc. A span with the property display:block will not flow in the same way as an inline-block element but will create a carriage return and have default margin.

Note that inline-block is not supported in all browsers. For instance in Firefox 2 and less you must use:

display: -moz-inline-stack;

which displays slightly different than an inline block element in FF3.

There is a great article here on creating cross browser inline-block elements.

MySQL Error 1264: out of range value for column

You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.

SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10

Ternary operator (?:) in Bash

This is much like Vladimir's fine answer. If your "ternary" is a case of "if true, string, if false, empty", then you can simply do:

$ c="it was five"
$ b=3
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a

$ b=5
$ a="$([[ $b -eq 5 ]] && echo "$c")"
$ echo $a
it was five

How to empty the content of a div

you can .remove() each child:

const div = document.querySelector('div.my-div')
while(div.firstChild) div.firstChild.remove()

How to force addition instead of concatenation in javascript

Should also be able to do this:

total += eval(myInt1) + eval(myInt2) + eval(myInt3);

This helped me in a different, but similar, situation.

jQuery append() vs appendChild()

appendChild is a DOM vanilla-js function.

append is a jQuery function.

They each have their own quirks.

Convert base64 string to ArrayBuffer

Using TypedArray.from:

Uint8Array.from(atob(base64_string), c => c.charCodeAt(0))

Performance to be compared with the for loop version of Goran.it answer.

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

'nuget' is not recognized but other nuget commands working

In [Package Manager Console] try the below

Install-Package NuGet.CommandLine

Swift double to string

let double = 1.5 
let string = double.description

update Xcode 7.1 • Swift 2.1:

Now Double is also convertible to String so you can simply use it as you wish:

let double = 1.5
let doubleString = String(double)   // "1.5"

Swift 3 or later we can extend LosslessStringConvertible and make it generic

Xcode 11.3 • Swift 5.1 or later

extension LosslessStringConvertible { 
    var string: String { .init(self) } 
}

let double = 1.5 
let string = double.string  //  "1.5"

For a fixed number of fraction digits we can extend FloatingPoint protocol:

extension FloatingPoint where Self: CVarArg {
    func fixedFraction(digits: Int) -> String {
        .init(format: "%.*f", digits, self)
    }
}

If you need more control over your number format (minimum and maximum fraction digits and rounding mode) you can use NumberFormatter:

extension Formatter {
    static let number = NumberFormatter()
}

extension FloatingPoint {
    func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
        Formatter.number.minimumFractionDigits = min
        Formatter.number.maximumFractionDigits = max
        Formatter.number.roundingMode = roundingMode
        Formatter.number.numberStyle = .decimal
        return Formatter.number.string(for: self) ?? ""
    }
}

2.12345.fractionDigits()                                    // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up)   // "2.124"

How to get the number of characters in a string

I tried to make to do the normalization a bit faster:

    en, _ = glyphSmart(data)

    func glyphSmart(text string) (int, int) {
        gc := 0
        dummy := 0
        for ind, _ := range text {
            gc++
            dummy = ind
        }
        dummy = 0
        return gc, dummy
    }

How to get C# Enum description from value?

You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)((TEnum)value));  // error!
}

but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)(object)((TEnum)(object)value));  // ugly, but works
}

You can now call this to get a description for whatever type of enum is at hand:

GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);

How to determine the content size of a UIWebView?

Resurrecting this question because I found Ortwin's answer to only work MOST of the time...

The webViewDidFinishLoad method may be called more than once, and the first value returned by sizeThatFits is only some portion of what the final size should be. Then for whatever reason the next call to sizeThatFits when webViewDidFinishLoad fires again will incorrectly return the same value it did before! This will happen randomly for the same content as if it's some kind of concurrency problem. Maybe this behaviour has changed over time, because I'm building for iOS 5 and have also found that sizeToFit works in much the same way (although previously this didn't?)

I have settled on this simple solution:

- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{        
    CGFloat height = [[aWebView stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];
    CGFloat width = [[aWebView stringByEvaluatingJavaScriptFromString:@"document.width"] floatValue];
    CGRect frame = aWebView.frame;
    frame.size.height = height;
    frame.size.width = width;
    aWebView.frame = frame;
}

Swift (2.2):

func webViewDidFinishLoad(webView: UIWebView) {

    if let heightString = webView.stringByEvaluatingJavaScriptFromString("document.height"),
        widthString = webView.stringByEvaluatingJavaScriptFromString("document.width"),
        height = Float(heightString),
        width = Float(widthString) {

        var rect = webView.frame
        rect.size.height = CGFloat(height)
        rect.size.width = CGFloat(width)
        webView.frame = rect
    }
}

Update: I have found as mentioned in the comments this doesn't seem to catch the case where the content has shrunk. Not sure if it's true for all content and OS version, give it a try.

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

Why does my 'git branch' have no master?

If you create a new repository from the Github web GUI, you sometimes get the name 'main' instead of 'master'. By using the command git status from your terminal you'd see which location you are. In some cases, you'd see origin/main.

If you are trying to push your app to a cloud service via CLI then use 'main', not 'master'.

example: git push heroku main

How to make type="number" to positive numbers only

It depends on how precise you want to be. It you want to accept only integers, than:

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

If you want floats with, for example, two digits after decimal point:

_x000D_
_x000D_
<input type="number" min="0.01" step="0.01">
_x000D_
_x000D_
_x000D_

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

How to stop C++ console application from exiting immediately?

Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.

cin.get();

Why is there no ForEach extension method on IEnumerable?

If you have F# (which will be in the next version of .NET), you can use

Seq.iter doSomething myIEnumerable

Convert datetime to Unix timestamp and convert it back in python

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

>>> import datetime
>>> datetime.datetime(2012, 04, 01, 0, 0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012, 04, 01, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> import datetime
>>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
1333234800.0

How to set Angular 4 background image?

I wanted a profile picture of size 96x96 with data from api. The following solution worked for me in project Angular 7.

.ts:

  @Input() profile;

.html:

 <span class="avatar" [ngStyle]="{'background-image': 'url('+ profile?.public_picture +')'}"></span>

.scss:

 .avatar {
      border-radius: 100%;
      background-size: cover;
      background-position: center center;
      background-repeat: no-repeat;
      width: 96px;
      height: 96px;
    }

Please note that if you write background instead of 'background-image' in [ngStyle], the styles you write (even in style of element) for other background properties like background-position/size, etc. won't work. Because you will already fix it's properties with background: 'url(+ property +) (no providers for size, position, etc. !)'. The [ngStyle] priority is higher than style of element. In background here, only url() property will work. Be sure to use 'background-image' instead of 'background'in case you want to write more properties to background image.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

While loop to test if a file exists in bash

I had the same problem, put the ! outside the brackets;

while ! [ -f /tmp/list.txt ];
do
    echo "#"
    sleep 1
done

Also, if you add an echo inside the loop it will tell you if you are getting into the loop or not.

Get class name of object as string in Swift

Swift 5

 NSStringFromClass(CustomClass.self)

Correct way to select from two tables in SQL Server with no common field to join on

You can (should) use CROSS JOIN. Following query will be equivalent to yours:

SELECT 
   table1.columnA
 , table2.columnA
FROM table1 
CROSS JOIN table2
WHERE table1.columnA = 'Some value'

or you can even use INNER JOIN with some always true conditon:

FROM table1 
INNER JOIN table2 ON 1=1

Java Currency Number format

  public static String formatPrice(double value) {
        DecimalFormat formatter;
        if (value<=99999)
          formatter = new DecimalFormat("###,###,##0.00");
        else
            formatter = new DecimalFormat("#,##,##,###.00");

        return formatter.format(value);
    }

Resetting a multi-stage form with jQuery

I'm just an intermediate in PHP, and a bit lazy to dive into a new language like JQuery, but isn't the following a simple and elegant solution?

<input name="Submit1" type="submit" value="Get free quote" />
<input name="submitreset" type="submit" value="Reset" />

Can't see a reason why not have two submit buttons, just with different purposes. Then simply:

if ($_POST['submitreset']=="Reset") {
$_source = "--Choose language from--";
$_target = "--Choose language to--"; }

You just redefine your values back to whatever the default is supposed to be.

Stopping a CSS3 Animation on last frame

The best way seems to put the final state at the main part of css. Like here, i put width to 220px, so that it finally becomes 220px. But starting to 0px;

div.menu-item1 {
  font-size: 20px;
  border: 2px solid #fff;
  width: 220px;
  animation: slide 1s;
  -webkit-animation: slide 1s; /* Safari and Chrome */
}
@-webkit-keyframes slide { /* Safari and Chrome */
  from {width:0px;}
  to {width:220px;}
}  

Batch script to install MSI

Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like

  • Using start /wait
  • Using !ERRORLEVEL! variable instead of %ERRORLEVEL%
  • Using SetLocal EnableDelayedExpansion

Nothing works and what mostly annoys me it's the fact that it works in the command line.

MSSQL Error 'The underlying provider failed on Open'

I had this error suddenly happen out of the blue on one of our sites. In my case, it turned out that the SQL user's password had expired! Unticking the password expiration box in SQL Server Management Studio did the trick!

True/False vs 0/1 in MySQL

Bit is also an option if tinyint isn't to your liking. A few links:

Not surprisingly, more info about numeric types is available in the manual.

One more link: http://blog.mclaughlinsoftware.com/2010/02/26/mysql-boolean-data-type/

And a quote from the comment section of the article above:

  • TINYINT(1) isn’t a synonym for bit(1).
  • TINYINT(1) can store -9 to 9.
  • TINYINT(1) UNSIGNED: 0-9
  • BIT(1): 0, 1. (Bit, literally).

Edit: This edit (and answer) is only remotely related to the original question...

Additional quotes by Justin Rovang and the author maclochlainn (comment section of the linked article).

Excuse me, seems I’ve fallen victim to substr-ism: TINYINT(1): -128-+127 TINYINT(1) UNSIGNED: 0-255 (Justin Rovang 25 Aug 11 at 4:32 pm)

True enough, but the post was about what PHPMyAdmin listed as a Boolean, and there it only uses 0 or 1 from the entire wide range of 256 possibilities. (maclochlainn 25 Aug 11 at 11:35 pm)

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

How to show/hide if variable is null

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;

Limit String Length

To truncate a string provided by the maximum limit without breaking a word use this:

/**
 * truncate a string provided by the maximum limit without breaking a word
 * @param string $str
 * @param integer $maxlen
 * @return string
 */
public static function truncateStringWords($str, $maxlen): string
{
    if (strlen($str) <= $maxlen) return $str;

    $newstr = substr($str, 0, $maxlen);
    if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));

    return $newstr;
}

Making PHP var_dump() values display one line per value

I really love var_export(). If you like copy/paste-able code, try:

echo '<pre>' . var_export($data, true) . '</pre>';

Or even something like this for color syntax highlighting:

highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");

Tomcat Server not starting with in 45 seconds

If you are trying to debug the application on server, just check out the breakpoints. You might had include the whole class as breakpoint. So remove that breakpoint.

This thing worked in my case when i was trying to debug.

file_get_contents() Breaks Up UTF-8 Characters

Exemple :

$string = file_get_contents(".../File.txt");
$string = mb_convert_encoding($string, 'UTF-8', "ISO-8859-1");
echo $string;

How can I exclude $(this) from a jQuery selector?

You can also use the jQuery .siblings() method:

HTML

<div class="content">
  <a href="#">A</a>
  <a href="#">B</a>
  <a href="#">C</a>
</div>

Javascript

$(".content").on('click', 'a', function(e) {
  e.preventDefault();
  $(this).siblings().hide('slow');
});

Working demo: http://jsfiddle.net/wTm5f/

C# Connecting Through Proxy

If you want the app to use the system default proxy, add this to your Application.exe.config (where application.exe is the name of your application):

<system.net>
   <defaultProxy enabled="true" useDefaultCredentials="true">
   <proxy usesystemdefault="true" bypassonlocal="true" />
   </defaultProxy>
</system.net>

More details can be found on in the MSDN article on System.Net

Received fatal alert: handshake_failure through SSLHandshakeException

Ugg! This turned out to simply be a Java version issue for me. I got the handshake error using JRE 1.6 and everything worked perfectly using JRE 1.8.0_144.

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.

Because of the adds and removes in arbitrary places on the list, I went with the LinkedList implementation.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

Where is body in a nodejs http.get response?

Needle module is also good, here is an example which uses needle module

var needle = require('needle');

needle.get('http://www.google.com', function(error, response) {
  if (!error && response.statusCode == 200)
    console.log(response.body);
});

C#: How to access an Excel cell?

I think, that you have to declare the associated sheet!

Try something like this

objsheet(1).Cells[i,j].Value;

How to change color in circular progress bar?

styles.xml

<style name="CircularProgress" parent="Theme.AppCompat.Light">
    <item name="colorAccent">@color/yellow</item>
</style>

  <ProgressBar
        android:layout_width="@dimen/d_40"
        android:layout_height="@dimen/d_40"
        android:indeterminate="true"
        style="@style/Widget.AppCompat.ProgressBar"
        android:theme="@style/CircularProgress"/>

Making a UITableView scroll when text field is selected

I just discovered another bug when using UITableViewController. It wasn't scrolling automatically when keyboard showed up. I noticed that it was because of contentInsetAdjustmentBehavior = .never on UITableView.

Facebook api: (#4) Application request limit reached

The Facebook API limit isn't really documented, but apparently it's something like: 600 calls per 600 seconds, per token & per IP. As the site is restricted, quoting the relevant part:

After some testing and discussion with the Facebook platform team, there is no official limit I'm aware of or can find in the documentation. However, I've found 600 calls per 600 seconds, per token & per IP to be about where they stop you. I've also seen some application based rate limiting but don't have any numbers.

As a general rule, one call per second should not get rate limited. On the surface this seems very restrictive but remember you can batch certain calls and use the subscription API to get changes.

As you can access the Graph API on the client side via the Javascript SDK; I think if you travel your request for photos from the client, you won't hit any application limit as it's the user (each one with unique id) who's fetching data, not your application server (unique ID).

This may mean a huge refactor if everything you do go through a server. But it seems like the best solution if you have so many request (as it'll give a breath to your server).

Else, you can try batch request, but I guess you're already going this way if you have big traffic.


If nothing of this works, according to the Facebook Platform Policy you should contact them.

If you exceed, or plan to exceed, any of the following thresholds please contact us as you may be subject to additional terms: (>5M MAU) or (>100M API calls per day) or (>50M impressions per day).

What is Func, how and when is it used

Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.

Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2); 

So, Func is a built-in delegate which brings some functional programming features and helps reduce code verbosity.

PHP - Get key name of array value

Here is another option

$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one']; 

Best Practices for Custom Helpers in Laravel 5

Having sifted through a variety of answers on SO and Google, I still couldn't find an optimal approach. Most answers suggest we leave the application and rely on 3rd party tool Composer to do the job, but I'm not convinced coupling to a tool just to include a file is wise.

Andrew Brown's answer came the closest to how I think it should be approached, but (at least in 5.1), the service provider step is unnecessary. Heisian's answer highlights the use of PSR-4 which brings us one step closer. Here's my final implementation for helpers in views:

First, create a helper file anywhere in your apps directory, with a namespace:

namespace App\Helpers;

class BobFinder
{
    static function bob()
    {
        return '<strong>Bob?! Is that you?!</strong>';
    }
}

Next, alias your class in config\app.php, in the aliases array:

'aliases' => [
    // Other aliases
    'BobFinder' => App\Helpers\BobFinder::class
]

And that should be all you need to do. PSR-4 and the alias should expose the helper to your views, so in your view, if you type:

{!! BobFinder::bob() !!}

It should output:

<strong>Bob?! Is that you?!</strong>

How can I list the contents of a directory in Python?

glob.glob or os.listdir will do it.

How to position one element relative to another with jQuery?

tl;dr: (try it here)

If you have the following HTML:

<div id="menu" style="display: none;">
   <!-- menu stuff in here -->
   <ul><li>Menu item</li></ul>
</div>

<div class="parent">Hover over me to show the menu here</div>

then you can use the following JavaScript code:

$(".parent").mouseover(function() {
    // .position() uses position relative to the offset parent, 
    var pos = $(this).position();

    // .outerWidth() takes into account border and padding.
    var width = $(this).outerWidth();

    //show the menu directly over the placeholder
    $("#menu").css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width) + "px"
    }).show();
});

But it doesn't work!

This will work as long as the menu and the placeholder have the same offset parent. If they don't, and you don't have nested CSS rules that care where in the DOM the #menu element is, use:

$(this).append($("#menu"));

just before the line that positions the #menu element.

But it still doesn't work!

You might have some weird layout that doesn't work with this approach. In that case, just use jQuery.ui's position plugin (as mentioned in an answer below), which handles every conceivable eventuality. Note that you'll have to show() the menu element before calling position({...}); the plugin can't position hidden elements.

Update notes 3 years later in 2012:

(The original solution is archived here for posterity)

So, it turns out that the original method I had here was far from ideal. In particular, it would fail if:

  • the menu's offset parent is not the placeholder's offset parent
  • the placeholder has a border/padding

Luckily, jQuery introduced methods (position() and outerWidth()) way back in 1.2.6 that make finding the right values in the latter case here a lot easier. For the former case, appending the menu element to the placeholder works (but will break CSS rules based on nesting).

Error: «Could not load type MvcApplication»

I was getting this error because I was running the project despite some compile time errors. This I didn't notice.

axios post request to send form data

import axios from "axios";
import qs from "qs";   

const url = "https://yourapplicationbaseurl/api/user/authenticate";
    let data = {
      Email: "[email protected]",
      Password: "Admin@123"
    };
    let options = {
      method: "POST",
      headers: { "content-type": "application/x-www-form-urlencoded" },
      data: qs.stringify(data),
      url
    };
    axios(options)
      .then(res => {
        console.log("yeh we have", res.data);
      })
      .catch(er => {
        console.log("no data sorry ", er);
      });
  };

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

Why not use Double or Float to represent currency?

To add on previous answers, there is also option of implementing Joda-Money in Java, besides BigDecimal, when dealing with the problem addressed in the question. Java modul name is org.joda.money.

It requires Java SE 8 or later and has no dependencies.

To be more precise, there is compile-time dependency but it is not required.

<dependency>
  <groupId>org.joda</groupId>
  <artifactId>joda-money</artifactId>
  <version>1.0.1</version>
</dependency>

Examples of using Joda Money:

  // create a monetary value
  Money money = Money.parse("USD 23.87");

  // add another amount with safe double conversion
  CurrencyUnit usd = CurrencyUnit.of("USD");
  money = money.plus(Money.of(usd, 12.43d));

  // subtracts an amount in dollars
  money = money.minusMajor(2);

  // multiplies by 3.5 with rounding
  money = money.multipliedBy(3.5d, RoundingMode.DOWN);

  // compare two amounts
  boolean bigAmount = money.isGreaterThan(dailyWage);

  // convert to GBP using a supplied rate
  BigDecimal conversionRate = ...;  // obtained from code outside Joda-Money
  Money moneyGBP = money.convertedTo(CurrencyUnit.GBP, conversionRate, RoundingMode.HALF_UP);

  // use a BigMoney for more complex calculations where scale matters
  BigMoney moneyCalc = money.toBigMoney();

Documentation: http://joda-money.sourceforge.net/apidocs/org/joda/money/Money.html

Implementation examples: https://www.programcreek.com/java-api-examples/?api=org.joda.money.Money

How can I know if a branch has been already merged into master?

On the topic of cleaning up remote branches

git branch -r | xargs -t -n 1 git branch -r --contains

This lists each remote branch followed by which remote branches their latest SHAs are within.

This is useful to discern which remote branches have been merged but not deleted, and which haven't been merged and thus are decaying.

If you're using 'tig' (its like gitk but terminal based) then you can

tig origin/feature/someones-decaying-feature

to see a branch's commit history without having to git checkout

How to get access token from FB.login method in javascript SDK

response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details: SDKs & Tools › JavaScript SDK › FB.login

one line if statement in php

use the ternary operator ?:

change this

<?php if ($requestVars->_name == '') echo $redText; ?>

with

<?php echo ($requestVars->_name == '') ? $redText : ''; ?>

In short

// (Condition)?(thing's to do if condition true):(thing's to do if condition false);

How to set locale in DatePipe in Angular 2?

Ok, I propose this solution, very simple, using ngx-translate

import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'localizedDate',
  pure: false
})
export class LocalizedDatePipe implements PipeTransform {

  constructor(private translateService: TranslateService) {
}

  transform(value: any): any {
    const date = new Date(value);

    const options = { weekday: 'long',
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit'
                    };

    return date.toLocaleString(this.translateService.currentLang, options);
  }

}

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Best way to create unique token in Rails?

I think token should be handled just like password. As such, they should be encrypted in DB.

I'n doing something like this to generate a unique new token for a model:

key = ActiveSupport::KeyGenerator
                .new(Devise.secret_key)
                .generate_key("put some random or the name of the key")

loop do
  raw = SecureRandom.urlsafe_base64(nil, false)
  enc = OpenSSL::HMAC.hexdigest('SHA256', key, raw)

  break [raw, enc] unless Model.exist?(token: enc)
end

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

React Hooks useState() with Object

I think best solution is Immer. It allows you to update object like you are directly modifying fields (masterField.fieldOne.fieldx = 'abc'). But it will not change actual object of course. It collects all updates on a draft object and gives you a final object at the end which you can use to replace original object.

How to select the last record from MySQL table using SQL syntax

SELECT   *
FROM     table
ORDER BY id DESC
LIMIT    0, 1

Firestore Getting documents id from collection

For document references, not collections, you need:

// when you know the 'id'

this.afs.doc(`items/${id}`)
  .snapshotChanges().pipe(
    map((doc: any) => {
      const data = doc.payload.data();
      const id = doc.payload.id;
      return { id, ...data };
    });

as .valueChanges({ idField: 'id'}); will not work here. I assume it was not implemented since generally you search for a document by the id...

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

Why does the C++ STL not provide any "tree" containers?

There are two reasons you could want to use a tree:

You want to mirror the problem using a tree-like structure:
For this we have boost graph library

Or you want a container that has tree like access characteristics For this we have

Basically the characteristics of these two containers is such that they practically have to be implemented using trees (though this is not actually a requirement).

See also this question: C tree Implementation

Change bootstrap datepicker date format on select

for me with bootstrap 4 datetime picker (http://www.eyecon.ro/bootstrap-datepicker/) format worked only with upper case:

$('.datepicker').datetimepicker({
            format: 'DD/MM/YYYY'
        });

How do I flush the PRINT buffer in TSQL?

Building on the answer by @JoelCoehoorn, my approach is to leave all my PRINT statements in place, and simply follow them with the RAISERROR statement to cause the flush.

For example:

PRINT 'MyVariableName: ' + @MyVariableName
RAISERROR(N'', 0, 1) WITH NOWAIT

The advantage of this approach is that the PRINT statements can concatenate strings, whereas the RAISERROR cannot. (So either way you have the same number of lines of code, as you'd have to declare and set a variable to use in RAISERROR).

If, like me, you use AutoHotKey or SSMSBoost or an equivalent tool, you can easily set up a shortcut such as "]flush" to enter the RAISERROR line for you. This saves you time if it is the same line of code every time, i.e. does not need to be customised to hold specific text or a variable.

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

Cannot add a project to a Tomcat server in Eclipse

  1. Right click on the project name in the Package Explorer view.
  2. Select Properties
  3. Select Project Facets
  4. Click on the Runtimes tab
  5. Check Server
  6. Click on OK

And now:

  1. Right click on the server name in the Servers view
  2. Click on Add and Remove...
  3. Move resources to the right column

Ubuntu: OpenJDK 8 - Unable to locate package

After adding the JDK repo, before Installing you might want to run an update first so the repo can be added run apt update

an then continue with your installation sudo apt install adoptopenjdk-8-hotspot

Laravel Redirect Back with() Message

In Laravel 5.5:

return back()->withErrors($arrayWithErrors);

In the view using Blade:

@if($errors->has())
    <ul>
    @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

Why compile Python code?

Yep, performance is the main reason and, as far as I know, the only reason.

If some of your files aren't getting compiled, maybe Python isn't able to write to the .pyc file, perhaps because of the directory permissions or something. Or perhaps the uncompiled files just aren't ever getting loaded... (scripts/modules only get compiled when they first get loaded)

How to clear a notification in Android

Actually as answered before starting with API Level 18 you can cancel Notifications posted by other apps differet than your own using NotificationListenerService but that approach will no longer work on Lollipop, here is the way to remove notifications covering also Lillipop API.

if (Build.VERSION.SDK_INT < 21) {
    cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
else {
    cancelNotification(sbn.getKey());
}

Difference between setTimeout with and without quotes and parentheses

Totally agree with Joseph.

Here is a fiddle to test this: http://jsfiddle.net/nicocube/63s2s/

In the context of the fiddle, the string argument do not work, in my opinion because the function is not defined in the global scope.

How to check if Thread finished execution

Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.

ASP.Net MVC 4 Form with 2 submit buttons/actions

_x000D_
_x000D_
<input type="submit" value="Create" name="button"/>_x000D_
<input type="submit" value="Reset" name="button" />
_x000D_
_x000D_
_x000D_

write the following code in Controler.

[HttpPost]
        public ActionResult Login(string button)
        {
            switch (button)
            {
                case "Create":
                    return RedirectToAction("Deshboard", "Home");
                    break;
                case "Reset":
                    return RedirectToAction("Login", "Home");
                    break;
            }

            return View();
        }

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

Below is the native PowerShell command for the most up-voted solution. Instead of: netsh advfirewall firewall set rule group="Windows Management Instrumentation (WMI)" new enable=yes

Use could use the slightly simpler syntax of:

Enable-NetFirewallRule -DisplayGroup "Windows Management Instrumentation (WMI-In)"

How to commit a change with both "message" and "description" from the command line?

In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.

git rebase -i origin/master

Then, your commits will appear:

pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments

Select the commit you want to reword and save.

pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments

Now, you have the opportunity to add header and body, where the first line will be the header.

Create perpetuum mobile

Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.

Access to Image from origin 'null' has been blocked by CORS policy

Try to bypass CORS:

For Chrome: edit shortcut or with cmd: C:\Chrome.exe --disable-web-security

For Firefox: Open Firefox and type about:config into the URL bar. search for: security.fileuri.strict_origin_policy set to false

make a header full screen (width) css

Remove the max-width from the body, and put it to the #container.

So, instead of:

body {
    max-width:1250px;
}

You should have:

#container {
    max-width:1250px;
}

What is the time complexity of indexing, inserting and removing from common data structures?

Amortized Big-O for hashtables:

  • Insert - O(1)
  • Retrieve - O(1)
  • Delete - O(1)

Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.

Numpy converting array from float to strings

You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.

The string representation of a float doesn't work this way. For example, repr(1.3) yields '1.3', but repr(1.33) yields '1.3300000000000001'.

A accurate string representation of a floating point number produces a variable length string.

Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.

If you use x.astype('str'), it will always convert things to an array of strings of length 1.

For example, using x = np.array(1.344566), x.astype('str') yields '1'!

You need to be more explict and use the '|Sx' dtype syntax, where x is the length of the string for each element of the array.

For example, use x.astype('|S10') to convert the array to strings of length 10.

Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...

Working copy XXX locked and cleanup failed in SVN

Clean up certainly is not enough to solve this issue sometimes.

If you use TortoiseSVN v1.7.2 or greater, right click on the Parent directory of the locked file and select TortoiseSVN -> Repo Browser from the menu. In the Repro Browser GUI right click the file that is locked and there will be an option to remove the lock.

toggle show/hide div with button?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
    $('#content').toggle('show');
  });
});
</script>

And the html

<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>

How to get the first line of a file in a bash script?

Just echo the first list of your source file into your target file.

echo $(head -n 1 source.txt) > target.txt

1030 Got error 28 from storage engine

I had a similar issue, because of my replication binary logs.

If this is the case, just create a cronjob to run this query every day:

PURGE BINARY LOGS BEFORE DATE_SUB( NOW(), INTERVAL 2 DAY );

This will remove all binary logs older than 2 days.

I found this solution here.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

PoC

As Niklas mentioned you can use the html2canvas library to take a screenshot using JS in the browser. I will extend his answer in this point by providing an example of taking a screenshot using this library ("Proof of Concept"):

_x000D_
_x000D_
function report() {
  let region = document.querySelector("body"); // whole screen
  html2canvas(region, {
    onrendered: function(canvas) {
      let pngUrl = canvas.toDataURL(); // png in dataURL format
      let img = document.querySelector(".screen");
      img.src = pngUrl; 

      // here you can allow user to set bug-region
      // and send it with 'pngUrl' to server
    },
  });
}
_x000D_
.container {
  margin-top: 10px;
  border: solid 1px black;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div>Screenshot tester</div>
<button onclick="report()">Take screenshot</button>

<div class="container">
  <img width="75%" class="screen">
</div>
_x000D_
_x000D_
_x000D_

In report() function in onrendered after getting image as data URI you can show it to the user and allow him to draw "bug region" by mouse and then send a screenshot and region coordinates to the server.

In this example async/await version was made: with nice makeScreenshot() function.

UPDATE

Simple example which allows you to take screenshot, select region, describe bug and send POST request (here jsfiddle) (the main function is report()).

_x000D_
_x000D_
async function report() {
    let screenshot = await makeScreenshot(); // png dataUrl
    let img = q(".screen");
    img.src = screenshot; 
    
    let c = q(".bug-container");
    c.classList.remove('hide')
        
    let box = await getBox();    
    c.classList.add('hide');

    send(screenshot,box); // sed post request  with bug image, region and description
    alert('To see POST requset with image go to: chrome console > network tab');
}

// ----- Helper functions

let q = s => document.querySelector(s); // query selector helper
window.report = report; // bind report be visible in fiddle html

async function  makeScreenshot(selector="body") 
{
  return new Promise((resolve, reject) => {  
    let node = document.querySelector(selector);
    
    html2canvas(node, { onrendered: (canvas) => {
        let pngUrl = canvas.toDataURL();      
        resolve(pngUrl);
    }});  
  });
}

async function getBox(box) {
  return new Promise((resolve, reject) => {
     let b = q(".bug");
     let r = q(".region");
     let scr = q(".screen");
     let send = q(".send");
     let start=0;
     let sx,sy,ex,ey=-1;
     r.style.width=0;
     r.style.height=0;
     
     let drawBox= () => {
         r.style.left   = (ex > 0 ? sx : sx+ex ) +'px'; 
         r.style.top    = (ey > 0 ? sy : sy+ey) +'px';
         r.style.width  = Math.abs(ex) +'px';
         r.style.height = Math.abs(ey) +'px'; 
     }
     
     
     
     //console.log({b,r, scr});
     b.addEventListener("click", e=>{
       if(start==0) {
         sx=e.pageX;
         sy=e.pageY;
         ex=0;
         ey=0;
         drawBox();
       }
       start=(start+1)%3;       
     });
     
     b.addEventListener("mousemove", e=>{
       //console.log(e)
       if(start==1) {
           ex=e.pageX-sx;
           ey=e.pageY-sy
           drawBox(); 
       }
     });
     
     send.addEventListener("click", e=>{
       start=0;
       let a=100/75 //zoom out img 75%       
       resolve({
          x:Math.floor(((ex > 0 ? sx : sx+ex )-scr.offsetLeft)*a),
          y:Math.floor(((ey > 0 ? sy : sy+ey )-b.offsetTop)*a),
          width:Math.floor(Math.abs(ex)*a),
          height:Math.floor(Math.abs(ex)*a),
          desc: q('.bug-desc').value
          });
          
     });
  });
}

function send(image,box) {

    let formData = new FormData();
    let req = new XMLHttpRequest();
    
    formData.append("box", JSON.stringify(box)); 
    formData.append("screenshot", image);     
    
    req.open("POST", '/upload/screenshot');
    req.send(formData);
}
_x000D_
.bug-container { background: rgb(255,0,0,0.1); margin-top:20px; text-align: center; }
.send { border-radius:5px; padding:10px; background: green; cursor: pointer; }
.region { position: absolute; background: rgba(255,0,0,0.4); }
.example { height: 100px; background: yellow; }
.bug { margin-top: 10px; cursor: crosshair; }
.hide { display: none; }
.screen { pointer-events: none }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<body>
<div>Screenshot tester</div>
<button onclick="report()">Report bug</button>

<div class="example">Lorem ipsum</div>

<div class="bug-container hide">
  <div>Select bug region: click once - move mouse - click again</div>
  <div class="bug">    
    <img width="75%" class="screen" >
    <div class="region"></div> 
  </div>
  <div>
    <textarea class="bug-desc">Describe bug here...</textarea>
  </div>
  <div class="send">SEND BUG</div>
</div>

</body>
_x000D_
_x000D_
_x000D_

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

LDAP is trying to authenticate with AD when sending a transaction to another server DB. This authentication fails because the user has recently changed her password, although this transaction was generated using the previous credentials. This authentication will keep failing until ... unless you change the transaction status to Complete or Cancel in which case LDAP will stop sending these transactions.

Select 2 columns in one and combine them

(SELECT column1 as column FROM table )
UNION 
(SELECT column2 as column FROM table )

Hide vertical scrollbar in <select> element

I worked out Arraxas solution to:

  • expand the box to include all elements

  • change background & color on hover

  • get and alert value on click

  • do not keep highlighting selection after clicking

_x000D_
_x000D_
let selElem=document.getElementById('myselect').children[0];_x000D_
selElem.size=selElem.length;_x000D_
selElem.value=-1;_x000D_
_x000D_
selElem.addEventListener('change', e => {_x000D_
  alert(e.target.value);_x000D_
  e.target.value=-1;_x000D_
});
_x000D_
#myselect {_x000D_
  display:inline-block; overflow:hidden; border:solid black 1px;_x000D_
}_x000D_
_x000D_
#myselect > select {_x000D_
  padding:10px; margin:-5px -20px -5px -5px;";_x000D_
}_x000D_
_x000D_
#myselect > select > option:hover {_x000D_
  box-shadow: 0 0 10px 100px #4A8CF7 inset; color: white;_x000D_
}
_x000D_
<div id="myselect">_x000D_
  <select>_x000D_
    <option value="2010">2010</option>_x000D_
    <option value="2011">2011</option>_x000D_
    <option value="2012">2012</option>_x000D_
    <option value="2013">2013</option>_x000D_
    <option value="2014">2014</option>_x000D_
    <option value="2015">2015</option>_x000D_
    <option value="2016">2016</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to select all columns, except one column in pandas?

When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:

df.loc[:, df.columns != 'b']

          a         c         d
0  0.561196  0.013768  0.772827
1  0.882641  0.615396  0.075381
2  0.368824  0.651378  0.397203
3  0.788730  0.568099  0.869127

How to capture the browser window close event?

Perhaps you could handle OnSubmit and set a flag that you later check in your OnBeforeUnload handler.

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

Random float number generation

drand48(3) is the POSIX standard way. GLibC also provides a reentrant version, drand48_r(3).

The function was declared obsolete in SVID 3 but no adequate alternative was provided so IEEE Std 1003.1-2013 still includes it and has no notes that it's going anywhere anytime soon.

In Windows, the standard way is CryptGenRandom().

Underscore prefix for property and method names in JavaScript

import/export is now doing the job with ES6. I still tend to prefix not exported functions with _ if most of my functions are exported.

If you export only a class (like in angular projects), it's not needed at all.

export class MyOpenClass{

    open(){
         doStuff()
         this._privateStuff()
         return close();
    }

    _privateStuff() { /* _ only as a convention */} 

}

function close(){ /*... this is really private... */ }

Setting an environment variable before a command in Bash is not working for the second command in a pipe

You can also use eval:

FOO=bar eval 'somecommand someargs | somecommand2'

Since this answer with eval doesn't seem to please everyone, let me clarify something: when used as written, with the single quotes, it is perfectly safe. It is good as it will not launch an external process (like the accepted answer) nor will it execute the commands in an extra subshell (like the other answer).

As we get a few regular views, it's probably good to give an alternative to eval that will please everyone, and has all the benefits (and perhaps even more!) of this quick eval “trick”. Just use a function! Define a function with all your commands:

mypipe() {
    somecommand someargs | somecommand2
}

and execute it with your environment variables like this:

FOO=bar mypipe

grep for special characters in Unix

Tell grep to treat your input as fixed string using -F option.

grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

Option -n is required to get the line number,

grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

if else statement in AngularJS templates

Ternary is the most clear way of doing this.

<div>{{ConditionVar ? 'varIsTrue' : 'varIsFalse'}}</div>

How do I delete virtual interface in Linux?

You can use sudo ip link delete to remove the interface.

Check if table exists in SQL Server

I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay.

Here is the solution:

SELECT COUNT(*) FROM <yourTableNameHere>

So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it).

The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver..

if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {
  // myTable doesn't exist..
}

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

GET and POST methods with the same Action name in the same Controller

Can not multi action same name and same parameter

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(int id)
    {
        return View();
    }

althought int id is not used

Preserve line breaks in angularjs

With CSS this can be achieve easily.

<div ng-repeat="item in items">
<span style="white-space:pre-wrap;"> {{item.description}}</span>
</div>  

Or a CSS class can be created for this purpose and can be used from external CSS file

How do I set a path in Visual Studio?

None of the answers solved exactly my problem (the solution file I was running was trying to find xcopy to copy a dll after generation).

What solved it for me was going into menu "Project -> Properties"

Then in the window that opens choosing on the left pane: "Configuration Properties -> VC++ Directories

On the right pane under "General" choosing "Executable Directories "

And then adding:

$(SystemRoot)\system32;$(SystemRoot);$(SystemRoot)\System32\Wbem;$(SystemRoot)\System32\WindowsPowerShell\v1.0\;$(ExecutablePath)

XmlWriter to Write to a String Instead of to a File

Use StringBuilder:

var sb = new StringBuilder();
    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
    {
        ...
    }
return sb.ToString();

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

Your response must return some sort of Response object. You can't just return an object.

So change it to something like:

return Response::json($promotion);

or my favorite using the helper function:

return response()->json($promotion);

If returning a response doesn't work it may be some sort of encoding issue. See this article: The Response content must be a string or object implementing __toString(), \"boolean\" given."

PostgreSQL: Why psql can't connect to server?

I could resolve this by setting the right permissions to datadir. It should be

chmod 700 /var/lib/postgresql/10/main
chown postgres.postgres /var/lib/postgresql/10/main

Get screenshot on Windows with Python?

import pyautogui

s = pyautogui.screenshot()
s.save(r'C:\\Users\\NAME\\Pictures\\s.png')

What does [object Object] mean? (JavaScript)

Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

method in class cannot be applied to given types

I think you want something like this. The formatting is off, but it should give the essential information you want.

   import java.util.Scanner;
public class BookstoreCredit 
{

   public static void computeDiscount(String name, double gpa) 
   {
      double credits;
      credits = gpa * 10;
      System.out.println(name + " your GPA is " +
         gpa + " so your credit is $" + credits);
   
   }

   public static void main (String args[]) 
   {
      String studentName;
      double gradeAverage;
      Scanner inputDevice = new Scanner(System.in);
      System.out.println("Enter Student name: ");
      studentName = inputDevice.nextLine();
      System.out.println("Enter student GPA: ");
      gradeAverage = inputDevice.nextDouble();  
      
      computeDiscount(studentName, gradeAverage);
   }
}

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:

(Get-ChildItem "[FILEPATH]" -recurse).FullName |
  Foreach-Object {
   (Get-Content $_ -Raw).
     Replace('abt7d9epp4','w2svuzf54f').
     Replace('AccountName=adtestnego','AccountName=zadtestnego').
     Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
   Set-Content $_
  }

Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.

What is the difference between Set and List?

Hi So many answers are already given..Let me point out some points which are not mentioned so far:

  • Most of the List implementations (ArrayList,Vector) implement RandomAccess interface which is a marker interface for faster access. None of the Set implementations do that.
  • List uses one special Iterator called ListIterator which supports iteration in both directions. Set uses Iterator which supports only 1 way iteration
  • HashSet takes 5.5 times more memory than ArrayList for storing same number of elements.

How to get just the date part of getdate()?

SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)

or

SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))

Call Javascript onchange event by programmatically changing textbox value

You're misinterpreting what the onchange event does when applied to a textarea. It won't fire until it loses focus or you hit enter. Why not fire the function from an onchange on the select that fills in the text area?

Check out here for more on the onchange event: w3schools

Plotting 4 curves in a single plot, with 3 y-axes

Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.

Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!

close all
clear all 

display('Generating data');

x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);

display('Plotting');

figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
    'YColor','b',...
    'YLim',[0,1],...
    'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)

ax2 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','left',...
           'Color','none',...
           'XColor','k',...
           'YColor','r',...
           'YLim',[0,10],...
           'YTick',[1, 3, 5, 7, 9],...
           'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)

ax3 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','g',...
           'YLim',[0,100],...
           'YTick',[0, 20, 40, 60, 80, 100],...
           'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)

ax4 = axes('Position',get(ax1,'Position'),...
           'XAxisLocation','bottom',...
           'YAxisLocation','right',...
           'Color','none',...
           'XColor','k',...
           'YColor','c',...
           'YLim',[0,100],...
           'YTick',[10, 30, 50, 70, 90],...
           'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)

alt text
(source: pablorodriguez.info)

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

The right answer is

Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.

link (expand Revision 17)

Adding files to a GitHub repository

You can use Git GUI on Windows, see instructions:

  1. Open the Git Gui (After installing the Git on your computer).

enter image description here

  1. Clone your repository to your local hard drive:

enter image description here

  1. After cloning, GUI opens, choose: "Rescan" for changes that you made:

enter image description here

  1. You will notice the scanned files:

enter image description here

  1. Click on "Stage Changed":

enter image description here

  1. Approve and click "Commit":

enter image description here

  1. Click on "Push":

enter image description here

  1. Click on "Push":

enter image description here

  1. Wait for the files to upload to git:

enter image description here

enter image description here

How to delete the top 1000 rows from a table using Sql Server 2008?

delete from [mytab]
where [mytab].primarykeyid in
(
select top 1000 primarykeyid
from [mytab]
)

C#: calling a button event handler method without actually clicking the button

Inside first button event call second button(imagebutton) event:

imagebutton_Click((ImageButton)this.divXXX.FindControl("imagbutton"), EventArgs.Empty);

you can use the button state such as the imagebutton's commandArgument if you save something into it.

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

How can I tell AngularJS to "refresh"

The solution was to call...

$scope.$apply();

...in my jQuery event callback.

How to set focus to a button widget programmatically?

Try this:

btn.requestFocusFromTouch();

posting hidden value

Maybe a little late to the party but why don't you use sessions to store your data?

bookingfacilities.php

session_start();
$_SESSION['form_date'] = $date;

successfulbooking.php

session_start();
$date = $_SESSION['form_date']; 

Nobody will see this.

Could not resolve this reference. Could not locate the assembly

If anyone face this issue with some nuget packages, you can fix that by reinstalling the packages using the Package Manager Console:

Update-Package -reinstall 

What are all codecs and formats supported by FFmpeg?

You can see the list of supported codecs in the official documentation:

Supported video codecs

Supported audio codecs

What's the difference between faking, mocking, and stubbing?

the thing that you assert on it,is called a mock object and everything else that just helped the test run, is a stub.

Scroll to the top of the page after render in react.js

I tried everything, but this is the only thing that worked.

 useLayoutEffect(() => {
  document.getElementById("someID").scrollTo(0, 0);
 });

What is the advantage of using REST instead of non-REST HTTP?

IMHO the biggest advantage that REST enables is that of reducing client/server coupling. It is much easier to evolve a REST interface over time without breaking existing clients.

Making text background transparent but not text itself

box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);

How to sort alphabetically while ignoring case sensitive?

Here is an example to sort an array : Case-insensitive

import java.text.Collator;
import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    String[] myArray = new String[] { "A", "B", "b" };
    Arrays.sort(myArray, Collator.getInstance());

  System.out.println(Arrays.toString(myArray));

 }

}

/* Output:[A, b, B] */

How to get MAC address of client using PHP?

To get client's device ip and mac address

{
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

    $macCommandString   =   "arp " . $ipaddress . " | awk 'BEGIN{ i=1; } { i++; if(i==3) print $3 }'";

    $mac = exec($macCommandString);

    return ['ip' => $ipaddress, 'mac' => $mac];
}

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

One I use (notice this doesnt make "TestString" as "T est String" or " Test String").

function seperateCapitalised(capitalisedString) {
    if (typeof capitalisedString !== "string" || capitalisedString.length === 0)
        return capitalisedString;

    var newStr = capitalisedString[0];
    for (var i = 1; i < capitalisedString.length; i++) {
        var char = capitalisedString[i];

        if (char === char.toUpperCase() && isNaN(char)) {
            newStr += ' ' + char;
        }
        else {
            newStr += char;
        }
    }
    return newStr;
}

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

Java code: write this in onCreate()
getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setCustomView(R.layout.action_bar);

and for you custom view, simply use FrameLayout, east peasy!
android.support.v7.widget.Toolbar is another option

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|center_vertical"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/app_name"
        android:textColor="@color/black"
        android:id="@+id/textView" />
</FrameLayout>

python-pandas and databases like mysql

This helped for me for connecting to AWS MYSQL(RDS) from python 3.x based lambda function and loading into a pandas DataFrame

import json
import boto3
import pymysql
import pandas as pd
user = 'username'
password = 'XXXXXXX'
client = boto3.client('rds')
def lambda_handler(event, context):
    conn = pymysql.connect(host='xxx.xxxxus-west-2.rds.amazonaws.com', port=3306, user=user, passwd=password, db='database name', connect_timeout=5)
    df= pd.read_sql('select * from TableName limit 10',con=conn)
    print(df)
    # TODO implement
    #return {
    #    'statusCode': 200,
    #    'df': df
    #}

write multiple lines in a file in python

this also works:

target.write("{}" "\n" "{}" "\n" "{}" "\n".format(line1, line2, line3))

How do I view 'git diff' output with my preferred diff tool/ viewer?

Here's a batch file that works for Windows - assumes DiffMerge installed in default location, handles x64, handles forward to backslash replacement as necessary and has ability to install itself. Should be easy to replace DiffMerge with your favourite diff program.

To install:

gitvdiff --install 

gitvdiff.bat:

@echo off

REM ---- Install? ----
REM To install, run gitvdiff --install

if %1==--install goto install



REM ---- Find DiffMerge ----

if DEFINED ProgramFiles^(x86^) (
    Set DIFF="%ProgramFiles(x86)%\SourceGear\DiffMerge\DiffMerge.exe"
) else (
    Set DIFF="%ProgramFiles%\SourceGear\DiffMerge\DiffMerge.exe"
)



REM ---- Switch forward slashes to back slashes ----

set oldW=%2
set oldW=%oldW:/=\%
set newW=%5
set newW=%newW:/=\%


REM ---- Launch DiffMerge ----

%DIFF% /title1="Old Version" %oldW% /title2="New Version" %newW%

goto :EOF



REM ---- Install ----
:install
set selfL=%~dpnx0
set selfL=%selfL:\=/%
@echo on
git config --global diff.external %selfL%
@echo off


:EOF

How to include a class in PHP

I suggest you also take a look at __autoload.
This will clean up the code of requires and includes.

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

IDENTITY_INSERT is set to OFF - How to turn it ON?

The Reference: http://technet.microsoft.com/en-us/library/aa259221%28v=sql.80%29.aspx

My table is named Genre with the 3 columns of Id, Name and SortOrder

The code that I used is as:

SET IDENTITY_INSERT Genre ON

INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

Getting the "real" Facebook profile picture URL from graph API

ImageView user_picture;
userpicture=(ImageView)findViewById(R.id.userpicture);
URL img_value = null;
img_value = new URL("http://graph.facebook.com/"+id+"/picture?type=large");
Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
userpicture.setImageBitmap(mIcon1);

Where ID is one your profile ID.

Insertion Sort vs. Selection Sort

I'll give it yet another try: consider what happens in the lucky case of almost sorted array.

While sorting, the array can be thought of as having two parts: left hand side - sorted, right hand side - unsorted.

Insertion sort - pick first unsorted element and try to find a place for it among the already sorted part. Since you search from right to left it might very well happen that the first sorted element you are comparing to (the largest one, most right in the left part) is smaller than the picked element so you can immediately continue with the next unsorted element.

Selection sort - pick the first unsorted element and try to find the smallest element of the whole unsorted part, and exchange those two if desirable. The problem is, since the right part is unsorted, you have to go thought every element every time, since you cannot possibly be sure whether there is or is not even smaller element than the picked one.

Btw., this is exactly what heapsort improves upon selection sort - it is able to find the smallest element much more quickly because of the heap.

subquery in codeigniter active record

->where() support passing any string to it and it will use it in the query.

You can try using this:

$this->db->select('*')->from('certs');
$this->db->where('`id` NOT IN (SELECT `id_cer` FROM `revokace`)', NULL, FALSE);

The ,NULL,FALSE in the where() tells CodeIgniter not to escape the query, which may mess it up.

UPDATE: You can also check out the subquery library I wrote.

$this->db->select('*')->from('certs');
$sub = $this->subquery->start_subquery('where_in');
$sub->select('id_cer')->from('revokace');
$this->subquery->end_subquery('id', FALSE);

How to test my servlet using JUnit

First you should probably refactor this a bit so that the DataManager is not created in the doPost code.. you should try Dependency Injection to get an instance. (See the Guice video for a nice intro to DI.). If you're being told to start unit testing everything, then DI is a must-have.

Once your dependencies are injected you can test your class in isolation.

To actually test the servlet, there are other older threads that have discussed this.. try here and here.

Are PHP Variables passed by value or by reference?

It seems a lot of people get confused by the way objects are passed to functions and what passing by reference means. Object are still passed by value, it's just the value that is passed in PHP5 is a reference handle. As proof:

<?php
class Holder {
    private $value;

    public function __construct($value) {
        $this->value = $value;
    }

    public function getValue() {
        return $this->value;
    }
}

function swap($x, $y) {
    $tmp = $x;
    $x = $y;
    $y = $tmp;
}

$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);

echo $a->getValue() . ", " . $b->getValue() . "\n";

Outputs:

a, b

To pass by reference means we can modify the variables that are seen by the caller, which clearly the code above does not do. We need to change the swap function to:

<?php
function swap(&$x, &$y) {
    $tmp = $x;
    $x = $y;
    $y = $tmp;
}

$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);

echo $a->getValue() . ", " . $b->getValue() . "\n";

Outputs:

b, a

in order to pass by reference.

Find Java classes implementing an interface

In full generality, this functionality is impossible. The Java ClassLoader mechanism guarantees only the ability to ask for a class with a specific name (including pacakge), and the ClassLoader can supply a class, or it can state that it does not know that class.

Classes can be (and frequently are) loaded from remote servers, and they can even be constructed on the fly; it is not difficult at all to write a ClassLoader that returns a valid class that implements a given interface for any name you ask from it; a List of the classes that implement that interface would then be infinite in length.

In practice, the most common case is an URLClassLoader that looks for classes in a list of filesystem directories and JAR files. So what you need is to get the URLClassLoader, then iterate through those directories and archives, and for each class file you find in them, request the corresponding Class object and look through the return of its getInterfaces() method.

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Freely convert between List<T> and IEnumerable<T>

To prevent duplication in memory, resharper is suggesting this:

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myList as List<string>() ?? myEnumerable.ToList();

.ToList() returns a new immutable list. So changes to listAgain does not effect myList in @Tamas Czinege answer. This is correct in most instances for least two reasons: This helps prevent changes in one area effecting the other area (loose coupling), and it is very readable, since we shouldn't be designing code with compiler concerns.

But there are certain instances, like being in a tight loop or working on an embedded or low memory system, where compiler considerations should be taken into consideration.