Programs & Examples On #Desktop wallpaper

Converting Integer to String with comma for thousands

can't you use a

System.out.printf("%n%,d",int name);

The comma in the printf should add the commas into the %d inter.

Not positive about it, but works for me.

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

How to use enums as flags in C++?

Easiest way to do this as shown here, using the standard library class bitset.

To emulate the C# feature in a type-safe way, you'd have to write a template wrapper around the bitset, replacing the int arguments with an enum given as a type parameter to the template. Something like:

    template <class T, int N>
class FlagSet
{

    bitset<N> bits;

    FlagSet(T enumVal)
    {
        bits.set(enumVal);
    }

    // etc.
};

enum MyFlags
{
    FLAG_ONE,
    FLAG_TWO
};

FlagSet<MyFlags, 2> myFlag;

PHP check file extension

$file = $_FILES["file"] ["tmp_name"]; 
$check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
if ($check_ext == "fileext") {
    //code
}
else { 
    //code
}

Chart.js v2 hide dataset labels

Replace options with this snippet, will fix for Vanilla JavaScript Developers

_x000D_
_x000D_
options: {
            title: {
                text: 'Hello',
                display: true
            },
            scales: {
                xAxes: [{
                    ticks: {
                        display: false
                    }
                }]
            },
            legend: {
                display: false
            }
        }
_x000D_
_x000D_
_x000D_

Concatenate two char* strings in a C program

strcat attempts to append the second parameter to the first. This won't work since you are assigning implicitly sized constant strings.

If all you want to do is print two strings out

printf("%s%s",str1,str2);

Would do.

You could do something like

char *str1 = calloc(sizeof("SSSS")+sizeof("KKKK")+1,sizeof *str1);
strcpy(str1,"SSSS");
strcat(str1,str2);

to create a concatenated string; however strongly consider using strncat/strncpy instead. And read the man pages carefully for the above. (oh and don't forget to free str1 at the end).

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

clear data inside text file in c++

As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.

ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append

The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.

How many times does each value appear in a column?

I second Dave's idea. I'm not always fond of pivot tables, but in this case they are pretty straightforward to use.

Here are my results:

Enter image description here

It was so simple to create it that I have even recorded a macro in case you need to do this with VBA:

Sub Macro2()
'
' Macro2 Macro
'

'
    Range("Table1[[#All],[DATA]]").Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Table1", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
        :="Sheet3!R3C7", TableName:="PivotTable4", DefaultVersion:= _
        xlPivotTableVersion14
    Sheets("Sheet3").Select
    Cells(3, 7).Select
    With ActiveSheet.PivotTables("PivotTable4").PivotFields("DATA")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables( _
        "PivotTable4").PivotFields("DATA"), "Count of DATA", xlCount
End Sub

How to use an environment variable inside a quoted string in Bash

You are doing it right, so I guess something else is at fault (not export-ing COLUMNS ?).

A trick to debug these cases is to make a specialized command (a closure for programming language guys). Create a shell script named diff-columns doing:

exec /usr/bin/diff -x -y -w -p -W "$COLUMNS" "$@"

and just use

svn diff "$@" --diff-cmd  diff-columns

This way your code is cleaner to read and more modular (top-down approach), and you can test the diff-columns code thouroughly separately (bottom-up approach).

Does C# have a String Tokenizer like Java's?

You could use String.Split method.

class ExampleClass
{
    public ExampleClass()
    {
        string exampleString = "there is a cat";
        // Split string on spaces. This will separate all the words in a string
        string[] words = exampleString.Split(' ');
        foreach (string word in words)
        {
            Console.WriteLine(word);
            // there
            // is
            // a
            // cat
        }
    }
}

For more information see Sam Allen's article about splitting strings in c# (Performance, Regex)

android button selector

You can use this code:

<Button
android:id="@+id/img_sublist_carat"
android:layout_width="70dp"
android:layout_height="68dp"
android:layout_centerVertical="true"
android:layout_marginLeft="625dp"
android:contentDescription=""
android:background="@drawable/img_sublist_carat_selector"
android:visibility="visible" />

(Selector File) img_sublist_carat_selector.xml:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_focused="true" 
       android:state_pressed="true"        
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:state_pressed="true" 
       android:drawable="@drawable/img_sublist_carat_highlight" />
 <item android:drawable="@drawable/img_sublist_carat_normal" />
</selector>

How to set the margin or padding as percentage of height of parent container?

A 50% padding wont center your child, it will place it below the center. I think you really want a padding-top of 25%. Maybe you're just running out of space as your content gets taller? Also have you tried setting the margin-top instead of padding-top?

EDIT: Nevermind, the w3schools site says

% Specifies the padding in percent of the width of the containing element

So maybe it always uses width? I'd never noticed.

What you are doing can be acheived using display:table though (at least for modern browsers). The technique is explained here.

Just what is an IntPtr exactly?

It's a "native (platform-specific) size integer." It's internally represented as void* but exposed as an integer. You can use it whenever you need to store an unmanaged pointer and don't want to use unsafe code. IntPtr.Zero is effectively NULL (a null pointer).

How to use OpenSSL to encrypt/decrypt files?

Short Answer:

You likely want to use gpg instead of openssl so see "Additional Notes" at the end of this answer. But to answer the question using openssl:

To Encrypt:

openssl enc -aes-256-cbc -in un_encrypted.data -out encrypted.data

To Decrypt:

openssl enc -d -aes-256-cbc -in encrypted.data -out un_encrypted.data

Note: You will be prompted for a password when encrypting or decrypt.


Long Answer:

Your best source of information for openssl enc would probably be: https://www.openssl.org/docs/man1.1.1/man1/enc.html

Command line: openssl enc takes the following form:

openssl enc -ciphername [-in filename] [-out filename] [-pass arg]
[-e] [-d] [-a/-base64] [-A] [-k password] [-kfile filename] 
[-K key] [-iv IV] [-S salt] [-salt] [-nosalt] [-z] [-md] [-p] [-P] 
[-bufsize number] [-nopad] [-debug] [-none] [-engine id]

Explanation of most useful parameters with regards to your question:

-e
    Encrypt the input data: this is the default.

-d    
    Decrypt the input data.

-k <password>
    Only use this if you want to pass the password as an argument. 
    Usually you can leave this out and you will be prompted for a 
    password. The password is used to derive the actual key which 
    is used to encrypt your data. Using this parameter is typically
    not considered secure because your password appears in 
    plain-text on the command line and will likely be recorded in 
    bash history.

-kfile <filename>
    Read the password from the first line of <filename> instead of
    from the command line as above.

-a
    base64 process the data. This means that if encryption is taking 
    place the data is base64 encoded after encryption. If decryption 
    is set then the input data is base64 decoded before being 
    decrypted.
    You likely DON'T need to use this. This will likely increase the
    file size for non-text data. Only use this if you need to send 
    data in the form of text format via email etc.

-salt
    To use a salt (randomly generated) when encrypting. You always
    want to use a salt while encrypting. This parameter is actually
    redundant because a salt is used whether you use this or not 
    which is why it was not used in the "Short Answer" above!

-K key    
    The actual key to use: this must be represented as a string
    comprised only of hex digits. If only the key is specified, the
    IV must additionally be specified using the -iv option. When 
    both a key and a password are specified, the key given with the
    -K option will be used and the IV generated from the password 
    will be taken. It probably does not make much sense to specify 
    both key and password.

-iv IV
    The actual IV to use: this must be represented as a string 
    comprised only of hex digits. When only the key is specified 
    using the -K option, the IV must explicitly be defined. When a
    password is being specified using one of the other options, the 
    IV is generated from this password.

-md digest
    Use the specified digest to create the key from the passphrase.
    The default algorithm as of this writing is sha-256. But this 
    has changed over time. It was md5 in the past. So you might want
    to specify this parameter every time to alleviate problems when
    moving your encrypted data from one system to another or when
    updating openssl to a newer version.

Additional Notes:

Though you have specifically asked about OpenSSL you might want to consider using GPG instead for the purpose of encryption based on this article OpenSSL vs GPG for encrypting off-site backups?

To use GPG to do the same you would use the following commands:

To Encrypt:

gpg --output encrypted.data --symmetric --cipher-algo AES256 un_encrypted.data

To Decrypt:

gpg --output un_encrypted.data --decrypt encrypted.data

Note: You will be prompted for a password when encrypting or decrypt.

Socket send and receive byte array

You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.

This is the easiest case for a known size (100 bytes):

in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);

In this case DataInputStream makes sense as it offers readFully(). If you don't use it, you need to loop yourself until the expected number of bytes is read.

Xcode 10 Error: Multiple commands produce

For me the problem was tied to having the same file included in the bundle resources twice. Not sure how that happened, but I removed one of them and it compiled fine with the new build system.

How to connect to my http://localhost web server from Android Emulator

I used 10.0.2.2 successfully on my home machine, but at work, it did not work. After hours of fooling around, I created a new emulator instance using the Android Virtual Device (AVD) manager, and finally the 10.0.2.2 worked.

I don't know what was wrong with the other emulator instance (the platform was the same), but if you find 10.0.2.2 does not work, try creating a new emulator instance.

minimum double value in C/C++

Try this:

-1 * numeric_limits<double>::max()

Reference: numeric_limits

This class is specialized for each of the fundamental types, with its members returning or set to the different values that define the properties that type has in the specific platform in which it compiles.

How do I toggle an ng-show in AngularJS based on a boolean?

If you have multiple Menus with Submenus, then you can go with the below solution.

HTML

          <ul class="sidebar-menu" id="nav-accordion">
             <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('dashboard')">
                      <i class="fa fa-book"></i>
                      <span>Dashboard</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showDash">
                      <li><a ng-class="{ active: isActive('/dashboard/loan')}" href="#/dashboard/loan">Loan</a></li>
                      <li><a ng-class="{ active: isActive('/dashboard/recovery')}" href="#/dashboard/recovery">Recovery</a></li>
                  </ul>
              </li>
              <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('customerCare')">
                      <i class="fa fa-book"></i>
                      <span>Customer Care</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showCC">
                      <li><a ng-class="{ active: isActive('/customerCare/eligibility')}" href="#/CC/eligibility">Eligibility</a></li>
                      <li><a ng-class="{ active: isActive('/customerCare/transaction')}" href="#/CC/transaction">Transaction</a></li>
                  </ul>
              </li>
          </ul>

There are two functions i have called first is ng-click = hasSubMenu('dashboard'). This function will be used to toggle the menu and it is explained in the code below. The ng-class="{ active: isActive('/customerCare/transaction')} it will add a class active to the current menu item.

Now i have defined some functions in my app:

First, add a dependency $rootScope which is used to declare variables and functions. To learn more about $roootScope refer to the link : https://docs.angularjs.org/api/ng/service/$rootScope

Here is my app file:

 $rootScope.isActive = function (viewLocation) { 
                return viewLocation === $location.path();
        };

The above function is used to add active class to the current menu item.

        $rootScope.showDash = false;
        $rootScope.showCC = false;

        var location = $location.url().split('/');

        if(location[1] == 'customerCare'){
            $rootScope.showCC = true;
        }
        else if(location[1]=='dashboard'){
            $rootScope.showDash = true;
        }

        $rootScope.hasSubMenu = function(menuType){
            if(menuType=='dashboard'){
                $rootScope.showCC = false;
                $rootScope.showDash = $rootScope.showDash === false ? true: false;
            }
            else if(menuType=='customerCare'){
                $rootScope.showDash = false;
                $rootScope.showCC = $rootScope.showCC === false ? true: false;
            }
        }

By default $rootScope.showDash and $rootScope.showCC are set to false. It will set the menus to closed when page is initially loaded. If you have more than two submenus add accordingly.

hasSubMenu() function will work for toggling between the menus. I have added a small condition

if(location[1] == 'customerCare'){
                $rootScope.showCC = true;
            }
            else if(location[1]=='dashboard'){
                $rootScope.showDash = true;
            }

it will remain the submenu open after reloading the page according to selected menu item.

I have defined my pages like:

$routeProvider
        .when('/dasboard/loan', {
            controller: 'LoanController',
            templateUrl: './views/loan/view.html',
            controllerAs: 'vm'
        })

You can use isActive() function only if you have a single menu without submenu. You can modify the code according to your requirement. Hope this will help. Have a great day :)

hibernate - get id after save object

By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

Pinging servers in Python

If you don't need to support Windows, here's a really concise way to do it:

import os
hostname = "google.com" #example
response = os.system("ping -c 1 " + hostname)

#and then check the response...
if response == 0:
  print hostname, 'is up!'
else:
  print hostname, 'is down!'

This works because ping returns a non-zero value if the connection fails. (The return value actually differs depending on the network error.) You could also change the ping timeout (in seconds) using the '-t' option. Note, this will output text to the console.

Curl to return http status code along with the response

the verbose mode will tell you everything

curl -v http://localhost

Is there a method for String conversion to Title Case?

Sorry I am a beginner so my coding habit sucks!

public class TitleCase {

    String title(String sent)
    {   
        sent =sent.trim();
        sent = sent.toLowerCase();
        String[] str1=new String[sent.length()];
        for(int k=0;k<=str1.length-1;k++){
            str1[k]=sent.charAt(k)+"";
    }

        for(int i=0;i<=sent.length()-1;i++){
            if(i==0){
                String s= sent.charAt(i)+"";
                str1[i]=s.toUpperCase();
                }
            if(str1[i].equals(" ")){
                String s= sent.charAt(i+1)+"";
                str1[i+1]=s.toUpperCase();
                }

            System.out.print(str1[i]);
            }

        return "";
        }

    public static void main(String[] args) {
        TitleCase a = new TitleCase();
        System.out.println(a.title("   enter your Statement!"));
    }
}

Numpy: Creating a complex array from 2 real ones?

There's of course the rather obvious:

Data[...,0] + 1j * Data[...,1]

How can I view an object with an alert()

You should really use Firebug or Webkit's console for debugging. Then you can just do console.debug(product); and examine the object.

$(document).ready not Working

One possibility, take a look:

<script language="javascript" type="text/javascript" src="./jquery-3.1.1.slim.min.js" />

vs

<script language="javascript" type="text/javascript" src="./jquery-3.1.1.slim.min.js"></script>

The first method is actually wrong, however the browser does not complain at all. You need to be sure that you are indeed closing the javascript tag in the proper way.

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

Adjust list style image position?

Another option you can do, is the following:

li:before{
    content:'';
    padding: 0 0 0 25px;
    background:url(../includes/images/layouts/featured-list-arrow.png) no-repeat 0 3px;
}

Use (0 3px) to position the list image.

Works in IE8+, Chrome, Firefox, and Opera.

I use this option because you can swap out list-style easily and a good chance you may not even have to use an image at all. (fiddle below)

http://jsfiddle.net/flashminddesign/cYAzV/1/

UPDATE:

This will account for text / content going into the second line:

ul{ 
    list-style-type:none;
}

li{
    position:relative;
}

ul li:before{
    content:'>';
    padding:0 10px 0 0;
    position:absolute;
    top:0; left:-10px;
}

Add padding-left: to the li if you want more space between the bullet and content.

http://jsfiddle.net/McLeodWebDev/wfzwm0zy/

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <label>Email</label>
    <input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  
  </form>
</section>

and controller code:

app.controller('MainCtrl', function($scope) {  
  $scope.save = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
      console.log(model); 
    } else {
      console.log('Errors in form data');
    }
  };
});

I hope this helps.

month name to month number and vice versa in python

Using calendar module:

Number-to-Abbr calendar.month_abbr[month_number]

Abbr-to-Number list(calendar.month_abbr).index(month_abbr)

java.lang.RuntimeException: Unable to start activity ComponentInfo

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

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Note: If you are using Bootstrap + AngularJS + UI Bootstrap, .left .right and .next classes are never added. Using the example at the following link and the CSS from Robert McKee answer works. I wanted to comment because it took 3 days to find a full solution. Hope this helps others!

https://angular-ui.github.io/bootstrap/#/carousel

Code snip from UI Bootstrap Demo at the above link.

angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
  $scope.myInterval = 5000;
  var slides = $scope.slides = [];
  $scope.addSlide = function() {
    var newWidth = 600 + slides.length + 1;
    slides.push({
      image: 'http://placekitten.com/' + newWidth + '/300',
      text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
        ['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
    });
  };
  for (var i=0; i<4; i++) {
    $scope.addSlide();
  }
});

Html From UI Bootstrap, Notice I added the .fade class to the example.

<div ng-controller="CarouselDemoCtrl">
    <div style="height: 305px">
        <carousel class="fade" interval="myInterval">
          <slide ng-repeat="slide in slides" active="slide.active">
            <img ng-src="{{slide.image}}" style="margin:auto;">
            <div class="carousel-caption">
              <h4>Slide {{$index}}</h4>
              <p>{{slide.text}}</p>
            </div>
          </slide>
        </carousel>
    </div>
</div>

CSS from Robert McKee's answer above

.carousel.fade {
opacity: 1;
}
.carousel.fade .item {
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
left: 0 !important;
opacity: 0;
top:0;
position:absolute;
width: 100%;
display:block !important;
z-index:1;
}
.carousel.fade .item:first-child {
top:auto;
position:relative;
}
.carousel.fade .item.active {
opacity: 1;
-moz-transition: opacity ease-in-out .7s;
-o-transition: opacity ease-in-out .7s;
-webkit-transition: opacity ease-in-out .7s;
transition: opacity ease-in-out .7s;
z-index:2;
}
/*
Added z-index to raise the left right controls to the top
*/
.carousel-control {
z-index:3;
}

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.

df.sample(frac=1)

Why does my sorting loop seem to append an element where it shouldn't?

If you use:

if (Array[i].compareToIgnoreCase(Array[j]) < 0)

you will get:

Example  Hello  is  Sorting  This

which I think is the output you were looking for.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Build project into a JAR automatically in Eclipse

Regarding to Peter's answer and Micheal's addition to it you may find How Do I Automatically Generate A .jar File In An Eclipse Java Project useful. Because even you have "*.jardesc" file on your project you have to run it manually. It may cools down your "eclipse click hassle" a bit.

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I decided to share my finding on this error after resolving it myself.

First of all, BalusC solutions should be taken seriously but then there is another likely issue in Netbeans to be aware of especially when building an Enterprise Application Project(EAR) using Maven.

Netbeans generates, a parent POM file, an EAR project, an EJB project and a WAR project. Everything else in my project was fine, and I almost assumed the problem is a bug in probably GlassFish 4.0(I had to install and plug it into Netbeans) because GlassFish 4.1 has a Weld CDI bug which makes the embedded GlassFish 4.1 in Netbeans 8.0.2 unusable except through a patch.

Solution:

To resolve the "Target Unreachable, identifier 'bean' resolved to null" error-

I Right-click the parent POM project, and select Properties. A Project Properties Dialog appears, click "Sources", you will be surprised to see the "Source/Binary Format" set to 1.5 and "Encoding" set to Windows 1250. Change the "Source/Binary Format" to 1.6 0r 1.7, whichever you prefer to make your project CDI compliant, and "Encoding" to UTF-8.

Do the same for all the other subprojects(EAR, EJB, WAR) if they are not already compartible. Run your project, and you won't get that error again.

I hope this helps someone out there having similar error.

Generate a random letter in Python

A summary and improvement of some of the answers.

import numpy as np
n = 5
[chr(i) for i in np.random.randint(ord('a'), ord('z') + 1, n)]
# ['b', 'f', 'r', 'w', 't']

Transition of background-color

Another way of accomplishing this is using animation which provides more control.

#content #nav a {
    background-color: #FF0;
    
    /* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
    animation-duration: 1s; /* same as transition duration */
    animation-timing-function: linear; /* kind of same as transition timing */
    animation-delay: 0ms; /* same as transition delay */
    animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
    animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
    animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
    animation-play-state: running; /* can be set dynamically to pause mid animation*/
    
    /* declaring the states of the animation to transition through */
    /* optionally add other properties that will change here, or new states (50% etc) */
    @keyframes onHoverAnimation {
    0% {
      background-color: #FF0;  
    }
    100% {
      background-color: #AD310B;
    }
  }
}

#content #nav a:hover {
    /* animation wont run unless the element is given the name of the animation. This is set on hover */
    animation-name: onHoverAnimation;
}

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

gmdate() is doing exactly what you asked for.

Look at formats here: http://php.net/manual/en/function.gmdate.php

Angular2 get clicked element id

You could just pass a static value (or a variable from *ngFor or whatever)

<button (click)="toggle(1)" class="someclass">
<button (click)="toggle(2)" class="someclass">

Regular expression to extract URL from an HTML link

If you're only looking for one:

import re
match = re.search(r'href=[\'"]?([^\'" >]+)', s)
if match:
    print(match.group(1))

If you have a long string, and want every instance of the pattern in it:

import re
urls = re.findall(r'href=[\'"]?([^\'" >]+)', s)
print(', '.join(urls))

Where s is the string that you're looking for matches in.

Quick explanation of the regexp bits:

r'...' is a "raw" string. It stops you having to worry about escaping characters quite as much as you normally would. (\ especially -- in a raw string a \ is just a \. In a regular string you'd have to do \\ every time, and that gets old in regexps.)

"href=[\'"]?" says to match "href=", possibly followed by a ' or ". "Possibly" because it's hard to say how horrible the HTML you're looking at is, and the quotes aren't strictly required.

Enclosing the next bit in "()" says to make it a "group", which means to split it out and return it separately to us. It's just a way to say "this is the part of the pattern I'm interested in."

"[^\'" >]+" says to match any characters that aren't ', ", >, or a space. Essentially this is a list of characters that are an end to the URL. It lets us avoid trying to write a regexp that reliably matches a full URL, which can be a bit complicated.

The suggestion in another answer to use BeautifulSoup isn't bad, but it does introduce a higher level of external requirements. Plus it doesn't help you in your stated goal of learning regexps, which I'd assume this specific html-parsing project is just a part of.

It's pretty easy to do:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_to_parse)
for tag in soup.findAll('a', href=True):
    print(tag['href'])

Once you've installed BeautifulSoup, anyway.

How to comment/uncomment in HTML code

The following works well in a .php file.

<php? /*your block you want commented out*/ ?>

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

In Mac OS X, the solution is creating the file androidtool.cfg in our user .android folder and then add this line. Sure it is working also for Linux

sdkman.force.http=true

I hope that helps!

Unable to resolve host "<insert URL here>" No address associated with hostname

Are you able to reach that url from within the built-in browser?

If not, it means that your network setup is not correct. If you are in the emulator, you may have a look at the networking section of the docs.

If you are on OS/X, the emulator is using "the first" interface, en0 even if you are on wireless (en1), as en0 without a cable is still marked as up. You can issue ifconfig en0 down and restart the emulator. I think I have read about similar behavior on Windows.

If you are on Wifi/3G, call your network provider for the correct DNS settings.

How do I move focus to next input with jQuery?

JQuery UI already has this, in my example below I included a maxchar attribute to focus on the next focus-able element (input, select, textarea, button and object) if i typed in the max number of characters

HTML:

text 1 <input type="text" value="" id="txt1" maxchar="5" /><br />
text 2 <input type="text" value="" id="txt2" maxchar="5" /><br />
checkbox 1 <input type="checkbox" value="" id="chk1" /><br />
checkbox 2 <input type="checkbox" value="" id="chk2" /><br />
dropdown 1 <select id="dd1" >
    <option value="1">1</option>
    <option value="1">2</option>
</select><br />
dropdown 2 <select id="dd2">
    <option value="1">1</option>
    <option value="1">2</option>
</select>

Javascript:

$(function() {
    var focusables = $(":focusable");   
    focusables.keyup(function(e) {
        var maxchar = false;
        if ($(this).attr("maxchar")) {
            if ($(this).val().length >= $(this).attr("maxchar"))
                maxchar = true;
            }
        if (e.keyCode == 13 || maxchar) {
            var current = focusables.index(this),
                next = focusables.eq(current+1).length ? focusables.eq(current+1) : focusables.eq(0);
            next.focus();
        }
    });
});

Loading basic HTML in Node.js

https://gist.github.com/xgqfrms-GitHub/7697d5975bdffe8d474ac19ef906e906

Here is my simple demo codes for host static HTML files by using Express server!

hope it helps for you!

_x000D_
_x000D_
// simple express server for HTML pages!_x000D_
// ES6 style_x000D_
_x000D_
const express = require('express');_x000D_
const fs = require('fs');_x000D_
const hostname = '127.0.0.1';_x000D_
const port = 3000;_x000D_
const app = express();_x000D_
_x000D_
let cache = [];// Array is OK!_x000D_
cache[0] = fs.readFileSync( __dirname + '/index.html');_x000D_
cache[1] = fs.readFileSync( __dirname + '/views/testview.html');_x000D_
_x000D_
app.get('/', (req, res) => {_x000D_
    res.setHeader('Content-Type', 'text/html');_x000D_
    res.send( cache[0] );_x000D_
});_x000D_
_x000D_
app.get('/test', (req, res) => {_x000D_
    res.setHeader('Content-Type', 'text/html');_x000D_
    res.send( cache[1] );_x000D_
});_x000D_
_x000D_
app.listen(port, () => {_x000D_
    console.log(`_x000D_
        Server is running at http://${hostname}:${port}/ _x000D_
        Server hostname ${hostname} is listening on port ${port}!_x000D_
    `);_x000D_
});
_x000D_
_x000D_
_x000D_

How do I get the value of a registry key and ONLY the value using powershell

If you create an object, you get a more readable output and also gain an object with properties you can access:

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$obj  = New-Object -TypeName psobject

Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
$command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_)
$value = Invoke-Expression -Command $command
$obj | Add-Member -MemberType NoteProperty -Name $_ -Value $value}

Write-Output $obj | fl

Sample output: InstallRoot : C:\Windows\Microsoft.NET\Framework\

And the object: $obj.InstallRoot = C:\Windows\Microsoft.NET\Framework\

The truth of the matter is this is way more complicated than it needs to be. Here is a much better example, and much simpler:

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$objReg = Get-ItemProperty -Path $path | Select -Property *

$objReg is now a custom object where each registry entry is a property name. You can view the formatted list via:

write-output $objReg

InstallRoot        : C:\Windows\Microsoft.NET\Framework\
DbgManagedDebugger : "C:\windows\system32\vsjitdebugger.exe"

And you have access to the object itself:

$objReg.InstallRoot
C:\Windows\Microsoft.NET\Framework\

Magento - How to add/remove links on my account navigation?

Also, you need to do something like this in config.xml if you are developing a customized module

    <frontend>
        <layout>
            <updates>
                <hpcustomer>
                    <file>hpcustomer.xml</file>
                </hpcustomer>
            </updates>
        </layout>
    </frontend>

How do I instantiate a Queue object in java?

Queue is an interface in java, you can not do that.

Instead you have two options:

option1:

Queue<Integer> Q = new LinkedList<>();

option2:

Queue<Integer> Q = new ArrayDeque<>();

I recommend using option2 as it is bit faster than the other

How to select all instances of a variable and edit variable name in Sublime

This worked for me. Put your cursor at the beginning of the word you want to replace, then

CtrlK, CtrlD, CtrlD ...

That should select as many instances of the word as you like, then you can just type the replacement.

How to convert a char to a String?

I've tried the suggestions but ended up implementing it as follows

editView.setFilters(new InputFilter[]{new InputFilter()
        {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend)
            {
                String prefix = "http://";

                //make sure our prefix is visible
                String destination = dest.toString();

                //Check If we already have our prefix - make sure it doesn't
                //get deleted
                if (destination.startsWith(prefix) && (dstart <= prefix.length() - 1))
                {
                    //Yep - our prefix gets modified - try preventing it.
                    int newEnd = (dend >= prefix.length()) ? dend : prefix.length();

                    SpannableStringBuilder builder = new SpannableStringBuilder(
                            destination.substring(dstart, newEnd));
                    builder.append(source);
                    if (source instanceof Spanned)
                    {
                        TextUtils.copySpansFrom(
                                (Spanned) source, 0, source.length(), null, builder, newEnd);
                    }

                    return builder;
                }
                else
                {
                    //Accept original replacement (by returning null)
                    return null;
                }
            }
        }});

Set folder browser dialog start location

To set the directory selected path and the retrieve the new directory:

dlgBrowseForLogDirectory.SelectedPath = m_LogDirectory;
if (dlgBrowseForLogDirectory.ShowDialog() == DialogResult.OK)
{
     txtLogDirectory.Text = dlgBrowseForLogDirectory.SelectedPath;
}

writing to existing workbook using xlwt

You need xlutils.copy. Try something like this:

from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

Keep in mind you can't overwrite cells by default as noted in this question.

disable viewport zooming iOS 10+ safari?

It appears that this behavior is supposedly changed in the latest beta, which at the time of writing is beta 6.

From the release notes for iOS 10 Beta 6:

WKWebView now defaults to respecting user-scalable=no from a viewport. Clients of WKWebView can improve accessibility and allow users to pinch-to-zoom on all pages by setting the WKWebViewConfiguration property ignoresViewportScaleLimits to YES.

However, in my (very limited) testing, I can't yet confirm this to be the case.

Edit: verified, iOS 10 Beta 6 respects user-scalable=no by default for me.

int to string in MySQL

You could use CONCAT, and the numeric argument of it is converted to its equivalent binary string form.

select t2.* 
from t1 join t2 
on t2.url=CONCAT('site.com/path/%', t1.id, '%/more') where t1.id > 9000

Sending HTTP Post request with SOAP action using org.apache.http

Here is the example i have tried and it is working for me:

Create the XML file SoapRequestFile.xml

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <tem:GetConversionRate>
             <!--Optional:-->
             <tem:CurrencyFrom>USD</tem:CurrencyFrom>
             <!--Optional:-->
             <tem:CurrencyTo>INR</tem:CurrencyTo>
             <tem:RateDate>2018-12-07</tem:RateDate>
          </tem:GetConversionRate>
       </soapenv:Body>
    </soapenv:Envelope>

And here the code in java:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
@Test
            public void getMethod() throws Exception  {
                //wsdl file :http://currencyconverter.kowabunga.net/converter.asmx?wsdl
                File soapRequestFile = new File(".\\SOAPRequest\\SoapRequestFile.xml");

                CloseableHttpClient client = HttpClients.createDefault(); //create client
                HttpPost request = new HttpPost("http://currencyconverter.kowabunga.net/converter.asmx"); //Create the request
                request.addHeader("Content-Type", "text/xml"); //adding header
                request.setEntity(new InputStreamEntity(new FileInputStream(soapRequestFile)));
                CloseableHttpResponse response =  client.execute(request);//Execute the command

                int statusCode=response.getStatusLine().getStatusCode();//Get the status code and assert
                System.out.println("Status code: " +statusCode );
                Assert.assertEquals(200, statusCode);

                String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");//Getting the Response body
                System.out.println(responseString);


                XmlPath jsXpath= new XmlPath(responseString);//Converting string into xml path to assert
                String rate=jsXpath.getString("GetConversionRateResult");
                System.out.println("rate returned is: " +  rate);



        }

How does Facebook Sharer select Images and other metadata when sharing my URL?

I couldn't get Facebook to pick the right image from a specific post, so I did what's outlined on this page:

https://webapps.stackexchange.com/questions/18468/adding-meta-tags-to-individual-blogger-posts

In other words, something like this:

<b:if cond='data:blog.url == "http://urlofyourpost.com"'>
  <meta content='http://urlofyourimage.png' property='og:image'/>
 </b:if>

Basically, you're going to hard code an if statement into your site's HTML to get it to change the meta content for whatever you've changed for that one post. It's a messy solution, but it works.

How do I find Waldo with Mathematica?

I have a quick solution for finding Waldo using OpenCV.

I used the template matching function available in OpenCV to find Waldo.

To do this a template is needed. So I cropped Waldo from the original image and used it as a template.

enter image description here

Next I called the cv2.matchTemplate() function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):

enter image description here

The position of the highest probable region was found using cv2.minMaxLoc() function, which I then used to draw the rectangle to highlight Waldo:

enter image description here

Spring Data JPA and Exists query

I think you can simply change the query to return boolean as

@Query("select count(e)>0 from MyEntity e where ...")

PS: If you are checking exists based on Primary key value CrudRepository already have exists(id) method.

sqlalchemy IS NOT NULL select

column_obj != None will produce a IS NOT NULL constraint:

In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.

or use isnot() (new in 0.7.9):

Implement the IS NOT operator.

Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

Demo:

>>> from sqlalchemy.sql import column
>>> column('YourColumn') != None
<sqlalchemy.sql.elements.BinaryExpression object at 0x10c8d8b90>
>>> str(column('YourColumn') != None)
'"YourColumn" IS NOT NULL'
>>> column('YourColumn').isnot(None)
<sqlalchemy.sql.elements.BinaryExpression object at 0x104603850>
>>> str(column('YourColumn').isnot(None))
'"YourColumn" IS NOT NULL'

how to make a cell of table hyperlink

Try this way:

<td><a href="..." style="display:block;">&nbsp;</a></td>

Indent multiple lines quickly in vi

Also try this for C-indenting indentation. Do :help = for more information:

={

That will auto-indent the current code block you're in.

Or just:

==

to auto-indent the current line.

HTTP requests and JSON parsing in Python

The requests Python module takes care of both retrieving JSON data and decoding it, due to its builtin JSON decoder. Here is an example taken from the module's documentation:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

So there is no use of having to use some separate module for decoding JSON.

TypeError: 'dict' object is not callable

strikes  = [number_map[int(x)] for x in input_str.split()]

Use square brackets to explore dictionaries.

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

Non-static variable cannot be referenced from a static context

Now you can add/use instances with in the method

public class Myprogram7 {

  Scanner scan;
  int compareCount = 0;
  int low = 0;
  int high = 0;
  int mid = 0;  
  int key = 0;  
  Scanner temp;  
  int[]list;  
  String menu, outputString;  
  int option = 1;  
  boolean found = false;  

  private void readLine() {

  }

  private void findkey() {

  }

  private void printCount() {

  }
  public static void main(String[] args){

    Myprogram7 myprg=new Myprogram7();
    myprg.readLine();
    myprg.findkey();
    myprg.printCount();
  }
}

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Python datetime objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (if no time zone info is given, assumed to be local time). You can use the pytz package to get some default time zones, or directly subclass tzinfo yourself:

from datetime import datetime, tzinfo, timedelta
class simple_utc(tzinfo):
    def tzname(self,**kwargs):
        return "UTC"
    def utcoffset(self, dt):
        return timedelta(0)

Then you can manually add the time zone info to utcnow():

>>> datetime.utcnow().replace(tzinfo=simple_utc()).isoformat()
'2014-05-16T22:51:53.015001+00:00'

Note that this DOES conform to the ISO 8601 format, which allows for either Z or +00:00 as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

Converting an integer to a hexadecimal string in Ruby

Here's another approach:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

How to move div vertically down using CSS

I don't see any mention of flexbox in here, so I will illustrate:

HTML

 <div class="wrapper">
   <div class="main">top</div>
   <div class="footer">bottom</div>
 </div>

CSS

 .wrapper {
   display: flex;
   flex-direction: column;
   min-height: 100vh;
  }
 .main {
   flex: 1;
 }
 .footer {
  flex: 0;
 }

How to properly set the 100% DIV height to match document/window height?

why don't you use width: 100% and height: 100%.

submit a form in a new tab

It is also possible to use the new button attribute called formtarget that was introduced with HTML5.

<form>
  <input type="submit" formtarget="_blank"/>
</form>

Opening a .ipynb.txt File

Below is the easiest way in case if Anaconda is already installed.

1) Under "Files", there is an option called,"Upload".

2) Click on "Upload" button and it asks for the path of the file and select the file and click on upload button present beside the file.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

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

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

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

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

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

Threading

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

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

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

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

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

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

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

these slides had some features missing elsewhere.

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

Removed:

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

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

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

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

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

Spec changes:

Further reference:

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

i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:

RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

to your .htaccess file

Service vs IntentService in the Android platform

If someone can show me an example of something that can be done with an IntentService and can not be done with a Service and the other way around.

By definition, that is impossible. IntentService is a subclass of Service, written in Java. Hence, anything an IntentService does, a Service could do, by including the relevant bits of code that IntentService uses.

Starting a service with its own thread is like starting an IntentService. Is it not?

The three primary features of an IntentService are:

  • the background thread

  • the automatic queuing of Intents delivered to onStartCommand(), so if one Intent is being processed by onHandleIntent() on the background thread, other commands queue up waiting their turn

  • the automatic shutdown of the IntentService, via a call to stopSelf(), once the queue is empty

Any and all of that could be implemented by a Service without extending IntentService.

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

If you can update your connector to a version, which supports the new authentication plugin of MySQL 8, then do that. If that is not an option for some reason, change the default authentication method of your database user to native.

How to create a button programmatically?

enter image description here

 func viewDidLoad(){
                    saveActionButton = UIButton(frame: CGRect(x: self.view.frame.size.width - 60, y: 0, width: 50, height: 50))
                    self.saveActionButton.backgroundColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 0.7)
                    saveActionButton.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
                    self.saveActionButton.setTitle("Done", for: .normal)
                    self.saveActionButton.layer.cornerRadius = self.saveActionButton.frame.size.width / 2
                    self.saveActionButton.layer.borderColor = UIColor.darkGray.cgColor
                    self.saveActionButton.layer.borderWidth = 1
                    self.saveActionButton.center.y = self.view.frame.size.height - 80
                    self.view.addSubview(saveActionButton)
        }

          func doneAction(){
          print("Write your own logic")
         }

Convert timestamp to readable date/time PHP

echo date("l M j, Y",$res1['timep']);
This is really good for converting a unix timestamp to a readable date along with day. Example: Thursday Jul 7, 2016

How do I run a VBScript in 32-bit mode on a 64-bit machine?

In the launcher script you can force it, it permits to keep the same script and same launcher for both architecture

:: For 32 bits architecture, this line is sufficent (32bits is the only cscript available)
set CSCRIPT="cscript.exe"
:: Detect windows 64bits and use the expected cscript (SysWOW64 contains 32bits executable)
if exist "C:\Windows\SysWOW64\cscript.exe" set CSCRIPT="C:\Windows\SysWOW64\cscript.exe"
%CSCRIPT% yourscript.vbs

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

I like this one since it modifies tables, views, sequences and functions owner of a certain schema in one go (in one sql statement), without creating a function and you can use it directly in PgAdmin III and psql:

(Tested in PostgreSql v9.2)

DO $$DECLARE r record;
DECLARE
    v_schema varchar := 'public';
    v_new_owner varchar := '<NEW_OWNER>';
BEGIN
    FOR r IN 
        select 'ALTER TABLE "' || table_schema || '"."' || table_name || '" OWNER TO ' || v_new_owner || ';' as a from information_schema.tables where table_schema = v_schema
        union all
        select 'ALTER TABLE "' || sequence_schema || '"."' || sequence_name || '" OWNER TO ' || v_new_owner || ';' as a from information_schema.sequences where sequence_schema = v_schema
        union all
        select 'ALTER TABLE "' || table_schema || '"."' || table_name || '" OWNER TO ' || v_new_owner || ';' as a from information_schema.views where table_schema = v_schema
        union all
        select 'ALTER FUNCTION "'||nsp.nspname||'"."'||p.proname||'"('||pg_get_function_identity_arguments(p.oid)||') OWNER TO ' || v_new_owner || ';' as a from pg_proc p join pg_namespace nsp ON p.pronamespace = nsp.oid where nsp.nspname = v_schema
    LOOP
        EXECUTE r.a;
    END LOOP;
END$$;

Based on answers provided by @rkj, @AlannaRose, @SharoonThomas, @user3560574 and this answer by @a_horse_with_no_name

Thank's a lot.


Better yet: Also change database and schema owner.

DO $$DECLARE r record;
DECLARE
    v_schema varchar := 'public';
    v_new_owner varchar := 'admin_ctes';
BEGIN
    FOR r IN 
        select 'ALTER TABLE "' || table_schema || '"."' || table_name || '" OWNER TO ' || v_new_owner || ';' as a from information_schema.tables where table_schema = v_schema
        union all
        select 'ALTER TABLE "' || sequence_schema || '"."' || sequence_name || '" OWNER TO ' || v_new_owner || ';' as a from information_schema.sequences where sequence_schema = v_schema
        union all
        select 'ALTER TABLE "' || table_schema || '"."' || table_name || '" OWNER TO ' || v_new_owner || ';' as a from information_schema.views where table_schema = v_schema
        union all
        select 'ALTER FUNCTION "'||nsp.nspname||'"."'||p.proname||'"('||pg_get_function_identity_arguments(p.oid)||') OWNER TO ' || v_new_owner || ';' as a from pg_proc p join pg_namespace nsp ON p.pronamespace = nsp.oid where nsp.nspname = v_schema
        union all
        select 'ALTER SCHEMA "' || v_schema || '" OWNER TO ' || v_new_owner 
        union all
        select 'ALTER DATABASE "' || current_database() || '" OWNER TO ' || v_new_owner 
    LOOP
        EXECUTE r.a;
    END LOOP;
END$$;

Using a custom typeface in Android

Absolutely possible. Many ways to do it. The fastest way, create condition with try - catch method.. try your certain font style condition, catch the error, and define the other font style.

Handling errors in Promise.all

I've found a way (workaround) to do this without making it sync.

So as it was mentioned before Promise.all is all of none.

so... Use an enclosing promise to catch and force resolve.


      let safePromises = originalPrmises.map((imageObject) => {
            return new Promise((resolve) => {
              // Do something error friendly
              promise.then(_res => resolve(res)).catch(_err => resolve(err))
            })
        })
    })

    // safe
    return Promise.all(safePromises)

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Getting request payload from POST request in Java servlet

You only need

request.getParameterMap()

for getting the POST and GET - Parameters.

The Method returns a Map<String,String[]>.

You can read the parameters in the Map by

Map<String, String[]> map = request.getParameterMap();
//Reading the Map
//Works for GET && POST Method
for(String paramName:map.keySet()) {
    String[] paramValues = map.get(paramName);

    //Get Values of Param Name
    for(String valueOfParam:paramValues) {
        //Output the Values
        System.out.println("Value of Param with Name "+paramName+": "+valueOfParam);
    }
}

How do I loop through items in a list box and then remove those item?

How about:

foreach(var s in listBox1.Items.ToArray())
{
    MessageBox.Show(s);
    //do stuff with (s);
    listBox1.Items.Remove(s);
}

The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.

javac error: Class names are only accepted if annotation processing is explicitly requested

Perhaps you may be compiling with file name instead of method name....Check once I too made the same mistake but I corrected it quickly .....#happy Coding

Reference an Element in a List of Tuples

You also can use itemgetter operator:

from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)

How to read a text file directly from Internet using Java?

What really worked to me: (source: oracle documentation "reading url")

 import java.net.*;
 import java.io.*;

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

    URL oracle = new URL("http://yoursite.com/yourfile.txt");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
}
 }

FFmpeg on Android

After a lot of research, right now this is the most updated compiled library for Android that I found:

https://github.com/bravobit/FFmpeg-Android

  • At this moment is using FFmpeg release n4.0-39-gda39990
  • Includes FFmpeg and FFProbe
  • Contains Java interface to launch the commands
  • FFprobe or FFmpeg could be removed from the APK, check the wiki https://github.com/bravobit/FFmpeg-Android/wiki

Not able to pip install pickle in python 3.6

I had a similar error & this is what I found.

My environment details were as below: steps followed at my end

c:\>pip --version
pip 20.0.2 from c:\python37_64\lib\site-packages\pip (python 3.7)

C:\>python --version
Python 3.7.6

As per the documentation, apparently, python 3.7 already has the pickle package. So it does not require any additional download. I checked with the following command to make sure & it worked.

C:\Python\Experiements>python
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>>

So, pip install pickle not required for python v3.7 for sure

Bootstrap: How do I identify the Bootstrap version?

The Bootstrap version will be stated at the top of the CSS file. Simply open it and look at the top of the file.

e.g.

/*!
 * Bootstrap v2.3.0
 *
 * Copyright 2012 Twitter, Inc
 * Licensed under the Apache License v2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Designed and built with all the love in the world @twitter by @mdo and @fat.
 */

How to remove &quot; from my Json in javascript?

var data = $('<div>').html('[{&quot;Id&quot;:1,&quot;Name&quot;:&quot;Name}]')[0].textContent;

that should parse all the encoded values you need.

Allow click on twitter bootstrap dropdown toggle link?

For those of you complaining about "the submenus don't drop down", I solved it this way, which looks clean to me:

1) Besides your

<a class="dropdown-toggle disabled" href="http://google.com">
     Dropdown <b class="caret"></b>
</a>

put a new

<a class="dropdown-toggle"><b class="caret"></b></a>

and remove the <b class="caret"></b> tag, so it will look like

<a class="dropdown-toggle disabled" href="http://google.com">
Dropdown</a><a class="dropdown-toggle"><b class="caret"></b></a>

2) Style them with the following css rules:

.caret1 {
    position: absolute !important; top: 0; right: 0;
}

.dropdown-toggle.disabled {
    padding-right: 40px;
}

The style in .caret1 class is for positioning it absolutely inside your li, at the right corner.

The second style is for adding some padding to the right of the dropdown to place the caret, preventing overlapping the text of the menu item.

Now you have a nice responsive menu item which looks nice both in desktop and mobile versions and that is both clickable and dropdownable depending on whether you click on the text or on the caret.

How to start automatic download of a file in Internet Explorer?

A simple bit of jQuery solved this problem for me.

$(function() {
   $(window).bind('load', function() {
      $("div.downloadProject").delay(1500).append('<iframe width="0" height="0" frameborder="0" src="[YOUR FILE SRC]"></iframe>'); 
   });
});

In my HTML, I simply have

<div class="downloadProject"></div>

All this does is wait a second and a half, then append the div with the iframe referring to the file that you want to download. When the iframe is updated onto the page, your browser downloads the file. Simple as that. :D

How to build a Debian/Ubuntu package from source?

Here is a tutorial for building a Debian package.

Basically, you need to:

  1. Set up your folder structure
  2. Create a control file
  3. Optionally create postinst or prerm scripts
  4. Run dpkg-deb

I usually do all of this in my Makefile so I can just type make to spit out the binary and package it in one go.

Check if one list contains element from the other

You can use Apache Commons CollectionUtils:

if(CollectionUtils.containsAny(list1,list2)) {  
    // do whatever you want
} else { 
    // do other thing 
}  

This assumes that you have properly overloaded the equals functionality for your custom objects.

Fastest way to check if string contains only digits

The char already has an IsDigit(char c) which does this:

 public static bool IsDigit(char c)
    {
      if (!char.IsLatin1(c))
        return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber;
      if ((int) c >= 48)
        return (int) c <= 57;
      else
        return false;
    }

You can simply do this:

var theString = "839278";
bool digitsOnly = theString.All(char.IsDigit);

django change default runserver port

Actually the easiest way to change (only) port in development Django server is just like:

python manage.py runserver 7000

that should run development server on http://127.0.0.1:7000/

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also had the same problem. I used next way:

1.Added settings.xml file (~/.m2/settings.xml) with next content

<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>qq-proxya</host>
      <port>8080</port>
      <username>user</username>
      <password>passw</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>

3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !

  1. After that updated project in the Eclipse(Alt + F5) or right click on project -> Maven -> Update project

P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.

Spring CORS No 'Access-Control-Allow-Origin' header is present

Helpful tip - if you're using Spring data rest you need a different approach.

@Component
public class SpringDataRestCustomization extends RepositoryRestConfigurerAdapter {

 @Override
 public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    config.getCorsRegistry().addMapping("/**")
            .allowedOrigins("http://localhost:9000");
  }
}

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

This answer explains what's going on behind the scenes, and the basics of how to solve this problem in any language. For reference, see the MDN docs on this topic.

You are making a request for a URL from JavaScript running on one domain (say domain-a.com) to an API running on another domain (domain-b.com). When you do that, the browser has to ask domain-b.com if it's okay to allow requests from domain-a.com. It does that with an HTTP OPTIONS request. Then, in the response, the server on domain-b.com has to give (at least) the following HTTP headers that say "Yeah, that's okay":

HTTP/1.1 204 No Content                            // or 200 OK
Access-Control-Allow-Origin: https://domain-a.com  // or * for allowing anybody
Access-Control-Allow-Methods: POST, GET, OPTIONS   // What kind of methods are allowed
...                                                // other headers

If you're in Chrome, you can see what the response looks like by pressing F12 and going to the "Network" tab to see the response the server on domain-b.com is giving.

So, back to the bare minimum from @threeve's original answer:

header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")

if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
}

This will allow anybody from anywhere to access this data. The other headers he's included are necessary for other reasons, but these headers are the bare minimum to get past the CORS (Cross Origin Resource Sharing) requirements.

Differences between "java -cp" and "java -jar"?

java -cp CLASSPATH is necesssary if you wish to specify all code in the classpath. This is useful for debugging code.

The jarred executable format: java -jar JarFile can be used if you wish to start the app with a single short command. You can specify additional dependent jar files in your MANIFEST using space separated jars in a Class-Path entry, e.g.:

Class-Path: mysql.jar infobus.jar acme/beans.jar

Both are comparable in terms of performance.

Dynamically create and submit form

Try with this code -
It is a totally dynamic solution:

    var form = $(document.createElement('form'));
    $(form).attr("action", "reserves.php");
    $(form).attr("method", "POST");

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla");
    $(form).append($(input));
    $(form).submit();

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

What does <a href="#" class="view"> mean?

It probably works with Javascript. When you click the link, nothing happens because it points to the current site. The javascript will then load a window or an url. It's used a lot in AJAX web apps.

Why am I getting a " Traceback (most recent call last):" error?

At the beginning of your file you set raw_input to 0. Do not do this, at it modifies the built-in raw_input() function. Therefore, whenever you call raw_input(), it is essentially calling 0(), which raises the error. To remove the error, remove the first line of your code:

M = 1.6
# Miles to Kilometers 
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(raw_input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: %f\n" % M_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(raw_input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: %f\n") % F_conv
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(raw_input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: %f\n" % G_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(raw_input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: %f\n" % P_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(raw_input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: %f\n" % inches_conv)
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

How to properly URL encode a string in PHP?

You can use URL Encoding Functions PHP has the

rawurlencode() 

function

ASP has the

Server.URLEncode() 

function

In JavaScript you can use the

encodeURIComponent() 

function.

Changing the resolution of a VNC session in linux

Solution by @omiday worked for me in Xvnc TigerVNC 1.1.0, so I condensed it into a single bash function vncsize x y. Use it like this: vncsize 1400 1000. It works for any VNC output name, "default" or "VNC-0".

function vncsize {
    local x=$1 y=$2
    local mode
    if mode=$(cvt "$x" "$y" 2>/dev/null)
    then
        if [[ $mode =~ "Modeline (.*)$" ]]
        then
            local newMode=${BASH_REMATCH[1]//\"/}
            local modeName=${newMode%% *}
            local newSize=( ${modeName//[\"x_]/ } )
            local screen=$(xrandr -q|grep connected|cut -d' ' -f1)
            xrandr --newmode $newMode
            xrandr --addmode "$screen" "$modeName"
            xrandr --size "${newSize[0]}x${newSize[1]}" &&
                return 0
        else
            echo "Unable to parse modeline for ($x $y) from $mode"
            return 2
        fi
    else
        echo "\`$x $y' is not a valid X Y pair"
        return 1
    fi
}

How to test my servlet using JUnit

Another approach would be to create an embedded server to "host" your servlet, allowing you to write calls against it with libraries meant to make calls to actual servers (the usefulness of this approach somewhat depends on how easily you can make "legitimate" programatic calls to the server - I was testing a JMS (Java Messaging Service) access point, for which clients abound).

There are a couple of different routes you can go - the usual two are tomcat and jetty.

Warning: something to be mindful of when choosing the server to embed is the version of servlet-api you are using (the library which provides classes like HttpServletRequest). If you are using 2.5, I found Jetty 6.x to work well (which is the example I'll give below). If you're using servlet-api 3.0, the tomcat-7 embedded stuff seems to be a good option, however I had to abandon my attempt to use it, as the application I was testing used servlet-api 2.5. Trying to mix the two will result in NoSuchMethod and other such exceptions when attempting to configure or start the server.

You can set up such a server like this (Jetty 6.1.26, servlet-api 2.5):

public void startServer(int port, Servlet yourServletInstance){
    Server server = new Server(port);
    Context root = new Context(server, "/", Context.SESSIONS);

    root.addServlet(new ServletHolder(yourServletInstance), "/servlet/context/path");

    //If you need the servlet context for anything, such as spring wiring, you coudl get it like this
    //ServletContext servletContext = root.getServletContext();

    server.start();
}

python pandas convert index to datetime

I just give other option for this question - you need to use '.dt' in your code:

_x000D_
_x000D_
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
_x000D_
_x000D_

Remove decimal values using SQL query

Since all your values end with ".00", there will be no rounding issues, this will work

SELECT CAST(columnname AS INT) AS columnname from tablename

to update

UPDATE tablename
SET columnname = CAST(columnname AS INT)
WHERE .....

Python: Finding differences between elements of a list

The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:

v = numpy.diff(t)

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The solution for me is to install this VB6 patch. I'm on Server2008 (32-bit).

http://www.microsoft.com/en-us/download/details.aspx?id=10019

It makes me sad that we're still talking about this in 2014... but here it is. :)


From puetzk's comment: These are outdated: you want to be using Microsoft Visual Basic 6.0 Service Pack 6 Cumulative Update (kb957924).

How to get the integer value of day of week

DateTime currentDateTime = DateTime.Now;
int week = (int) currentDateTime.DayOfWeek;

Retaining file permissions with Git

In case you are coming into this right now, I've just been through it today and can summarize where this stands. If you did not try this yet, some details here might help.

I think @Omid Ariyan's approach is the best way. Add the pre-commit and post-checkout scripts. DON'T forget to name them exactly the way Omid does and DON'T forget to make them executable. If you forget either of those, they have no effect and you run "git commit" over and over wondering why nothing happens :) Also, if you cut and paste out of the web browser, be careful that the quotation marks and ticks are not altered.

If you run the pre-commit script once (by running a git commit), then the file .permissions will be created. You can add it to the repository and I think it is unnecessary to add it over and over at the end of the pre-commit script. But it does not hurt, I think (hope).

There are a few little issues about the directory name and the existence of spaces in the file names in Omid's scripts. The spaces were a problem here and I had some trouble with the IFS fix. For the record, this pre-commit script did work correctly for me:

#!/bin/bash  

SELF_DIR=`git rev-parse --show-toplevel`
DATABASE=$SELF_DIR/.permissions

# Clear the permissions database file
> $DATABASE

echo -n "Backing-up file permissions..."

IFSold=$IFS
IFS=$'\n'
for FILE  in `git ls-files`
do
   # Save the permissions of all the files in the index
   echo $FILE";"`stat -c "%a;%U;%G" $FILE` >> $DATABASE
done
IFS=${IFSold}
# Add the permissions database file to the index
git add $DATABASE

echo "OK"

Now, what do we get out of this?

The .permissions file is in the top level of the git repo. It has one line per file, here is the top of my example:

$ cat .permissions
.gitignore;660;pauljohn;pauljohn
05.WhatToReport/05.WhatToReport.doc;664;pauljohn;pauljohn
05.WhatToReport/05.WhatToReport.pdf;664;pauljohn;pauljohn

As you can see, we have

filepath;perms;owner;group

In the comments about this approach, one of the posters complains that it only works with same username, and that is technically true, but it is very easy to fix it. Note the post-checkout script has 2 action pieces,

# Set the file permissions
chmod $PERMISSIONS $FILE
# Set the file owner and groups
chown $USER:$GROUP $FILE

So I am only keeping the first one, that's all I need. My user name on the Web server is indeed different, but more importantly you can't run chown unless you are root. Can run "chgrp", however. It is plain enough how to put that to use.

In the first answer in this post, the one that is most widely accepted, the suggestion is so use git-cache-meta, a script that is doing the same work that the pre/post hook scripts here are doing (parsing output from git ls-files). These scripts are easier for me to understand, the git-cache-meta code is rather more elaborate. It is possible to keep git-cache-meta in the path and write pre-commit and post-checkout scripts that would use it.

Spaces in file names are a problem with both of Omid's scripts. In the post-checkout script, you'll know you have the spaces in file names if you see errors like this

$ git checkout -- upload.sh
Restoring file permissions...chmod: cannot access  '04.StartingValuesInLISREL/Open': No such file or directory
chmod: cannot access 'Notebook.onetoc2': No such file or directory
chown: cannot access '04.StartingValuesInLISREL/Open': No such file or directory
chown: cannot access 'Notebook.onetoc2': No such file or directory

I'm checking on solutions for that. Here's something that seems to work, but I've only tested in one case

#!/bin/bash

SELF_DIR=`git rev-parse --show-toplevel`
DATABASE=$SELF_DIR/.permissions

echo -n "Restoring file permissions..."
IFSold=${IFS}
IFS=$
while read -r LINE || [[ -n "$LINE" ]];
do
   FILE=`echo $LINE | cut -d ";" -f 1`
   PERMISSIONS=`echo $LINE | cut -d ";" -f 2`
   USER=`echo $LINE | cut -d ";" -f 3`
   GROUP=`echo $LINE | cut -d ";" -f 4`

   # Set the file permissions
   chmod $PERMISSIONS $FILE
   # Set the file owner and groups
   chown $USER:$GROUP $FILE
done < $DATABASE
IFS=${IFSold}
echo "OK"

exit 0

Since the permissions information is one line at a time, I set IFS to $, so only line breaks are seen as new things.

I read that it is VERY IMPORTANT to set the IFS environment variable back the way it was! You can see why a shell session might go badly if you leave $ as the only separator.

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

How to unmount a busy device

Multiple mounts inside a folder

An additional reason could be a secondary mount inside your primary mount folder, e.g. after you worked on an SD card for an embedded device:

# mount /dev/sdb2 /mnt       # root partition which contains /boot
# mount /dev/sdb1 /mnt/boot  # boot partition

Unmounting /mnt will fail:

# umount /mnt
umount: /mnt: target is busy.

First we have to unmount the boot folder and then the root:

# umount /mnt/boot
# umount /mnt

DBCC CHECKIDENT Sets Identity to 0

Simply do this:

IF EXISTS (SELECT * FROM tablename)
BEGIN
    DELETE from  tablename
    DBCC checkident ('tablename', reseed, 0)
END

How do I export a project in the Android studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

How can I programmatically check whether a keyboard is present in iOS app?

SWIFT 4.2 / SWIFT 5

class Listener {
   public static let shared = Listener()
   var isVisible = false

   // Start this listener if you want to present the toast above the keyboard.
   public func startKeyboardListener() {
      NotificationCenter.default.addObserver(self, selector: #selector(didShow), name: UIResponder.keyboardWillShowNotification, object: nil)
      NotificationCenter.default.addObserver(self, selector: #selector(didHide), name: UIResponder.keyboardWillHideNotification, object: nil)
   }

   @objc func didShow() {
     isVisible = true
   }

    @objc func didHide(){
       isVisible = false
    }
}

How to get all the AD groups for a particular user?

PrincipalContext pc1 = new PrincipalContext(ContextType.Domain, "DomainName", UserAccountOU, UserName, Password);
UserPrincipal UserPrincipalID = UserPrincipal.FindByIdentity(pc1, IdentityType.SamAccountName, UserID);

searcher.Filter = "(&(ObjectClass=group)(member = " + UserPrincipalID.DistinguishedName + "));

How to parse dates in multiple formats using SimpleDateFormat

Here is the complete example (with main method) which can be added as a utility class in your project. All the format mentioned in SimpleDateFormate API is supported in the below method.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.time.DateUtils;

public class DateUtility {

    public static Date parseDate(String inputDate) {

        Date outputDate = null;
        String[] possibleDateFormats =
              {
                    "yyyy.MM.dd G 'at' HH:mm:ss z",
                    "EEE, MMM d, ''yy",
                    "h:mm a",
                    "hh 'o''clock' a, zzzz",
                    "K:mm a, z",
                    "yyyyy.MMMMM.dd GGG hh:mm aaa",
                    "EEE, d MMM yyyy HH:mm:ss Z",
                    "yyMMddHHmmssZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
                    "YYYY-'W'ww-u",
                    "EEE, dd MMM yyyy HH:mm:ss z", 
                    "EEE, dd MMM yyyy HH:mm zzzz",
                    "yyyy-MM-dd'T'HH:mm:ssZ",
                    "yyyy-MM-dd'T'HH:mm:ss.SSSzzzz", 
                    "yyyy-MM-dd'T'HH:mm:sszzzz",
                    "yyyy-MM-dd'T'HH:mm:ss z",
                    "yyyy-MM-dd'T'HH:mm:ssz", 
                    "yyyy-MM-dd'T'HH:mm:ss",
                    "yyyy-MM-dd'T'HHmmss.SSSz",
                    "yyyy-MM-dd",
                    "yyyyMMdd",
                    "dd/MM/yy",
                    "dd/MM/yyyy"
              };

        try {

            outputDate = DateUtils.parseDate(inputDate, possibleDateFormats);
            System.out.println("inputDate ==> " + inputDate + ", outputDate ==> " + outputDate);

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return outputDate;

    }

    public static String formatDate(Date date, String requiredDateFormat) {
        SimpleDateFormat df = new SimpleDateFormat(requiredDateFormat);
        String outputDateFormatted = df.format(date);
        return outputDateFormatted;
    }

    public static void main(String[] args) {

        DateUtility.parseDate("20181118");
        DateUtility.parseDate("2018-11-18");
        DateUtility.parseDate("18/11/18");
        DateUtility.parseDate("18/11/2018");
        DateUtility.parseDate("2018.11.18 AD at 12:08:56 PDT");
        System.out.println("");
        DateUtility.parseDate("Wed, Nov 18, '18");
        DateUtility.parseDate("12:08 PM");
        DateUtility.parseDate("12 o'clock PM, Pacific Daylight Time");
        DateUtility.parseDate("0:08 PM, PDT");
        DateUtility.parseDate("02018.Nov.18 AD 12:08 PM");
        System.out.println("");
        DateUtility.parseDate("Wed, 18 Nov 2018 12:08:56 -0700");
        DateUtility.parseDate("181118120856-0700");
        DateUtility.parseDate("2018-11-18T12:08:56.235-0700");
        DateUtility.parseDate("2018-11-18T12:08:56.235-07:00");
        DateUtility.parseDate("2018-W27-3");
    }

}

How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?

I found a very easy process to find you MD5, SHA-1 fingerprint using Android Studio.

  1. Run your project
  2. Go to Gradle Menu (Menu: View -> Tool Windows -> Gradle)
  3. Go to 'signingReport' in Gradle window. (Your project -> Tasks -> android -> signingReport)
  4. Run it. (Using double-click or Ctrl + Shift + F10)
  5. In Run window you will find all info.

It's work only for debug mode. In realease mode I can not see sha-1. Here result of gradlew signingReport

Variant: release
Config: none
----------
Variant: releaseUnitTest
Config: none
----------
Variant: debug
Config: debug
Store: path\Android\avd\.android\debug.keystore
Alias: AndroidDebugKey
MD5: xx:xx:xx:62:86:B7:9C:BC:FB:AD:C8:C6:64:69:xx:xx
SHA1: xx:xx:xx:xx:0F:B0:82:86:1D:14:0D:AF:67:99:58:1A:01:xx:xx:xx
Valid until: Friday, July 19, 2047
----------

So I must use keytool to get sha-1. Here official Firebase doc:

Get_sha-1_for_release

Ubuntu apt-get unable to fetch packages

I tried this really interesting solution today, which worked for me on an Ubuntu server. Some DNS or another issue in the apt was making it adamant to not installing some packages from a custom PPA. What I did was install the apt-fast package and use it to install my packages instead of apt.

apt-fast is an alternative to apt which works on top of apt but uses aria2c to download packages. It is used to increase the download speed. In my case, it also solved whatever network problem was making apt to fail.

Using it is exactly the same as apt:

sudo apt-fast install package-name

How do you calculate program run time in python?

I don't know if this is a faster alternative, but I have another solution -

from datetime import datetime
start=datetime.now()

#Statements

print datetime.now()-start

Filter multiple values on a string column in dplyr

This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:

  1. Install dplyr package.
  2. Run the below code
library(dplyr) 

df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))

Explanation:

So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:

filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.

How do I add a new column to a Spark DataFrame (using PySpark)?

I would like to offer a generalized example for a very similar use case:

Use Case: I have a csv consisting of:

First|Third|Fifth
data|data|data
data|data|data
...billion more lines

I need to perform some transformations and the final csv needs to look like

First|Second|Third|Fourth|Fifth
data|null|data|null|data
data|null|data|null|data
...billion more lines

I need to do this because this is the schema defined by some model and I need for my final data to be interoperable with SQL Bulk Inserts and such things.

so:

1) I read the original csv using spark.read and call it "df".

2) I do something to the data.

3) I add the null columns using this script:

outcols = []
for column in MY_COLUMN_LIST:
    if column in df.columns:
        outcols.append(column)
    else:
        outcols.append(lit(None).cast(StringType()).alias('{0}'.format(column)))

df = df.select(outcols)

In this way, you can structure your schema after loading a csv (would also work for reordering columns if you have to do this for many tables).

remove objects from array by object property

If you just want to remove it from the existing array and not create a new one, try:

var items = [{Id: 1},{Id: 2},{Id: 3}];
items.splice(_.indexOf(items, _.find(items, function (item) { return item.Id === 2; })), 1);

How to import image (.svg, .png ) in a React Component

Simple way is using location.origin
it will return your domain
ex
http://localhost:8000
https://yourdomain.com

then concat with some string...
Enjoy...

<img src={ location.origin+"/images/robot.svg"} alt="robot"/>

More images ?

var images =[
"img1.jpg",
"img2.png",
"img3.jpg",
]

images.map( (image,index) => (

  <img key={index} 
       src={ location.origin+"/images/"+image} 
       alt="robot"
  />
) )

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Uninstall your application from the emulator or device. Run the app again. (OnCreate() is not executed when the database already exists)

How can I keep Bootstrap popovers alive while being hovered?

I know I'm kinda late to the party but I was looking for a solution for this..and I bumped into this post. Here is my take on this, maybe it will help some of you.

The html part:

<button type="button" class="btn btn-lg btn-danger" data-content="test" data-placement="right" data-toggle="popover" title="Popover title" >Hover to toggle popover</button><br>
// with custom html stored in a separate element, using "data-target"
<button type="button" class="btn btn-lg btn-danger" data-target="#custom-html" data-placement="right" data-toggle="popover" >Hover to toggle popover</button>

<div id="custom-html" style="display: none;">
    <strong>Helloooo!!</strong>
</div>

The js part:

$(function () {
        let popover = '[data-toggle="popover"]';

        let popoverId = function(element) {
            return $(element).popover().data('bs.popover').tip.id;
        }

        $(popover).popover({
            trigger: 'manual',
            html: true,
            animation: false
        })
        .on('show.bs.popover', function() {
            // hide all other popovers  
            $(popover).popover("hide");
        })
        .on("mouseenter", function() {
            // add custom html from element
            let target = $(this).data('target');
            $(this).popover().data('bs.popover').config.content = $(target).html();

            // show the popover
            $(this).popover("show");
            
            $('#' + popoverId(this)).on("mouseleave", () => {
               $(this).popover("hide");
            });

        }).on("mouseleave", function() {
            setTimeout(() => {
                if (!$("#" + popoverId(this) + ":hover").length) {
                    $(this).popover("hide");
                }
            }, 100);
        });
    })

Bootstrap dropdown menu not working (not dropping down when clicked)

Adding this script to my code fixed the dropdown menu.

<script>
    $(document).ready(function () {
        $('.dropdown-toggle').dropdown();
    });
</script>

Inner join with count() on three tables

As Frank pointed out, you need to use DISTINCT. Also, since you are using composite primary keys (which is perfectly fine, BTW) you need to make sure that you use the whole key in your joins:

SELECT
    P.pe_name,
    COUNT(DISTINCT O.ord_id) AS num_orders,
    COUNT(I.item_id) AS num_items
FROM
    People P
INNER JOIN Orders O ON
    O.pe_id = P.pe_id
INNER JOIN Items I ON
    I.ord_id = O.ord_id AND
    I.pe_id = O.pe_id
GROUP BY
    P.pe_name

Without I.ord_id = O.ord_id it was joining each item row to every order row for a person.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Maintaining the final state at end of a CSS3 animation

If you are using more animation attributes the shorthand is:

animation: bubble 2s linear 0.5s 1 normal forwards;

This gives:

  • bubble animation name
  • 2s duration
  • linear timing-function
  • 0.5s delay
  • 1 iteration-count (can be 'infinite')
  • normal direction
  • forwards fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})

How to find a value in an array and remove it by using PHP array functions?

The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)

How to export collection to CSV in MongoDB?

For all those who are stuck with an error.

Let me give you guys a solution with a brief explanation of the same:-

command to connect:-

mongoexport --host your_host --port your_port -u your_username -p your_password --db your_db --collection your_collection --type=csv --out file_name.csv --fields all_the_fields --authenticationDatabase admin

--host --> host of Mongo server

--port --> port of Mongo server

-u --> username

-p --> password

--db --> db from which you want to export

--collection --> collection you want to export

--type --> type of export in my case CSV

--out --> file name where you want to export

--fields --> all the fields you want to export (don't give spaces in between two field name in between commas in case of CSV)

--authenticationDatabase --> database where all your user information is stored

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

The assertion libraries in Mocha work by throwing an error if the assertion was not correct. Throwing an error results in a rejected promise, even when thrown in the executor function provided to the catch method.

.catch((error) => {
  assert.isNotOk(error,'Promise error');
  done();
});

In the above code the error objected evaluates to true so the assertion library throws an error... which is never caught. As a result of the error the done method is never called. Mocha's done callback accepts these errors, so you can simply end all promise chains in Mocha with .then(done,done). This ensures that the done method is always called and the error would be reported the same way as when Mocha catches the assertion's error in synchronous code.

it('should transition with the correct event', (done) => {
  const cFSM = new CharacterFSM({}, emitter, transitions);
  let timeout = null;
  let resolved = false;
  new Promise((resolve, reject) => {
    emitter.once('action', resolve);
    emitter.emit('done', {});
    timeout = setTimeout(() => {
      if (!resolved) {
        reject('Timedout!');
      }
      clearTimeout(timeout);
    }, 100);
  }).then(((state) => {
    resolved = true;
    assert(state.action === 'DONE', 'should change state');
  })).then(done,done);
});

I give credit to this article for the idea of using .then(done,done) when testing promises in Mocha.

Escape single quote character for use in an SQLite query

Just in case if you have a loop or a json string that need to insert in the database. Try to replace the string with a single quote . here is my solution. example if you have a string that contain's a single quote.

String mystring = "Sample's";
String myfinalstring = mystring.replace("'","''");

 String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";

this works for me in c# and java

What is the difference between gravity and layout_gravity in Android?

If a we want to set the gravity of content inside a view then we will use "android:gravity", and if we want to set the gravity of this view (as a whole) within its parent view then we will use "android:layout_gravity".

Locate Git installation folder on Mac OS X

Is it in your PATH? If so just run which git in the terminal and it will tell you.

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

How can building a heap be O(n) time complexity?

I really like explanation by Jeremy west.... another approach which is really easy for understanding is given here http://courses.washington.edu/css343/zander/NotesProbs/heapcomplexity

since, buildheap depends using depends on heapify and shiftdown approach is used which depends upon sum of the heights of all nodes. So, to find the sum of height of nodes which is given by S = summation from i = 0 to i = h of (2^i*(h-i)), where h = logn is height of the tree solving s, we get s = 2^(h+1) - 1 - (h+1) since, n = 2^(h+1) - 1 s = n - h - 1 = n- logn - 1 s = O(n), and so complexity of buildheap is O(n).

Improve SQL Server query performance on large tables

There are a few issues with this query (and this apply to every query).

Lack of index

Lack of index on er101_upd_date_iso column is most important thing as Oded has already mentioned.

Without matching index (which lack of could cause table scan) there is no chance to run fast queries on big tables.

If you cannot add indexes (for various reasons including there is no point in creating index for just one ad-hoc query) I would suggest a few workarounds (which can be used for ad-hoc queries):

1. Use temporary tables

Create temporary table on subset (rows and columns) of data you are interested in. Temporary table should be much smaller that original source table, can be indexed easily (if needed) and can cached subset of data which you are interested in.

To create temporary table you can use code (not tested) like:

-- copy records from last month to temporary table
INSERT INTO
   #my_temporary_table
SELECT
    *
FROM
    er101_acct_order_dtl WITH (NOLOCK)
WHERE 
    er101_upd_date_iso > DATEADD(month, -1, GETDATE())

-- you can add any index you need on temp table
CREATE INDEX idx_er101_upd_date_iso ON #my_temporary_table(er101_upd_date_iso)

-- run other queries on temporary table (which can be indexed)
SELECT TOP 100
    * 
FROM 
    #my_temporary_table 
ORDER BY 
    er101_upd_date_iso DESC

Pros:

  • Easy to do for any subset of data.
  • Easy to manage -- it's temporary and it's table.
  • Doesn't affect overall system performance like view.
  • Temporary table can be indexed.
  • You don't have to care about it -- it's temporary :).

Cons:

  • It's snapshot of data -- but probably this is good enough for most ad-hoc queries.

2. Common table expression -- CTE

Personally I use CTE a lot with ad-hoc queries -- it's help a lot with building (and testing) a query piece by piece.

See example below (the query starting with WITH).

Pros:

  • Easy to build starting from big view and then selecting and filtering what really you need.
  • Easy to test.

Cons:

  • Some people dislike CDE -- CDE queries seem to be long and difficult to understand.

3. Create views

Similar to above, but create views instead of temporary tables (if you play often with the same queries and you have MS SQL version which supports indexed views.

You can create views or indexed views on subset of data you are interested in and run queries on view -- which should contain only interesting subset of data much smaller than the whole table.

Pros:

  • Easy to do.
  • It's up to date with source data.

Cons:

  • Possible only for defined subset of data.
  • Could be inefficient for large tables with high rate of updates.
  • Not so easy to manage.
  • Can affect overall system performance.
  • I am not sure indexed views are available in every version of MS SQL.

Selecting all columns

Running star query (SELECT * FROM) on big table is not good thing...

If you have large columns (like long strings) it takes a lot of time to read them from disk and pass by network.

I would try to replace * with column names which you really need.

Or, if you need all columns try to rewrite query to something like (using common data expression):

;WITH recs AS (
    SELECT TOP 100 
        id as rec_id -- select primary key only
    FROM 
        er101_acct_order_dtl 
    ORDER BY 
        er101_upd_date_iso DESC
)
SELECT
    er101_acct_order_dtl.*
FROM
    recs
    JOIN
      er101_acct_order_dtl
    ON
      er101_acct_order_dtl.id = recs.rec_id
ORDER BY 
    er101_upd_date_iso DESC 

Dirty reads

Last thing which could speed up the ad-hoc query is allowing dirty reads with table hint WITH (NOLOCK).

Instead of hint you can set transaction isolation level to read uncommited:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

or set proper SQL Management Studio setting.

I assume for ad-hoc queries dirty reads is good enough.

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

Only Objective-C is allowed by now... but since a few months ago you are allowed to write scripts that will be interpreted in your application.

So you may be able to write a LUA interpreter or a Python interpreter, then write some part of your application in this scripting language. If you want your application accepted on the App Store, these scripts have to be bundled with the application (your application cannot download it from the Internet for example)

see new app store rules

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

Finding the next available id in MySQL

One way to do it is to set the index to be auto incrementing. Then your SQL statement simply specifies NULL and then SQL parser does the rest for you.

INSERT INTO foo VALUES (null);

How to set cache: false in jQuery.get call

I'm very late in the game, but this might help others. I hit this same problem with $.get and I didn't want to blindly turn off caching and I didn't like the timestamp patch. So after a little research I found that you can simply use $.post instead of $.get which does NOT use caching. Simple as that. :)

Extract substring from a string

use text untold class from android:
TextUtils.substring (charsequence source, int start, int end)

Setting a Sheet and cell as variable

Yes. For that ensure that you declare the worksheet

For example

Previous Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet3")

    Debug.Print ws.Cells(23, 4).Value
End Sub

New Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet4")

    Debug.Print ws.Cells(23, 4).Value
End Sub

How to access environment variable values?

If you are planning to use the code in a production web application code,
using any web framework like Django/Flask, use projects like envparse, using it you can read the value as your defined type.

from envparse import env
# will read WHITE_LIST=hello,world,hi to white_list = ["hello", "world", "hi"]
white_list = env.list("WHITE_LIST", default=[]) 
# Perfect for reading boolean
DEBUG = env.bool("DEBUG", default=False)

NOTE: kennethreitz's autoenv is a recommended tool for making project specific environment variables, please note that those who are using autoenv please keep the .env file private (inaccessible to public)

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

Using DataContractSerializer to serialize, but can't deserialize back

This best for XML Deserialize

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

(Windows) If you have already installed MySQL server

cd C:\Program Files\MySQL\MySQL Server X.X\bin mysqld --install

and still cannot connect, then the service did not start automatically. Just try

Start > Search "services"

and scroll down until you see "MySQLXX", where the XX represents the MySQL Server version. If the Status isn't "Started", then

Right Click > Start

If you are here you should be golden: enter image description here

How to bind multiple values to a single WPF TextBlock?

If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"/>
        <TextBlock Text="{Binding ID}"/>
    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.

List of macOS text editors and code editors

I've been using TextWrangler, it's pretty decent.

But I REALLY miss the Search and Replace and other capabilities of UltraEdit... enough that it's usually worth firing up Parallels to use it instead (UltraEdit runs poorly under Wine at the moment).

How to check if user input is not an int value

Try this one:

    for (;;) {
        if (!sc.hasNextInt()) {
            System.out.println(" enter only integers!: ");
            sc.next(); // discard
            continue;
        }
        choose = sc.nextInt();
        if (choose >= 0) {
            System.out.print("no problem with input");

        } else {
            System.out.print("invalid inputs");

        }
    break;
  }

Making heatmap from pandas DataFrame

Useful sns.heatmap api is here. Check out the parameters, there are a good number of them. Example:

import seaborn as sns
%matplotlib inline

idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)

# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)

enter image description here

how to set font size based on container size?

I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;

  • I have a container that changed size depending on the viewport using media queries
  • Text inside is dynamically generated
  • I want to scale up as well as down

Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)

_x000D_
_x000D_
var TextFit = function(){_x000D_
 var container = $('.container');_x000D_
  container.each(function(){_x000D_
    var container_width = $(this).width(),_x000D_
      width_offset = parseInt($(this).data('width-offset')),_x000D_
        font_container = $(this).find('.font-container');_x000D_
 _x000D_
     if ( width_offset > 0 ) {_x000D_
         container_width -= width_offset;_x000D_
     }_x000D_
                _x000D_
    font_container.each(function(){_x000D_
      var font_container_width = $(this).width(),_x000D_
          font_size = parseFloat( $(this).css('font-size') );_x000D_
_x000D_
      var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);_x000D_
 _x000D_
      var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );_x000D_
      _x000D_
      if (diff_percentage !== 0){_x000D_
          if ( container_width > font_container_width ) {_x000D_
            new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          } else if ( container_width < font_container_width ) {_x000D_
            new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );_x000D_
          }_x000D_
      }_x000D_
      $(this).css('font-size', new_font_size + 'px');_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
  TextFit();_x000D_
  $(window).resize(function(){_x000D_
   TextFit();_x000D_
  });_x000D_
});
_x000D_
.container {_x000D_
  width:341px;_x000D_
  height:341px;_x000D_
  background-color:#000;_x000D_
  padding:20px;_x000D_
 }_x000D_
 .font-container {_x000D_
  font-size:131px;_x000D_
  text-align:center;_x000D_
  color:#fff;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container" data-width-offset="10">_x000D_
 <span class="font-container">£5000</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/Merch80/b8hoctfb/7/

How can I check if a MySQL table exists with PHP?

$res = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = '$databasename' AND table_name = '$tablename';");

If no records are returned then it doesn't exist.

Reason to Pass a Pointer by Reference in C++?

You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to.

This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.

Filtering Pandas DataFrames on dates

The shortest way to filter your dataframe by date: Lets suppose your date column is type of datetime64[ns]

# filter by single day
df = df[df['date'].dt.strftime('%Y-%m-%d') == '2014-01-01']

# filter by single month
df = df[df['date'].dt.strftime('%Y-%m') == '2014-01']

# filter by single year
df = df[df['date'].dt.strftime('%Y') == '2014']

Maximum size of a varchar(max) variable

EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value syntax is incorrect.

I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. error message. In 2008, the modified script is still successful.

declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = str_replace(' ', '_', $journalName);

to remove white space

Add values to app.config and retrieve them

Are you missing the reference to System.Configuration.dll? ConfigurationManager class lies there.

EDIT: The System.Configuration namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

Cannot find firefox binary in PATH. Make sure firefox is installed

Did you add firefox to your path after you have started the selenium server? If that is the case selenium will still use old path. The solution is to tear down & restart selenium so that it will use the updated Path environment variable.

To check if firefox is added in your path correctly you can just launch a command line terminal "cmd" and type "firefox" + ENTER there. If firefox starts then everything is alright and restarting selenium server should fix the problem.

'heroku' does not appear to be a git repository

The following commands will work well for ruby on rails application deployment on heroku if heroku is already installed on developers machine. # indicates a comment

  1. heroku login
  2. heroku create
  3. heroku keys:add #this adds local machines keys to heroku so as to avoid repeated password entry
  4. git push heroku master
  5. heroku rename new-application-name #rename application to the preferred name other than the auto generated heroku name

WPF loading spinner

Here's an example of an all-xaml solution. It binds to an "IsWorking" boolean in the viewmodel to show the control and start the animation.

<UserControl x:Class="MainApp.Views.SpinnerView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
    </UserControl.Resources>

    <StackPanel Orientation="Horizontal" Margin="5"
                     Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisConverter}}">
        <Label>Wait...</Label>
        <Ellipse x:Name="spinnerEllipse" 
                     Width="20" Height="20">
            <Ellipse.Fill>
                <LinearGradientBrush StartPoint="1,1" EndPoint="0,0" >
                    <GradientStop Color="White" Offset="0"/>
                    <GradientStop Color="CornflowerBlue" Offset="1"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
            <Ellipse.RenderTransform>
                <RotateTransform x:Name="SpinnerRotate" CenterX="10" CenterY="10"/>
            </Ellipse.RenderTransform>
            <Ellipse.Style>
                <Style TargetType="Ellipse">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsWorking}" Value="True">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard x:Name="SpinStoryboard">
                                    <Storyboard TargetProperty="RenderTransform.Angle" >
                                        <DoubleAnimation
                                            From="0" To="360" Duration="0:0:01"
                                            RepeatBehavior="Forever" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </DataTrigger.EnterActions>
                            <DataTrigger.ExitActions>
                                <StopStoryboard BeginStoryboardName="SpinStoryboard"></StopStoryboard>
                            </DataTrigger.ExitActions>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
        </Ellipse>
    </StackPanel>
</UserControl>  

Force an Android activity to always use landscape mode

This works for Xamarin.Android. In OnCreate()

RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;

Copying files from server to local computer using SSH

You need to name the file in both directory paths.

scp [email protected]:/dir/of/file.txt \local\dir\file.txt

How to scroll to top of the page in AngularJS?

You can use $anchorScroll.

Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

Determine the number of rows in a range

You can also use:

Range( RangeName ).end(xlDown).row

to find the last row with data in it starting at your named range.

Convert time.Time to string

strconv.Itoa(int(time.Now().Unix()))

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

You are getting close!

# Find all of the text between paragraph tags and strip out the html
page = soup.find('p').getText()

Using find (as you've noticed) stops after finding one result. You need find_all if you want all the paragraphs. If the pages are formatted consistently ( just looked over one), you could also use something like

soup.find('div',{'id':'ctl00_PlaceHolderMain_RichHtmlField1__ControlWrapper_RichHtmlField'})

to zero in on the body of the article.

img onclick call to JavaScript function

In response to the good solution from macek. The solution didn't work for me. I have to bind the values of the datas to the export function. This solution works for me:

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  var img = images[i];
  var boundExportToForm = exportToForm.bind(undefined, 
          img.getAttribute("data-a"), 
            img.getAttribute("data-b"),
            img.getAttribute("data-c"),
            img.getAttribute("data-d"),
            img.getAttribute("data-e"))

  img.addEventListener("click", boundExportToForm);
  }

Return Bit Value as 1/0 and NOT True/False in SQL Server

just you pass this things in your select query. using CASE

CASE WHEN  gender=0 then 'Female' WHEN  gender=1 then 'Male' END as Genderdisp

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

My JSON response was like this:

{"items": 
  &nbsp;[
    &nbsp;&nbsp;{
      "index": 1,
      "name": "Samantha",
      "rarity": "Scarborough",
      "email": "[email protected]"
    },
    &nbsp;&nbsp;{
      "index": 2,
      "name": "Amanda",
      "rarity": "Vick",
      "email": "[email protected]"
    }]
}

So, I used ng-repeat = "item in variables.items" to display it.

Add a fragment to the URL without causing a redirect?

Try this

var URL = "scratch.mit.edu/projects";
var mainURL = window.location.pathname;

if (mainURL == URL) {
    mainURL += ( mainURL.match( /[\?]/g ) ? '&' : '#' ) + '_bypasssharerestrictions_';
    console.log(mainURL)
}

How can I String.Format a TimeSpan object with a custom format in .NET?

The Substring method works perfectly when you only want the Hours:Minutes:Seconds. It's simple, clean code and easy to understand.

    var yourTimeSpan = DateTime.Now - DateTime.Now.AddMinutes(-2);

    var formatted = yourTimeSpan.ToString().Substring(0,8);// 00:00:00 

    Console.WriteLine(formatted);

Javascript change color of text and background to input value

Depending on which event you actually want to use (textbox change, or button click), you can try this:

HTML:

<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>

JS:

function changeBackground(obj) {
    document.getElementById("coltext").style.color = obj.value;
}

DEMO: http://jsfiddle.net/6pLUh/

One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange allows you to change the color based on the input.

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

'Static readonly' vs. 'const'

Const: Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.

Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime

Reference: c-sharpcorner

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

Detect click outside element

@Denis Danilenko solutions works for me, here's what I did: By the way I'm using VueJS CLI3 and NuxtJS here and with Bootstrap4, but it will work on VueJS without NuxtJS also:

<div
    class="dropdown ml-auto"
    :class="showDropdown ? null : 'show'">
    <a 
        href="#" 
        class="nav-link" 
        role="button" 
        id="dropdownMenuLink" 
        data-toggle="dropdown" 
        aria-haspopup="true" 
        aria-expanded="false"
        @click="showDropdown = !showDropdown"
        @blur="unfocused">
        <i class="fas fa-bars"></i>
    </a>
    <div 
        class="dropdown-menu dropdown-menu-right" 
        aria-labelledby="dropdownMenuLink"
        :class="showDropdown ? null : 'show'">
        <nuxt-link class="dropdown-item" to="/contact">Contact</nuxt-link>
        <nuxt-link class="dropdown-item" to="/faq">FAQ</nuxt-link>
    </div>
</div>
export default {
    data() {
        return {
            showDropdown: true
        }
    },
    methods: {
    unfocused() {
        this.showDropdown = !this.showDropdown;
    }
  }
}

How to use paginator from material angular?

based on Wesley Coetzee's answer i wrote this. Hope it can help anyone googling this issue. I had bugs with swapping the paginator size in the middle of the list that's why i submit my answer:

Paginator html and list

<mat-paginator [length]="localNewspapers.length" pageSize=20
               (page)="getPaginatorData($event)" [pageSizeOptions]="[10, 20, 30]"
               showFirstLastButtons="false">
</mat-paginator>
<mat-list>
   <app-newspaper-pagi-item *ngFor="let paper of (localNewspapers | 
                         slice: lowValue : highValue)"
                         [newspaper]="paper"> 
  </app-newspaper-pagi-item>

Component logic

import {Component, Input, OnInit} from "@angular/core";
import {PageEvent} from "@angular/material";

@Component({
  selector: 'app-uniques-newspaper-list',
  templateUrl: './newspaper-uniques-list.component.html',
})
export class NewspaperUniquesListComponent implements OnInit {
  lowValue: number = 0;
  highValue: number = 20;

  // used to build an array of papers relevant at any given time
  public getPaginatorData(event: PageEvent): PageEvent {
    this.lowValue = event.pageIndex * event.pageSize;
    this.highValue = this.lowValue + event.pageSize;
    return event;
  }

}

Colors in JavaScript console

This library is fantastic:

https://github.com/adamschwartz/log

Use Markdown for log messages.

How can I quickly sum all numbers in a file?

Bash variant

raw=$(cat file)
echo $(( ${raw//$'\n'/+} ))

$ wc -l file
10000 file

$ time ./test
323390

real    0m3,096s
user    0m3,095s
sys     0m0,000s

A hex viewer / editor plugin for Notepad++?

According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.

Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!