Programs & Examples On #Wix3

For issues relating to deployment using Windows Installer XML, version 3.

WiX tricks and tips

Fantastic question. I'd love to see some best practices shown.

I've got a lot of files that I distribute, so I've set up my project into several wxs source files.

I have a top level source file which I call Product.wxs which basically contains the structure for the installation, but not the actual components. This file has several sections:

<Product ...>
  <Package ...>
    <Media>... 
   <Condition>s ...
   <Upgrade ..>
   <Directory> 
        ...
   </Directory>
   <Feature>
      <ComponentGroupRef ... > A bunch of these that
   </Feature>
   <UI ...>
   <Property...>
   <Custom Actions...>
   <Install Sequences....
  </Package>
</Product>

The rest of the .wix files are composed of Fragments that contain ComponentGroups which are referenced in the Feature tag in the Product.wxs. My project contains a nice logical grouping of the files that I distribute

<Fragment>
   <ComponentGroup>
     <ComponentRef>
     ....
    </ComponentGroup>
    <DirectoryRef>
      <Component... for each file
      .... 
    </DirectoryRef>
</Fragment>

This isn't perfect, my OO spider sense tingles a bit because the fragments have to reference names in the Product.wxs file (e.g. the DirectoryRef) but I find it easier to maintain that a single large source file.

I'd love to hear comments on this, or if anyone has any good tips too!

Using an if statement to check if a div is empty

In my case I had multiple elements to hide on document.ready. This is the function (filter) that worked for me so far:

$('[name="_invisibleIfEmpty"]').filter(function () {
    return $.trim($(this).html()).length == 0;
}).hide();

or .remove() rather than .hide(), whatever you prefer.

FYI: This, in particular, is the solution I am using to hide annoying empty table cells in SharePoint (in addition with this condition "|| $(this).children("menu").length".

Use 'import module' or 'from module import'?

My own answer to this depends mostly on first, how many different modules I'll be using. If i'm only going to use one or two, I'll often use from ... import since it makes for fewer keystrokes in the rest of the file, but if I'm going to make use of many different modules, I prefer just import because that means that each module reference is self-documenting. I can see where each symbol comes from without having to hunt around.

Usuaully I prefer the self documenting style of plain import and only change to from.. import when the number of times I have to type the module name grows above 10 to 20, even if there's only one module being imported.

How to install trusted CA certificate on Android device?

What I did to beable to use startssl certificates was quite easy. (on my rooted phone)

I copied /system/etc/security/cacerts.bks to my sdcard

Downloaded http://www.startssl.com/certs/ca.crt and http://www.startssl.com/certs/sub.class1.server.ca.crt

Went to portecle.sourceforge.net and ran portecle directly from the webpage.

Opened my cacerts.bks file from my sdcard (entered nothing when asked for a password)

Choose import in portacle and opened sub.class1.server.ca.crt, im my case it allready had the ca.crt but maybe you need to install that too.

Saved the keystore and copied it baxck to /system/etc/security/cacerts.bks (I made a backup of that file first just in case)

Rebooted my phone and now I can vist my site thats using a startssl certificate without errors.

How do I set hostname in docker-compose?

Based on docker documentation: https://docs.docker.com/compose/compose-file/#/command

I simply put hostname: <string> in my docker-compose file.

E.g.:

[...]

lb01:
  hostname: at-lb01
  image: at-client-base:v1

[...]

and container lb01 picks up at-lb01 as hostname.

XAMPP Apache won't start

For Linux Users:

The solution: In terminal: sudo /etc/init.d/apache2 stop

Edit: If you still get this kind of error at next computer start then you probably have apache2 process starting at computer startup.

To prevent apache2 starting automatically at startup: cd /etc/init.d/ sudo update-rc.d -f apache2 remove

Reboot your computer and now hopefully you can turn on Apache from the XAMPP Control Panel!

Force SSL/https using .htaccess and mod_rewrite

try this code, it will work for all version of URLs like

  • website.com
  • www.website.com
  • http://website.com
  • http://www.website.com

    RewriteCond %{HTTPS} off
    RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
    RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
    

How do I debug Node.js applications?

Enable VS Code preference Auto Attach from File -> Preferences -> Settings -> Search for Auto Attach and set it On, open the console (ctrl + *) or from the menu Terminal -> New Terminal, set a breakpoint in your code, type in the command

node --inspect <name of your file>

This will start the debugging and the VS Code will show the Debug menu.

Note: Auto Attach is also very helpful if you are working with node cluster worker threads.

C# binary literals

You can use 0b000001 since Visual Studio 2017 (C# 7.0)

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Problem in running .net framework 4.0 website on iis 7.0

If you look in the ISAPI And CGI Restrictions, and everything is already set to Allowed, and the ASP.NET installed is v4.0.30319, then in the right, at the "Actions" panel click in the "Edit Feature Settings..." and check both boxes. In my case, they were not.

How to prevent ENTER keypress to submit a web form?

You will have to call this function whic will just cancel the default submit behaviour of the form. You can attach it to any input field or event.

function doNothing() {  
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if( keyCode == 13 ) {


    if(!e) var e = window.event;

    e.cancelBubble = true;
    e.returnValue = false;

    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}

How to store phone numbers on MySQL databases?

varchar, Don't store separating characters you may want to format the phone numbers differently for different uses. so store (619) 123-4567 as 6191234567 I work with phone directory data and have found this to be the best practice.

Dropping a connected user from an Oracle 10g database schema

Just my two cents : the best way (but probably not the quickest in the short term) would probably be for each developer to work on his own database instance (see rule #1 for database work).

Installing Oracle on a developer station has become a no brainer since Oracle Database 10g Express Edition.

Can I apply multiple background colors with CSS3?

In this LIVE DEMO i've achieved this by using the :before css selector which seems to work quite nicely.

_x000D_
_x000D_
.myDiv  {_x000D_
position: relative; /*Parent MUST be relative*/_x000D_
z-index: 9;_x000D_
background: green;_x000D_
    _x000D_
/*Set width/height of the div in 'parent'*/    _x000D_
width:100px;_x000D_
height:100px;_x000D_
}_x000D_
_x000D_
_x000D_
.myDiv:before {_x000D_
content: "";_x000D_
position: absolute;/*set 'child' to be absolute*/_x000D_
z-index: -1; /*Make this lower so text appears in front*/_x000D_
   _x000D_
    _x000D_
/*You can choose to align it left, right, top or bottom here*/_x000D_
top: 0; _x000D_
right:0;_x000D_
bottom: 60%;_x000D_
left: 0;_x000D_
    _x000D_
    _x000D_
background: red;_x000D_
}
_x000D_
<div class="myDiv">this is my div with multiple colours. It work's with text too!</div>
_x000D_
_x000D_
_x000D_

I thought i would add this as I feel it could work quite well for a percentage bar/visual level of something.

It also means you're not creating multiple divs if you don't have to, and keeps this page up-to-date

PHP list of specific files in a directory

You can extend the RecursiveFilterIterator class like this:

class ExtensionFilter extends RecursiveFilterIterator
{
  /**
  * Hold the extensions pass to the class constructor 
  */
  protected $extensions;

  /**
   * ExtensionFilter constructor.
   *  
   * @param RecursiveIterator $iterator
   * @param string|array $extensions Extension to filter as an array ['php'] or
   * as string with commas in between 'php, exe, ini'
   */
  public function __construct(RecursiveIterator $iterator, $extensions)
  {
     parent::__construct($iterator);
     $this->extensions = is_array($extensions) ? $extensions :  array_map('trim', explode(',', $extensions));
  }

  public function accept()
  {
      if ($this->hasChildren()) {
         return true;
      }

      return $this->current()->isFile() &&
         in_array(strtolower($this->current()->getExtension()), $this->extensions);
  }

  public function getChildren()
  {
     return new self($this->getInnerIterator()->getChildren(), $this->extensions);
  }

Now you can instantiate RecursiveDirectoryIterator with path as an argument like this:

 $iterator = new RecursiveDirectoryIterator('\path\to\dir');
 $iterator = new ExtensionFilter($iterator, 'xml, php, ini');

 foreach($iterator as $file)
 {
   echo $file . '<br />';
 }

This will list files under the current folder only.

To get the files in subdirectories also, pass the $iterator ( ExtensionFIlter Iterator) to RecursiveIteratorIterator as argument:

$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

Now run the foreach loop on this iterator. You will get the files with specified extension

Note:-- Also make sure to run the ExtensionFilter before RecursiveIteratorIterator, otherwise you will get all the files

Find where python is installed (if it isn't default dir)

For Windows Users:

If the python command is not in your $PATH environment var.

Open PowerShell and run these commands to find the folder

cd \
ls *ython* -Recurse -Directory

That should tell you where python is installed

Can't choose class as main class in IntelliJ

The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

How to select data from 30 days?

For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )

Which is more efficient, a for-each loop, or an iterator?

We should avoid using traditional for loop while working with Collections. The simple reason what I will give is that the complexity of for loop is of the order O(sqr(n)) and complexity of Iterator or even the enhanced for loop is just O(n). So it gives a performence difference.. Just take a list of some 1000 items and print it using both ways. and also print the time difference for the execution. You can sees the difference.

Git - push current branch shortcut

For what it's worth, the ultimate shortcut:

In my .bash_profile I have alias push="git push origin HEAD", so whenever i type push I know I'm pushing to the current branch I'm on.

install apt-get on linux Red Hat server

I think you're running into problems because RedHat uses RPM for managing packages. Debian based systems use DEBs, which are managed with tools like apt.

Failure [INSTALL_FAILED_INVALID_APK]

Force Stop the application in the device settings.

Connect to external server by using phpMyAdmin

You can use the phpmyadmin setup page (./phpmyadmin/setup) to generate a new config file (config.inc.php) for you. This file is found at the root of the phpMyAdmin directory.

Just create the config folder as prompted in setup page, add your servers, then click the 'Save' button. This will create a new config file in the config folder you just created.

You now have only to move the config.inc.php file to the main phpMyAdmin folder, or just copy the lines concerning the servers if you got some old configuration done already you'd like to keep.

Don't forget to delete the config folder afterwards.

How do I run a terminal inside of Vim?

Assuming your version of vim supports +term command first, set shell for vim to use in one command (e.g. set=/usr/bin/zsh), and then run the command +term (i.e. bo 15vs +term). you may have to do some additional maneuvering of your windows (i.e. deleting one and rotating), but you'll have your terminal.

How to do this using jQuery - document.getElementById("selectlist").value

Chaos is spot on, though for these sorts of questions you should check out the Jquery Documentation online - it really is quite comprehensive. The feature you are after is called 'jquery selectors'

Generally you do $('#ID').val() - the .afterwards can do a number of things on the element that is returned from the selector. You can also select all of the elements on a certain class and do something to each of them. Check out the documentation for some good examples.

Transferring files over SSH

You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.

Generally, if you want to download, it will go:

# download: remote -> local
scp user@remote_host:remote_file local_file 

where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:

# upload: local -> remote
scp local_file user@remote_host:remote_file

If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.

Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.

Java String to SHA1

This is my solution of converting string to sha1. It works well in my Android app:

private static String encryptPassword(String password)
{
    String sha1 = "";
    try
    {
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(password.getBytes("UTF-8"));
        sha1 = byteToHex(crypt.digest());
    }
    catch(NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
    catch(UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    return sha1;
}

private static String byteToHex(final byte[] hash)
{
    Formatter formatter = new Formatter();
    for (byte b : hash)
    {
        formatter.format("%02x", b);
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}

BeanFactory vs ApplicationContext

  1. ApplicationContext is more preferred way than BeanFactory

  2. In new Spring versions BeanFactory is replaced with ApplicationContext. But still BeanFactory exists for backward compatability

  3. ApplicationContext extends BeanFactory and has the following benefits
    • it supports internationalization for text messages
    • it supports event publication to the registered listeners
    • access to the resources such as URLs and files

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How to return a html page from a restful controller in spring boot?

The answer from Kukkuz did not work for me until I added in this dependency into the pom file:

<!-- Spring boot Thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

From the guide here.

As well as updating the registry resources as outlined here.

It then started working just fine. If anyone in the future runs into the same issue and following the first answer does not solve your problem, follow these 2 other steps after utilizing the code in @Kukkuz's answer and see if that makes a difference.

Class constants in python

class Animal:
    HUGE = "Huge"
    BIG = "Big"

class Horse:
    def printSize(self):
        print(Animal.HUGE)

CSS Printing: Avoiding cut-in-half DIVs between pages?

I got this problem while using Bootstrap and I had multiple columns in each rows.

I was trying to give page-break-inside: avoid; or break-inside: avoid; to the col-md-6 div elements. That was not working.

I took a hint from the answers given above by DOK that floating elements do not work well with page-break-inside: avoid;.

Instead, I had to give page-break-inside: avoid; or break-inside: avoid; to the <div class="row"> element. And I had multiple rows in my print page.

That is, each row only had 2 columns in it. And they always fit horizontally and do not wrap on a new line.

In another example case, if you want 4 columns in each row, then use col-md-3.

How to substitute shell variables in complex text files

Call the perl binary, in search and replace per line mode ( the -pi ) by running the perl code ( the -e) in the single quotes, which iterates over the keys of the special %ENV hash containing the exported variable names as keys and the exported variable values as the keys' values and for each iteration simple replace a string containing a $<<key>> with its <<value>>.

 perl -pi -e 'foreach $key(sort keys %ENV){ s/\$$key/$ENV{$key}/g}' file

Caveat: An additional logic handling is required for cases in which two or more vars start with the same string ...

How do we determine the number of days for a given month in python

Alternative solution:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29

WPF checkbox binding

This works for me (essential code only included, fill more for your needs):

In XAML a user control is defined:

<UserControl x:Class="Mockup.TestTab" ......>
    <!-- a checkbox somewhere within the control -->
    <!-- IsChecked is bound to Property C1 of the DataContext -->
    <CheckBox Content="CheckBox 1" IsChecked="{Binding C1, Mode=TwoWay}" />
</UserControl>

In code behind for UserControl

public partial class TestTab : UserControl
{
    public TestTab()
    {
        InitializeComponent();  // the standard bit

    // then we set the DataContex of TestTab Control to a MyViewModel object
    // this MyViewModel object becomes the DataContext for all controls
         // within TestTab ... including our CheckBox
         DataContext = new MyViewModel(....);
    }

}

Somewhere in solution class MyViewModel is defined

public class MyViewModel : INotifyPropertyChanged 
{
    public event PropertyChangedEventHandler PropertyChanged;
    private bool m_c1 = true;

    public bool C1 {
        get { return m_c1; }
        set {
            if (m_c1 != value) {
                m_c1 = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("C1"));
            }
        }
    }
}

Explanation of <script type = "text/template"> ... </script>

Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.

By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.

Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.

pandas python how to count the number of records or rows in a dataframe

Simple method to get the records count:

df.count()[0]

Disabled form fields not submitting data

We can also use the readonly only with below attributes -

readonly onclick='return false;'

This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.

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

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.

http://en.wikipedia.org/wiki/HTML5_video

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

YES!....always style textarea using CSS and avoid the attributes, unless you need to support some very old agent that does not support style sheets. Otherwise, you have full power to use CSS. Below is my default CSS formatting for textarea that looks beautiful in any website. Customize it as you like. Comments are included below so you can see why I chose those CSS properties and values:

textarea {
    display: inline-block;
    margin: 0;
    padding: .2em;
    width: auto;
    min-width: 30em;
    /* The max-width "100%" value fixes a weird issue where width is too wide by default and extends beyond 100% of the parent in some agents. */
    max-width: 100%;
    /* Height "auto" will allow the text area to expand vertically in size with a horizontal scrollbar if pre-existing content is added to the box before rendering. Remove this if you want a pre-set height. Use "em" to match the font size set in the website. */
    height: auto;
    /* Use "em" to define the height based on the text size set in your website and the text rows in the box, not a static pixel value. */
    min-height: 10em;
    /* Do not use "border" in textareas unless you want to remove the 3D box most browsers assign and flatten the box design. */
    /*border: 1px solid black;*/
    cursor: text;
    /* Some textareas have a light gray background by default anyway. */
    background-color: #eee;
    /* Overflow "auto" allows the box to start with no scrollbars but add them as content fills the box. */
    overflow: auto;
    /* Resize creates a tab in the lower right corner of textarea for most modern browsers and allows users to resize the box manually. Note: Resize isn't supported by most older agents and IE. */
    resize: both;
}

In my "reset" element style sheet I set these values as defaults for "textarea" by default, which give all your textareas a nice look and feel with scrolling when detected, a resizing tab (non-IE browsers), and fixes for dimensions, including a height that allows the box to size itself based on existing content you put in it for the user and a width that does not break out beyond its parent containers limitations.

Using CSS how to change only the 2nd column of a table

You could designate a class for each cell in the second column.

<table>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
</table>

Whether a variable is undefined

if (var === undefined)

or more precisely

if (typeof var === 'undefined')

Note the === is used

Anaconda-Navigator - Ubuntu16.04

To run anaconda-navigator:

$ source ~/anaconda3/bin/activate root
$ anaconda-navigator

"Strict Standards: Only variables should be passed by reference" error

Instead of parsing it manually it's better to use pathinfo function:

$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];

Cropping an UIImage

Here is my UIImage crop implementation which obeys the imageOrientation property. All orientations were thoroughly tested.

inline double rad(double deg)
{
    return deg / 180.0 * M_PI;
}

UIImage* UIImageCrop(UIImage* img, CGRect rect)
{
    CGAffineTransform rectTransform;
    switch (img.imageOrientation)
    {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };
    rectTransform = CGAffineTransformScale(rectTransform, img.scale, img.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], CGRectApplyAffineTransform(rect, rectTransform));
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:img.scale orientation:img.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

Batch script loop

You could do something to the following effect avoiding the FOR loop.

set counter=0
:loop
echo "input commands here"
SET /A counter=%counter%+1
if %counter% GTR 200
(GOTO exit) else (GOTO loop)
:exit
exit

How do I determine the size of my array in C?

If you know the data type of the array, you can use something like:

int arr[] = {23, 12, 423, 43, 21, 43, 65, 76, 22};

int noofele = sizeof(arr)/sizeof(int);

Or if you don't know the data type of array, you can use something like:

noofele = sizeof(arr)/sizeof(arr[0]);

Note: This thing only works if the array is not defined at run time (like malloc) and the array is not passed in a function. In both cases, arr (array name) is a pointer.

Issue with virtualenv - cannot activate

if you already cd your project type only in windows 10

Scripts/activate

That works for me:)

How to show progress bar while loading, using ajax

<script>
$(function() {
    $("#client").on("change", function() {
      var clientid=$("#client").val();
     //show the loading div here
    $.ajax({
            type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
        success:function(data){
             $("#result").html(data);
          //hide the loading div here
        }
    }); 
    });
});
</script>

Or you can also do this:

$(document).ajaxStart(function() {
        // show loader on start
        $("#loader").css("display","block");
    }).ajaxSuccess(function() {
        // hide loader on success
        $("#loader").css("display","none");
    });

How to sync with a remote Git repository?

Assuming their updates are on master, and you are on the branch you want to merge the changes into.

git remote add origin https://github.com/<github-username>/<repo-name>.git
git pull origin master

Also note that you will then want to push the merge back to your copy of the repository:

git push origin master

React proptype array with shape

And there it is... right under my nose:

From the react docs themselves: https://facebook.github.io/react/docs/reusable-components.html

// An array of a certain type
    optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),

Best way to check if a drop down list contains a value?

There are two methods that come to mind:

You could use Contains like so:

if (ddlCustomerNumber.Items.Contains(new 
    ListItem(GetCustomerNumberCookie().ToString())))
{
    // ... code here
}

or modifying your current strategy:

if (ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString()) != null)
{
    // ... code here
}

EDIT: There's also a DropDownList.Items.FindByValue that works the same way as FindByText, except it searches based on values instead.

Convert a 1D array to a 2D array in numpy

There is a simple way as well, we can use the reshape function in a different way:

A_reshape = A.reshape(No_of_rows, No_of_columns)

Simplest way to download and unzip files in Node.js cross-platform?

I was looking forward this for a long time, and found no simple working example, but based on these answers I created the downloadAndUnzip() function.

The usage is quite simple:

downloadAndUnzip('http://your-domain.com/archive.zip', 'yourfile.xml')
    .then(function (data) {
        console.log(data); // unzipped content of yourfile.xml in root of archive.zip
    })
    .catch(function (err) {
        console.error(err);
    });

And here is the declaration:

var AdmZip = require('adm-zip');
var request = require('request');

var downloadAndUnzip = function (url, fileName) {

    /**
     * Download a file
     * 
     * @param url
     */
    var download = function (url) {
        return new Promise(function (resolve, reject) {
            request({
                url: url,
                method: 'GET',
                encoding: null
            }, function (err, response, body) {
                if (err) {
                    return reject(err);
                }
                resolve(body);
            });
        });
    };

    /**
     * Unzip a Buffer
     * 
     * @param buffer
     * @returns {Promise}
     */
    var unzip = function (buffer) {
        return new Promise(function (resolve, reject) {

            var resolved = false;

            var zip = new AdmZip(buffer);
            var zipEntries = zip.getEntries(); // an array of ZipEntry records

            zipEntries.forEach(function (zipEntry) {
                if (zipEntry.entryName == fileName) {
                    resolved = true;
                    resolve(zipEntry.getData().toString('utf8'));
                }
            });

            if (!resolved) {
                reject(new Error('No file found in archive: ' + fileName));
            }
        });
    };


    return download(url)
        .then(unzip);
};

C - casting int to char and append char to char

Casting int to char is done simply by assigning with the type in parenthesis:

int i = 65535;
char c = (char)i;

Note: I thought that you might be losing data (as in the example), because the type sizes are different.

Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h> functions like strcat or sprintf.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

In my case even though I used all the solutions mentioned above but nothing worked for me. So I decided to uninstall docker and install it again.

Now in the process, I have noticed that I did not check Use Windows containers instead of Linux containers (this can be changed after installation) in my previous installation, and that is why I got the problem above and the solutions still did not fix it. So ensure to check it before you run desktop docker or uninstall it and install it again by checking this option.

Docker Installation Process

Pandas: Convert Timestamp to datetime.date

As of pandas 0.20.3, use .to_pydatetime() to convert any pandas.DateTimeIndex instances to Python datetime.datetime.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

I had a mismatch between projects: one with multi-byte character set, the other with Unicode. Correcting these to agree on Unicode corrected the problem.

jquery select option click handler

The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.

I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:

let blockChange = false;

$element.keydown(function (e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);

    // prevents select opening when enter is pressed
    if (keycode === 13) {
        e.preventDefault();
    }

    // lets the change event know that these keypresses are to be ignored
    if([38, 40].indexOf(keycode) > -1){
        blockChange = true;
    }

});

$element.keyup(function(e) {

    const keycode = (e.keyCode ? e.keyCode : e.which);
    // handle enter press
    if(keycode === 13) {
        doSomething();
    }

});

$element.change(function(e) {

    // this effective handles the click only as preventDefault was used on enter
    if(!blockChange) {
        doSomething();
    }
    blockChange = false;

});

Class constructor type in typescript?

Like that:

class Zoo {
    AnimalClass: typeof Animal;

    constructor(AnimalClass: typeof Animal ) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

Or just:

class Zoo {
    constructor(public AnimalClass: typeof Animal ) {
        let Hector = new AnimalClass();
    }
}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

Here's the relevant part of TypeScript docs. Search for the typeof. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.

Principal Component Analysis (PCA) in Python

For the sake def plot_pca(data): will work, it is necessary to replace the lines

data_resc, data_orig = PCA(data)
ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)

with lines

newData, data_resc, data_orig = PCA(data)
ax1.plot(newData[:, 0], newData[:, 1], '.', mfc=clr1, mec=clr1)

PHP: How to remove all non printable characters in a string?

All of the solutions work partially, and even below probably does not cover all of the cases. My issue was in trying to insert a string into a utf8 mysql table. The string (and its bytes) all conformed to utf8, but had several bad sequences. I assume that most of them were control or formatting.

function clean_string($string) {
  $s = trim($string);
  $s = iconv("UTF-8", "UTF-8//IGNORE", $s); // drop all non utf-8 characters

  // this is some bad utf-8 byte sequence that makes mysql complain - control and formatting i think
  $s = preg_replace('/(?>[\x00-\x1F]|\xC2[\x80-\x9F]|\xE2[\x80-\x8F]{2}|\xE2\x80[\xA4-\xA8]|\xE2\x81[\x9F-\xAF])/', ' ', $s);

  $s = preg_replace('/\s+/', ' ', $s); // reduce all multiple whitespace to a single space

  return $s;
}

To further exacerbate the problem is the table vs. server vs. connection vs. rendering of the content, as talked about a little here

Changing Shell Text Color (Windows)

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

Git Remote: Error: fatal: protocol error: bad line length character: Unab

This error message is a bit obtuse, but what it's actually trying to tell you is that the remote server didn't reply with a proper git response. Ultimately, there was a problem on the server running the git-receive-pack process.

In the Git protocol, the first four bytes should be the line length. Instead, they were the characters Unab... which is probably the beginning an error message of some kind. (ie, it's probably "Unable to..." do something).

What happens when you run ssh <host> git-receive-pack <path-to-git-repository>? You should see the error message that your git client is barfing on and you may be able to correct it.

How to configure port for a Spring Boot application

There are three ways to do it

1 Set server.port property in application.properties file

server.port = 8090

2 Set server port property in application.yml file

server:
     port: 8090

3 Set the property as system property in main method

System.setProperty("server.port","8090");

'invalid value encountered in double_scalars' warning, possibly numpy

Sometimes NaNs or null values in data will generate this error with Numpy. If you are ingesting data from say, a CSV file or something like that, and then operating on the data using numpy arrays, the problem could have originated with your data ingest. You could try feeding your code a small set of data with known values, and see if you get the same result.

How can bcrypt have built-in salts?

I believe that phrase should have been worded as follows:

bcrypt has salts built into the generated hashes to prevent rainbow table attacks.

The bcrypt utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt). Put another way, the "hash" generated by bcrypt is not just the hash. Rather, it is the hash and the salt concatenated.

How can I get last characters of a string

Here 2 examples that will show you always the last character

_x000D_
_x000D_
var id="ctl03_Tabs1";

console.log(id.charAt(id.length - 1)); 

console.log(id[id.length - 1]); 
_x000D_
_x000D_
_x000D_

Getting list of pixel values from PIL

Python shouldn't crash when you call getdata(). The image might be corrupted or there is something wrong with your PIL installation. Try it with another image or post the image you are using.

This should break down the image the way you want:

from PIL import Image
im = Image.open('um_000000.png')

pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]

Best way to generate a random float in C#

Any reason not to use Random.NextDouble and then cast to float? That will give you a float between 0 and 1.

If you want a different form of "best" you'll need to specify your requirements. Note that Random shouldn't be used for sensitive matters such as finance or security - and you should generally reuse an existing instance throughout your application, or one per thread (as Random isn't thread-safe).

EDIT: As suggested in comments, to convert this to a range of float.MinValue, float.MaxValue:

// Perform arithmetic in double type to avoid overflowing
double range = (double) float.MaxValue - (double) float.MinValue;
double sample = rng.NextDouble();
double scaled = (sample * range) + float.MinValue;
float f = (float) scaled;

EDIT: Now you've mentioned that this is for unit testing, I'm not sure it's an ideal approach. You should probably test with concrete values instead - making sure you test with samples in each of the relevant categories - infinities, NaNs, denormal numbers, very large numbers, zero, etc.

What is the difference between UTF-8 and Unicode?

UTF-8 is one possible encoding scheme for Unicode text.

Unicode is a broad-scoped standard which defines over 140,000 characters and allocates each a numerical code (a code point). It also defines rules for how to sort this text, normalise it, change its case, and more. A character in Unicode is represented by a code point from zero up to 0x10FFFF inclusive, though some code points are reserved and cannot be used for characters.

There is more than one way that a string of Unicode code points can be encoded into a binary stream. These are called "encodings". The most straightforward encoding is UTF-32, which simply stores each code point as a 32-bit integer, with each being 4 bytes wide.

UTF-8 is another encoding, and is becoming the de-facto standard, due to a number of advantages over UTF-32 and others. UTF-8 encodes each code point as a sequence of either 1, 2, 3 or 4 byte values. Code points in the ASCII range are encoded as a single byte value, to be compatible with ASCII. Code points outside this range use either 2, 3, or 4 bytes each, depending on what range they are in.

UTF-8 has been designed with these properties in mind:

  • ASCII characters are encoded exactly as they are in ASCII, such that an ASCII string is also a valid UTF-8 string representing the same characters.

  • Binary sorting: Sorting UTF-8 strings using a binary sort will still result in all code points being sorted in numerical order.

  • When a code point uses multiple bytes, none of those bytes contain values in the ASCII range, ensuring that no part of them could be mistaken for an ASCII character. This is also a security feature.

  • UTF-8 can be easily validated, and distinguished from other character encodings by a validator. Text in other 8-bit or multi-byte encodings will very rarely also validate as UTF-8 due to the very specific structure of UTF-8.

  • Random access: At any point in a UTF-8 string it is possible to tell if the byte at that position is the first byte of a character or not, and to find the start of the next or current character, without needing to scan forwards or backwards more than 3 bytes or to know how far into the string we started reading from.

Cannot connect to local SQL Server with Management Studio

Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.

How do I raise the same Exception with a custom message in Python?

This only works with Python 3. You can modify the exception's original arguments and add your own arguments.

An exception remembers the args it was created with. I presume this is so that you can modify the exception.

In the function reraise we prepend the exception's original arguments with any new arguments that we want (like a message). Finally we re-raise the exception while preserving the trace-back history.

def reraise(e, *args):
  '''re-raise an exception with extra arguments
  :param e: The exception to reraise
  :param args: Extra args to add to the exception
  '''

  # e.args is a tuple of arguments that the exception with instantiated with.
  #
  e.args = args + e.args

  # Recreate the expection and preserve the traceback info so thta we can see 
  # where this exception originated.
  #
  raise e.with_traceback(e.__traceback__)   


def bad():
  raise ValueError('bad')

def very():
  try:
    bad()
  except Exception as e:
    reraise(e, 'very')

def very_very():
  try:
    very()
  except Exception as e:
    reraise(e, 'very')

very_very()

output

Traceback (most recent call last):
  File "main.py", line 35, in <module>
    very_very()
  File "main.py", line 30, in very_very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 28, in very_very
    very()
  File "main.py", line 24, in very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 22, in very
    bad()
  File "main.py", line 18, in bad
    raise ValueError('bad')
ValueError: ('very', 'very', 'bad')

Is there a unique Android device ID?

I have came across this question several years ago, and have learn to implement a generalized solution based on various answers.

I have used the generalized solution for several years, in a real-world product. It serves me quite well so far. Here's the code snippet, based on various provided answers.

Note, getEmail will return null most of the time, as we didn't ask for permission explicitly.

private static UniqueId getUniqueId() {
    MyApplication app = MyApplication.instance();

    // Our prefered method of obtaining unique id in the following order.
    // (1) Advertising id
    // (2) Email
    // (2) ANDROID_ID
    // (3) Instance ID - new id value, when reinstall the app.

    ////////////////////////////////////////////////////////////////////////////////////////////
    // ADVERTISING ID
    ////////////////////////////////////////////////////////////////////////////////////////////
    AdvertisingIdClient.Info adInfo = null;
    try {
        adInfo = AdvertisingIdClient.getAdvertisingIdInfo(app);
    } catch (IOException e) {
        Log.e(TAG, "", e);
    } catch (GooglePlayServicesNotAvailableException e) {
        Log.e(TAG, "", e);
    } catch (GooglePlayServicesRepairableException e) {
        Log.e(TAG, "", e);
    }

    if (adInfo != null) {
        String aid = adInfo.getId();
        if (!Utils.isNullOrEmpty(aid)) {
            return UniqueId.newInstance(aid, UniqueId.Type.aid);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // EMAIL
    ////////////////////////////////////////////////////////////////////////////////////////////
    final String email = Utils.getEmail();
    if (!Utils.isNullOrEmpty(email)) {
        return UniqueId.newInstance(email, UniqueId.Type.eid);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // ANDROID ID
    ////////////////////////////////////////////////////////////////////////////////////////////
    final String sid = Settings.Secure.getString(app.getContentResolver(), Settings.Secure.ANDROID_ID);
    if (!Utils.isNullOrEmpty(sid)) {
        return UniqueId.newInstance(sid, UniqueId.Type.sid);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // INSTANCE ID
    ////////////////////////////////////////////////////////////////////////////////////////////
    final String iid = com.google.android.gms.iid.InstanceID.getInstance(MyApplication.instance()).getId();
    if (!Utils.isNullOrEmpty(iid)) {
        return UniqueId.newInstance(iid, UniqueId.Type.iid);
    }

    return null;
}

public final class UniqueId implements Parcelable {
    public enum Type implements Parcelable {
        aid,
        sid,
        iid,
        eid;

        ////////////////////////////////////////////////////////////////////////////
        // Handling Parcelable nicely.

        public static final Parcelable.Creator<Type> CREATOR = new Parcelable.Creator<Type>() {
            public Type createFromParcel(Parcel in) {
                return Type.valueOf(in.readString());
            }

            public Type[] newArray(int size) {
                return new Type[size];
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel parcel, int flags) {
            parcel.writeString(this.name());
        }

        // Handling Parcelable nicely.
        ////////////////////////////////////////////////////////////////////////////
    }

    public static boolean isValid(UniqueId uniqueId) {
        if (uniqueId == null) {
            return false;
        }
        return uniqueId.isValid();
    }

    private boolean isValid() {
        return !org.yccheok.jstock.gui.Utils.isNullOrEmpty(id) && type != null;
    }

    private UniqueId(String id, Type type) {
        if (org.yccheok.jstock.gui.Utils.isNullOrEmpty(id) || type == null) {
            throw new java.lang.IllegalArgumentException();
        }
        this.id = id;
        this.type = type;
    }

    public static UniqueId newInstance(String id, Type type) {
        return new UniqueId(id, type);
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + id.hashCode();
        result = 31 * result + type.hashCode();
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof UniqueId)) {
            return false;
        }

        UniqueId uniqueId = (UniqueId)o;
        return this.id.equals(uniqueId.id) && this.type == uniqueId.type;
    }

    @Override
    public String toString() {
        return type + ":" + id;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Handling Parcelable nicely.

    public static final Parcelable.Creator<UniqueId> CREATOR = new Parcelable.Creator<UniqueId>() {
        public UniqueId createFromParcel(Parcel in) {
            return new UniqueId(in);
        }

        public UniqueId[] newArray(int size) {
            return new UniqueId[size];
        }
    };

    private UniqueId(Parcel in) {
        this.id = in.readString();
        this.type = in.readParcelable(Type.class.getClassLoader());
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeString(this.id);
        parcel.writeParcelable(this.type, 0);
    }

    // Handling Parcelable nicely.
    ////////////////////////////////////////////////////////////////////////////

    public final String id;
    public final Type type;
}

public static String getEmail() {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
    AccountManager accountManager = AccountManager.get(MyApplication.instance());
    Account[] accounts = accountManager.getAccountsByType("com.google");
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            String possibleEmail = account.name;
            return possibleEmail;
        }
    }

    accounts = accountManager.getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            String possibleEmail = account.name;
            return possibleEmail;
        }
    }

    return null;
} 

C#: Converting byte array to string and printing out to console

This is just an updated version of Jesse Webbs code that doesn't append the unnecessary trailing , character.

public static string PrintBytes(this byte[] byteArray)
{
    var sb = new StringBuilder("new byte[] { ");
    for(var i = 0; i < byteArray.Length;i++)
    {
        var b = byteArray[i];
        sb.Append(b);
        if (i < byteArray.Length -1)
        {
            sb.Append(", ");
        }
    }
    sb.Append(" }");
    return sb.ToString();
}

The output from this method would be:

new byte[] { 48, ... 135, 31, 178, 7, 157 }

Response to preflight request doesn't pass access control check

JavaScript XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

You have to send the Access-Control-Allow-Origin: * HTTP header from your server side.

If you are using Apache as your HTTP server then you can add it to your Apache configuration file like this:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled by running:

 a2enmod headers

Git push hangs when pushing to Github?

Restart your ssh agent!

killall ssh-agent; eval `ssh-agent`

SQL query, store result of SELECT in local variable

Isn't this a much simpler solution, if I correctly understand the question, of course.

I want to load email addresses that are in a table called "spam" into a variable.

select email from spam

produces the following list, say:

.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu

To load into the variable @list:

declare @list as varchar(8000)
set @list += @list (select email from spam)

@list may now be INSERTed into a table, etc.

I hope this helps.

To use it for a .csv file or in VB, spike the code:

declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list

and it produces ready-made code to use elsewhere:

".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"

One can be very creative.

Thanks

Nico

c++ custom compare function for std::sort()

Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

It says:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • comp - comparison function which returns ?true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

std::sort(std::begin(container), std::end(container),
          [] (const auto& lhs, const auto& rhs) {
    return lhs.first < rhs.first;
});

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

Calling Non-Static Method In Static Method In Java

public class StaticMethod{

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

    public int methodOne(){
        System.out.println("we are in first methodOne");
        return 1;
    }
}

the above code not executed because static method must have that class reference.

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

        StaticMethod sm=new StaticMethod();
        sm.methodOne();
    }

    public int methodOne(){
        System.out.println("we are in first methodOne");
        return 1;
    }
}

This will be definitely get executed. Because here we are creating reference which nothing but "sm" by using that reference of that class which is nothing but (StaticMethod=new Static method()) we are calling method one (sm.methodOne()).

I hope this will be helpful.

Do copyright dates need to be updated?

Your OCD is to blame :)

You do not have to put anything about copyright on your page - copyright automatically applies until you explicitly license it otherwise. Copyright also applies for a preset number of years as determined by international treaties. I do not know what the exact number of years is, but it is a lot, so there is absolutely no point in updating the year in your copyright notice.

In Android EditText, how to force writing uppercase?

try this code it will make your input into upper case

edittext.setFilters(new InputFilter[] {new InputFilter.AllCaps()});

Clear the value of bootstrap-datepicker

You can use jQuery to clear the value of your date input.

For exemple with a button and a text input like this :

<input type="text" id="datepicker">
<button id="reset-date">Reset</button>

You can use the .val() function of jQuery.

$("#reset-date").click(function(){
    $('#datepicker').val("").datepicker("update");
})

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Android Completely transparent Status Bar?

All you need to do is set these properties in your theme:

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>

Your activity / container layout you wish to have a transparent status bar needs this property set:

android:fitsSystemWindows="true"

It is generally not possible to perform this for sure on pre-kitkat, looks like you can do it but some strange code makes it so.

EDIT: I would recommend this lib: https://github.com/jgilfelt/SystemBarTint for lots of pre-lollipop status bar color control.

Well after much deliberation I've learned that the answer to totally disabling the translucency or any color placed on the status bar and navigation bar for lollipop is to set this flag on the window:

// In Activity's onCreate() for instance
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    Window w = getWindow();
    w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}

No other theme-ing is necessary, it produces something like this:

enter image description here

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

How do I get the Date & Time (VBS)

nowreturns the current date and time

Append TimeStamp to a File Name

You can use DateTime.ToString Method (String)

DateTime.Now.ToString("yyyyMMddHHmmssfff")

or string.Format

string.Format("{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now);

or Interpolated Strings

$"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}"

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).

With Extension Method

Usage:

string result = "myfile.txt".AppendTimeStamp();
//myfile20130604234625642.txt

Extension method

public static class MyExtensions
{
    public static string AppendTimeStamp(this string fileName)
    {
        return string.Concat(
            Path.GetFileNameWithoutExtension(fileName),
            DateTime.Now.ToString("yyyyMMddHHmmssfff"),
            Path.GetExtension(fileName)
            );
    }
}

Stopword removal with NLTK

There is an in-built stopword list in NLTK made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html

>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop] 
['foo', 'bar', 'sentence']

I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?

Merging dictionaries in C#

@Tim: Should be a comment, but comments don't allow for code editing.

Dictionary<string, string> t1 = new Dictionary<string, string>();
t1.Add("a", "aaa");
Dictionary<string, string> t2 = new Dictionary<string, string>();
t2.Add("b", "bee");
Dictionary<string, string> t3 = new Dictionary<string, string>();
t3.Add("c", "cee");
t3.Add("d", "dee");
t3.Add("b", "bee");
Dictionary<string, string> merged = t1.MergeLeft(t2, t2, t3);

Note: I applied the modification by @ANeves to the solution by @Andrew Orsich, so the MergeLeft looks like this now:

public static Dictionary<K, V> MergeLeft<K, V>(this Dictionary<K, V> me, params IDictionary<K, V>[] others)
    {
        var newMap = new Dictionary<K, V>(me, me.Comparer);
        foreach (IDictionary<K, V> src in
            (new List<IDictionary<K, V>> { me }).Concat(others))
        {
            // ^-- echk. Not quite there type-system.
            foreach (KeyValuePair<K, V> p in src)
            {
                newMap[p.Key] = p.Value;
            }
        }
        return newMap;
    }

Export to CSV using MVC, C# and jQuery

What happens if you get rid of the stringwriter:

        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=adressenbestand.csv");
        Response.ContentType = "text/csv";
        //write the header
        Response.Write(String.Format("{0},{1},{2},{3}", CMSMessages.EmailAddress, CMSMessages.Gender, CMSMessages.FirstName, CMSMessages.LastName));

        //write every subscriber to the file
        var resourceManager = new ResourceManager(typeof(CMSMessages));
        foreach (var record in filterRecords.Select(x => x.First().Subscriber))
        {
            Response.Write(String.Format("{0},{1},{2},{3}", record.EmailAddress, record.Gender.HasValue ? resourceManager.GetString(record.Gender.ToString()) : "", record.FirstName, record.LastName));
        }

        Response.End();

Numpy where function multiple conditions

The accepted answer explained the problem well enough. However, the more Numpythonic approach for applying multiple conditions is to use numpy logical functions. In this case, you can use np.logical_and:

np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))

Javascript to Select Multiple options

Based on @Peter Baley answer, I created a more generic function:

   @objectId: HTML object ID
   @values: can be a string or an array. String is less "secure" (should not contain repeated value).
   function checkMultiValues(objectId, values){
        selectMultiObject=document.getElementById(objectId);
        for ( var i = 0, l = selectMultiObject.options.length, o; i < l; i++ )
        {
          o = selectMultiObject.options[i];
          if ( values.indexOf( o.value ) != -1 )
          {
            o.selected = true;
          } else {
            o.selected = false;
          }
        }
    }

Example: checkMultiValues('thisMultiHTMLObject','a,b,c,d');

Upgrade python without breaking yum

Daniel's answer is probably the most ideal one as it doesn't involve changing OS files. However, I found myself in a situation where I needed a 3rd party program which invoked python by calling usr/bin/python, but required Python 2.7.16, while the default Python was 2.7.5. That meant I had to make usr/bin/python point to a Python version of 2.7.16 version, which meant that yum wouldn't work.

What I ended up doing is editing the file /usr/bin/yum and replacing the shebang there to use to the system default Python (in my case, that meant changing #! /usr/bin/python to #! /usr/bin/python2). However, after that running yum gave me an error:

ImportError: No module named urlgrabber.grabber

I solved that by replacing the shebang in /usr/libexec/urlgrabber-ext-down the same way as in /usr/bin/yum. I.e., #! /usr/bin/python to #! /usr/bin/python2. After that yum worked.

This is a hack and should be used with care. As mentioned in other comments, modifying OS files should be last resort only.

Round number to nearest integer

If you need (for example) a two digit approximation for A, then int(A*100+0.5)/100.0 will do what you are looking for.

If you need three digit approximation multiply and divide by 1000 and so on.

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

HashMap allows duplicates?

Code example:

HashMap<Integer,String> h = new HashMap<Integer,String> ();

h.put(null,null);
h.put(null, "a");

System.out.println(h);

Output:

{null=a}

It overrides the value at key null.

When is del useful in Python?

Firstly, you can del other things besides local variables

del list_item[4]
del dictionary["alpha"]

Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer. Compare:

del foo

to

foo = None

I know in the case of del foo that the intent is to remove the variable from scope. It's not clear that foo = None is doing that. If somebody just assigned foo = None I might think it was dead code. But I instantly know what somebody who codes del foo was trying to do.

Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
    df1.user_id,
    c.rating
from df1
    inner join df2 on df2.user_i = df1.user_id
    outer apply (
        select df1.rating union all
        select df2.rating
    ) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
   user_id  rating
0        3      20
0        3      30

PHP regular expression - filter number only

Another way to get only the numbers in a regex string is as shown below:

$output = preg_replace("/\D+/", "", $input);

Downloading a file from spring controllers

If it helps anyone. You can do what the accepted answer by Infeligo has suggested but just put this extra bit in the code for a forced download.

response.setContentType("application/force-download");

Python - difference between two strings

The answer to my comment above on the Original Question makes me think this is all he wants:

loopnum = 0
word = 'afrykanerskojezyczny'
wordlist = ['afrykanerskojezycznym','afrykanerskojezyczni','nieafrykanerskojezyczni']
for i in wordlist:
    wordlist[loopnum] = word
    loopnum += 1

This will do the following:

For every value in wordlist, set that value of the wordlist to the origional code.

All you have to do is put this piece of code where you need to change wordlist, making sure you store the words you need to change in wordlist, and that the original word is correct.

Hope this helps!

What data type to use for hashed password field and what length?

You should use TEXT (storing unlimited number of characters) for the sake of forward compatibility. Hashing algorithms (need to) become stronger over time and thus this database field will need to support more characters over time. Additionally depending on your migration strategy you may need to store new and old hashes in the same field, so fixing the length to one type of hash is not recommended.

Setting device orientation in Swift iOS

If someone wants the answer, I think I just got it. Try this:

  • Go to your .plist file and check all the orientations.
  • In the view controller you want to force orientation, add the following code:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait.toRaw().hashValue | UIInterfaceOrientationMask.PortraitUpsideDown.toRaw().hashValue
}

Hope it helps !

EDIT :

To force rotation, use the following code :

let value = UIInterfaceOrientation.LandscapeRight.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

It works for iOS 7 & 8 !

Setting format and value in input type="date"

@cOnstructOr provided a great idea, but it left a comma in place

var today = new Date().toLocaleString('en-GB').split(' ')[0].slice(0,-1).split('/').reverse().join('-');

fixes that

Onchange open URL via select - jQuery

If you don't want the url to put it on option's value, i'll give u example :

<select class="abc">
    <option value="0" href="hello">Hell</option>
    <option value="1" href="dello">Dell</option>
    <option value="2" href="cello">Cell</option>
</select>

    $("select").bind('change',function(){
        alert($(':selected',this).attr('href'));
    })

Increase number of axis ticks

You can override ggplots default scales by modifying scale_x_continuous and/or scale_y_continuous. For example:

library(ggplot2)
dat <- data.frame(x = rnorm(100), y = rnorm(100))

ggplot(dat, aes(x,y)) +
  geom_point()

Gives you this:

enter image description here

And overriding the scales can give you something like this:

ggplot(dat, aes(x,y)) +
  geom_point() +
  scale_x_continuous(breaks = round(seq(min(dat$x), max(dat$x), by = 0.5),1)) +
  scale_y_continuous(breaks = round(seq(min(dat$y), max(dat$y), by = 0.5),1))

enter image description here

If you want to simply "zoom" in on a specific part of a plot, look at xlim() and ylim() respectively. Good insight can also be found here to understand the other arguments as well.

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

How to edit/save a file through Ubuntu Terminal

Normal text editors are nano, or vi.

For example:

root@user:# nano galfit.feedme

or

root@user:# vi galfit.feedme

How can I detect window size with jQuery?

You can get the values for the width and height of the browser using the following:

$(window).height();
$(window).width();

To get notified when the browser is resized, use this bind callback:

$(window).resize(function() {
    // Do something
});

Most Pythonic way to provide global configuration variables in config.py?

How about using classes?

# config.py
class MYSQL:
    PORT = 3306
    DATABASE = 'mydb'
    DATABASE_TABLES = ['tb_users', 'tb_groups']

# main.py
from config import MYSQL

print(MYSQL.PORT) # 3306

javascript cell number validation

<script type="text/javascript">
    function MobileNoValidation()
    {
       var phno=/^\d{10}$/
       if(textMobileNo.value=="")
       {
        alert("Mobile No Should Not Be Empty");
       }
       else if(!textMobileNo.value.match(phno))
       {
        alert("Mobile no must be ten digit");
       }
       else
       {
        alert("valid Mobile No");
       }
    }
</script>

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

Cross-Origin Read Blocking (CORB)

In most cases, the blocked response should not affect the web page's behavior and the CORB error message can be safely ignored. For example, the warning may occur in cases when the body of the blocked response was empty already, or when the response was going to be delivered to a context that can't handle it (e.g., a HTML document such as a 404 error page being delivered to an tag).

https://www.chromium.org/Home/chromium-security/corb-for-developers

I had to clean my browser's cache, I was reading in this link, that, if the request get a empty response, we get this warning error. I was getting some CORS on my request, and so the response of this request got empty, All I had to do was clear the browser's cache, and the CORS got away. I was receiving CORS because the chrome had saved the PORT number on the cache, The server would just accept localhost:3010 and I was doing localhost:3002, because of the cache.

How to remove specific session in asp.net?

There is nothing like session container , so you can set it as null

but rather you can set individual session element as null or ""

like Session["userid"] = null;

How to add a hook to the application context initialization event?

Spring has some standard events which you can handle.

To do that, you must create and register a bean that implements the ApplicationListener interface, something like this:

package test.pack.age;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            // now you can do applicationContext.getBean(...)
            // ...
        }
    }
}

You then register this bean within your servlet.xml or applicationContext.xml file:

<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />

and Spring will notify it when the application context is initialized.

In Spring 3 (if you are using this version), the ApplicationListener class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        // now you can do applicationContext.getBean(...)
        // ...
    }
}

How to extract text from a string using sed?

The pattern \d might not be supported by your sed. Try [0-9] or [[:digit:]] instead.

To only print the actual match (not the entire matching line), use a substitution.

sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Pillow is new version

PIL-1.1.7.win-amd64-py2.x installers are available at

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

Npm Please try using this command again as root/administrator

Deleting the global npm-cache and/or running my cmd line as admin did not work for me. Also, as of npm version 5.x.x, it supposedly recovers from cache corruption by itself.

This did work:

1. Deleted the node_modules folder in my current project.

2. Deleted the package-lock.json in my current project

3. Installed the new package. In my case: npm install bootstrap@next --save

4. Ran npm install for my current project.

Everything now works. In general, nuking node_modules and package-lock.json usually fix these "no apparent reason" bugs for me.

EDIT

I just had the same problem again. But I noticed that everything was installed correctly even though it threw the error after I had followed the steps outlined above. So I could just run ng serve (for Angular), and everything worked.

This sure is a weird error...

PHP Redirect with POST data

You can let PHP do a POST, but then your php will get the return, with all sorts of complications. I think the simplest would be to actually let the user do the POST.

So, kind-of what you suggested, you'll get indeed this part:

Customer fill detail in Page A, then in Page B we create another page show all the customer detail there, click a CONFIRM button then POST to Page C.

But you can actually do a javascript submit on page B, so there is no need for a click. Make it a "redirecting" page with a loading animation, and you're set.

How do I convert a float number to a whole number in JavaScript?

There are many suggestions here. The bitwise OR seems to be the simplest by far. Here is another short solution which works with negative numbers as well using the modulo operator. It is probably easier to understand than the bitwise OR:

intval = floatval - floatval%1;

This method also works with high value numbers where neither '|0' nor '~~' nor '>>0' work correctly:

> n=4294967295;
> n|0
-1
> ~~n
-1
> n>>0
-1
> n-n%1
4294967295

What is the difference between \r and \n?

\r is Carriage Return; \n is New Line (Line Feed) ... depends on the OS as to what each means. Read this article for more on the difference between '\n' and '\r\n' ... in C.

Remove all constraints affecting a UIView

You can remove all constraints in a view by doing this:

self.removeConstraints(self.constraints)

EDIT: To remove the constraints of all subviews, use the following extension in Swift:

extension UIView {
    func clearConstraints() {
        for subview in self.subviews {
            subview.clearConstraints()
        }
        self.removeConstraints(self.constraints)
    }
}

How to highlight a selected row in ngRepeat?

You probably want to have LI rather than the UL have the background-color:

.selected li {
  background-color: red;
}

Then you want to have a dynamic class for the UL:

<ul ng-repeat="vote in votes" ng-click="setSelected()" class="{{selected}}">

Now you need to update the $scope.selected when clicking the row:

$scope.setSelected = function() {
   console.log("show", arguments, this);
   this.selected = 'selected';
}

and then un-select the previously highlighted row:

$scope.setSelected = function() {
   // console.log("show", arguments, this);
   if ($scope.lastSelected) {
     $scope.lastSelected.selected = '';
   }
   this.selected = 'selected';
   $scope.lastSelected = this;
}

Working solution:

http://plnkr.co/edit/wq6nxc?p=preview

Android: adb pull file on desktop

do adb pull \sdcard\log.txt C:Users\admin\Desktop

Python Brute Force algorithm

from random import choice

sl = 4  #start length
ml = 8 #max length 
ls = '9876543210qwertyuiopasdfghjklzxcvbnm' # list
g = 0
tries = 0

file = open("file.txt",'w') #your file

for j in range(0,len(ls)**4):
    while sl <= ml:
        i = 0
        while i < sl:
            file.write(choice(ls))
            i += 1
        sl += 1
        file.write('\n')
        g += 1
    sl -= g
    g = 0
    print(tries)
    tries += 1


file.close()

When to use Hadoop, HBase, Hive and Pig?

Understanding in depth

Hadoop

Hadoop is an open source project of the Apache foundation. It is a framework written in Java, originally developed by Doug Cutting in 2005. It was created to support distribution for Nutch, the text search engine. Hadoop uses Google's Map Reduce and Google File System Technologies as its foundation.

Features of Hadoop

  1. It is optimized to handle massive quantities of structured, semi-structured and unstructured data using commodity hardware.
  2. It has shared nothing architecture.
  3. It replicates its data into multiple computers so that if one goes down, the data can still be processed from another machine that stores its replica.
  4. Hadoop is for high throughput rather than low latency. It is a batch operation handling massive quantities of data; therefore the response time is not immediate.
  5. It complements Online Transaction Processing and Online Analytical Processing. However, it is not a replacement for a RDBMS.
  6. It is not good when work cannot be parallelized or when there are dependencies within the data.
  7. It is not good for processing small files. It works best with huge data files and data sets.

Versions of Hadoop

There are two versions of Hadoop available :

  1. Hadoop 1.0
  2. Hadoop 2.0

Hadoop 1.0

It has two main parts :

1. Data Storage Framework

It is a general-purpose file system called Hadoop Distributed File System (HDFS).

HDFS is schema-less

It simply stores data files and these data files can be in just about any format.

The idea is to store files as close to their original form as possible.

This in turn provides the business units and the organization the much needed flexibility and agility without being overly worried by what it can implement.

2. Data Processing Framework

This is a simple functional programming model initially popularized by Google as MapReduce.

It essentially uses two functions: MAP and REDUCE to process data.

The "Mappers" take in a set of key-value pairs and generate intermediate data (which is another list of key-value pairs).

The "Reducers" then act on this input to produce the output data.

The two functions seemingly work in isolation with one another, thus enabling the processing to be highly distributed in highly parallel, fault-tolerance and scalable way.

Limitations of Hadoop 1.0

  1. The first limitation was the requirement of MapReduce programming expertise.

  2. It supported only batch processing which although is suitable for tasks such as log analysis, large scale data mining projects but pretty much unsuitable for other kinds of projects.

  3. One major limitation was that Hadoop 1.0 was tightly computationally coupled with MapReduce, which meant that the established data management vendors where left with two opinions:

    1. Either rewrite their functionality in MapReduce so that it could be executed in Hadoop or

    2. Extract data from HDFS or process it outside of Hadoop.

None of the options were viable as it led to process inefficiencies caused by data being moved in and out of the Hadoop cluster.

Hadoop 2.0

In Hadoop 2.0, HDFS continues to be data storage framework.

However, a new and seperate resource management framework called Yet Another Resource Negotiater (YARN) has been added.

Any application capable of dividing itself into parallel tasks is supported by YARN.

YARN coordinates the allocation of subtasks of the submitted application, thereby further enhancing the flexibility, scalability and efficiency of applications.

It works by having an Application Master in place of Job Tracker, running applications on resources governed by new Node Manager.

ApplicationMaster is able to run any application and not just MapReduce.

This means it does not only support batch processing but also real-time processing. MapReduce is no longer the only data processing option.

Advantages of Hadoop

It stores data in its native from. There is no structure imposed while keying in data or storing data. HDFS is schema less. It is only later when the data needs to be processed that the structure is imposed on the raw data.

It is scalable. Hadoop can store and distribute very large datasets across hundreds of inexpensive servers that operate in parallel.

It is resilient to failure. Hadoop is fault tolerance. It practices replication of data diligently which means whenever data is sent to any node, the same data also gets replicated to other nodes in the cluster, thereby ensuring that in event of node failure,there will always be another copy of data available for use.

It is flexible. One of the key advantages of Hadoop is that it can work with any kind of data: structured, unstructured or semi-structured. Also, the processing is extremely fast in Hadoop owing to the "move code to data" paradigm.

Hadoop Ecosystem

Following are the components of Hadoop ecosystem:

HDFS: Hadoop Distributed File System. It simply stores data files as close to the original form as possible.

HBase: It is Hadoop's database and compares well with an RDBMS. It supports structured data storage for large tables.

Hive: It enables analysis of large datasets using a language very similar to standard ANSI SQL, which implies that anyone familier with SQL should be able to access data on a Hadoop cluster.

Pig: It is an easy to understand data flow language. It helps with analysis of large datasets which is quite the order with Hadoop. Pig scripts are automatically converted to MapReduce jobs by the Pig interpreter.

ZooKeeper: It is a coordination service for distributed applications.

Oozie: It is a workflow schedular system to manage Apache Hadoop jobs.

Mahout: It is a scalable machine learning and data mining library.

Chukwa: It is data collection system for managing large distributed system.

Sqoop: It is used to transfer bulk data between Hadoop and structured data stores such as relational databases.

Ambari: It is a web based tool for provisioning, managing and monitoring Hadoop clusters.

Hive

Hive is a data warehouse infrastructure tool to process structured data in Hadoop. It resides on top of Hadoop to summarize Big Data and makes querying and analyzing easy.

Hive is not

  1. A relational database

  2. A design for Online Transaction Processing (OLTP).

  3. A language for real-time queries and row-level updates.

Features of Hive

  1. It stores schema in database and processed data into HDFS.

  2. It is designed for OLAP.

  3. It provides SQL type language for querying called HiveQL or HQL.

  4. It is familier, fast, scalable and extensible.

Hive Architecture

The following components are contained in Hive Architecture:

  1. User Interface: Hive is a data warehouse infrastructure that can create interaction between user and HDFS. The User Interfaces that Hive supports are Hive Web UI, Hive Command line and Hive HD Insight(In Windows Server).

  2. MetaStore: Hive chooses respective database servers to store the schema or Metadata of tables, databases, columns in a table, their data types and HDFS mapping.

  3. HiveQL Process Engine: HiveQL is similar to SQL for querying on schema info on the Metastore. It is one of the replacements of traditional approach for MapReduce program. Instead of writing MapReduce in Java, we can write a query for MapReduce and process it.

  4. Exceution Engine: The conjunction part of HiveQL process engine and MapReduce is the Hive Execution Engine. Execution engine processes the query and generates results as same as MapReduce results. It uses the flavor of MapReduce.

  5. HDFS or HBase: Hadoop Distributed File System or HBase are the data storage techniques to store data into file system.

Warning: date_format() expects parameter 1 to be DateTime

Best way is use DateTime object to convert your date.

$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');

Note: It will support for PHP 5 >= 5.3.0 only.

Convert HTML + CSS to PDF

After some investigation and general hair-pulling the solution seems to be HTML2PDF. DOMPDF did a terrible job with tables, borders and even moderately complex layout and htmldoc seems reasonably robust but is almost completely CSS-ignorant and I don't want to go back to doing HTML layout without CSS just for that program.

HTML2PDF looked the most promising but I kept having this weird error about null reference arguments to node_type. I finally found the solution to this. Basically, PHP 5.1.x worked fine with regex replaces (preg_replace_*) on strings of any size. PHP 5.2.1 introduced a php.ini config directive called pcre.backtrack_limit. What this config parameter does is limits the string length for which matching is done. Why this was introduced I don't know. The default value was chosen as 100,000. Why such a low value? Again, no idea.

A bug was raised against PHP 5.2.1 for this, which is still open almost two years later.

What's horrifying about this is that when the limit is exceeded, the replace just silently fails. At least if an error had been raised and logged you'd have some indication of what happened, why and what to change to fix it. But no.

So I have a 70k HTML file to turn into PDF. It requires the following php.ini settings:

  • pcre.backtrack_limit = 2000000; # probably more than I need but that's OK
  • memory_limit = 1024M; # yes, one gigabyte; and
  • max_execution_time = 600; # yes, 10 minutes.

Now the astute reader may have noticed that my HTML file is smaller than 100k. The only reason I can guess as to why I hit this problem is that html2pdf does a conversion into xhtml as part of the process. Perhaps that took me over (although nearly 50% bloat seems odd). Whatever the case, the above worked.

Now, html2pdf is a resource hog. My 70k file takes approximately 5 minutes and at least 500-600M of RAM to create a 35 page PDF file. Not quick enough (by far) for a real-time download unfortunately and the memory usage puts the memory usage ratio in the order of 1000-to-1 (600M of RAM for a 70k file), which is utterly ridiculous.

Unfortunately, that's the best I've come up with.

Call a stored procedure with parameter in c#

Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money

public void SaveTransaction(Transaction transaction) 
{
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        using (var cmd = new SqlCommand("spAddTransaction", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

Set cellpadding and cellspacing in CSS?

From what I understand from the W3C classifications is that <table>s are meant for displaying data 'only'.

Based on that I found it a lot easier to create a <div> with the backgrounds and all that and have a table with data floating over it using position: absolute; and background: transparent;...

It works on Chrome, Internet Explorer (6 and later) and Mozilla Firefox (2 and later).

Margins are used (or meant anyways) to create a spacer between container elements, like <table>, <div> and <form>, not <tr>, <td>, <span> or <input>. Using it for anything other than container elements will keep you busy adjusting your website for future browser updates.

Cross-browser custom styling for file upload button

This seems to take care of business pretty well. A fidde is here:

HTML

<label for="upload-file">A proper input label</label>

<div class="upload-button">

    <div class="upload-cover">
         Upload text or whatevers
    </div>

    <!-- this is later in the source so it'll be "on top" -->
    <input name="upload-file" type="file" />

</div> <!-- .upload-button -->

CSS

/* first things first - get your box-model straight*/
*, *:before, *:after {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

label {
    /* just positioning */
    float: left; 
    margin-bottom: .5em;
}

.upload-button {
    /* key */
    position: relative;
    overflow: hidden;

    /* just positioning */
    float: left; 
    clear: left;
}

.upload-cover { 
    /* basically just style this however you want - the overlaying file upload should spread out and fill whatever you turn this into */
    background-color: gray;
    text-align: center;
    padding: .5em 1em;
    border-radius: 2em;
    border: 5px solid rgba(0,0,0,.1);

    cursor: pointer;
}

.upload-button input[type="file"] {
    display: block;
    position: absolute;
    top: 0; left: 0;
    margin-left: -75px; /* gets that button with no-pointer-cursor off to the left and out of the way */
    width: 200%; /* over compensates for the above - I would use calc or sass math if not here*/
    height: 100%;
    opacity: .2; /* left this here so you could see. Make it 0 */
    cursor: pointer;
    border: 1px solid red;
}

.upload-button:hover .upload-cover {
    background-color: #f06;
}

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Kotlin version:

Use these extensions with infix functions that simplify later calls

infix fun View.below(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

infix fun View.leftOf(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}

infix fun View.alightParentRightIs(aligned: Boolean) {
    val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
    if (aligned) {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
    } else {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
    }
    this.layoutParams = layoutParams
}

Then use them as infix functions calls:

view1 below view2
view1 leftOf view2
view1 alightParentRightIs true

Or you can use them as normal functions:

view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)

jQuery: enabling/disabling datepicker

The most up-voted solution did not work for me. I have date pickers with default of disabled, which works fine. When it comes time to enable them in the window.onload function, though, the $("#award_start_date").datepicker( 'enable' ); syntax did not enable the widgets. I was able to edit the field as if it were a text input field, but did not get the calendar chooser.

What does work is this:

if (x[i].id == "award_start_date") {
  $("#award_start_date").datepicker( {enabled: true} );
}
if (x[i].id == "award_end_date") {
  $("#award_end_date").datepicker( {enabled: true} );
}

It may be that this simply recreates the datepickers, but for my purposes, that is fine.

This is my second day using jQuery UI awesomeness, so I may be missing some of the finer points...

No resource identifier found for attribute '...' in package 'com.app....'

I solved is by using android:background instead of app:srcCompact.

This is caused by xmlns:app="http://schemas.android.com/apk/res-auto". As people have suggested above, you could use /lib-auto or /lib/your-package but I got suspicious namespace error when I tried using /lib-auto and unexpected namespace prefix error with /lib/my-package .

Create a git patch from the uncommitted changes in the current working directory

git diff and git apply will work for text files, but won't work for binary files.

You can easily create a full binary patch, but you will have to create a temporary commit. Once you've made your temporary commit(s), you can create the patch with:

git format-patch <options...>

After you've made the patch, run this command:

git reset --mixed <SHA of commit *before* your working-changes commit(s)>

This will roll back your temporary commit(s). The final result leaves your working copy (intentionally) dirty with the same changes you originally had.

On the receiving side, you can use the same trick to apply the changes to the working copy, without having the commit history. Simply apply the patch(es), and git reset --mixed <SHA of commit *before* the patches>.

Note that you might have to be well-synced for this whole option to work. I've seen some errors when applying patches when the person making them hadn't pulled down as many changes as I had. There are probably ways to get it to work, but I haven't looked far into it.


Here's how to create the same patches in Tortoise Git (not that I recommend using that tool):

  1. Commit your working changes
  2. Right click the branch root directory and click Tortoise Git -> Create Patch Serial
    1. Choose whichever range makes sense (Since: FETCH_HEAD will work if you're well-synced)
    2. Create the patch(es)
  3. Right click the branch root directory and click Tortise Git -> Show Log
  4. Right click the commit before your temporary commit(s), and click reset "<branch>" to this...
  5. Select the Mixed option

And how to apply them:

  1. Right click the branch root directory and click Tortoise Git -> Apply Patch Serial
  2. Select the correct patch(es) and apply them
  3. Right click the branch root directory and click Tortise Git -> Show Log
  4. Right click the commit before the patch's commit(s), and click reset "<branch>" to this...
  5. Select the Mixed option

What does the "@" symbol do in SQL?

What you are talking about is the way a parameterized query is written. '@' just signifies that it is a parameter. You can add the value for that parameter during execution process

eg:
sqlcommand cmd = new sqlcommand(query,connection);
cmd.parameters.add("@custid","1");
sqldatareader dr = cmd.executequery();

Getting the first and last day of a month, using a given DateTime object

easy way to do it

Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month,1).ToShortDateString();
End = new DataFim.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToShortDateString();

Get text from pressed button

The view you get passed in on onClick() is the Button you are looking for.

public void onClick(View v) {
    // 1) Possibly check for instance of first 
    Button b = (Button)v;
    String buttonText = b.getText().toString();
}

1) If you are using a non-anonymous class as onClickListener, you may want to check for the type of the view before casting it, as it may be something different than a Button.

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

How to force an entire layout View refresh?

Solution:

Guys I tried all of your Solutions but they did not worked for me, I have to set setVisibility of EditText to VISIBLE and this EditText should be visible then in ScrollView, but I was unable to refresh root view to take effect. I solved my problem, when I need to refresh the view so I changed the ScrollView visibility to GONE and then again set it to VISIBLE to take effect and it worked for me. This is not the exact solution but it only worked.

 private void refreshView(){
    mScrollView.setVisibility(View.GONE);
    mScrollView.setVisibility(View.VISIBLE);
}

How to convert md5 string to normal text?

Md5 is a hashing algorithm. There is no way to retrieve the original input from the hashed result.

If you want to add a "forgotten password?" feature, you could send your user an email with a temporary link to create a new password.

Note: Sending passwords in plain text is a BAD idea :)

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

JavaScript

a == a +1

In JavaScript, there are no integers but only Numbers, which are implemented as double precision floating point numbers.

It means that if a Number a is large enough, it can be considered equal to three consecutive integers:

_x000D_
_x000D_
a = 100000000000000000_x000D_
if (a == a+1 && a == a+2 && a == a+3){_x000D_
  console.log("Precision loss!");_x000D_
}
_x000D_
_x000D_
_x000D_

True, it's not exactly what the interviewer asked (it doesn't work with a=0), but it doesn't involve any trick with hidden functions or operator overloading.

Other languages

For reference, there are a==1 && a==2 && a==3 solutions in Ruby and Python. With a slight modification, it's also possible in Java.

Ruby

With a custom ==:

class A
  def ==(o)
    true
  end
end

a = A.new

if a == 1 && a == 2 && a == 3
  puts "Don't do this!"
end

Or an increasing a:

def a
  @a ||= 0
  @a += 1
end

if a == 1 && a == 2 && a == 3
  puts "Don't do this!"
end

Python

class A:
    def __eq__(self, who_cares):
        return True
a = A()

if a == 1 and a == 2 and a == 3:
    print("Don't do that!")

Java

It's possible to modify Java Integer cache:

package stackoverflow;

import java.lang.reflect.Field;

public class IntegerMess
{
    public static void main(String[] args) throws Exception {
        Field valueField = Integer.class.getDeclaredField("value");
        valueField.setAccessible(true);
        valueField.setInt(1, valueField.getInt(42));
        valueField.setInt(2, valueField.getInt(42));
        valueField.setInt(3, valueField.getInt(42));
        valueField.setAccessible(false);

        Integer a = 42;

        if (a.equals(1) && a.equals(2) && a.equals(3)) {
            System.out.println("Bad idea.");
        }
    }
}

How to get time (hour, minute, second) in Swift 3 using NSDate?

This might be handy for those who want to use the current date in more than one class.

extension String {


func  getCurrentTime() -> String {

    let date = Date()
    let calendar = Calendar.current


    let year = calendar.component(.year, from: date)
    let month = calendar.component(.month, from: date)
    let day = calendar.component(.day, from: date)
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)

    let realTime = "\(year)-\(month)-\(day)-\(hour)-\(minutes)-\(seconds)"

    return realTime
}

}

Usage

        var time = ""
        time = time.getCurrentTime()
        print(time)   // 1900-12-09-12-59

How to force NSLocalizedString to use a specific language

This function will try to get localized string for current language and if it's not found it will get it using english language.

- (NSString*)L:(NSString*)key
{
    static NSString* valueNotFound = @"VALUE_NOT_FOUND";
    static NSBundle* enBundle = nil;

    NSString* pl = [NSLocale preferredLanguages][0];
    NSString* bp = [[NSBundle mainBundle] pathForResource:pl ofType:@"lproj"];
    NSBundle* b = [NSBundle bundleWithPath:bp];

    NSString* s = [b localizedStringForKey:key value:valueNotFound table:nil];
    if ( [s isEqualToString:valueNotFound] ) {
        if ( !enBundle ) {
            bp = [[NSBundle mainBundle] pathForResource:@"en" ofType:@"lproj"];
            enBundle = [NSBundle bundleWithPath:bp];
        }
        s = [enBundle localizedStringForKey:key value:key table:nil];
    }

    return s;
}

Get current URL from IFRAME

If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:

var currentUrl = document.referrer;

and - here you've got the main url!

Parameter "stratify" from method "train_test_split" (scikit Learn)

For my future self who comes here via Google:

train_test_split is now in model_selection, hence:

from sklearn.model_selection import train_test_split

# given:
# features: xs
# ground truth: ys

x_train, x_test, y_train, y_test = train_test_split(xs, ys,
                                                    test_size=0.33,
                                                    random_state=0,
                                                    stratify=ys)

is the way to use it. Setting the random_state is desirable for reproducibility.

Changing file permission in Python

All the current answers clobber the non-writing permissions: they make the file readable-but-not-executable for everybody. Granted, this is because the initial question asked for 444 permissions -- but we can do better!

Here's a solution that leaves all the individual "read" and "execute" bits untouched. I wrote verbose code to make it easy to understand; you can make it more terse if you like.

import os
import stat

def remove_write_permissions(path):
    """Remove write permissions from this path, while keeping all other permissions intact.

    Params:
        path:  The path whose permissions to alter.
    """
    NO_USER_WRITING = ~stat.S_IWUSR
    NO_GROUP_WRITING = ~stat.S_IWGRP
    NO_OTHER_WRITING = ~stat.S_IWOTH
    NO_WRITING = NO_USER_WRITING & NO_GROUP_WRITING & NO_OTHER_WRITING

    current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
    os.chmod(path, current_permissions & NO_WRITING)

Why does this work?

As John La Rooy pointed out,stat.S_IWUSR basically means "the bitmask for the user's write permissions". We want to set the corresponding permission bit to 0. To do that, we need the exact opposite bitmask (i.e., one with a 0 in that location, and 1's everywhere else). The ~ operator, which flips all the bits, gives us exactly that. If we apply this to any variable via the "bitwise and" operator (&), it will zero out the corresponding bit.

We need to repeat this logic with the "group" and "other" permission bits, too. Here we can save some time by just &'ing them all together (forming the NO_WRITING bit constant).

The last step is to get the current file's permissions, and actually perform the bitwise-and operation.

MySQL Removing Some Foreign keys

first need to get actual constrain name by this query

SHOW CREATE TABLE TABLE_NAME

This query will result constrain name of the foreign key, now below query will drop it.

ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1

last number in above constrain name depends how many foreign keys you have in table

Setting up and using Meld as your git difftool and mergetool

For Windows. Run these commands in Git Bash:

git config --global diff.tool meld
git config --global difftool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
git config --global difftool.prompt false

git config --global merge.tool meld
git config --global mergetool.meld.path "C:\Program Files (x86)\Meld\Meld.exe"
git config --global mergetool.prompt false

(Update the file path for Meld.exe if yours is different.)

For Linux. Run these commands in Git Bash:

git config --global diff.tool meld
git config --global difftool.meld.path "/usr/bin/meld"
git config --global difftool.prompt false

git config --global merge.tool meld
git config --global mergetool.meld.path "/usr/bin/meld"
git config --global mergetool.prompt false

You can verify Meld's path using this command:

which meld

Python class input argument

class Person:

def init(self,name,age,weight,sex,mob_no,place):

self.name = str(name)
self.age = int(age)
self.weight = int(weight)
self.sex = str(sex)
self.mob_no = int(mob_no)
self.place = str(place)

Creating an instance to class Person

p1 = Person(Muthuswamy,50,70,Male,94*****23,India)

print(p1.name)

print(p1.place)

Output

Muthuswamy

India

How to use border with Bootstrap

If you are using Bootstrap 4 and higher try this to put borders around your empty divs use border border-primary here is an example of my code:

<div class="row border border-primary">
        <div class="col border border-primary">logo</div>
        <div class="col border border-primary">navbar</div>
    </div>

Here is the link to the border utility in Bootstrap 4: https://getbootstrap.com/docs/4.2/utilities/borders/

How to remove unused dependencies from composer?

In fact, it is very easy.

composer update

will do all this for you, but it will also update the other packages.

To remove a package without updating the others, specifiy that package in the command, for instance:

composer update monolog/monolog

will remove the monolog/monolog package.

Nevertheless, there may remain some empty folders or files that cannot be removed automatically, and that have to be removed manually.

what is the difference between GROUP BY and ORDER BY in sql

ORDER BY shows a field in ascending or descending order. While GROUP BY shows same fieldnames, id's etc in only one output.

Display the current date and time using HTML and Javascript with scrollable effects in hta application

<script>
    var today = new Date;
    document.getElementById('date').innerHTML= today.toDateString();
</script>

Fixed digits after decimal with f-strings

When it comes to float numbers, you can use format specifiers:

f'{value:{width}.{precision}}'

where:

  • value is any expression that evaluates to a number
  • width specifies the number of characters used in total to display, but if value needs more space than the width specifies then the additional space is used.
  • precision indicates the number of characters used after the decimal point

What you are missing is the type specifier for your decimal value. In this link, you an find the available presentation types for floating point and decimal.

Here you have some examples, using the f (Fixed point) presentation type:

# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: '     5.500'

# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}' 
Out[2]: '3001.7'

In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'

# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}' 
Out[4]: '7.234'

# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'

how to wait for first command to finish?

Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait, and wait short time in every loop. This will result in something like

max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
   if [ -f /tmp/st_new.tmp ]; then
      break # call results.sh outside loop
   else
      (( retry = retry + 1 ))
      sleep 1
   fi
done
if [ -f /tmp/st_new.tmp ]; then
   source ../../results.sh 
   rm -f /tmp/st_new.tmp
else
   echo Something wrong with st_new.sh
fi

FormsAuthentication.SignOut() does not log the user out

I've struggled with this before too.

Here's an analogy for what seems to be going on... A new visitor, Joe, comes to the site and logs in via the login page using FormsAuthentication. ASP.NET generates a new identity for Joe, and gives him a cookie. That cookie is like the key to the house, and as long as Joe returns with that key, he can open the lock. Each visitor is given a new key and a new lock to use.

When FormsAuthentication.SignOut() is called, the system tells Joe to lose the key. Normally, this works, since Joe no longer has the key, he cannot get in.

However, if Joe ever comes back, and does have that lost key, he is let back in!

From what I can tell, there is no way to tell ASP.NET to change the lock on the door!

The way I can live with this is to remember Joe's name in a Session variable. When he logs out, I abandon the Session so I don't have his name anymore. Later, to check if he is allowed in, I simply compare his Identity.Name to what the current session has, and if they don't match, he is not a valid visitor.

In short, for a web site, do NOT rely on User.Identity.IsAuthenticated without also checking your Session variables!

How to change color of Toolbar back button in Android?

I am using <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar> theme in my android application and in NoActionBar theme, colorControlNormal property is used to change the color of navigation icon default Back button arrow in my toolbar

styles.xml

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/your_color</item> 
</style>

Change hover color on a button with Bootstrap customization

or can do this...
set all btn ( class name like : .btn- + $theme-colors: map-merge ) styles at one time :

@each $color, $value in $theme-colors {
  .btn-#{$color} {
    @include button-variant($value, $value,
    // modify
    $hover-background: lighten($value, 7.5%),
    $hover-border: lighten($value, 10%),
    $active-background: lighten($value, 10%),
    $active-border: lighten($value, 12.5%)
    // /modify
    );
  }
}

// code from "node_modules/bootstrap/scss/_buttons.scss"

should add into your customization scss file.

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

I was experiencing the same issue so just added the @Transactional annotation from where I was calling the DAO method. It just works. I think the problem was Hibernate doesn't allow to retrieve sub-objects from the database unless specifically all the required objects at the time of calling.

compilation error: identifier expected

You also will have to catch or throw the IOException. See below. Not always the best way, but it will get you a result:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

Laravel 5 route not defined, while it is?

Please note that the command

php artisan route:list

Or to get more filter down list

php artisan route:list | grep your_route|your_controller

the forth column tells you the names of routes that are registered (usually generated by Route::resource)

Trim characters in Java

CharMatcher – Google Guava

In the past, I'd second Colins’ Apache commons-lang answer. But now that Google’s guava-libraries is released, the CharMatcher class will do what you want quite nicely:

String j = CharMatcher.is('\\').trimFrom("\\joe\\jill\\"); 
// j is now joe\jill

CharMatcher has a very simple and powerful set of APIs as well as some predefined constants which make manipulation very easy. For example:

CharMatcher.is(':').countIn("a:b:c"); // returns 2
CharMatcher.isNot(':').countIn("a:b:c"); // returns 3
CharMatcher.inRange('a', 'b').countIn("a:b:c"); // returns 2
CharMatcher.DIGIT.retainFrom("a12b34"); // returns "1234"
CharMatcher.ASCII.negate().removeFrom("a®¶b"); // returns "ab";

Very nice stuff.

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

getString Outside of a Context or Activity

BTW, one of the reason of symbol not found error may be that your IDE imported android.R; class instead of yours one. Just change import android.R; to import your.namespace.R;

So 2 basic things to get string visible in the different class:

//make sure you are importing the right R class
import your.namespace.R;

//don't forget about the context
public void some_method(Context context) {
   context.getString(R.string.YOUR_STRING);
}

cmake - find_library - custom library location

The simplest solution may be to add HINTS to each find_* request.

For example:

find_library(CURL_LIBRARY
    NAMES curl curllib libcurl_imp curllib_static
    HINTS "${CMAKE_PREFIX_PATH}/curl/lib"
)

For Boost I would strongly recommend using the FindBoost standard module and setting the BOOST_DIR variable to point to your Boost libraries.

Iteration over std::vector: unsigned vs signed index variable

A bit of history:

To represent whether a number is negative or not computer use a 'sign' bit. int is a signed data type meaning it can hold positive and negative values (about -2billion to 2billion). Unsigned can only store positive numbers (and since it doesn't waste a bit on metadata it can store more: 0 to about 4billion).

std::vector::size() returns an unsigned, for how could a vector have negative length?

The warning is telling you that the right operand of your inequality statement can hold more data then the left.

Essentially if you have a vector with more then 2 billion entries and you use an integer to index into you'll hit overflow problems (the int will wrap back around to negative 2 billion).

Why am I getting AttributeError: Object has no attribute

These kind of bugs are common when Python multi-threading. What happens is that, on interpreter tear-down, the relevant module (myThread in this case) goes through a sort-of del myThread.

The call self.sample() is roughly equivalent to myThread.__dict__["sample"](self). But if we're during the interpreter's tear-down sequence, then its own dictionary of known types might've already had myThread deleted, and now it's basically a NoneType - and has no 'sample' attribute.

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

Printing string variable in Java

You could also use BufferedReader:

import java.io.*;

public class TestApplication {
   public static void main (String[] args) {
      System.out.print("Enter a password: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String password = null;
      try {
         password = br.readLine();
      } catch (IOException e) {
         System.out.println("IO error trying to read your password!");
         System.exit(1);
      }
      System.out.println("Successfully read your password.");
   }
}

What exactly is an instance in Java?

The Literal meaning of instance is "an example or single occurrence of something." which is very closer to the Instance in Java terminology.

Java follows dynamic loading, which is not like C language where the all code is copied into the RAM at runtime. Lets capture this with an example.

   class A
    {
    int x=0;
    public static void main(String [] args)    
     {
    int y=0;
    y=y+1;
    x=x+1;
     }   

    }

Let us compile and run this code.

step 1: javac A.class (.class file is generated which is byte code)

step 2: java A (.class file is converted into executable code)

During the step 2,The main method and the static elements are loaded into the RAM for execution. In the above scenario, No issue until the line y=y+1. But whenever x=x+1 is executed, the run time error will be thrown as the JVM does not know what the x is which is declared outside the main method(non-static).

So If by some means the content of .class file is available in the memory for CPU to execute, there is no more issue.

This is done through creating the Object and the keyword NEW does this Job.

"The concept of reserving memory in the RAM for the contents of hard disk (here .class file) at runtime is called Instance "

The Object is also called the instance of the class.

Perl: Use s/ (replace) and return new string

print "bla: ", $myvar =~ tr{a}{b},"\n";

error: Unable to find vcvarsall.bat

Maybe somebody can be interested, the following worked for me for the py2exe package. (I have windows 7 64 bit and portable python 2.7, Visual Studio 2005 Express with Windows SDK for Windows 7 and .NET Framework 4)

set VS90COMNTOOLS=%VS80COMNTOOLS%

then:

python.exe setup.py install

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Try adding the following to your eclipse.ini file:

-vm
C:\Program Files\Java\jdk1.7.0_01\bin\java.exe

You might also have to change the Dosgi.requiredJavaVersion to 1.7 in the same file.

How do I tell Maven to use the latest version of a dependency?

Unlike others I think there are many reasons why you might always want the latest version. Particularly if you are doing continuous deployment (we sometimes have like 5 releases in a day) and don't want to do a multi-module project.

What I do is make Hudson/Jenkins do the following for every build:

mvn clean versions:use-latest-versions scm:checkin deploy -Dmessage="update versions" -DperformRelease=true

That is I use the versions plugin and scm plugin to update the dependencies and then check it in to source control. Yes I let my CI do SCM checkins (which you have to do anyway for the maven release plugin).

You'll want to setup the versions plugin to only update what you want:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>versions-maven-plugin</artifactId>
    <version>1.2</version>
    <configuration>
        <includesList>com.snaphop</includesList>
        <generateBackupPoms>false</generateBackupPoms>
        <allowSnapshots>true</allowSnapshots>
    </configuration>
</plugin>

I use the release plugin to do the release which takes care of -SNAPSHOT and validates that there is a release version of -SNAPSHOT (which is important).

If you do what I do you will get the latest version for all snapshot builds and the latest release version for release builds. Your builds will also be reproducible.

Update

I noticed some comments asking some specifics of this workflow. I will say we don't use this method anymore and the big reason why is the maven versions plugin is buggy and in general is inherently flawed.

It is flawed because to run the versions plugin to adjust versions all the existing versions need to exist for the pom to run correctly. That is the versions plugin cannot update to the latest version of anything if it can't find the version referenced in the pom. This is actually rather annoying as we often cleanup old versions for disk space reasons.

Really you need a separate tool from maven to adjust the versions (so you don't depend on the pom file to run correctly). I have written such a tool in the the lowly language that is Bash. The script will update the versions like the version plugin and check the pom back into source control. It also runs like 100x faster than the mvn versions plugin. Unfortunately it isn't written in a manner for public usage but if people are interested I could make it so and put it in a gist or github.

Going back to workflow as some comments asked about that this is what we do:

  1. We have 20 or so projects in their own repositories with their own jenkins jobs
  2. When we release the maven release plugin is used. The workflow of that is covered in the plugin's documentation. The maven release plugin sort of sucks (and I'm being kind) but it does work. One day we plan on replacing this method with something more optimal.
  3. When one of the projects gets released jenkins then runs a special job we will call the update all versions job (how jenkins knows its a release is a complicated manner in part because the maven jenkins release plugin is pretty crappy as well).
  4. The update all versions job knows about all the 20 projects. It is actually an aggregator pom to be specific with all the projects in the modules section in dependency order. Jenkins runs our magic groovy/bash foo that will pull all the projects update the versions to the latest and then checkin the poms (again done in dependency order based on the modules section).
  5. For each project if the pom has changed (because of a version change in some dependency) it is checked in and then we immediately ping jenkins to run the corresponding job for that project (this is to preserve build dependency order otherwise you are at the mercy of the SCM Poll scheduler).

At this point I'm of the opinion it is a good thing to have the release and auto version a separate tool from your general build anyway.

Now you might think maven sort of sucks because of the problems listed above but this actually would be fairly difficult with a build tool that does not have a declarative easy to parse extendable syntax (aka XML).

In fact we add custom XML attributes through namespaces to help hint bash/groovy scripts (e.g. don't update this version).

UIView background color in Swift

If you want to set your custom RGB color try this:

self.view.backgroundColor = UIColor(red: 20/255.0, green: 106/255.0, blue: 93/255.0, alpha: 1)

Don't forget to keep /255.0 for every color

SQL keys, MUL vs PRI vs UNI

DESCRIBE <table>; 

This is acutally a shortcut for:

SHOW COLUMNS FROM <table>;

In any case, there are three possible values for the "Key" attribute:

  1. PRI
  2. UNI
  3. MUL

The meaning of PRI and UNI are quite clear:

  • PRI => primary key
  • UNI => unique key

The third possibility, MUL, (which you asked about) is basically an index that is neither a primary key nor a unique key. The name comes from "multiple" because multiple occurrences of the same value are allowed. Straight from the MySQL documentation:

If Key is MUL, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.

There is also a final caveat:

If more than one of the Key values applies to a given column of a table, Key displays the one with the highest priority, in the order PRI, UNI, MUL.

As a general note, the MySQL documentation is quite good. When in doubt, check it out!

Sleep function in ORACLE

There is a good article on this topic: PL/SQL: Sleep without using DBMS_LOCK that helped me out. I used Option 2 wrapped in a custom package. Proposed solutions are:

Option 1: APEX_UTIL.sleep

If APEX is installed you can use the procedure “PAUSE” from the publicly available package APEX_UTIL.

Example – “Wait 5 seconds”:

SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    APEX_UTIL.PAUSE(5);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/

Option 2: java.lang.Thread.sleep

An other option is the use of the method “sleep” from the Java class “Thread”, which you can easily use through providing a simple PL/SQL wrapper procedure:

Note: Please remember, that “Thread.sleep” uses milliseconds!

--- create ---
CREATE OR REPLACE PROCEDURE SLEEP (P_MILLI_SECONDS IN NUMBER) 
AS LANGUAGE JAVA NAME 'java.lang.Thread.sleep(long)';

--- use ---
SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    SLEEP(5 * 1000);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

How to convert FormData (HTML5 object) to JSON

If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.

Here is the modern ES6-variant:

function formToJSON( elem ) {
  let output = {};
  new FormData( elem ).forEach(
    ( value, key ) => {
      // Check if property already exist
      if ( Object.prototype.hasOwnProperty.call( output, key ) ) {
        let current = output[ key ];
        if ( !Array.isArray( current ) ) {
          // If it's not an array, convert it to an array.
          current = output[ key ] = [ current ];
        }
        current.push( value ); // Add the new value to the array.
      } else {
        output[ key ] = value;
      }
    }
  );
  return JSON.stringify( output );
}

Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)

function formToJSON( elem ) {
  var current, entries, item, key, output, value;
  output = {};
  entries = new FormData( elem ).entries();
  // Iterate over values, and assign to item.
  while ( item = entries.next().value )
    {
      // assign to variables to make the code more readable.
      key = item[0];
      value = item[1];
      // Check if key already exist
      if (Object.prototype.hasOwnProperty.call( output, key)) {
        current = output[ key ];
        if ( !Array.isArray( current ) ) {
          // If it's not an array, convert it to an array.
          current = output[ key ] = [ current ];
        }
        current.push( value ); // Add the new value to the array.
      } else {
        output[ key ] = value;
      }
    }
    return JSON.stringify( output );
  }

SyntaxError: Unexpected token o in JSON at position 1

var data = JSON.parse(userData); console.log(data);

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

There is a lot of confusion here, especially if you read outdated sources.

The basic one is Activity, which can show Fragments. You can use this combination if you're on Android version > 4.

However, there is also a support library which encompasses the other classes you mentioned: FragmentActivity, ActionBarActivity and AppCompat. Originally they were used to support fragments on Android versions < 4, but actually they're also used to backport functionality from newer versions of Android (material design for example).

The latest one is AppCompat, the other 2 are older. The strategy I use is to always use AppCompat, so that the app will be ready in case of backports from future versions of Android.

.htaccess or .htpasswd equivalent on IIS?

I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.

How to check if a variable exists in a FreeMarker template?

To check if the value exists:

[#if userName??]
   Hi ${userName}, How are you?
[/#if]

Or with the standard freemarker syntax:

<#if userName??>
   Hi ${userName}, How are you?
</#if>

To check if the value exists and is not empty:

<#if userName?has_content>
    Hi ${userName}, How are you?
</#if>

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

Input type DateTime - Value format?

This works for setting the value of the INPUT:

strftime('%Y-%m-%dT%H:%M:%S', time())

Spring Could not Resolve placeholder

Hopefully it will be still helpful, the application.properties (or application.yml) file must be in both the paths:

  • src/main/resource/config
  • src/test/resource/config

containing the same property you are referring

How to check for palindrome using Python logic

import string

word = input('Please select a word to test \n')
word = word.lower()
num = len(word)

x = round((len(word)-1)/2)
#defines first half of string
first = word[:x]

#reverse second half of string
def reverse_odd(text):
    lst = []
    count = 1
    for i in range(x+1, len(text)):

        lst.append(text[len(text)-count])
        count += 1
    lst = ''.join(lst)
    return lst

#reverse second half of string
def reverse_even(text):
    lst = []
    count = 1
    for i in range(x, len(text)):
        lst.append(text[len(text)-count])
        count += 1
    lst = ''.join(lst)
    return lst


if reverse_odd(word) == first or reverse_even(word) == first:
    print(string.capwords(word), 'is a palindrome')
else:
    print(string.capwords(word), 'is not a palindrome')

Best way to select random rows PostgreSQL

If you want just one row, you can use a calculated offset derived from count.

select * from table_name limit 1
offset floor(random() * (select count(*) from table_name));