Programs & Examples On #Prettify

A JavaScript module and CSS file that allows syntax highlighting of source code snippets in an HTML page.

Sublime Text 2 Code Formatting

Sublime CodeFormatter has formatting support for PHP, JavaScript/JSON/JSONP, HTML, CSS, Python. Although I haven't used CodeFormatter for very long, I have been impressed with it's JS, HTML, and CSS "beautifying" capabilities. I haven't tried using it with PHP (I don't do any PHP development) or Python (which I have no experience with) but both languages have many options in the .sublime-settings file.

One note however, the settings aren't very easy to find. On Windows you will need to go to your %AppData%\Roaming\Sublime Text #\Packages\CodeFormatter\CodeFormatter.sublime-settings. As I don't have a Mac I'm not sure where the settings file is on OS X.

As for a shortcut key, I added this key binding to my "Key Bindings - User" file:

{
    "keys": ["ctrl+k", "ctrl+d"],
    "command": "code_formatter"
}

I use Ctrl + K, Ctrl + D because that's what Visual Studio uses for formatting. You can change it, of course, just remember that what you choose might conflict with some other feature's keyboard shortcut.

Update:

It seems as if the developers of Sublime Text CodeFormatter have made it easier to access the .sublime-settings file. If you install CodeFormatter with the Package Control plugin, you can access the settings via the Preferences -> Package Settings -> CodeFormatter -> Settings - Default and override those settings using the Preferences -> Package Settings -> CodeFormatter -> Settings - User menu item.

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

Initialize a byte array to a certain value, other than the default null?

var array = Encoding.ASCII.GetBytes(new string(' ', 100));

Formatting a Date String in React Native

The Date constructor is very picky about what it allows. The string you pass in must be supported by Date.parse(), and if it is unsupported, it will return NaN. Different versions of JavaScript do support different formats, if those formats deviate from the official ISO documentation.

See the examples here for what is supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Typing Greek letters etc. in Python plots

Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:

from matplotlib import rc

rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)

This would change your serif latex font. You can also specify the sans-serif Helvetica like so

rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})

Other options are cursive and monospace with their respective font names. Your label would then be

fig.gca().set_xlabel(r'wavelength $5000 \AA$')

If the font doesn't supply an Angstrom symbol you can try using \mathring{A}

Count characters in textarea

HTML

<form method="post">
<textarea name="postes" id="textAreaPost" placeholder="Write what's you new" maxlength="500"></textarea>

<div id="char_namb" style="padding: 4px; float: right; font-size: 20px; font-family: Cocon; text-align: center;">500 : 0</div>
</form>

jQuery

$(function(){
    $('#textAreaPost').keyup(function(){
      var charsno = $(this).val().length;
      $('#char_namb').html("500 : " + charsno);
    });
});

Python: most idiomatic way to convert None to empty string?

If it is about formatting strings, you can do the following:

from string import Formatter

class NoneAsEmptyFormatter(Formatter):
    def get_value(self, key, args, kwargs):
        v = super().get_value(key, args, kwargs)
        return '' if v is None else v

fmt = NoneAsEmptyFormatter()
s = fmt.format('{}{}', a, b)

Shell Script Syntax Error: Unexpected End of File

I had this problem when running some script in cygwin. Fixed by running dos2unix on the script, with proper description of problem and solution given in that answer

Set markers for individual points on a line in Matplotlib

Hello There is an example:

import numpy as np
import matplotlib.pyplot as ptl

def grafica_seno_coseno():
    x = np.arange(-4,2*np.pi, 0.3)
    y = 2*np.sin(x)
    y2 = 3*np.cos(x)
    ptl.plot(x, y,  '-gD')
    ptl.plot(x, y2, '-rD')
    for xitem,yitem in np.nditer([x,y]):
        etiqueta = "{:.1f}".format(xitem)
        ptl.annotate(etiqueta, (xitem,yitem), textcoords="offset points",xytext=(0,10),ha="center")
    for xitem,y2item in np.nditer([x,y2]):
        etiqueta2 = "{:.1f}".format(xitem)
        ptl.annotate(etiqueta2, (xitem,y2item), textcoords="offset points",xytext=(0,10),ha="center")
    ptl.grid(True)
    return ptl.show()

Image convert to Base64

It's useful to work with Deferred Object in this case, and return promise:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

And above function could be used in this way:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

Or in your case:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

How can I check if an argument is defined when starting/calling a batch file?

A more-advanced example:

? unlimited arguments.

? exist on file system (either file or directory?) or a generic string.

? specify if is a file

? specify is a directory

? no extensions, would work in legacy scripts!

? minimal code ?

@echo off

:loop
      ::-------------------------- has argument ?
      if ["%~1"]==[""] (
        echo done.
        goto end
      )
      ::-------------------------- argument exist ?
      if not exist %~s1 (
        echo not exist
      ) else (
        echo exist
        if exist %~s1\NUL (
          echo is a directory
        ) else (
          echo is a file
        )
      )
      ::--------------------------
      shift
      goto loop
      
      
:end

pause

? other stuff..?

¦ in %~1 - the ~ removes any wrapping " or '.

¦ in %~s1 - the s makes the path be DOS 8.3 naming, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "s.

¦ the ["%~1"]==[""] "can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1 (just without the " wrapping, if any..)

if there were no arguments of if we've used shift and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""].

¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)

¦ execution examples

save it as identifier.cmd

it can identify an unlimited arguments (normally you are limited to %1-%9), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).


this allows you to run the following commands:

?identifier.cmd c:\windows and to get

exist
is a directory
done

?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE" and to get

exist
is a file
done

? and multiple arguments (of course this is the whole-deal..)

identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world

and to get

exist
is a directory
exist
is a file
exist
is a file
not exist
done.

naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)

Hope it helps anyone :)

published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory

and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

#!/bin/bash
ipcs -m | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -m
ipcs -s | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -s
ipcs -q | grep `whoami` | awk '{ print $2 }' | xargs -n1 ipcrm -q

What does axis in pandas mean?

axis refers to the dimension of the array, in the case of pd.DataFrames axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

Example: Think of an ndarray with shape (3,5,7).

a = np.ones((3,5,7))

a is a 3 dimensional ndarray, i.e. it has 3 axes ("axes" is plural of "axis"). The configuration of a will look like 3 slices of bread where each slice is of dimension 5-by-7. a[0,:,:] will refer to the 0-th slice, a[1,:,:] will refer to the 1-st slice etc.

a.sum(axis=0) will apply sum() along the 0-th axis of a. You will add all the slices and end up with one slice of shape (5,7).

a.sum(axis=0) is equivalent to

b = np.zeros((5,7))
for i in range(5):
    for j in range(7):
        b[i,j] += a[:,i,j].sum()

b and a.sum(axis=0) will both look like this

array([[ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.],
       [ 3.,  3.,  3.,  3.,  3.,  3.,  3.]])

In a pd.DataFrame, axes work the same way as in numpy.arrays: axis=0 will apply sum() or any other reduction function for each column.

N.B. In @zhangxaochen's answer, I find the phrases "along the rows" and "along the columns" slightly confusing. axis=0 should refer to "along each column", and axis=1 "along each row".

Extracting .jar file with command line

jar xf myFile.jar
change myFile to name of your file
this will save the contents in the current folder of .jar file
that should do :)

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

I found the solution!

Follow these steps:

Flutter Firebase and Android issue - unable to Initialise. Cannot find google-services.json with latest migration instructions executed

After that, execute:

flutter build apk --debug
flutter build apk --profile
flutter build apk --release

and then, run app! it works for me!

CodeIgniter 500 Internal Server Error

Just in case somebody else stumbles across this problem, I inherited an older CodeIgniter project and had a lot of trouble getting it to install.

I wasted a ton of time trying to create a local installation of the site and tried everything. In the end, the solution was simple.

The problem is that older CodeIgniter versions (like 1.7 and below), don't work with PHP 5.3. The solution is to switch to PHP 5.2 or something older.

How to check if IsNumeric

There's the TryParse method, which returns a bool indicating if the conversion was successful.

word-wrap break-word does not work in this example

This combination of properties helped for me:

display: inline-block;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal;
line-break: strict;
hyphens: none;
-webkit-hyphens: none;
-moz-hyphens: none;

Detect click inside/outside of element with single event handler

Instead of using the body you could create a curtain with z-index of 100 (to pick a number) and give the inside element a higher z-index while all other elements have a lower z-index than the curtain.

See working example here: http://jsfiddle.net/Flandre/6JvFk/

jQuery:

$('#curtain').on("click", function(e) {

    $(this).hide();
    alert("clicked ouside of elements that stand out");

});

CSS:

.aboveCurtain
{
    z-index: 200; /* has to have a higher index than the curtain */
    position: relative;
    background-color: pink;
}

#curtain
{
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    background-color: black;
    width: 100%;
    z-index:100;   
    opacity:0.5 /* change opacity to 0 to make it a true glass effect */
}

How to have a drop down <select> field in a rails form?

Please have a look here

Either you can use rails tag Or use plain HTML tags

Rails tag

<%= select("Contact", "email_provider", Contact::PROVIDERS, {:include_blank => true}) %>

*above line of code would become HTML code(HTML Tag), find it below *

HTML tag

<select name="Contact[email_provider]">
  <option></option>
  <option>yahoo</option>
  <option>gmail</option>
  <option>msn</option>
</select>

Running AngularJS initialization code when view is loaded

Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:

function MyCtrl($scope) {
    $scope.isSaving = false;

    (function() {  // init
        if (true) { // $routeParams.Id) {
            //get an existing object
        } else {
            //create a new object
        }
    })()

    $scope.isClean = function () {
       return $scope.hasChanges() && !$scope.isSaving;
    }

    $scope.hasChanges = function() { return false }
}

How to retrieve absolute path given relative

use:

find "$(pwd)"/ -type f

to get all files or

echo "$(pwd)/$line"

to display full path (if relative path matters to)

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

How to load a controller from another controller in codeigniter?

you cannot call a controller method from another controller directly

my solution is to use inheritances and extend your controller from the library controller

class Controller1 extends CI_Controller {

    public function index() {
        // some codes here
    }

    public function methodA(){
        // code here
    }
}

in your controller we call it Mycontoller it will extends Controller1

include_once (dirname(__FILE__) . "/controller1.php");

class Mycontroller extends Controller1 {

    public function __construct() {
        parent::__construct();
    }

    public function methodB(){
        // codes....
    }
}

and you can call methodA from mycontroller

http://example.com/mycontroller/methodA

http://example.com/mycontroller/methodB

this solution worked for me

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

How can I detect the touch event of an UIImageView?

You might want to override the touchesBegan:withEvent: method of the UIView (or subclass) that contains your UIImageView subview.

Within this method, test if any of the UITouch touches fall inside the bounds of the UIImageView instance (let's say it is called imageView).

That is, does the CGPoint element [touch locationInView] intersect with with the CGRect element [imageView bounds]? Look into the function CGRectContainsPoint to run this test.

How to round a number to significant figures in Python

If you want to round without involving strings, the link I found buried in the comments above:

http://code.activestate.com/lists/python-tutor/70739/

strikes me as best. Then when you print with any string formatting descriptors, you get a reasonable output, and you can use the numeric representation for other calculation purposes.

The code at the link is a three liner: def, doc, and return. It has a bug: you need to check for exploding logarithms. That is easy. Compare the input to sys.float_info.min. The complete solution is:

import sys,math

def tidy(x, n):
"""Return 'x' rounded to 'n' significant digits."""
y=abs(x)
if y <= sys.float_info.min: return 0.0
return round( x, int( n-math.ceil(math.log10(y)) ) )

It works for any scalar numeric value, and n can be a float if you need to shift the response for some reason. You can actually push the limit to:

sys.float_info.min*sys.float_info.epsilon

without provoking an error, if for some reason you are working with miniscule values.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

The fact that the same number of rows is returned is an after fact, the query optimizer cannot know in advance that every row in Accepts has a matching row in Marker, can it?

If you join two tables A and B, say A has 1 million rows and B has 1 row. If you say A LEFT INNER JOIN B it means only rows that match both A and B can result, so the query plan is free to scan B first, then use an index to do a range scan in A, and perhaps return 10 rows. But if you say A LEFT OUTER JOIN B then at least all rows in A have to be returned, so the plan must scan everything in A no matter what it finds in B. By using an OUTER join you are eliminating one possible optimization.

If you do know that every row in Accepts will have a match in Marker, then why not declare a foreign key to enforce this? The optimizer will see the constraint, and if is trusted, will take it into account in the plan.

assign value using linq

It can be done this way as well

foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
                {
                    //do your stuff here
                    company.Id= 2;
                    company.Name= "Sample"
                }

How many threads can a Java VM support?

After reading Charlie Martin's post, I was curious about whether the heap size makes any difference in the number of threads you can create, and I was totally dumbfounded by the result.

Using JDK 1.6.0_11 on Vista Home Premium SP1, I executed Charlie's test application with different heap sizes, between 2 MB and 1024 MB.

For example, to create a 2 MB heap, I'd invoke the JVM with the arguments -Xms2m -Xmx2m.

Here are my results:

2 mb --> 5744 threads
4 mb --> 5743 threads
8 mb --> 5735 threads
12 mb --> 5724 threads
16 mb --> 5712 threads
24 mb --> 5687 threads
32 mb --> 5662 threads
48 mb --> 5610 threads
64 mb --> 5561 threads
96 mb --> 5457 threads
128 mb --> 5357 threads
192 mb --> 5190 threads
256 mb --> 5014 threads
384 mb --> 4606 threads
512 mb --> 4202 threads
768 mb --> 3388 threads
1024 mb --> 2583 threads

So, yeah, the heap size definitely matters. But the relationship between heap size and maximum thread count is INVERSELY proportional.

Which is weird.

Execute script after specific delay using JavaScript

delay function:

/**
 * delay or pause for some time
 * @param {number} t - time (ms)
 * @return {Promise<*>}
 */
const delay = async t => new Promise(resolve => setTimeout(resolve, t));

usage inside async function:

await delay(1000);

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

How to add text inside the doughnut chart using Chart.js?

@Cmyker, great solution for chart.js v2

One little enhancement: It makes sense to check for the appropriate canvas id, see the modified snippet below. Otherwise the text (i.e. 75%) is also rendered in middle of other chart types within the page.

  Chart.pluginService.register({
    beforeDraw: function(chart) {
      if (chart.canvas.id === 'doghnutChart') {
        let width = chart.chart.width,
            height = chart.chart.outerRadius * 2,
            ctx = chart.chart.ctx;

        rewardImg.width = 40;
        rewardImg.height = 40;
        let imageX = Math.round((width - rewardImg.width) / 2),
            imageY = (height - rewardImg.height ) / 2;

        ctx.drawImage(rewardImg, imageX, imageY, 40, 40);
        ctx.save();
      }
    }
  });

Since a legend (see: http://www.chartjs.org/docs/latest/configuration/legend.html) magnifies the chart height, the value for height should be obtained by the radius.

What are sessions? How do they work?

Think of HTTP as a person(A) who has SHORT TERM MEMORY LOSS and forgets every person as soon as that person goes out of sight.

Now, to remember different persons, A takes a photo of that person and keeps it. Each Person's pic has an ID number. When that person comes again in sight, that person tells it's ID number to A and A finds their picture by ID number. And voila !!, A knows who is that person.

Same is with HTTP. It is suffering from SHORT TERM MEMORY LOSS. It uses Sessions to record everything you did while using a website, and then, when you come again, it identifies you with the help of Cookies(Cookie is like a token). Picture is the Session here, and ID is the Cookie here.

How do you create a custom AuthorizeAttribute in ASP.NET Core?

For authorization in our app. We had to call a service based on the parameters passed in authorization attribute.

For example, if we want to check if logged in doctor can view patient appointments we will pass "View_Appointment" to custom authorize attribute and check that right in DB service and based on results we will athorize. Here is the code for this scenario:

    public class PatientAuthorizeAttribute : TypeFilterAttribute
    {
    public PatientAuthorizeAttribute(params PatientAccessRights[] right) : base(typeof(AuthFilter)) //PatientAccessRights is an enum
    {
        Arguments = new object[] { right };
    }

    private class AuthFilter : IActionFilter
    {
        PatientAccessRights[] right;

        IAuthService authService;

        public AuthFilter(IAuthService authService, PatientAccessRights[] right)
        {
            this.right = right;
            this.authService = authService;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var allparameters = context.ActionArguments.Values;
            if (allparameters.Count() == 1)
            {
                var param = allparameters.First();
                if (typeof(IPatientRequest).IsAssignableFrom(param.GetType()))
                {
                    IPatientRequest patientRequestInfo = (IPatientRequest)param;
                    PatientAccessRequest userAccessRequest = new PatientAccessRequest();
                    userAccessRequest.Rights = right;
                    userAccessRequest.MemberID = patientRequestInfo.PatientID;
                    var result = authService.CheckUserPatientAccess(userAccessRequest).Result; //this calls DB service to check from DB
                    if (result.Status == ReturnType.Failure)
                    {
                        //TODO: return apirepsonse
                        context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
                    }
                }
                else
                {
                    throw new AppSystemException("PatientAuthorizeAttribute not supported");
                }
            }
            else
            {
                throw new AppSystemException("PatientAuthorizeAttribute not supported");
            }
        }
    }
}

And on API action we use it like this:

    [PatientAuthorize(PatientAccessRights.PATIENT_VIEW_APPOINTMENTS)] //this is enum, we can pass multiple
    [HttpPost]
    public SomeReturnType ViewAppointments()
    {

    }

How to insert a new line in strings in Android

Try:

String str = "my string \n my other string";

When printed you will get:

my string
my other string

NSArray + remove item from array

Made a category like mxcl, but this is slightly faster.

My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).

Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.

- (NSArray *)prefix_arrayByRemovingObject:(id)object 
{
    if (!object) {
        return self;
    }

    NSUInteger indexOfObject = [self indexOfObject:object];
    NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
    NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
    NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];

    return newArray;
}

How to generate range of numbers from 0 to n in ES2015 only?

const keys = Array(n).keys();
[...Array.from(keys)].forEach(callback);

in Typescript

How to rollback just one step using rake db:migrate

  try {
        $result=DB::table('users')->whereExists(function ($Query){
            $Query->where('id','<','14162756');
            $Query->whereBetween('password',[14162756,48384486]);
            $Query->whereIn('id',[3,8,12]);
        });
    }catch (\Exception $error){
        Log::error($error);
        DB::rollBack(1);
        return redirect()->route('bye');
    }

Move the most recent commit(s) to a new branch with Git

Much simpler solution using git stash

Here's a far simpler solution for commits to the wrong branch. Starting on branch master that has three mistaken commits:

git reset HEAD~3
git stash
git checkout newbranch
git stash pop

When to use this?

  • If your primary purpose is to roll back master
  • You want to keep file changes
  • You don't care about the messages on the mistaken commits
  • You haven't pushed yet
  • You want this to be easy to memorize
  • You don't want complications like temporary/new branches, finding and copying commit hashes, and other headaches

What this does, by line number

  1. Undoes the last three commits (and their messages) to master, yet leaves all working files intact
  2. Stashes away all the working file changes, making the master working tree exactly equal to the HEAD~3 state
  3. Switches to an existing branch newbranch
  4. Applies the stashed changes to your working directory and clears the stash

You can now use git add and git commit as you normally would. All new commits will be added to newbranch.

What this doesn't do

  • It doesn't leave random temporary branches cluttering your tree
  • It doesn't preserve the mistaken commit messages, so you'll need to add a new commit message to this new commit
  • Update! Use up-arrow to scroll through your command buffer to reapply the prior commit with its commit message (thanks @ARK)

Goals

The OP stated the goal was to "take master back to before those commits were made" without losing changes and this solution does that.

I do this at least once a week when I accidentally make new commits to master instead of develop. Usually I have only one commit to rollback in which case using git reset HEAD^ on line 1 is a simpler way to rollback just one commit.

Don't do this if you pushed master's changes upstream

Someone else may have pulled those changes. If you are only rewriting your local master there's no impact when it's pushed upstream, but pushing a rewritten history to collaborators can cause headaches.

Find the host name and port using PSQL commands

This command will give you postgres port number

 \conninfo

If postgres is running on Linux server, you can also use the following command

sudo netstat -plunt |grep postgres

OR (if it comes as postmaster)

sudo netstat -plunt |grep postmaster

and you will see something similar as this

tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      140/postgres
tcp6       0      0 ::1:5432                :::*                    LISTEN      140/postgres

in this case, port number is 5432 which is also default port number

credits link

How do I change a single value in a data.frame?

To change a cell value using a column name, one can use

iris$Sepal.Length[3]=999

disable a hyperlink using jQuery

Below will replace the link with it's text

$('a').each(function () {
    $(this).replaceWith($(this).text());
});

Edit :

Above given code will work with hyperlinks with text only, it will not work with images. When we'll try it with image link it won't show any image.

To make this code compatible with image links following will work fine

// below given function will replace links with images i.e. for image links
$('a img').each(function () {
    var image = this.src;
    var img = $('<img>', { src: image });
    $(this).parent().replaceWith(img);
});

// This piece of code will replace links with its text i.e. for text links
$('a').each(function () {
    $(this).replaceWith($(this).text());
});

explanation : In above given code snippets, in first snippet we are replacing all the image links with it's images only. After that we are replacing text links with it's text.

How do I find the location of Python module sources?

Another way to check if you have multiple python versions installed, from the terminal.

-MBP:~python3 -m pip show pyperclip

Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-

MBP:~ python -m pip show pyperclip

Location: /Users/umeshvuyyuru/Library/Python/2.7/lib/python/site-packages

No shadow by default on Toolbar?

This worked for me very well:

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primary"
    card_view:cardElevation="4dp"
    card_view:cardCornerRadius="0dp">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/primary"
        android:minHeight="?attr/actionBarSize" />

</android.support.v7.widget.CardView>

How to hide code from cells in ipython notebook visualized with nbviewer?

There is a nice solution provided here that works well for notebooks exported to HTML. The website even links back here to this SO post, but I don't see Chris's solution here! (Chris, where are you at?)

This is basically the same solution as the accepted answer from harshil, but it has the advantage of hiding the toggle code itself in the exported HTML. I also like that this approach avoids the need for the IPython HTML function.

To implement this solution, add the following code to a 'Raw NBConvert' cell at the top of your notebook:

<script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()">
  <input type="submit" id="toggleButton" value="Show Code">
</form>

Then simply export the notebook to HTML. There will be a toggle button at the top of the notebook to show or hide the code.

Chris also provides an example here.

I can verify that this works in Jupyter 5.0.0

Update: It is also convenient to show/hide the div.prompt elements along with the div.input elements. This removes the In [##]: and Out: [##] text and reduces the margins on the left.

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

As @j_random_hacker pointed out, this is quite similar to Finding duplicates in O(n) time and O(1) space, and an adaptation of my answer there works here too.

Assuming that the "bag" is represented by a 1-based array A[] of size N - k, we can solve Qk in O(N) time and O(k) additional space.

First, we extend our array A[] by k elements, so that it is now of size N. This is the O(k) additional space. We then run the following pseudo-code algorithm:

for i := n - k + 1 to n
    A[i] := A[1]
end for

for i := 1 to n - k
    while A[A[i]] != A[i] 
        swap(A[i], A[A[i]])
    end while
end for

for i := 1 to n
    if A[i] != i then 
        print i
    end if
end for

The first loop initialises the k extra entries to the same as the first entry in the array (this is just a convenient value that we know is already present in the array - after this step, any entries that were missing in the initial array of size N-k are still missing in the extended array).

The second loop permutes the extended array so that if element x is present at least once, then one of those entries will be at position A[x].

Note that although it has a nested loop, it still runs in O(N) time - a swap only occurs if there is an i such that A[i] != i, and each swap sets at least one element such that A[i] == i, where that wasn't true before. This means that the total number of swaps (and thus the total number of executions of the while loop body) is at most N-1.

The third loop prints those indexes of the array i that are not occupied by the value i - this means that i must have been missing.

Mod in Java produces negative numbers

The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.

You can find the positive value by doing this:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)

Create an array or List of all dates between two dates

Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Python Selenium accessing HTML source

driver.page_source will help you get the page source code. You can check if the text is present in the page source or not.

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("some url")
if "your text here" in driver.page_source:
    print('Found it!')
else:
    print('Did not find it.')

If you want to store the page source in a variable, add below line after driver.get:

var_pgsource=driver.page_source

and change the if condition to:

if "your text here" in var_pgsource:

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

What does "async: false" do in jQuery.ajax()?

From

https://xhr.spec.whatwg.org/#synchronous-flag

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user's experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when the JavaScript global environment is a document environment. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an InvalidAccessError exception when it occurs. The future direction is to only allow XMLHttpRequests in worker threads. The message is intended to be a warning to that effect.

List passed by ref - help me explain this behaviour

There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.

When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();

This is probably a more "correct" way of getting it.

Change values of select box of "show 10 entries" of jquery datatable

you can achieve this easily without writing Js. Just add an attribute called data-page-length={put your number here}. see example below, I used 100 for example

<table id="datatable-keytable" data-page-length='100' class="p-table table table-bordered" width="100%">

how to open *.sdf files?

It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it.

Visual Studio can also open the files directly if was created with the right version of SQL Compact.

There are also some third-party tools for manipulating them.

Command line tool to dump Windows DLL version?

There is an command line application called "ShowVer" at CodeProject:

ShowVer.exe command-line VERSIONINFO display program

As usual the application comes with an exe and the source code (VisualC++ 6).

Out outputs all the meta data available:

On a German Win7 system the output for user32.dll is like this:

VERSIONINFO for file "C:\Windows\system32\user32.dll":  (type:0)
  Signature:       feef04bd
  StrucVersion:    1.0
  FileVersion:     6.1.7601.17514
  ProductVersion:  6.1.7601.17514
  FileFlagsMask:   0x3f
  FileFlags:       0
  FileOS:          VOS_NT_WINDOWS32
  FileType:        VFT_DLL
  FileDate:        0.0
 LangID: 040704B0
  CompanyName       : Microsoft Corporation
  FileDescription   : Multi-User Windows USER API Client DLL
  FileVersion       : 6.1.7601.17514 (win7sp1_rtm.101119-1850)
  InternalName      : user32
  LegalCopyright    : ® Microsoft Corporation. Alle Rechte vorbehalten.
  OriginalFilename  : user32
  ProductName       : Betriebssystem Microsoft« Windows«
  ProductVersion    : 6.1.7601.17514
 Translation: 040704b0

How can I use grep to find a word inside a folder?

grep -nr 'yourString*' .

The dot at the end searches the current directory. Meaning for each parameter:

-n            Show relative line number in the file
'yourString*' String for search, followed by a wildcard character
-r            Recursively search subdirectories listed
.             Directory for search (current directory)

grep -nr 'MobileAppSer*' . (Would find MobileAppServlet.java or MobileAppServlet.class or MobileAppServlet.txt; 'MobileAppASer*.*' is another way to do the same thing.)

To check more parameters use man grep command.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

Quickfix

I had similar issue and I resolved it doing the following

  1. Navigate to jenkins > Manage jenkins > In-process Script Approval
  2. There was a pending command, which I had to approve.

In process approval link in Jenkins 2.61 Alternative 1: Disable sandbox

As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.

Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script: enter image description here

Alternative 2: Disable script security

As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:

-Dpermissive-script-security.enabled=true

So you jenkins.xml will look something like this:

<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>

Make sure you know what you are doing if you implement this!

What is difference between sleep() method and yield() method of multi threading?

yield(): yield method is used to pause the execution of currently running process so that other waiting thread with the same priority will get CPU to execute.Threads with lower priority will not be executed on yield. if there is no waiting thread then this thread will start its execution.

join(): join method stops currently executing thread and wait for another to complete on which in calls the join method after that it will resume its own execution.

For detailed explanation, see this link.

What is HEAD in Git?

To quote other people:

A head is simply a reference to a commit object. Each head has a name (branch name or tag name, etc). By default, there is a head in every repository called master. A repository can contain any number of heads. At any given time, one head is selected as the “current head.” This head is aliased to HEAD, always in capitals".

Note this difference: a “head” (lowercase) refers to any one of the named heads in the repository; “HEAD” (uppercase) refers exclusively to the currently active head. This distinction is used frequently in Git documentation.

Another good source that quickly covers the inner workings of git (and therefor a better understanding of heads/HEAD) can be found here. References (ref:) or heads or branches can be considered like post-it notes stuck onto commits in the commit history. Usually they point to the tip of series of commits, but they can be moved around with git checkout or git reset etc.

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

    <mvc:annotation-driven />
    <mvc:default-servlet-handler />
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <context:component-scan base-package="com.sapta.hr" />

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

    <bean id="messageSource" 
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

Input and output numpy arrays to h5py

h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:

http://docs.h5py.org/en/latest/quick.html

A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:

In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">

In [6]: h5f.close()

You can then load that data back in using: '

In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()

In [13]: np.allclose(a,b)
Out[13]: True

Definitely check out the docs:

http://docs.h5py.org

Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save, np.savez etc:

http://docs.scipy.org/doc/numpy/reference/routines.io.html

Why should you use strncpy instead of strcpy?

This may be used in many other scenarios, where you need to copy only a portion of your original string to the destination. Using strncpy() you can copy a limited portion of the original string as opposed by strcpy(). I see the code you have put up comes from publib.boulder.ibm.com.

How can I force a hard reload in Chrome for Android

I found a solution that works, but it's ugly.

  • Connect the Android device to your PC with a USB cable and open Chrome on your desktop.
  • Right-click anywhere on a page and select "Inspect".
  • Click the three-dot menu and select "Remote devices" under the "More tools" menu:

    enter image description here

  • In the panel that opens, select your device and then the "Inspect" button next to the name of the tab on your phone that needs to be refreshed:

    enter image description here

  • In the window that opens, click the "Network" tab and check the "Disable cache" checkbox:

    enter image description here

  • Reload the page on your phone or using the reload button in the DevTools window.

Note: if your phone doesn't appear in the device list:

  • make sure the USB connection is using File Transfer mode and isn't simply charging
  • try restarting ADB or run adb devices to see if the device is being detected

How to declare a variable in SQL Server and use it in the same Stored Procedure

CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS    
BEGIN

DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand 
WHERE BrandName = @BrandName

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (@CategoryID, @BrandID)

END

EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1

ADB error: cannot connect to daemon

I was using Genymotion 2.9.0. I updated to 3.0.0 Now it is working. So please check Genymotion version.

Ubuntu says "bash: ./program Permission denied"

Sounds like you don't have the execute flag set on the file permissions, try:

chmod u+x program_name

Calculate number of hours between 2 dates in PHP

The newer PHP-Versions provide some new classes called DateTime, DateInterval, DateTimeZone and DatePeriod. The cool thing about this classes is, that it considers different timezones, leap years, leap seconds, summertime, etc. And on top of that it's very easy to use. Here's what you want with the help of this objects:

// Create two new DateTime-objects...
$date1 = new DateTime('2006-04-12T12:30:00');
$date2 = new DateTime('2006-04-14T11:30:00');

// The diff-methods returns a new DateInterval-object...
$diff = $date2->diff($date1);

// Call the format method on the DateInterval-object
echo $diff->format('%a Day and %h hours');

The DateInterval-object, which is returned also provides other methods than format. If you want the result in hours only, you could to something like this:

$date1 = new DateTime('2006-04-12T12:30:00');
$date2 = new DateTime('2006-04-14T11:30:00');

$diff = $date2->diff($date1);

$hours = $diff->h;
$hours = $hours + ($diff->days*24);

echo $hours;

And here are the links for documentation:

All these classes also offer a procedural/functional way to operate with dates. Therefore take a look at the overview: http://php.net/manual/book.datetime.php

CSS Cell Margin

A word of warning: though padding-right might solve your particular (visual) problem, it is not the right way to add spacing between table cells. What padding-right does for a cell is similar to what it does for most other elements: it adds space within the cell. If the cells do not have a border or background colour or something else that gives the game away, this can mimic the effect of setting the space between the cells, but not otherwise.

As someone noted, margin specifications are ignored for table cells:

CSS 2.1 Specification – Tables – Visual layout of table contents

Internal table elements generate rectangular boxes with content and borders. Cells have padding as well. Internal table elements do not have margins.

What's the "right" way then? If you are looking to replace the cellspacing attribute of the table, then border-spacing (with border-collapse disabled) is a replacement. However, if per-cell "margins" are required, I am not sure how that can be correctly achieved using CSS. The only hack I can think of is to use padding as above, avoid any styling of the cells (background colours, borders, etc.) and instead use container DIVs inside the cells to implement such styling.

I am not a CSS expert, so I could well be wrong in the above (which would be great to know! I too would like a table cell margin CSS solution).

Cheers!

java.net.SocketException: Connection reset

Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

Your code should like this:

<span id="replies">8</span>

var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);

Hacks N Tricks

How to execute an Oracle stored procedure via a database link

for me, this worked

exec utl_mail.send@myotherdb(
  sender => '[email protected]',recipients => '[email protected], 
  cc => null, subject => 'my subject', message => 'my message'
); 

Python 3 turn range to a list

Python 3:

my_list = [*range(1001)]

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

How to set null to a GUID property

Choose your poison - if you can't change the type of the property to be nullable then you're going to have to use a "magic" value to represent NULL. Guid.Empty seems as good as any unless you have some specific reason for not wanting to use it. A second choice would be Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff") but that's a lot uglier IMHO.

How can I define colors as variables in CSS?

There's no easy CSS only solution. You could do this:

  • Find all instances of background-color and color in your CSS file and create a class name for each unique color.

    .top-header { color: #fff; }
    .content-text { color: #f00; }
    .bg-leftnav { background-color: #fff; }
    .bg-column { background-color: #f00; }
    
  • Next go through every single page on your site where color was involved and add the appropriate classes for both color and background color.

  • Last, remove any references of colors in your CSS other than your newly created color classes.

How to pip install a package with min and max version range?

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

How might I convert a double to the nearest integer value?

I know this question is old, but I came across it in my search for the answer to my similar question. I thought I would share the very useful tip that I have been given.

When converting to int, simply add .5 to your value before downcasting. As downcasting to int always drops to the lower number (e.g. (int)1.7 == 1), if your number is .5 or higher, adding .5 will bring it up into the next number and your downcast to int should return the correct value. (e.g. (int)(1.8 + .5) == 2)

How to get my activity context?

You can create a constructor using parameter Context of class A then you can use this context.

Context c;

A(Context context){ this.c=context }

From B activity you create a object of class A using this constructor and passing getApplicationContext().

Convert textbox text to integer

int num = int.Parse(textBox.Text);

try this. It worked for me

Getting value of HTML text input

If you want to use the value of the email input somewhere else on the same page, for example to do some sort of validation, you could use JavaScript. First I would assign an "id" attribute to your email textbox:

<input type="text" name="email" id="email"/>

and then I would retrieve the value with JavaScript:

var email = document.getElementById('email').value;

From there, you can do additional processing on the value of 'email'.

How to get a context in a recycler view adapter

you can use this:

itemView.getContext()

How to increase the vertical split window size in Vim

I have these mapped in my .gvimrc to let me hit command-[arrow] to move the height and width of my current window around:

" resize current buffer by +/- 5 
nnoremap <D-left> :vertical resize -5<cr>
nnoremap <D-down> :resize +5<cr>
nnoremap <D-up> :resize -5<cr>
nnoremap <D-right> :vertical resize +5<cr>

For MacVim, you have to put them in your .gvimrc (and not your .vimrc) as they'll otherwise get overwritten by the system .gvimrc

Add image to layout in ruby on rails

When using the new ruby, the image folder will go to asset folder on folder app

after placing your images in image folder, use

<%=image_tag("example_image.png", alt: "Example Image")%>

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

How Can I Override Style Info from a CSS Class in the Body of a Page?

you can test a color by writing the CSS inline like <div style="color:red";>...</div>

How to get C# Enum description from value?

I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects:

public static string DescriptionAttr<T>(this T source)
{
    FieldInfo fi = source.GetType().GetField(source.ToString());

    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0) return attributes[0].Description;
    else return source.ToString();
}

Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this:

string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

AS Scott mentioned here http://weblogs.asp.net/scottgu/archive/2010/09/30/asp-net-security-fix-now-on-windows-update.aspx After windows installed security update for .net framework, you will meet this problem. just modify the configuration section in your web.config file and switch to a different cookie name.

Lazy Loading vs Eager Loading

Consider the below situation

public class Person{
    public String Name{get; set;}
    public String Email {get; set;}
    public virtual Employer employer {get; set;}
}

public List<EF.Person> GetPerson(){
    using(EF.DbEntities db = new EF.DbEntities()){
       return db.Person.ToList();
    }
}

Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

Extract substring in Bash

I love sed's capability to deal with regex groups:

> var="someletters_12345_moreletters.ext"
> digits=$( echo $var | sed "s/.*_\([0-9]\+\).*/\1/p" -n )
> echo $digits
12345

A slightly more general option would be not to assume that you have an underscore _ marking the start of your digits sequence, hence for instance stripping off all non-numbers you get before your sequence: s/[^0-9]\+\([0-9]\+\).*/\1/p.


> man sed | grep s/regexp/replacement -A 2
s/regexp/replacement/
    Attempt to match regexp against the pattern space.  If successful, replace that portion matched with replacement.  The replacement may contain the special  character  &  to
    refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.

More on this, in case you're not too confident with regexps:

  • s is for _s_ubstitute
  • [0-9]+ matches 1+ digits
  • \1 links to the group n.1 of the regex output (group 0 is the whole match, group 1 is the match within parentheses in this case)
  • p flag is for _p_rinting

All escapes \ are there to make sed's regexp processing work.

Difference between dangling pointer and memory leak

Memory leak: When there is a memory area in a heap but no variable in the stack pointing to that memory.

char *myarea=(char *)malloc(10);

char *newarea=(char *)malloc(10);

myarea=newarea;

Dangling pointer: When a pointer variable in a stack but no memory in heap.

char *p =NULL;

A dangling pointer trying to dereference without allocating space will result in a segmentation fault.

jquery function val() is not equivalent to "$(this).value="?

One thing you can do is this:

$(this)[0].value = "Something";

This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

Check if object exists in JavaScript

You can use:

if (typeof objectName == 'object') {
    //do something
}

Where are the Properties.Settings.Default stored?

thanks for pointing me in the right direction. I found user.config located at this monstrosity: c:\users\USER\AppData\Local\COMPANY\APPLICATION.exe_Url_LOOKSLIKESOMEKINDOFHASH\VERSION\user.config.

I had to uprev the version on my application and all the settings seemed to have vanished. application created a new folder with the new version and used the default settings. took forever to find where the file was stored, but then it was a simple copy and paste to get the settings to the new version.

Regex match text between tags

var root = document.createElement("div");

root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var texts = [].map.call( root.querySelectorAll("b"), function(v){
    return v.textContent || v.innerText || "";
});

//["Bob", "20", "programming"]

How can I declare enums using java

public enum NewEnum {
   ONE("test"),
   TWO("test");

   private String s;

   private NewEnum(String s) {
      this.s = s);
   }

    public String getS() {
        return this.s;
    }
}

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

Commands out of sync; you can't run this command now

This is not related to the original question, but i had the same error-message and this thread is the first hit in Google and it took me a while to figure out what the Problem was, so it May be of use for others:

i'm NOT using mysqli, still using mysql_connect i had some simple querys, but ONE query caused all other querys to fail within the same Connection.

I use mysql 5.7 and php 5.6 i had a table with the data-Type "JSON". obviously, my php-version did not recognize the return value from mysql (php just did not know what to do with the JSON-Format because the built-in mysql-module was too old (at least i think))

for now i changed the JSON-Field-Type to Text (as for now i don't need the native mysql JSON-functionality) and everything works fine

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

In function post():

todo.author = users.get_current_user()

So, to get str(todo.author), you need str(users.get_current_user()). What is returned by get_current_user() function ?

If it is an object, check does it contain a str()" function?

I think the error lies there.

CodeIgniter htaccess and URL rewrite issues

Just add this in the .htaccess file:

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]

Run exe file with parameters in a batch file

Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe program, which won't open unnecessary windows.

Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2

Otherwise, just quote stuff as Andrew points out.


In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):

"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2

Custom HTTP headers : naming conventions

Modifying, or more correctly, adding additional HTTP headers is a great code debugging tool if nothing else.

When a URL request returns a redirect or an image there is no html "page" to temporarily write the results of debug code to - at least not one that is visible in a browser.

One approach is to write the data to a local log file and view that file later. Another is to temporarily add HTTP headers reflecting the data and variables being debugged.

I regularly add extra HTTP headers like X-fubar-somevar: or X-testing-someresult: to test things out - and have found a lot of bugs that would have otherwise been very difficult to trace.

How to $http Synchronous call with AngularJS

I have worked with a factory integrated with google maps autocomplete and promises made??, I hope you serve.

http://jsfiddle.net/the_pianist2/vL9nkfe3/1/

you only need to replace the autocompleteService by this request with $ http incuida being before the factory.

app.factory('Autocomplete', function($q, $http) {

and $ http request with

 var deferred = $q.defer();
 $http.get('urlExample').
success(function(data, status, headers, config) {
     deferred.resolve(data);
}).
error(function(data, status, headers, config) {
     deferred.reject(status);
});
 return deferred.promise;

<div ng-app="myApp">
  <div ng-controller="myController">
  <input type="text" ng-model="search"></input>
  <div class="bs-example">
     <table class="table" >
        <thead>
           <tr>
              <th>#</th>
              <th>Description</th>
           </tr>
        </thead>
        <tbody>
           <tr ng-repeat="direction in directions">
              <td>{{$index}}</td>
              <td>{{direction.description}}</td>
           </tr>
        </tbody>
     </table>
  </div>

'use strict';
 var app = angular.module('myApp', []);

  app.factory('Autocomplete', function($q) {
    var get = function(search) {
    var deferred = $q.defer();
    var autocompleteService = new google.maps.places.AutocompleteService();
    autocompleteService.getPlacePredictions({
        input: search,
        types: ['geocode'],
        componentRestrictions: {
            country: 'ES'
        }
    }, function(predictions, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            deferred.resolve(predictions);
        } else {
            deferred.reject(status);
        }
    });
    return deferred.promise;
};

return {
    get: get
};
});

app.controller('myController', function($scope, Autocomplete) {
$scope.$watch('search', function(newValue, oldValue) {
    var promesa = Autocomplete.get(newValue);
    promesa.then(function(value) {
        $scope.directions = value;
    }, function(reason) {
        $scope.error = reason;
    });
 });

});

the question itself is to be made on:

deferred.resolve(varResult); 

when you have done well and the request:

deferred.reject(error); 

when there is an error, and then:

return deferred.promise;

How do you check that a number is NaN in JavaScript?

NaN in JavaScript stands for "Not A Number", although its type is actually number.

typeof(NaN) // "number"

To check if a variable is of value NaN, we cannot simply use function isNaN(), because isNaN() has the following issue, see below:

var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN

What really happens here is that myVar is implicitly coerced to a number:

var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact

It actually makes sense, because "A" is actually not a number. But what we really want to check is if myVar is exactly of value NaN.

So isNaN() cannot help. Then what should we do instead?

In the light that NaN is the only JavaScript value that is treated unequal to itself, so we can check for its equality to itself using !==

var myVar; // undefined
myVar !== myVar // false

var myVar = "A";
myVar !== myVar // false

var myVar = NaN
myVar !== myVar // true

So to conclude, if it is true that a variable !== itself, then this variable is exactly of value NaN:

function isOfValueNaN(v) {
    return v !== v;
}

var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false

Populating a database in a Laravel migration file

Here is a very good explanation of why using Laravel's Database Seeder is preferable to using Migrations: https://web.archive.org/web/20171018135835/http://laravelbook.com/laravel-database-seeding/

Although, following the instructions on the official documentation is a much better idea because the implementation described at the above link doesn't seem to work and is incomplete. http://laravel.com/docs/migrations#database-seeding

What are .tpl files? PHP, web design

Other possibilities for .tpl: HTML::SimpleTemplate, example:

Hello $name

, and Template Toolkit, example:

Hello [% world %]!

Setting default values for columns in JPA

  1. @Column(columnDefinition='...') doesn't work when you set the default constraint in database while inserting the data.
  2. You need to make insertable = false and remove columnDefinition='...' from annotation, then database will automatically insert the default value from the database.
  3. E.g. when you set varchar gender is male by default in database.
  4. You just need to add insertable = false in Hibernate/JPA, it will work.

Understanding Chrome network log "Stalled" state

My case is the page is sending multiple requests with different parameters when it was open. So most are being "stalled". Following requests immediately sent gets "stalled". Avoiding unnecessary requests would be better (to be lazy...).

How to fix HTTP 404 on Github Pages?

If you haven't already, choose a Jekyll theme in your GitHub Pages settings tab. Apparently this is required even if you're not using Jekyll for your Pages site.

GitHub settings screenshot

What is the size of ActionBar in pixels?

With the new v7 support library (21.0.0) the name in R.dimen has changed to @dimen/abc_action_bar_default_height_material.

When upgrading from a previous version of the support lib you should therefore use that value as the actionbar's height

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

excel VBA run macro automatically whenever a cell is changed

Another option is

Private Sub Worksheet_Change(ByVal Target As Range)
    IF Target.Address = "$D$2" Then
        MsgBox("Cell D2 Has Changed.")
    End If
End Sub

I believe this uses fewer resources than Intersect, which will be helpful if your worksheet changes a lot.

Convert String (UTF-16) to UTF-8 in C#

Check the Jon Skeet answer to this other question: UTF-16 to UTF-8 conversion (for scripting in Windows)

It contains the source code that you need.

Hope it helps.

Gradients on UIView and UILabels On iPhone

You could also use a graphic image one pixel wide as the gradient, and set the view property to expand the graphic to fill the view (assuming you are thinking of a simple linear gradient and not some kind of radial graphic).

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

Are SSL certificates bound to the servers ip address?

SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.

In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.

Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.

BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.

Load HTML File Contents to Div [without the use of iframes]

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

What is PAGEIOLATCH_SH wait type in SQL Server?

PAGEIOLATCH_SH wait type usually comes up as the result of fragmented or unoptimized index.

Often reasons for excessive PAGEIOLATCH_SH wait type are:

  • I/O subsystem has a problem or is misconfigured
  • Overloaded I/O subsystem by other processes that are producing the high I/O activity
  • Bad index management
  • Logical or physical drive misconception
  • Network issues/latency
  • Memory pressure
  • Synchronous Mirroring and AlwaysOn AG

In order to try and resolve having high PAGEIOLATCH_SH wait type, you can check:

  • SQL Server, queries and indexes, as very often this could be found as a root cause of the excessive PAGEIOLATCH_SH wait types
  • For memory pressure before jumping into any I/O subsystem troubleshooting

Always keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH can be expected.

You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types

How to force a list to be vertical using html css

I would add this to the LI's CSS

.list-item
{
    float: left;
    clear: left;
}

Setting "checked" for a checkbox with jQuery

$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();

The last one will fire the click event for the checkbox, the others will not. So if you have custom code in the onclick event for the checkbox that you want to fire, use the last one.

How to execute raw SQL in Flask-SQLAlchemy app

You can get the results of SELECT SQL queries using from_statement() and text() as shown here. You don't have to deal with tuples this way. As an example for a class User having the table name users you can try,

from sqlalchemy.sql import text

user = session.query(User).from_statement(
    text("""SELECT * FROM users where name=:name""")
).params(name="ed").all()

return user

Check if string ends with one of the strings from a list

Take an extension from the file and see if it is in the set of extensions:

>>> import os
>>> extensions = set(['.mp3','.avi'])
>>> file_name = 'test.mp3'
>>> extension = os.path.splitext(file_name)[1]
>>> extension in extensions
True

Using a set because time complexity for lookups in sets is O(1) (docs).

Typescript Date Type?

The answer is super simple, the type is Date:

const d: Date = new Date(); // but the type can also be inferred from "new Date()" already

It is the same as with every other object instance :)

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

I came across this error while making a segue from a table view controller to a view controller because I had forgotten to specify the custom class name for the view controller in the main storyboard.

Something simple that is worth checking if all else looks ok

How to read from stdin with fgets()?

here a concatenation solution:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10

int main() {
  char *text = calloc(1,1), buffer[BUFFERSIZE];
  printf("Enter a message: \n");
  while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
  {
    text = realloc( text, strlen(text)+1+strlen(buffer) );
    if( !text ) ... /* error handling */
    strcat( text, buffer ); /* note a '\n' is appended here everytime */
    printf("%s\n", buffer);
  }
  printf("\ntext:\n%s",text);
  return 0;
}

How can I remove file extension from a website address?

same as Igor but should work without line 2:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

How to remove leading whitespace from each line in a file

You can use AWK:

$ awk '{$1=$1}1' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

sed

$ sed 's|^[[:blank:]]*||g' file
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)
for (i = 0; i < 100; i++)

The shell's while/read loop

while read -r line
do
    echo $line
done <"file"

SVG: text inside rect

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <g>
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" />
    </linearGradient>
  </defs>
  <rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" />
  <text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text>
  </g>
</svg> 

How to set Java SDK path in AndroidStudio?

Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear. enter image description here

How to use relative/absolute paths in css URLs?

The URL is relative to the location of the CSS file, so this should work for you:

url('../../images/image.jpg')

The relative URL goes two folders back, and then to the images folder - it should work for both cases, as long as the structure is the same.

From https://www.w3.org/TR/CSS1/#url:

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

Python: How would you save a simple settings/config file?

try using cfg4py:

  1. Hierarchichal design, mulitiple env supported, so never mess up dev settings with production site settings.
  2. Code completion. Cfg4py will convert your yaml into a python class, then code completion is available while you typing your code.
  3. many more..

DISCLAIMER: I'm the author of this module

Check if bash variable equals 0

Try:

zero=0;

if [[ $depth -eq $zero ]]; then
  echo "false";
  exit;
fi

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:

' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook

' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook

' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)

Set customerWorkbook = Application.Workbooks.Open(customerFilename)

' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)

targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value

' Close customer workbook
customerWorkbook.Close

Doing a cleanup action just before Node.js exits

io.js has an exit and a beforeExit event, which do what you want.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

This code worked for me

public static void main(String[] args) {
    try {
        java.net.URL myUr = new java.net.URL("http://path");
        System.out.println("Instantiated new URL: " + connection_url);
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

Instantiated new URL: http://path

Python Matplotlib figure title overlaps axes label when using twiny

You can use pad for this case:

ax.set_title("whatever", pad=20)

How to add button inside input

Use a Flexbox, and put the border on the form.

The best way to do this now (2019) is with a flexbox.

  • Put the border on the containing element (in this case I've used the form, but you could use a div).
  • Use a flexbox layout to arrange the input and the button side by side. Allow the input to stretch to take up all available space.
  • Now hide the input by removing its border.

Run the snippet below to see what you get.

_x000D_
_x000D_
form {_x000D_
  /* This bit sets up the horizontal layout */_x000D_
  display:flex;_x000D_
  flex-direction:row;_x000D_
  _x000D_
  /* This bit draws the box around it */_x000D_
  border:1px solid grey;_x000D_
_x000D_
  /* I've used padding so you can see the edges of the elements. */_x000D_
  padding:2px;_x000D_
}_x000D_
_x000D_
input {_x000D_
  /* Tell the input to use all the available space */_x000D_
  flex-grow:2;_x000D_
  /* And hide the input's outline, so the form looks like the outline */_x000D_
  border:none;_x000D_
}_x000D_
_x000D_
input:focus {_x000D_
  /* removing the input focus blue box. Put this on the form if you like. */_x000D_
  outline: none;_x000D_
}_x000D_
_x000D_
button {_x000D_
  /* Just a little styling to make it pretty */_x000D_
  border:1px solid blue;_x000D_
  background:blue;_x000D_
  color:white;_x000D_
}
_x000D_
<form>_x000D_
  <input />_x000D_
  <button>Go</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Why this is good

  • It will stretch to any width.
  • The button will always be just as big as it needs to be. It won't stretch if the screen is wide, or shrink if the screen is narrow.
  • The input text will not go behind the button.

Caveats and Browser Support

There's limited Flexbox support in IE9, so the button will not be on the right of the form. IE9 has not been supported by Microsoft for some years now, so I'm personally quite comfortable with this.

I've used minimal styling here. I've left in the padding to show the edges of things. You can obviously make this look however you want it to look with rounded corners, drop shadows, etc..

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

Getting the document object of an iframe

This is the code I use:

var ifrm = document.getElementById('myFrame');
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write('Hello World!');
ifrm.document.close();

contentWindow vs. contentDocument

  • IE (Win) and Mozilla (1.7) will return the window object inside the iframe with oIFrame.contentWindow.
  • Safari (1.2.4) doesn't understand that property, but does have oIframe.contentDocument, which points to the document object inside the iframe.
  • To make it even more complicated, Opera 7 uses oIframe.contentDocument, but it points to the window object of the iframe. Because Safari has no way to directly access the window object of an iframe element via standard DOM (or does it?), our fully modern-cross-browser-compatible code will only be able to access the document within the iframe.

Big O, how do you calculate/approximate it?

I think about it in terms of information. Any problem consists of learning a certain number of bits.

Your basic tool is the concept of decision points and their entropy. The entropy of a decision point is the average information it will give you. For example, if a program contains a decision point with two branches, it's entropy is the sum of the probability of each branch times the log2 of the inverse probability of that branch. That's how much you learn by executing that decision.

For example, an if statement having two branches, both equally likely, has an entropy of 1/2 * log(2/1) + 1/2 * log(2/1) = 1/2 * 1 + 1/2 * 1 = 1. So its entropy is 1 bit.

Suppose you are searching a table of N items, like N=1024. That is a 10-bit problem because log(1024) = 10 bits. So if you can search it with IF statements that have equally likely outcomes, it should take 10 decisions.

That's what you get with binary search.

Suppose you are doing linear search. You look at the first element and ask if it's the one you want. The probabilities are 1/1024 that it is, and 1023/1024 that it isn't. The entropy of that decision is 1/1024*log(1024/1) + 1023/1024 * log(1024/1023) = 1/1024 * 10 + 1023/1024 * about 0 = about .01 bit. You've learned very little! The second decision isn't much better. That is why linear search is so slow. In fact it's exponential in the number of bits you need to learn.

Suppose you are doing indexing. Suppose the table is pre-sorted into a lot of bins, and you use some of all of the bits in the key to index directly to the table entry. If there are 1024 bins, the entropy is 1/1024 * log(1024) + 1/1024 * log(1024) + ... for all 1024 possible outcomes. This is 1/1024 * 10 times 1024 outcomes, or 10 bits of entropy for that one indexing operation. That is why indexing search is fast.

Now think about sorting. You have N items, and you have a list. For each item, you have to search for where the item goes in the list, and then add it to the list. So sorting takes roughly N times the number of steps of the underlying search.

So sorts based on binary decisions having roughly equally likely outcomes all take about O(N log N) steps. An O(N) sort algorithm is possible if it is based on indexing search.

I've found that nearly all algorithmic performance issues can be looked at in this way.

how to hide a vertical scroll bar when not needed

overflow: auto (or overflow-y: auto) is the correct way to go.

The problem is that your text area is taller than your div. The div ends up cutting off the textbox, so even though it looks like it should start scrolling when the text is taller than 159px it won't start scrolling until the text is taller than 400px which is the height of the textbox.

Try this: http://jsfiddle.net/G9rfq/1/

I set overflow:auto on the text box, and made the textbox the same size as the div.

Also I don't believe it's valid to have a div inside a label, the browser will render it, but it might cause some funky stuff to happen. Also your div isn't closed.

jQuery how to find an element based on a data-attribute value?

I improved upon psycho brm's filterByData extension to jQuery.

Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.

(function ($) {

    $.fn.filterByData = function (prop, val) {
        var $self = this;
        if (typeof val === 'undefined') {
            return $self.filter(
                function () { return typeof $(this).data(prop) !== 'undefined'; }
            );
        }
        return $self.filter(
            function () { return $(this).data(prop) == val; }
        );
    };

})(window.jQuery);

Usage:

$('<b>').data('x', 1).filterByData('x', 1).length    // output: 1
$('<b>').data('x', 1).filterByData('x').length       // output: 1

_x000D_
_x000D_
// test data_x000D_
function extractData() {_x000D_
  log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);_x000D_
  log('data-prop .......... ' + $('div').filterByData('prop').length);_x000D_
  log('data-random ........ ' + $('div').filterByData('random').length);_x000D_
  log('data-test .......... ' + $('div').filterByData('test').length);_x000D_
  log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#b5').data('test', 'anyval');_x000D_
});_x000D_
_x000D_
// the actual extension_x000D_
(function($) {_x000D_
_x000D_
  $.fn.filterByData = function(prop, val) {_x000D_
    var $self = this;_x000D_
    if (typeof val === 'undefined') {_x000D_
      return $self.filter(_x000D_
_x000D_
        function() {_x000D_
          return typeof $(this).data(prop) !== 'undefined';_x000D_
        });_x000D_
    }_x000D_
    return $self.filter(_x000D_
_x000D_
      function() {_x000D_
        return $(this).data(prop) == val;_x000D_
      });_x000D_
  };_x000D_
_x000D_
})(window.jQuery);_x000D_
_x000D_
_x000D_
//just to quickly log_x000D_
function log(txt) {_x000D_
  if (window.console && console.log) {_x000D_
    console.log(txt);_x000D_
    //} else {_x000D_
    //  alert('You need a console to check the results');_x000D_
  }_x000D_
  $("#result").append(txt + "<br />");_x000D_
}
_x000D_
#bPratik {_x000D_
  font-family: monospace;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="bPratik">_x000D_
  <h2>Setup</h2>_x000D_
  <div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
  <div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
  <div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>_x000D_
  <div id="b4" data-test="val">Data added inline :: data-test="val"</div>_x000D_
  <div id="b5">Data will be added via jQuery</div>_x000D_
  <h2>Output</h2>_x000D_
  <div id="result"></div>_x000D_
_x000D_
  <hr />_x000D_
  <button onclick="extractData()">Reveal</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or the fiddle: http://jsfiddle.net/PTqmE/46/

ssh: connect to host github.com port 22: Connection timed out

Changing the repo url from ssh to https is not very meaningful to me. As I prefer ssh over https because of some sort of extra benefits which I don't want to discard. Above answers are pretty good and accurate. If you face this problem in GitLab, please go to their official documentation page and change your config file like that.

Host gitlab.com
  Hostname altssh.gitlab.com
  User git
  Port 443
  PreferredAuthentications publickey
  IdentityFile ~/.ssh/gitlab

How to get http headers in flask?

If any one's trying to fetch all headers that were passed then just simply use:

dict(request.headers)

it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy

How do I create an average from a Ruby array?

Ruby versions >= 2.4 has an Enumerable#sum method.

And to get floating point average, you can use Integer#fdiv

arr = [0,4,8,2,5,0,2,6]

arr.sum.fdiv(arr.size)
# => 3.375

For older versions:

arr.reduce(:+).fdiv(arr.size)
# => 3.375

Copy/duplicate database without using mysqldump

In PHP:

function cloneDatabase($dbName, $newDbName){
    global $admin;
    $db_check = @mysql_select_db ( $dbName );
    $getTables  =   $admin->query("SHOW TABLES");   
    $tables =   array();
    while($row = mysql_fetch_row($getTables)){
        $tables[]   =   $row[0];
    }
    $createTable    =   mysql_query("CREATE DATABASE `$newDbName` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;") or die(mysql_error());
    foreach($tables as $cTable){
        $db_check   =   @mysql_select_db ( $newDbName );
        $create     =   $admin->query("CREATE TABLE $cTable LIKE ".$dbName.".".$cTable);
        if(!$create) {
            $error  =   true;
        }
        $insert     =   $admin->query("INSERT INTO $cTable SELECT * FROM ".$dbName.".".$cTable);
    }
    return !isset($error);
}


// usage
$clone  = cloneDatabase('dbname','newdbname');  // first: toCopy, second: new database

how to run a winform from console application?

Here is the best method that I've found: First, set your projects output type to "Windows Application", then P/Invoke AllocConsole to create a console window.

internal static class NativeMethods
{
    [DllImport("kernel32.dll")]
    internal static extern Boolean AllocConsole();
}

static class Program
{

    static void Main(string[] args) {
        if (args.Length == 0) {
            // run as windows app
            Application.EnableVisualStyles();
            Application.Run(new Form1()); 
        } else {
            // run as console app
            NativeMethods.AllocConsole();
            Console.WriteLine("Hello World");
            Console.ReadLine();
        }
    }

}

how to set default main class in java?

If you're creating 2 executable JAR files, each will have it's own manifest file, and each manifest file will specify the class that contains the main() method you want to use to start execution.

In each JAR file, the manifest will be a file with the following path / name inside the JAR - META-INF/MANIFEST.MF

There are ways to specify alternatively named files as a JAR's manifest using the JAR command-line parameters.

The specific class you want to use is specified using Main-Class: package.classname inside the META-INF/MANIFEST.MF file.

As for how to do this in Netbeans - not sure off the top of my head - I usually use IntelliJ and / or Eclipse and usually build the JAR through ANT or Maven anyway.

How do you determine a processing time in Python?

Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit's default_timer():

>>> import timeit
>>> tic=timeit.default_timer()
>>> # Do Stuff
>>> toc=timeit.default_timer()
>>> toc - tic #elapsed time in seconds

This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit documentation chooses the most precise available real-world timer depending on the platform.

ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.

For more precise/complex performance calculations, timeit includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.

Uploading file using POST request in Node.js

Looks like you're already using request module.

in this case all you need to post multipart/form-data is to use its form feature:

var req = request.post(url, function (err, resp, body) {
  if (err) {
    console.log('Error!');
  } else {
    console.log('URL: ' + body);
  }
});
var form = req.form();
form.append('file', '<FILE_DATA>', {
  filename: 'myfile.txt',
  contentType: 'text/plain'
});

but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:

form.append('file', fs.createReadStream(filepath));

request will extract all related metadata by itself.

For more information on posting multipart/form-data see node-form-data module, which is internally used by request.

How do I install PyCrypto on Windows?

If you are on Windows and struggling with installing Pycrypcto just use the: pip install pycryptodome. It works like a miracle and it will make your life much easier than trying to do a lot of configurations and tweaks.

What is in your .vimrc?

my .vimrc. My word swap function is usually a big hit.

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

How to tell whether a point is to the right or left side of a line

The vector (y1 - y2, x2 - x1) is perpendicular to the line, and always pointing right (or always pointing left, if you plane orientation is different from mine).

You can then compute the dot product of that vector and (x3 - x1, y3 - y1) to determine if the point lies on the same side of the line as the perpendicular vector (dot product > 0) or not.

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

    System.out.println(jo.toString());

What happened to Lodash _.pluck?

Use _.map instead of _.pluck. In the latest version the _.pluck has been removed.

Convert a python UTC datetime to a local datetime using only python standard library?

You can't do it with only the standard library as the standard library doesn't have any timezones. You need pytz or dateutil.

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> from dateutil import tz
>>> HERE = tz.tzlocal()
>>> UTC = tz.gettz('UTC')

The Conversion:
>>> gmt = now.replace(tzinfo=UTC)
>>> gmt.astimezone(HERE)
datetime.datetime(2010, 12, 30, 15, 51, 22, 114668, tzinfo=tzlocal())

Or well, you can do it without pytz or dateutil by implementing your own timezones. But that would be silly.

Should I use typescript? or I can just use ES6?

I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.

Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.

If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.

ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.

Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

Root Cause

The JPA (Java persistence API) is a java specification for ORM (Object-Relational Mapping) tools. The spring-boot-starter-data-jpa dependency enables ORM in the context of the spring boot framework.

The JPA auto configuration feature of the spring boot application attempts to establish database connection using JPA Datasource. The JPA DataSource bean requires database driver to connect to a database.

The database driver should be available as a dependency in the pom.xml file. For the external databases such as Oracle, SQL Server, MySql, DB2, Postgres, MongoDB etc requires the database JDBC connection properties to establish the connection.

You need to configure the database driver and the JDBC connection properties to fix this exception Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class.

application.properties

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 

application.yaml

spring:
autoconfigure:
    exclude:org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

By Programming

@SpringBootApplication(exclude =  {DataSourceAutoConfiguration.class })

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

Changing minDate and maxDate on the fly using jQuery DatePicker

I have changed min date property of date time picker by using this

$('#date').data("DateTimePicker").minDate(startDate);

I hope this one help to someone !

How to query the permissions on an Oracle directory?

Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.

As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.

Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.

How to read appSettings section in the web.config file?

Here's the easy way to get access to the web.config settings anywhere in your C# project.

 Properties.Settings.Default

Use case:

litBodyText.Text = Properties.Settings.Default.BodyText;
litFootText.Text = Properties.Settings.Default.FooterText;
litHeadText.Text = Properties.Settings.Default.HeaderText;

Web.config file:

  <applicationSettings>
    <myWebSite.Properties.Settings> 
      <setting name="BodyText" serializeAs="String">
        <value>
          &lt;h1&gt;Hello World&lt;/h1&gt;
          &lt;p&gt;
      Ipsum Lorem
          &lt;/p&gt;
        </value>
      </setting>
      <setting name="HeaderText" serializeAs="String">
      My header text
        <value />
      </setting>
      <setting name="FooterText" serializeAs="String">
      My footer text
        <value />
      </setting>
    </myWebSite.Properties.Settings>
  </applicationSettings>

No need for special routines - everything is right there already. I'm surprised that no one has this answer for the best way to read settings from your web.config file.

Stop MySQL service windows

The Top Voted Answer is out of date. I just installed MySQL 5.7 and the service name is now MySQL57 so the new command is

net stop MySQL57

How to convert Json array to list of objects in c#

you have an unmatched jSon string, if you want to convert into a list, try this

{
    "id": "MyID",

     "values": [
        {
            "id": "100",
            "diaplayName": "MyValue1",
        },
        {
            "id": "200",
            "diaplayName": "MyValue2",
        }
   ]    
}

How to open the second form?

You need to handle an event on Form1 that is raised as a result of user interaction. For example, if you have a "Settings" button that the user clicks in order to show the settings form (Form2), you should handle the Click event for that button:

private void settingsButton_Click(Object sender, EventArgs e)
{
    // Create a new instance of the Form2 class
    Form2 settingsForm = new Form2();

    // Show the settings form
    settingsForm.Show();
}

In addition to the Show method, you could also choose to use the ShowDialog method. The difference is that the latter shows the form as a modal dialog, meaning that the user cannot interact with the other forms in your application until they close the modal form. This is the same way that a message box works. The ShowDialog method also returns a value indicating how the form was closed.


When the user closes the settings form (by clicking the "X" in the title bar, for example), Windows will automatically take care of closing it.

If you want to close it yourself before the user asks to close it, you can call the form's Close method:

this.Close();

PHP - print all properties of an object

As no one has not provided an OO approach yet here is like it would be done.

class Person {
    public $name = 'Alex Super Tramp';

    public $age = 100;

    private $property = 'property';
}


$r = new ReflectionClass(new Person);
print_r($r->getProperties());

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => name
            [class] => Person
        )

    [1] => ReflectionProperty Object
        (
            [name] => age
            [class] => Person
        )

    [2] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

The advantage when using reflection is that you can filter by visibility of property, like this:

print_r($r->getProperties(ReflectionProperty::IS_PRIVATE));

Since Person::$property is private it's returned when filtering by IS_PRIVATE:

//Outputs
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => property
            [class] => Person
        )

)

Read the docs!

Get Android API level of phone currently running my application

Integer.valueOf(android.os.Build.VERSION.SDK);

Values are:

Platform Version   API Level
Android 9.0        28
Android 8.1        27
Android 8.0        26
Android 7.1        25
Android 7.0        24
Android 6.0        23
Android 5.1        22
Android 5.0        21
Android 4.4W       20
Android 4.4        19
Android 4.3        18
Android 4.2        17
Android 4.1        16
Android 4.0.3      15
Android 4.0        14
Android 3.2        13
Android 3.1        12
Android 3.0        11
Android 2.3.3      10
Android 2.3        9
Android 2.2        8
Android 2.1        7
Android 2.0.1      6
Android 2.0        5
Android 1.6        4
Android 1.5        3
Android 1.1        2
Android 1.0        1

CAUTION: don't use android.os.Build.VERSION.SDK_INT if <uses-sdk android:minSdkVersion="3" />.

You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT is since SDK 4 (Donut 1.6).

Search for a string in all tables, rows and columns of a DB

If you are "getting data" from an application, the sensible thing would be to use the profiler and profile the database while running the application. Trace it, then search the results for that string.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

PostgreSQL: Which version of PostgreSQL am I running?

Don’t know how reliable this is, but you can get two tokens of version fully automatically:

psql --version 2>&1 | tail -1 | awk '{print $3}' | sed 's/\./ /g' | awk '{print $1 "." $2}'

So you can build paths to binaries:

/usr/lib/postgresql/9.2/bin/postgres

Just replace 9.2 with this command.

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

ReportViewer Client Print Control "Unable to load client print control"?

In my case when I get this message IE suggest me to install add-on from Microsoft. After install problem solved.

My software:
IE9 but work also on older
SQL SERVER 2008 R2

Is there a simple, elegant way to define singletons?

I'm very unsure about this, but my project uses 'convention singletons' (not enforced singletons), that is, if I have a class called DataController, I define this in the same module:

_data_controller = None
def GetDataController():
    global _data_controller
    if _data_controller is None:
        _data_controller = DataController()
    return _data_controller

It is not elegant, since it's a full six lines. But all my singletons use this pattern, and it's at least very explicit (which is pythonic).

How do you specify a different port number in SQL Management Studio?

You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.

SQL Server query to find all permissions/access for all users in a database

Great thanks for awesome audit scripts.

I highly recommend for audit user use awesome Kenneth Fisher (b | t) stored procedures:

What is causing this error - "Fatal error: Unable to find local grunt"

Do

npm install

to install Grunt locally in ./node_modules (and everything else specified in the package.json file)

IIS AppPoolIdentity and file system write access permissions

Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.

So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

NPM: npm-cli.js not found when running npm

Don't change any environment variables

It was the installer which caused the issue and did not install all the required file.

I just repaired the NODEJS setup on windows 7 and it works very well. May be you can reinstall, just incase something does not work.

How to create module-wide variables in Python?

You are falling for a subtle quirk. You cannot re-assign module-level variables inside a python function. I think this is there to stop people re-assigning stuff inside a function by accident.

You can access the module namespace, you just shouldn't try to re-assign. If your function assigns something, it automatically becomes a function variable - and python won't look in the module namespace.

You can do:

__DB_NAME__ = None

def func():
    if __DB_NAME__:
        connect(__DB_NAME__)
    else:
        connect(Default_value)

but you cannot re-assign __DB_NAME__ inside a function.

One workaround:

__DB_NAME__ = [None]

def func():
    if __DB_NAME__[0]:
        connect(__DB_NAME__[0])
    else:
        __DB_NAME__[0] = Default_value

Note, I'm not re-assigning __DB_NAME__, I'm just modifying its contents.

Sql connection-string for localhost server

When using SQL Express, you need to specify \SQLExpress instance in your connection string:

string str = "Data Source=HARIHARAN-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True" ;

Submit form without page reloading

if you're submitting to the same page where the form is you could write the form tags with out an action and it will submit, like this

<form method='post'> <!-- you can see there is no action here-->

Virtual/pure virtual explained

  • Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es).

  • Virtual functions are declared and defined in normal class.

  • Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class.

  • An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.

HTML input - name vs. id

If you are using JavaScript/CSS, you must use 'id' of control to apply any CSS/JavaScript stuff on it.

If you use name, CSS won't work for that control. As an example, if you use a JavaScript calendar attached to a textbox, you must use id of text control to assign it the JavaScript calendar.

How to save DataFrame directly to Hive?

Sorry writing late to the post but I see no accepted answer.

df.write().saveAsTable will throw AnalysisException and is not HIVE table compatible.

Storing DF as df.write().format("hive") should do the trick!

However, if that doesn't work, then going by the previous comments and answers, this is what is the best solution in my opinion (Open to suggestions though).

Best approach is to explicitly create HIVE table (including PARTITIONED table),

def createHiveTable: Unit ={
spark.sql("CREATE TABLE $hive_table_name($fields) " +
  "PARTITIONED BY ($partition_column String) STORED AS $StorageType")
}

save DF as temp table,

df.createOrReplaceTempView("$tempTableName")

and insert into PARTITIONED HIVE table:

spark.sql("insert into table default.$hive_table_name PARTITION($partition_column) select * from $tempTableName")
spark.sql("select * from default.$hive_table_name").show(1000,false)

Offcourse the LAST COLUMN in DF will be the PARTITION COLUMN so create HIVE table accordingly!

Please comment if it works! or not.


--UPDATE--

df.write()
  .partitionBy("$partition_column")
  .format("hive")
  .mode(SaveMode.append)
  .saveAsTable($new_table_name_to_be_created_in_hive)  //Table should not exist OR should be a PARTITIONED table in HIVE

How to change the color of an svg element?

Use an svg <mask> element. This works in IE too!

Bonus: color is inherited from font-color, so easy to use alongside text.

_x000D_
_x000D_
<svg style="color: green; width: 96px; height: 96px" viewBox="0 0 100 100" preserveAspectRatio="none">
  <defs>
    <mask id="fillMask" x="0" y="0" width="100" height="100">
      <image xlink:href="https://svgur.com/i/AFM.svg" x="0" y="0" width="100" height="100" src="ppngfallback.png" />
    </mask>
  </defs>
  <rect x="0" y="0" width="100" height="100" style="stroke: none; fill: currentColor" mask="url(&quot;#fillMask&quot;)" />
</svg>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/jamiegl/5jaL0s1t/19/

How to set a Default Route (To an Area) in MVC

routes.MapRoute(
                "Area",
                "{area}/",
                new { area = "AreaZ", controller = "ControlerX ", action = "ActionY " }
            );

Have you tried that ?

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

How to measure time taken by a function to execute

Thanks, Achim Koellner, will expand your answer a bit:

var t0 = process.hrtime();
//Start of code to measure

//End of code
var timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds

Please, note, that you shouldn't do anything apart from what you want to measure (for example, console.log will also take time to execute and will affect performance tests).

Note, that in order by measure asynchronous functions execution time, you should insert var timeInMilliseconds = process.hrtime(t0)[1]/1000000; inside the callback. For example,

var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;

});

Anonymous method in Invoke call

myControl.Invoke(new MethodInvoker(delegate() {...}))

libxml install error using pip

Installing a lxml binary would do the trick. Check this

Access Google's Traffic Data through a Web Service

I don't think Google will provide this API. And traffic data not only contains the incident data.

Today many online maps show city traffic, but they have not provide the API for the developer. We even don't know where they get the traffic data. Maybe the government has the data.

So I think you could think about it from another direction. For example, there are many social network website out there. Everybody could post the traffic information on the website. We can collection these information to get the traffic status. Or maybe we can create a this type website.

But that type traffic data (talked about above) is not accurate. Even the information provided by human will be wrong.

Luckily I found that my city now provides an Mobile App called "Real-time Bus Information". It could tell the citizen where the bus is now, and when will arrive at the bus station. And I sniff the REST API in this App. The data from REST API give the important data, for example the lat and lon, and also the bus speed. And it's real-time data! So I think we could compute the traffic status from these data (by some programming). Here is some sample data : https://github.com/sp-chenyang/bus/blob/master/sample_data/bjgj_aibang_com_8899_bjgj_php_city_linename_stationno_datatype_type.json

Even the bus data will not enough to compute the accurate real-time traffic status. Incidents, traffic light and other things will affect the traffic status. But I think this is the beginning.

At the end, I think you could try to find whether your city provides these data.

PS: I am always thinking that life will be better for people in the future , but not now.

Delete a row in Excel VBA

Something like this will do it:

Rows("12:12").Select
Selection.Delete

So in your code it would look like something like this:

Rows(CStr(rand) & ":" & CStr(rand)).Select
Selection.Delete

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

This means your google-services.json file either does not belong to your application(Did you download the google-services.json for another app?)...so to solve this do the following:

1:Sign in to Firebase and open your project. 2:Click the Settings icon and select Project settings. 3:In the Your apps card, select the package name of the app you need a config file for from the list. 4:Click google-services.json. After the download completes,add the new google-services.json to your project root folder,replacing the existing one..or just delete the old one. Its very normal to download the google-services.json for your first project and then assume or forget that this specific google-services.json is tailored for your current project alone,because not any other because all projects have a unique package name.