Programs & Examples On #Spoken language

Show row number in row header of a DataGridView

It seems that it doesn't turn it into a string. Try

row.HeaderCell.Value = String.Format("{0}", row.Index + 1);

Check file uploaded is in csv format

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
  // do something
} else {
  die("Sorry, mime type not allowed");
}

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.

Loading scripts after page load?

So, there's no way that this works:

window.onload = function(){
  <script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>
};

You can't freely drop HTML into the middle of javascript.


If you have jQuery, you can just use:

$.getScript("http://jact.atdmt.com/jaction/JavaScriptTest")

whenever you want. If you want to make sure the document has finished loading, you can do this:

$(document).ready(function() {
    $.getScript("http://jact.atdmt.com/jaction/JavaScriptTest");
});

In plain javascript, you can load a script dynamically at any time you want to like this:

var tag = document.createElement("script");
tag.src = "http://jact.atdmt.com/jaction/JavaScriptTest";
document.getElementsByTagName("head")[0].appendChild(tag);

Encoding as Base64 in Java

add this library into your app level dependancies

implementation 'org.apache.commons:commons-collections4:4.4'

Associating existing Eclipse project with existing SVN repository

I just wanted to add that if you don't see Team -> Share project, it's likely you have to remove the project from the workspace before importing it back in. This is what happened to me, and I had to remove and readd it to the workspace for it to fix itself. (This happened when moving from dramatically different Eclipse versions + plugins using the same workspace.)

subclipse not showing "share project" option on project context menu in eclipse

Perform curl request in javascript?

You can use JavaScripts Fetch API (available in your browser) to make network requests.

If using node, you will need to install the node-fetch package.

const url = "https://api.wit.ai/message?v=20140826&q=";

const options = {
  headers: {
    Authorization: "Bearer 6Q************"
  }
};

fetch(url, options)
  .then( res => res.json() )
  .then( data => console.log(data) );

Laravel Rule Validation for Numbers

If I correctly got what you want:

$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];

or

$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];

For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules

digits_between :min,max

The field under validation must have a length between the given min and max.

numeric

The field under validation must have a numeric value.

max:value

The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

min:value

The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.

How do I check if a variable is of a certain type (compare two types) in C?

C does not support this form of type introspection. What you are asking is not possible in C (at least without compiler-specific extensions; it would be possible in C++, however).

In general, with C you're expected to know the types of your variable. Since every function has concrete types for its parameters (except for varargs, I suppose), you don't need to check in the function body. The only remaining case I can see is in a macro body, and, well, C macros aren't really all that powerful.

Further, note that C does not retain any type information into runtime. This means that, even if, hypothetically, there was a type comparison extension, it would only work properly when the types are known at compile time (ie, it wouldn't work to test whether two void * point to the same type of data).

As for typeof: First, typeof is a GCC extension. It is not a standard part of C. It's typically used to write macros that only evaluate their arguments once, eg (from the GCC manual):

 #define max(a,b) \
   ({ typeof (a) _a = (a); \
      typeof (b) _b = (b); \
     _a > _b ? _a : _b; })

The typeof keyword lets the macro define a local temporary to save the values of its arguments, allowing them to be evaluated only once.

In short, C does not support overloading; you'll just have to make a func_a(struct a *) and func_b(struct b *), and call the correct one. Alternately, you could make your own introspection system:

struct my_header {
  int type;
};

#define TYPE_A 0
#define TYPE_B 1

struct a {
  struct my_header header;
  /* ... */
};

struct b {
  struct my_header header;
  /* ... */
};

void func_a(struct a *p);
void func_b(struct b *p);

void func_switch(struct my_header *head);
#define func(p) func_switch( &(p)->header )

void func_switch(struct my_header *head) {
  switch (head->type) {
    case TYPE_A: func_a((struct a *)head); break;
    case TYPE_B: func_b((struct b *)head); break;
    default: assert( ("UNREACHABLE", 0) );
  }
}

You must, of course, remember to initialize the header properly when creating these objects.

Convert seconds to HH-MM-SS with JavaScript?

For the special case of HH:MM:SS.MS (eq: "00:04:33.637") as used by FFMPEG to specify milliseconds.

[-][HH:]MM:SS[.m...]

HH expresses the number of hours, MM the number of minutes for a maximum of 2 digits, and SS the number of seconds for a maximum of 2 digits. The m at the end expresses decimal value for SS.

_x000D_
_x000D_
/* HH:MM:SS.MS to (FLOAT)seconds ---------------*/
function timerToSec(timer){
   let vtimer = timer.split(":")
   let vhours = +vtimer[0]
   let vminutes = +vtimer[1]
   let vseconds = parseFloat(vtimer[2])
   return vhours * 3600 + vminutes * 60 + vseconds
}

/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
  let o = new Date(0)
  let p =  new Date(sec*1000)  
  return new Date(p.getTime()-o.getTime())
    .toISOString()
    .split("T")[1]
    .split("Z")[0]
}

/* Example: 7hours, 4 minutes, 33 seconds and 637 milliseconds */
const t = "07:04:33.637"
console.log(
  t + " => " +
  timerToSec(t) +
  "s"
)

/* Test: 25473 seconds and 637 milliseconds */
const s = 25473.637 // "25473.637"
console.log(
  s + "s => " + 
  secToTimer(s)
)
_x000D_
_x000D_
_x000D_

Example usage, a milliseconds transport timer:

_x000D_
_x000D_
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
  let o = new Date(0)
  let p =  new Date(sec*1000)  
  return new Date(p.getTime()-o.getTime())
    .toISOString()
    .split("T")[1]
    .split("Z")[0]
}

let job, origin = new Date().getTime()
const timer = () => {
  job = requestAnimationFrame(timer)
  OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}

requestAnimationFrame(timer)
_x000D_
span {font-size:4rem}
_x000D_
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>
_x000D_
_x000D_
_x000D_

Example usage, binded to a media element

_x000D_
_x000D_
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
  let o = new Date(0)
  let p =  new Date(sec*1000)  
  return new Date(p.getTime()-o.getTime())
    .toISOString()
    .split("T")[1]
    .split("Z")[0]
}

VIDEO.addEventListener("timeupdate", function(e){
  OUT.textContent = secToTimer(e.target.currentTime)
}, false)
_x000D_
span {font-size:4rem}
_x000D_
<span id="OUT"></span><br>
<video id="VIDEO" width="400" controls autoplay>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
_x000D_
_x000D_
_x000D_


Outside the question, those functions written in php:

<?php 
/* HH:MM:SS to (FLOAT)seconds ------------------*/
function timerToSec($timer){
  $vtimer = explode(":",$timer);
  $vhours = (int)$vtimer[0];
  $vminutes = (int)$vtimer[1];
  $vseconds = (float)$vtimer[2];
  return $vhours * 3600 + $vminutes * 60 + $vseconds;
}
/* Seconds to (STRING)HH:MM:SS -----------------*/
function secToTimer($sec){
  return explode(" ", date("H:i:s", $sec))[0];  
}

Change select box option background color

Another option is to use Javascript:

if (document.getElementById('selectID').value == '1') {
       document.getElementById('optionID').style.color = '#000';

(Not as clean as the CSS attribute selector, but more powerful)

Multiple inputs with same name through POST in php

Change the names of your inputs:

<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum"  />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />

Then:

$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'

If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".

Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.

Insert 2 million rows into SQL Server quickly

I ran into this scenario recently (well over 7 million rows) and eneded up using sqlcmd via powershell (after parsing raw data into SQL insert statements) in segments of 5,000 at a time (SQL can't handle 7 million lines in one lump job or even 500,000 lines for that matter unless its broken down into smaller 5K pieces. You can then run each 5K script one after the other.) as I needed to leverage the new sequence command in SQL Server 2012 Enterprise. I couldn't find a programatic way to insert seven million rows of data quickly and efficiently with said sequence command.

Secondly, one of the things to look out for when inserting a million rows or more of data in one sitting is the CPU and memory consumption (mostly memory) during the insert process. SQL will eat up memory/CPU with a job of this magnitude without releasing said processes. Needless to say if you don't have enough processing power or memory on your server you can crash it pretty easily in a short time (which I found out the hard way). If you get to the point to where your memory consumption is over 70-75% just reboot the server and the processes will be released back to normal.

I had to run a bunch of trial and error tests to see what the limits for my server was (given the limited CPU/Memory resources to work with) before I could actually have a final execution plan. I would suggest you do the same in a test environment before rolling this out into production.

How to execute function in SQL Server 2008

It looks like there's something else called Afisho_rankimin in your DB so the function is not being created. Try calling your function something else. E.g.

CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
   BEGIN
       Declare @rankimi int
       Select @rankimi=dbo.RESTORANTET.Rankimi
       From RESTORANTET
       Where  dbo.RESTORANTET.ID_Rest=@emri_rest
       RETURN @rankimi
  END
  GO

Note that you need to call this only once, not every time you call the function. After that try calling

SELECT dbo.Afisho_rankimin1(5) AS Rankimi 

Rotate camera in Three.js with mouse

Take a look at THREE.PointerLockControls

Add Foreign Key to existing table

i geted through the same problem. I my case the table already have data and there were key in this table that was not present in the reference table. So i had to delete this rows that disrespect the constraints and everything worked.

Copy folder recursively in Node.js

Since I'm just building a simple Node.js script, I didn't want the users of the script to need to import a bunch of external modules and dependencies, so I put on my thinking cap and did a search for running commands from the Bash shell.

This Node.js code snippet recursively copies a folder called node-webkit.app to a folder called build:

child = exec("cp -r node-webkit.app build", function(error, stdout, stderr) {
    sys.print("stdout: " + stdout);
    sys.print("stderr: " + stderr);
    if(error !== null) {
        console.log("exec error: " + error);
    } else {

    }
});

Thanks to Lance Pollard at dzone for getting me started.

The above snippet is limited to Unix-based platforms, like macOS and Linux, but a similar technique may work for Windows.

How do I fix PyDev "Undefined variable from import" errors?

It is possible you just need to re-configure your python path within Eclipse. See my answer to a similar question.

Easy way to get a test file into JUnit

If you need to actually get a File object, you could do the following:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

Which has the benefit of working cross platform, as described in this blog post.

How to copy a selection to the OS X clipboard

You can use MacVim when you're on a Mac to easily access the clipboard using the standard OS keys.

It's also fully backward compatible with normal Vim, so I don't even have to have a separate .vimrc.

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something')).

How to paste yanked text into the Vim command line

"I'd like to paste yanked text into Vim command line."

While the top voted answer is very complete, I prefer editing the command history.

In normal mode, type: q:. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.

For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p (get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.

To get out of command history mode, it's the opposite. In normal mode in command history, type: :q + enter

Getting fb.me URL

I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

jQuery $.cookie is not a function

Here are all the possible problems/solutions I have come across:

1. Download the cookie plugin

$.cookie is not a standard jQuery function and the plugin needs to be downloaded here. Make sure to include the appropriate <script> tag where necessary (see next).

2. Include jQuery before the cookie plugin

When including the cookie script, make sure to include jQuery FIRST, then the cookie plugin.

<script src="~/Scripts/jquery-2.0.3.js" type="text/javascript"></script>
<script src="~/Scripts/jquery_cookie.js" type="text/javascript"></script>

3. Don't include jQuery more than once

This was my problem. Make sure you aren't including jQuery more than once. If you are, it is possible that:

  1. jQuery loads correctly.
  2. The cookie plugin loads correctly.
  3. Your second inclusion of jQuery overwrites the first and destroys the cookie plugin.

For anyone using ASP.Net MVC projects, be careful with the default javascript bundle inclusions. My second inclusion of jQuery was within one of my global layout pages under the line @Scripts.Render("~/bundles/jquery").

4. Rename the plugin file to not include ".cookie"

In some rare cases, renaming the file to something that does NOT include ".cookie" has fixed this error, apparently due to web server issues. By default, the downloaded script is titled "jquery.cookie.js" but try renaming it to something like "jquery_cookie.js" as shown above. More details on this problem are here.

Select data between a date/time range

You probably need to use STR_TO_DATE function:

select * from hockey_stats 
where
  game_date between STR_TO_DATE('11/3/2012 00:00:00', '%c/%e/%Y %H:%i:%s')
                and STR_TO_DATE('11/5/2012 23:59:00', '%c/%e/%Y %H:%i:%s') 
order by game_date desc;

(if game_date is a string, you might need to use STR_TO_DATE on it)

Validate SSL certificates with Python

You can use Twisted to verify certificates. The main API is CertificateOptions, which can be provided as the contextFactory argument to various functions such as listenSSL and startTLS.

Unfortunately, neither Python nor Twisted comes with a the pile of CA certificates required to actually do HTTPS validation, nor the HTTPS validation logic. Due to a limitation in PyOpenSSL, you can't do it completely correctly just yet, but thanks to the fact that almost all certificates include a subject commonName, you can get close enough.

Here is a naive sample implementation of a verifying Twisted HTTPS client which ignores wildcards and subjectAltName extensions, and uses the certificate-authority certificates present in the 'ca-certificates' package in most Ubuntu distributions. Try it with your favorite valid and invalid certificate sites :).

import os
import glob
from OpenSSL.SSL import Context, TLSv1_METHOD, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, OP_NO_SSLv2
from OpenSSL.crypto import load_certificate, FILETYPE_PEM
from twisted.python.urlpath import URLPath
from twisted.internet.ssl import ContextFactory
from twisted.internet import reactor
from twisted.web.client import getPage
certificateAuthorityMap = {}
for certFileName in glob.glob("/etc/ssl/certs/*.pem"):
    # There might be some dead symlinks in there, so let's make sure it's real.
    if os.path.exists(certFileName):
        data = open(certFileName).read()
        x509 = load_certificate(FILETYPE_PEM, data)
        digest = x509.digest('sha1')
        # Now, de-duplicate in case the same cert has multiple names.
        certificateAuthorityMap[digest] = x509
class HTTPSVerifyingContextFactory(ContextFactory):
    def __init__(self, hostname):
        self.hostname = hostname
    isClient = True
    def getContext(self):
        ctx = Context(TLSv1_METHOD)
        store = ctx.get_cert_store()
        for value in certificateAuthorityMap.values():
            store.add_cert(value)
        ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
        ctx.set_options(OP_NO_SSLv2)
        return ctx
    def verifyHostname(self, connection, x509, errno, depth, preverifyOK):
        if preverifyOK:
            if self.hostname != x509.get_subject().commonName:
                return False
        return preverifyOK
def secureGet(url):
    return getPage(url, HTTPSVerifyingContextFactory(URLPath.fromString(url).netloc))
def done(result):
    print 'Done!', len(result)
secureGet("https://google.com/").addCallback(done)
reactor.run()

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

Find the min/max element of an array in JavaScript

To prevent "max" and "min" to be listed in a "for ... in" loop:

Object.defineProperty(Array.prototype, "max", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.max.apply(null, this);
    }
});
Object.defineProperty(Array.prototype, "min", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.min.apply(null, this);
    }
});

Usage:

var x = [10,23,44,21,5];
x.max(); //44
x.min(); //5

How to delete cookies on an ASP.NET website

Taking the OP's Question title as deleting all cookies - "Delete Cookies in website"

I came across code from Dave Domagala on the web somewhere. I edited Dave's to allow for Google Analytics cookies too - which looped through all cookies found on the website and deleted them all. (From a developer angle - updating new code into an existing site, is a nice touch to avoid problems with users revisiting the site).

I use the below code in tandem with reading the cookies first, holding any required data - then resetting the cookies after washing everything clean with the below loop.

The code:

int limit = Request.Cookies.Count; //Get the number of cookies and 
                                   //use that as the limit.
HttpCookie aCookie;   //Instantiate a cookie placeholder
string cookieName;   

//Loop through the cookies
for(int i = 0; i < limit; i++)
{
 cookieName = Request.Cookies[i].Name;    //get the name of the current cookie
 aCookie = new HttpCookie(cookieName);    //create a new cookie with the same
                                          // name as the one you're deleting
 aCookie.Value = "";    //set a blank value to the cookie 
 aCookie.Expires = DateTime.Now.AddDays(-1);    //Setting the expiration date
                                                //in the past deletes the cookie

 Response.Cookies.Add(aCookie);    //Set the cookie to delete it.
}

Addition: If You Use Google Analytics

The above loop/delete will delete ALL cookies for the site, so if you use Google Analytics - it would probably be useful to hold onto the __utmz cookie as this one keeps track of where the visitor came from, what search engine was used, what link was clicked on, what keyword was used, and where they were in the world when your website was accessed.

So to keep it, wrap a simple if statement once the cookie name is known:

... 
aCookie = new HttpCookie(cookieName);    
if (aCookie.Name != "__utmz")
{
    aCookie.Value = "";    //set a blank value to the cookie 
    aCookie.Expires = DateTime.Now.AddDays(-1);   

    HttpContext.Current.Response.Cookies.Add(aCookie);    
}

Android: TextView: Remove spacing and padding on top and bottom

Use this in your ImageView xml

android:adjustViewBounds="true"

Execute php file from another php

This came across while working on a project on linux platform.

exec('wget http://<url to the php script>)

This runs as if you run the script from browser.

Hope this helps!!

Get value from SimpleXMLElement Object

$codeZero = null;
foreach ($xml->code->children() as $child) {
   $codeZero = $child;
}

$lat = null;
foreach ($codeZero->children() as $child) {
   if (isset($child->lat)) {
      $lat = $child->lat;
   }
}

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

Is there any boolean type in Oracle databases?

As per Ammoq and kupa's answers, We use number(1) with default of 0 and don't allow nulls.

here's an add column to demonstrate:

ALTER TABLE YourSchema.YourTable ADD (ColumnName NUMBER(1) DEFAULT 0 NOT NULL);

Hope this helps someone.

Downloading an entire S3 bucket?

For Windows, S3 Browser is the easiest way I have found. It is excellent software, and it is free for non-commercial use.

PHP Echo a large block of text

Man, PHP is not perl!
PHP can just escape from HTML :) http://www.php.net/manual/en/language.basic-syntax.phpmode.php

if (is_single()) {
//now we just close PHP tag
?>
</style> 
<script> 
<blah blah blah>
<?php
//open it back. here is your PHP again. easy!
}
?>

I wonder why such many people stuck to ugly heredoc.

Newline in string attribute

For those that have tried every answer to this question and are still scratching their heads as to why none of them work for you, you might have ran into a form of the issue I ran into.

My TextBlock.Text property was inside of a ToolTipService.ToolTip element and it was databound to a property of an object whose data was being pulled from a SQL stored procedure. Now the data from this particular property within the stored procedure was being pulled from a SQL function.

Since nothing had worked for me, I gave up my search and created the converter class below:

public class NewLineConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var s = string.Empty;

        if (value.IsNotNull())
        {
            s = value.ToString();

            if (s.Contains("\\r\\n"))
                s = s.Replace("\\r\\n", Environment.NewLine);

            if (s.Contains("\\n"))
                s = s.Replace("\\n", Environment.NewLine);

            if (s.Contains("&#x0a;&#x0d;"))
                s = s.Replace("&#x0a;&#x0d;", Environment.NewLine);

            if (s.Contains("&#x0a;"))
                s = s.Replace("&#x0a;", Environment.NewLine);

            if (s.Contains("&#x0d;"))
                s = s.Replace("&#x0d;", Environment.NewLine);

            if (s.Contains("&#10;&#13;"))
                s = s.Replace("&#10;&#13;", Environment.NewLine);

            if (s.Contains("&#10;"))
                s = s.Replace("&#10;", Environment.NewLine);

            if (s.Contains("&#13;"))
                s = s.Replace("&#13;", Environment.NewLine);

            if (s.Contains("<br />"))
                s = s.Replace("<br />", Environment.NewLine);

            if (s.Contains("<LineBreak />"))
                s = s.Replace("<LineBreak />", Environment.NewLine);
        }

        return s;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I ended up having to use the Enivornment.NewLine method from @dparker's answer. I instructed the converter to look for any possible textual representation of a newline and replace it with Environment.NewLine.

This worked!

However, I was still perplexed as to why none of the other methods worked with databound properties.

I left a comment on @BobKing's accepted answer:

@BobKing - This doesn't seem to work in the ToolTipService.ToolTip when binding to a field that has the line feeds embedded from a SQL sproc.

He replied with:

@CodeMaverick If you're binding to text with the new lines embedded, they should probably be real char 10 values (or 13's) and not the XML sentinels. This is only if you want to write literal new lines in XAML files.

A light bulb went off!

I went into my SQL function, replaced my textual representations of newlines with ...

CHAR( 13 ) + CHAR( 10 )

... removed the converter from my TextBlock.Text binding, and just like that ... it worked!

Replace duplicate spaces with a single space in T-SQL

I use FOR XML PATH solution to replace multiple spaces into single space

The idea is to replace spaces with XML tags Then split XML string into string fragments without XML tags Finally concatenating those string values by adding single space characters between two

Here is how final UDF function can be called

select dbo.ReplaceMultipleSpaces('   Sample   text  with  multiple  space     ')

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

In SSMS 2012, you'll have to use:

To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.

  1. Add "-m;" into parameters;
  2. Restart the service and logon this SQL instance by using windows authentication;
  3. The rest steps are same as above. Change your windows user account permission in security or reset SA account password.
  4. Last, remove "-m" parameter from "startup parameters";

MySQL add days to a date

update tablename set coldate=DATE_ADD(coldate, INTERVAL 2 DAY)

Read an Excel file directly from a R script

Yes. See the relevant page on the R wiki. Short answer: read.xls from the gdata package works most of the time (although you need to have Perl installed on your system -- usually already true on MacOS and Linux, but takes an extra step on Windows, i.e. see http://strawberryperl.com/). There are various caveats, and alternatives, listed on the R wiki page.

The only reason I see not to do this directly is that you may want to examine the spreadsheet to see if it has glitches (weird headers, multiple worksheets [you can only read one at a time, although you can obviously loop over them all], included plots, etc.). But for a well-formed, rectangular spreadsheet with plain numbers and character data (i.e., not comma-formatted numbers, dates, formulas with divide-by-zero errors, missing values, etc. etc. ..) I generally have no problem with this process.

OSX - How to auto Close Terminal window after the "exit" command executed.

Actually, you should set a config on your Terminal, when your Terminal is up press ?+, then you will see below screen:

enter image description here

Then press shell tab and you will see below screen:

enter image description here

Now select Close if the shell exited cleanly for When the shell exits.

By the above config each time with exit command the Terminal will close but won't quit.

PHP sessions default timeout

Yes typically, a session will end after 20 minutes in PHP.

JPA entity without id

I guess your entity_property has a composite key (entity_id, name) where entity_id is a foreign key to entity. If so, you can map it as follows:

@Embeddable
public class EntityPropertyPK {
    @Column(name = "name")
    private String name;

    @ManyToOne
    @JoinColumn(name = "entity_id")
    private Entity entity;

    ...
}

@Entity 
@Table(name="entity_property") 
public class EntityProperty { 
    @EmbeddedId
    private EntityPropertyPK id;

    @Column(name = "value")
    private String value; 

    ...
}

How to insert current datetime in postgresql insert query

For current datetime, you can use now() function in postgresql insert query.

You can also refer following link.

insert statement in postgres for data type timestamp without time zone NOT NULL,.

SQL Server 2008- Get table constraints

You should use the current sys catalog views (if you're on SQL Server 2005 or newer - the sysobjects views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.

There are quite a few views you might be interested in:

  • sys.default_constraints for default constraints on columns
  • sys.check_constraints for check constraints on columns
  • sys.key_constraints for key constraints (e.g. primary keys)
  • sys.foreign_keys for foreign key relations

and a lot more - check it out!

You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:

SELECT 
    TableName = t.Name,
    ColumnName = c.Name,
    dc.Name,
    dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name

How to convert milliseconds to "hh:mm:ss" format?

DateFormat df = new SimpleDateFormat("HH:mm:ss");
String formatted = df.format(aDateObject);

Good Free Alternative To MS Access

What about Microsoft's Visual Studio Express? http://www.microsoft.com/express/default.aspx SQL Server Express is also at that link...

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Clear text field value in JQuery

Use jQuery.prototype.val to get/set field values:

var value = $('#doc_title').val();    // get value
$('#doc_title').val('');    // clear value

How to put labels over geom_bar in R with ggplot2

As with many tasks in ggplot, the general strategy is to put what you'd like to add to the plot into a data frame in a way such that the variables match up with the variables and aesthetics in your plot. So for example, you'd create a new data frame like this:

dfTab <- as.data.frame(table(df))
colnames(dfTab)[1] <- "x"
dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq))

So that the x variable matches the corresponding variable in df, and so on. Then you simply include it using geom_text:

ggplot(df) + geom_bar(aes(x,fill=x)) + 
    geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),vjust=0) +
    opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),legend.title=theme_blank(),
        axis.title.y=theme_blank())

This example will plot just the percentages, but you can paste together the counts as well via something like this:

dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ")

Note that in the current version of ggplot2, opts is deprecated, so we would use theme and element_blank now.

How to load local html file into UIWebView

[[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];

It may be late but if the file from pathForResource is nil you should add it in the Build Phases > Copy Bundle Resources.

enter image description here

How do I get the path to the current script with Node.js?

index.js within any folder containing modules to export

const entries = {};
for (const aFile of require('fs').readdirSync(__dirname, { withFileTypes: true }).filter(ent => ent.isFile() && ent.name !== 'index.js')) {
  const [ name, suffix ] = aFile.name.split('.');
  entries[name] = require(`./${aFile.name}`);
}

module.exports = entries;

This will find all files in the root of the current directory, require and export every file present with the same export name as the filename stem.

How can one check to see if a remote file exists using PHP?

You can instruct curl to use the HTTP HEAD method via CURLOPT_NOBODY.

More or less

$ch = curl_init("http://www.example.com/favicon.ico");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode >= 400 -> not found, $retcode = 200, found.
curl_close($ch);

Anyway, you only save the cost of the HTTP transfer, not the TCP connection establishment and closing. And being favicons small, you might not see much improvement.

Caching the result locally seems a good idea if it turns out to be too slow. HEAD checks the time of the file, and returns it in the headers. You can do like browsers and get the CURLINFO_FILETIME of the icon. In your cache you can store the URL => [ favicon, timestamp ]. You can then compare the timestamp and reload the favicon.

How can I get log4j to delete old rotating log files?

Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:

<param name="MaxBackupIndex" value="20"/>

The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.

Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)

log4j.appender.[appenderName].MaxBackupIndex = 15

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

how to File.listFiles in alphabetical order?

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

PHP XML Extension: Not installed

I solved this issue with commands bellow:

$ sudo apt-get install php7.3-intl

$ sudo /etc/init.d/php7.3-fpm restart

These commands works for me in homestead with php7.3

What are the differences between git branch, fork, fetch, merge, rebase and clone?

Just to add to others, a note specific to forking.

It's good to realize that technically, cloning the repo and forking the repo are the same thing. Do:

git clone $some_other_repo

and you can tap yourself on the back---you have just forked some other repo.

Git, as a VCS, is in fact all about cloning forking. Apart from "just browsing" using remote UI such as cgit, there is very little to do with git repo that does not involve forking cloning the repo at some point.

However,

  • when someone says I forked repo X, they mean that they have created a clone of the repo somewhere else with intention to expose it to others, for example to show some experiments, or to apply different access control mechanism (eg. to allow people without Github access but with company internal account to collaborate).

    Facts that: the repo is most probably created with other command than git clone, that it's most probably hosted somewhere on a server as opposed to somebody's laptop, and most probably has slightly different format (it's a "bare repo", ie. without working tree) are all just technical details.

    The fact that it will most probably contain different set of branches, tags or commits is most probably the reason why they did it in the first place.

    (What Github does when you click "fork", is just cloning with added sugar: it clones the repo for you, puts it under your account, records the "forked from" somewhere, adds remote named "upstream", and most importantly, plays the nice animation.)

  • When someone says I cloned repo X, they mean that they have created a clone of the repo locally on their laptop or desktop with intention study it, play with it, contribute to it, or build something from source code in it.

The beauty of Git is that it makes this all perfectly fit together: all these repos share the common part of block commit chain so it's possible to safely (see note below) merge changes back and forth between all these repos as you see fit.


Note: "safely" as long as you don't rewrite the common part of the chain, and as long as the changes are not conflicting.

How To Get Selected Value From UIPickerView

       NSInteger SelectedRow;
                   SelectedRow = [yourPickerView selectedRowInComponent:0];
                   selectedPickerString = [YourPickerArray objectAtIndex:SelectedRow];
                   self.YourTextField.text= selectedPickerString;

    // if  you want to move pickerview to selected row then 
 for (int i = 0; I<YourPickerArray.count; i++) {
  if ([[YourPickerArray objectAtIndex:i] isEqualToString:self.YourTextField.text]) { 
[yourPickerView selectRow:i inComponent:0 animated:NO];
 }
}

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Replace a character at a specific index in a string?

I agree with Petar Ivanov but it is best if we implement in following way:

public String replace(String str, int index, char replace){     
    if(str==null){
        return str;
    }else if(index<0 || index>=str.length()){
        return str;
    }
    char[] chars = str.toCharArray();
    chars[index] = replace;
    return String.valueOf(chars);       
}

Replace single quotes in SQL Server

If you really must completely strip out the single quotes you can do this:

Replace(@strip, '''', '')

However, ordinarily you'd replace ' with '' and this will make SQL Server happy when querying the database. The trick with any of the built-in SQL functions (like replace) is that they too require you to double up your single quotes.

So to replace ' with '' in code you'd do this:

Replace(@strip, '''', '''''')

Of course... in some situations you can avoid having to do this entirely if you use parameters when querying the database. Say you're querying the database from a .NET application, then you'd use the SqlParameter class to feed the SqlCommand parameters for the query and all of this single quote business will be taken care of automatically. This is usually the preferred method as SQL parameters will also help prevent SQL injection attacks.

Is there a way to style a TextView to uppercase all of its letters?

I've come up with a solution which is similar with RacZo's in the fact that I've also created a subclass of TextView which handles making the text upper-case.

The difference is that instead of overriding one of the setText() methods, I've used a similar approach to what the TextView actually does on API 14+ (which is in my point of view a cleaner solution).

If you look into the source, you'll see the implementation of setAllCaps():

public void setAllCaps(boolean allCaps) {
    if (allCaps) {
        setTransformationMethod(new AllCapsTransformationMethod(getContext()));
    } else {
        setTransformationMethod(null);
    }
}

The AllCapsTransformationMethod class is not (currently) public, but still, the source is also available. I've simplified that class a bit (removed the setLengthChangesAllowed() method), so the complete solution is this:

public class UpperCaseTextView extends TextView {

    public UpperCaseTextView(Context context) {
        super(context);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setTransformationMethod(upperCaseTransformation);
    }

    private final TransformationMethod upperCaseTransformation =
            new TransformationMethod() {

        private final Locale locale = getResources().getConfiguration().locale;

        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return source != null ? source.toString().toUpperCase(locale) : null;
        }

        @Override
        public void onFocusChanged(View view, CharSequence sourceText,
                boolean focused, int direction, Rect previouslyFocusedRect) {}
    };
}

get an element's id

Yes you can just use the .id property of the dom element, for example:

myDOMElement.id

Or, something like this:

var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
  alert(inputs[i].id);
}

Javascript Get Values from Multiple Select Option Box

Take a look at HTMLSelectElement.selectedOptions.

HTML

<select name="north-america" multiple>
  <option valud="ca" selected>Canada</a>
  <option value="mx" selected>Mexico</a>
  <option value="us">USA</a>
</select>

JavaScript

var elem = document.querySelector("select");

console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]

This would also work on non-multiple <select> elements


Warning: Support for this selectedOptions seems pretty unknown at this point

Could not install packages due to an EnvironmentError: [Errno 13]

I have anaconda installed for Python 3. I also have Python2 in my mac.

python --version

gives me

Python 3.7.3

python2.7 --version

gives me

Python 2.7.10

I wanted to install pyspark package in python2, given that it was already installed in python3.

python2.7 -m pip install pyspark

gives me an error

Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pyspark' Consider using the --user option or check the permissions.

The below command solved it. Thank god I didn't have to do any config changes.

python2.7 -m pip install pyspark --user

Collecting pyspark Requirement already satisfied: py4j==0.10.7 in /Library/Python/2.7/site-packages (from pyspark) (0.10.7) Installing collected packages: pyspark Successfully installed pyspark-2.4.4 You are using pip version 18.1, however version 19.3.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command.

For files in directory, only echo filename (no path)

Another approach is to use ls when reading the file list within a directory so as to give you what you want, i.e. "just the file name/s". As opposed to reading the full file path and then extracting the "file name" component in the body of the for loop.

Example below that follows your original:

for filename in $(ls /home/user/)
do
  echo $filename
done;

If you are running the script in the same directory as the files, then it simply becomes:

for filename in $(ls)
do
  echo $filename
done;

Postgres and Indexes on Foreign Keys and Primary Keys

If you want to list the indexes of all the tables in your schema(s) from your program, all the information is on hand in the catalog:

select
     n.nspname  as "Schema"
    ,t.relname  as "Table"
    ,c.relname  as "Index"
from
          pg_catalog.pg_class c
     join pg_catalog.pg_namespace n on n.oid        = c.relnamespace
     join pg_catalog.pg_index i     on i.indexrelid = c.oid
     join pg_catalog.pg_class t     on i.indrelid   = t.oid
where
        c.relkind = 'i'
    and n.nspname not in ('pg_catalog', 'pg_toast')
    and pg_catalog.pg_table_is_visible(c.oid)
order by
     n.nspname
    ,t.relname
    ,c.relname

If you want to delve further (such as columns and ordering), you need to look at pg_catalog.pg_index. Using psql -E [dbname] comes in handy for figuring out how to query the catalog.

BootStrap : Uncaught TypeError: $(...).datetimepicker is not a function

I had this problem. Solution for me was to remove links to Vue.js files. Vue.js and JQuery have some conflicts in datepicker and datetimepicker functions.

Best dynamic JavaScript/JQuery Grid

My suggestion for dynamic JQuery Grid are below.

http://reconstrukt.com/ingrid/

https://github.com/mleibman/SlickGrid

http://www.datatables.net/index

Best one is :

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.

Variable length pagination

On-the-fly filtering

Multi-column sorting with data type detection

Smart handling of column widths

Display data from almost any data source

DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)

Scrolling options for table viewport

Fully internationalisable

jQuery UI ThemeRoller support

Rock solid - backed by a suite of 2600+ unit tests

Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more

Dynamic creation of tables

Ajax auto loading of data

Custom DOM positioning

Single column filtering

Alternative pagination types

Non-destructive DOM interaction

Sorting column(s) highlighting

Advanced data source options

Extensive plug-in support

Sorting, type detection, API functions, pagination and filtering

Fully themeable by CSS

Solid documentation

110+ pre-built examples

Full support for Adobe AIR

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

How to update two tables in one statement in SQL Server 2005?

For general updating table1 specific colom based on Table2 specific colom, below query works perfectly...

UPDATE table 1  
SET Col 2 = t2.Col2,  
Col 3 = t2.Col3  
FROM table1 t1  
INNER JOIN table 2 t2 ON t1.Col1 = t2.col1 

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

How to send image to PHP file using Ajax?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#abc').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            url: 'post.php',
            method:'POST',
            data: new FormData(this),
            contentType: false,
            cache:false,
            processData:false,
            success: function (data) {
              alert(data);
              location.reload();
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form enctype= "multipart/form-data" id="abc">
      <input name="fname" ><br>
      <input name="lname"><br>
      <input type="file" name="file" required=""><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

java.lang.OutOfMemoryError: GC overhead limit exceeded

Fix memory leaks in your application with help of profile tools like eclipse MAT or VisualVM

With JDK 1.7.x or later versions, use G1GC, which spends 10% on garbage collection unlike 2% in other GC algorithms.

Apart from setting heap memory with -Xms1g -Xmx2g , try `

-XX:+UseG1GC 
-XX:G1HeapRegionSize=n, 
-XX:MaxGCPauseMillis=m, 
-XX:ParallelGCThreads=n, 
-XX:ConcGCThreads=n`

Have a look at oracle article for fine-tuning these parameters.

Some question related to G1GC in SE:

Java 7 (JDK 7) garbage collection and documentation on G1

Java G1 garbage collection in production

Agressive garbage collector strategy

Vuejs and Vue.set(), update array

VueJS can't pickup your changes to the state if you manipulate arrays like this.

As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2 nor the .length property of an array.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    f: 'DD-MM-YYYY',_x000D_
    items: [_x000D_
      "10-03-2017",_x000D_
      "12-03-2017"_x000D_
    ]_x000D_
  },_x000D_
  methods: {_x000D_
_x000D_
    cha: function(index, item, what, count) {_x000D_
      console.log(item + " index > " + index);_x000D_
      val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
      this.items.$set(index, val)_x000D_
      console.log("arr length:  " + this.items.length);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
  <ul>_x000D_
    <li v-for="(index, item) in items">_x000D_
      <br><br>_x000D_
      <button v-on:click="cha(index, item, 'day', -1)">_x000D_
      - day</button> {{ item }}_x000D_
      <button v-on:click="cha(index, item, 'day', 1)">_x000D_
      + day</button>_x000D_
      <br><br>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Laravel 5 – Remove Public from URL

DON'T!

YOU REALLY SHOULD NOT rename server.php in your Laravel root folder to index.php and copy the .htaccess file from the /public directory to your Laravel root folder!!!

This way everyone can access some of your files (.env for example). Try it yourself. You don't want that!


DO

Instead, you should create an .htaccess file in your root like this:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]

This will silently rewrite all your base URIs to the /public folder. Even all Headers, for example the HTTP Authorization Header, and all optional URI parameters will silently be passed on to the /public folder as well.

That's all

Please note when setting up a Laravel project with Docker: you won't need to do any of this.

How to show two figures using matplotlib?

You should call plt.show() only at the end after creating all the plots.

Bootstrap 3 navbar active li not changing background-color

Did you include "bootstrap-theme.css" files on your code?

In "bootstrap-theme.min.css" files, background-image about ".active" is existed for "navbar" (check this screenshot: http://i.imgur.com/1etLIyY.png).

It will re-declare your style code, and then it will be effected on your code.

So after you delete or re-declare them (background-image), you can use your background color style about the ".active" tag.

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

This answer is in three parts, see below for the official release (v3 and v4)

I couldn't even find the col-lg-push-x or pull classes in the original files for RC1 i downloaded, so check your bootstrap.css file. hopefully this is something they will sort out in RC2.

anyways, the col-push-* and pull classes did exist and this will suit your needs. Here is a demo

<div class="row">
    <div class="col-sm-5 col-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

EDIT: BELOW IS THE ANSWER FOR THE OFFICIAL RELEASE v3.0

Also see This blog post on the subject

  • col-vp-push-x = push the column to the right by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

  • col-vp-pull-x = pull the column to the left by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

    vp = xs, sm, md, or lg

    x = 1 thru 12

I think what messes most people up, is that you need to change the order of the columns in your HTML markup (in the example below, B comes before A), and that it only does the pushing or pulling on view-ports that are greater than or equal to what was specified. i.e. col-sm-push-5 will only push 5 columns on sm view-ports or greater. This is because Bootstrap is a "mobile first" framework, so your HTML should reflect the mobile version of your site. The Pushing and Pulling are then done on the larger screens.

  • (Desktop) Larger view-ports get pushed and pulled.
  • (Mobile) Smaller view-ports render in normal order.

DEMO

<div class="row">
    <div class="col-sm-5 col-sm-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-sm-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

View-port >= sm

|A|B|C|

View-port < sm

|B|
|A|
|C|

EDIT: BELOW IS THE ANSWER FOR v4.0

With v4 comes flexbox and other changes to the grid system and the push\pull classes have been removed in favor of using flexbox ordering.

  • Use .order-* classes to control visual order (where * = 1 thru 12)
  • This can also be grid tier specific .order-md-*
  • Also .order-first (-1) and .order-last (13) avalable

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col order-2">1st yet 2nd</div>_x000D_
  <div class="col order-1">2nd yet 1st</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

In SSMS I had Diagram open showing the Key. After deleting the Key and truncating the file I refreshed then focused back on the Diagram and created an update by clearing then restoring an Identity box. Saving the Diagram brought up a Save dialog box, than a "Changes were made in the database while you where working" dialog box, clicking Yes restored the Key, restoring it from the latched copy in the Diagram.

CMake: How to build external projects and include their targets

This post has a reasonable answer:

CMakeLists.txt.in:

cmake_minimum_required(VERSION 2.8.2)

project(googletest-download NONE)

include(ExternalProject)
ExternalProject_Add(googletest
  GIT_REPOSITORY    https://github.com/google/googletest.git
  GIT_TAG           master
  SOURCE_DIR        "${CMAKE_BINARY_DIR}/googletest-src"
  BINARY_DIR        "${CMAKE_BINARY_DIR}/googletest-build"
  CONFIGURE_COMMAND ""
  BUILD_COMMAND     ""
  INSTALL_COMMAND   ""
  TEST_COMMAND      ""
)

CMakeLists.txt:

# Download and unpack googletest at configure time
configure_file(CMakeLists.txt.in
               googletest-download/CMakeLists.txt)
execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )
execute_process(COMMAND ${CMAKE_COMMAND} --build .
  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download )

# Prevent GoogleTest from overriding our compiler/linker options
# when building with Visual Studio
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)

# Add googletest directly to our build. This adds
# the following targets: gtest, gtest_main, gmock
# and gmock_main
add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src
                 ${CMAKE_BINARY_DIR}/googletest-build)

# The gtest/gmock targets carry header search path
# dependencies automatically when using CMake 2.8.11 or
# later. Otherwise we have to add them here ourselves.
if (CMAKE_VERSION VERSION_LESS 2.8.11)
  include_directories("${gtest_SOURCE_DIR}/include"
                      "${gmock_SOURCE_DIR}/include")
endif()

# Now simply link your own targets against gtest, gmock,
# etc. as appropriate

However it does seem quite hacky. I'd like to propose an alternative solution - use Git submodules.

cd MyProject/dependencies/gtest
git submodule add https://github.com/google/googletest.git
cd googletest
git checkout release-1.8.0
cd ../../..
git add *
git commit -m "Add googletest"

Then in MyProject/dependencies/gtest/CMakeList.txt you can do something like:

cmake_minimum_required(VERSION 3.3)

if(TARGET gtest) # To avoid diamond dependencies; may not be necessary depending on you project.
    return()
endif()

add_subdirectory("googletest")

I haven't tried this extensively yet but it seems cleaner.

Edit: There is a downside to this approach: The subdirectory might run install() commands that you don't want. This post has an approach to disable them but it was buggy and didn't work for me.

Edit 2: If you use add_subdirectory("googletest" EXCLUDE_FROM_ALL) it seems means the install() commands in the subdirectory aren't used by default.

div inside php echo

You can use the below sample, also you dont need the else clause to print nothing!

 <?php if ( ($cart->count_product) > 0) { ?>
           <div class="my_class">
               <?php print $cart->count_product; ?> 
           </div>
 <?php } ?>

Difference between String replace() and replaceAll()

Q: What's the difference between the java.lang.String methods replace() and replaceAll(), other than that the latter uses regex.

A: Just the regex. They both replace all :)

http://docs.oracle.com/javase/8/docs/api/java/lang/String.html

PS:

There's also a replaceFirst() (which takes a regex)

How do you specify table padding in CSS? ( table, not cell padding )

CSS doesn't really allow you to do this on a table level. Generally, I specify cellspacing="3" when I want to achieve this effect. Obviously not a css solution, so take it for what it's worth.

Bootstrap: Position of dropdown menu relative to navbar item

If you wants to center the dropdown, this is the solution.

<ul class="dropdown-menu" style="right:auto; left: auto;">

How to use Selenium with Python?

There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples

You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

Hide keyboard in react-native

Updated usage of ScrollView for React Native 0.39

<ScrollView scrollEnabled={false} contentContainerStyle={{flex: 1}} />

Although, there is still a problem with two TextInput boxes. eg. A username and password form would now dismiss the keyboard when switching between inputs. Would love to get some suggestions to keep keyboard alive when switching between TextInputs while using a ScrollView.

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

Save text file UTF-8 encoded with VBA

The traditional way to transform a string to a UTF-8 string is as follows:

StrConv("hello world",vbFromUnicode)

So put simply:

Dim fnum As Integer
fnum = FreeFile
Open "myfile.txt" For Output As fnum
Print #fnum, StrConv("special characters: äöüß", vbFromUnicode)
Close fnum

No special COM objects required

ASP.NET MVC controller actions that return JSON or partial html

In your action method, return Json(object) to return JSON to your page.

public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}

Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as

<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>

SomeMethod would be a javascript method that then evaluates the Json object returned.

If you want to return a plain string, you can just use the ContentResult:

public ActionResult SomeActionMethod() {
    return Content("hello world!");
}

ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:

return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");

How to open this .DB file?

I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

If it is a SQLite database, it will start with "SQLite format 3"

Is there a simple way to remove unused dependencies from a maven pom.xml?

As others have said, you can use the dependency:analyze goal to find which dependencies are used and declared, used and undeclared, or unused and declared. You may also find dependency:analyze-dep-mgt useful to look for mismatches in your dependencyManagement section.

You can simply remove unwanted direct dependencies from your POM, but if they are introduced by third-party jars, you can use the <exclusions> tags in a dependency to exclude the third-party jars (see the section titled Dependency Exclusions for details and some discussion). Here is an example excluding commons-logging from the Spring dependency:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring</artifactId>
  <version>2.5.5</version>
  <exclusions>
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
  </exclusions> 
</dependency>

Move all files except one

move all files(not include except file) to except_file
find -maxdepth 1 -mindepth 1 -not -name except_file -print0 |xargs -0 mv -t ./except_file
for example(cache is current except file)
find -maxdepth 1 -mindepth 1 -not -name cache -print0 |xargs -0 mv -t ./cache

PHPExcel Make first row bold

The simple way to make bold headers:

$row = 1;
foreach($tittles as $index => $tittle) {
    $worksheet->getStyleByColumnAndRow($index + 1, $row)->getFont()->setBold(true);
    $worksheet->setCellValueByColumnAndRow($index + 1, $row, $tittle);
}

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

There's a pretty good write up in the Adobe KB's on 'wmode' and other attributes with regards to their effect on presentation and performance.

http://kb2.adobe.com/cps/127/tn_12701.html

Most efficient way to remove special characters from string

HashSet is O(1)
Not sure if it is faster than the existing comparison

private static HashSet<char> ValidChars = new HashSet<char>() { 'a', 'b', 'c', 'A', 'B', 'C', '1', '2', '3', '_' };
public static string RemoveSpecialCharacters(string str)
{
    StringBuilder sb = new StringBuilder(str.Length / 2);
    foreach (char c in str)
    {
        if (ValidChars.Contains(c)) sb.Append(c);
    }
    return sb.ToString();
}

I tested and this in not faster than the accepted answer.
I will leave it up as if you needed a configurable set of characters this would be a good solution.

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

Session only cookies with Javascript

Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return false;
  }
  
  
  if(getCookie("KoiMilGaya")) {
    //alert('found'); 
    // Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again.. 
  } else {
    //alert('nothing');
    // Display popup or anthing here. it shows on first visit only.  
    // this will load again when user closer browser and open again. 
    setCookie('KoiMilGaya','1');
  }

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

How to open a web page from my application?

Microsoft explains it in the KB305703 article on How to start the default Internet browser programmatically by using Visual C#.

Don't forget to check the Troubleshooting section.

how to display data values on Chart.js

From chart.js samples (file Chart.js-2.4.0/samples/data_labelling.html) :

``` // Define a plugin to provide data labels

    Chart.plugins.register({
        afterDatasetsDraw: function(chartInstance, easing) {
            // To only draw at the end of animation, check for easing === 1
            var ctx = chartInstance.chart.ctx;

            chartInstance.data.datasets.forEach(function (dataset, i) {
                var meta = chartInstance.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function(element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';

                        var fontSize = 16;
                        var fontStyle = 'normal';
                        var fontFamily = 'Helvetica Neue';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

                        // Just naively convert to string for now
                        var dataString = dataset.data[index].toString();

                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });

```

How to list running screen sessions?

Multiple folks have already pointed that

$ screen -ls

would list the screen sessions.

Here is another trick that may be useful to you.

If you add the following command as a last line in your .bashrc file on server xxx, then it will automatically reconnect to your screen session on login.

screen -d -r

Hope you find it useful.

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
  $username = $_POST['username']; $password = $_POST['password'];
  if($username === 'admin' && $password === 'password'){
    $_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
  }
  if($username !== 'admin')$userError = 'Invalid Username';
  if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <style type='text.css'>
       @import common.css;
     </style>
   </head>
<body>
  <form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
    <label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
    <div class='error'><?php echo $userError;?></div>
    <label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
    <div class='error'><?php echo $passError;?></div>
    <input type='submit' value='Home' name='sub' />
  </form>
  <script type='text/javascript' src='common.js'></script>
</body>
</html>

How can I extract all values from a dictionary in Python?

Pythonic duck-typing should in principle determine what an object can do, i.e., its properties and methods. By looking at a dictionary object one may try to guess it has at least one of the following: dict.keys() or dict.values() methods. You should try to use this approach for future work with programming languages whose type checking occurs at runtime, especially those with the duck-typing nature.

Reliable and fast FFT in Java

I guess it depends on what you are processing. If you are calculating the FFT over a large duration you might find that it does take a while depending on how many frequency points you are wanting. However, in most cases for audio it is considered non-stationary (that is the signals mean and variance changes to much over time), so taking one large FFT (Periodogram PSD estimate) is not an accurate representation. Alternatively you could use Short-time Fourier transform, whereby you break the signal up into smaller frames and calculate the FFT. The frame size varies depending on how quickly the statistics change, for speech it is usually 20-40ms, for music I assume it is slightly higher.

This method is good if you are sampling from the microphone, because it allows you to buffer each frame at a time, calculate the fft and give what the user feels is "real time" interaction. Because 20ms is quick, because we can't really perceive a time difference that small.

I developed a small bench mark to test the difference between FFTW and KissFFT c-libraries on a speech signal. Yes FFTW is highly optimised, but when you are taking only short-frames, updating the data for the user, and using only a small fft size, they are both very similar. Here is an example on how to implement the KissFFT libraries in Android using LibGdx by badlogic games. I implemented this library using overlapping frames in an Android App I developed a few months ago called Speech Enhancement for Android.

Pretty git branch graphs

A nice and clean looking table-like git graph output for shells

with hashes as usally besides the graph tree

with hashes as usally besides the graph tree

or in an extra column

or in an extra column

EDIT: You want to start right away without reading all explanations? Jump to EDIT 6.

INFO: For a more branch-like colored version for shells, see also my second answer (https://stackoverflow.com/a/63253135/).

In all the answers to this question none showed a clean table-like looking output for shells so far. The closest was this answer from gospes where I started from.

The core point in my approach is to count only the tree characters shown to the user. Then fill them to a personal length with whitespaces.

Other than git you need these tools

  • grep
  • paste
  • printf
  • sed
  • seq
  • tr
  • wc

mostly on board with any linux distribution.

The code snippet is

while IFS=+ read -r graph hash time branch message;do
  
  # count needed amount of whitespaces and create them
  whitespaces=$((9-$(sed -nl1000 'l' <<< "$graph" | grep -Eo '\\\\|\||\/|\ |\*|_' | wc -l)))
  whitespaces=$(seq -s' ' $whitespaces|tr -d '[:digit:]')
  
  # show hashes besides the tree ...
  #graph_all="$graph_all$graph$(printf '%7s' "$hash")$whitespaces \n"
  
  # ... or in an own column
  graph_all="$graph_all$graph$whitespaces\n"
  hash_all="$hash_all$(printf '%7s' "$hash")  \n"
  
  # format all other columns
  time_all="$time_all$(printf '%12s' "$time") \n"
  branch_all="$branch_all$(printf '%15s' "$branch")\n"
  message_all="$message_all$message\n"
done < <(git log --all --graph --decorate=short --color --pretty=format:'+%C(bold 214)%<(7,trunc)%h%C(reset)+%C(dim white)%>(12,trunc)%cr%C(reset)+%C(214)%>(15,trunc)%d%C(reset)+%C(white)%s%C(reset)' && echo);

# paste the columns together and show the table-like output
paste -d' ' <(echo -e "$time_all") <(echo -e "$branch_all") <(echo -e "$graph_all") <(echo -e "$hash_all") <(echo -e "$message_all")

To calculate the needed whitespaces we use

  sed -nl1000 'l' <<< "$graph"

to get all characters (till 1000 per line) than select only the tree characters: * | / \ _ and whitespaces with

  grep -Eo '\\\\|\||\/|\ |\*|_'

finally count them and substract the result from our choosen length value, which is 9 in the example.

To produce the calculated amount of whitespaces we use

  seq -s' ' $whitespaces

and truncate the position numbers with

  tr -d '[:digit:]'

than add them to the end of our graph line. That's it!

Git has the nice option to format the length of the output specifiers already with the syntax '%><(amount_of_characters,truncate_option)', which adds whitespaces from the left '>' or right '<' side and can truncate characters from the start 'ltrunc', middle 'mtrunc' or end 'trunc'.

It is important that printf cmd's above use the same length values for the corresponding git column.

Have fun to style your own clean table-like looking output to your needs.

Extra:

To get the right length value you can use the following snippet

while read -r graph;do
    chars=$(sed -nl1000 'l' <<< "$graph" | grep -Eo '\\\\|\||\/|\ |\*|_' | wc -l)
    [[ $chars -gt ${max_chars:-0} ]] && max_chars=$chars
done < <(git log --all --graph --pretty=format:' ')

and use $max_chars as the right length value above.

EDIT 1: Just noticed that the underline charater is also used in the git tree and edit the code snippets above accordingly. If there are other characters missing, please leave a comment.

EDIT 2: If you want to get rid of the brackets around branch and tag entries, just use "%D" instead of "%d" in the git command, like in EDIT 3.

EDIT 3: Maybe the "auto" color option is the one you prefer most for branch and tag entries?

git bracketless auto color head and tag tablelike shell output

Change this part of the git command (color 214)

%C(214)%>(15,trunc)%D%C(reset)

to auto

%C(auto)%>(15,trunc)%D%C(reset)

EDIT 4: Or you like your own color mix for that part, a fancy output with blinking head?

git tree fancy styled tablelike output

To be able to style the head, branch names and tags first we need the "auto" color option in our git command like in EDIT 3.

Then we can replace the know color values with our own by adding these 3 lines

 # branch name styling
 branch=${branch//1;32m/38;5;214m}
 # head styling
 branch=${branch//1;36m/3;5;1;38;5;196m}
 # tag styling
 branch=${branch//1;33m/1;38;5;222m}

just before line

 branch_all="$branch_all$(printf '%15s' "$branch")\n"

in our code snippet. The replacement values produce the colors above.

For example the replacement value for head is

3;5;1;38;5;196

where 3; stands for italic, 5; for blinking and 1;38;5;196 for the color. For more infos start here. Note: This behavior depends on your favorite terminal and may therefore not be usable.

BUT you can choose any color value you prefer.

OVERVIEW of the git color values and ANSI equivalents

enter image description here

You find a list with git color/style option here.

If you need the output on your console for accurate colors (the picture above is scaled down by stackoverflow) you can produce the output with

for ((i=0;i<=255;i++));do
  while IFS='+' read -r tree hash;do 
    echo -e "$(printf '%-10s' "(bold $i)") $hash  $(sed -nl500 'l' <<< "$hash"|grep -Eom 1 '[0-9;]*[0-9]m'|tr -d 'm')"
  done < <(git log --all --graph --decorate=short --color --pretty=format:'+%C(bold '$i')%h%C(reset)'|head -n 1)
done

in your git project path which uses the first commit from your git log output.

EDIT 5: As member "Andras Deak" mentioned, there are some ways how to use this code:

1) as an alias:

alias does not accept parameters but a function can, therefore just define in your .bashrc

   function git_tably () {
     unset branch_all graph_all hash_all message_all time_all max_chars

     ### add here the same code as under "2) as a shell-script" ###

   }

and call the function git_tably (derived from table-like) directly under your git project path or from wherever you want with your git project path as first parameter.

2) as a shell-script:

I use it with the option to pass a git project directory as first parameter to it or if empty, take the working directory like the normal behavior. In it's entirety we have

# edit your color/style preferences here or use empty values for git auto style
tag_style="1;38;5;222"
head_style="1;3;5;1;38;5;196"
branch_style="38;5;214"

# determine the max character length of your git tree
while IFS=+ read -r graph;do
  chars_count=$(sed -nl1000 'l' <<< "$graph" | grep -Eo '\\\\|\||\/|\ |\*|_' | wc -l)
  [[ $chars_count -gt ${max_chars:-0} ]] && max_chars=$chars_count
done < <(cd "${1:-"$PWD"}" && git log --all --graph --pretty=format:' ')

# create the columns for your prefered table-like git graph output
while IFS=+ read -r graph hash time branch message;do

  # count needed amount of whitespaces and create them
  whitespaces=$(($max_chars-$(sed -nl1000 'l' <<< "$graph" | grep -Eo '\\\\|\||\/|\ |\*|_' | wc -l)))
  whitespaces=$(seq -s' ' $whitespaces|tr -d '[:digit:]')

  # show hashes besides the tree ...
  #graph_all="$graph_all$graph$(printf '%7s' "$hash")$whitespaces \n"

  # ... or in an own column
  graph_all="$graph_all$graph$whitespaces\n"
  hash_all="$hash_all$(printf '%7s' "$hash")  \n"

  # format all other columns
  time_all="$time_all$(printf '%12s' "$time") \n"
  branch=${branch//1;32m/${branch_style:-1;32}m}
  branch=${branch//1;36m/${head_style:-1;36}m}
  branch=${branch//1;33m/${tag_style:-1;33}m}
  branch_all="$branch_all$(printf '%15s' "$branch")\n"
  message_all="$message_all$message\n"

done < <(cd "${1:-"$PWD"}" && git log --all --graph --decorate=short --color --pretty=format:'+%C(bold 214)%<(7,trunc)%h%C(reset)+%C(dim white)%>(12,trunc)%cr%C(reset)+%C(auto)%>(15,trunc)%D%C(reset)+%C(white)%s%C(reset)' && echo);

# paste the columns together and show the table-like output
paste -d' ' <(echo -e "$time_all") <(echo -e "$branch_all") <(echo -e "$graph_all") <(echo -e "$hash_all") <(echo -e "$message_all")

3) as an git alias:

Maybe the most comfortable way is to add a git alias in your .gitconfig

[color "decorate"]
    HEAD = bold blink italic 196
    branch = 214
    tag = bold 222
    
[alias]
    count-log = log --all --graph --pretty=format:' '
    tably-log = log --all --graph --decorate=short --color --pretty=format:'+%C(bold 214)%<(7,trunc)%h%C(reset)+%C(dim white)%>(12,trunc)%cr%C(reset)+%C(auto)%>(15,trunc)%D%C(reset)+%C(white)%s%C(reset)'
    tably     = !bash -c '"                                                                                                    \
                  while IFS=+ read -r graph;do                                                                                 \
                    chars_count=$(sed -nl1000 \"l\" <<< \"$graph\" | grep -Eo \"\\\\\\\\\\\\\\\\|\\||\\/|\\ |\\*|_\" | wc -l); \
                    [[ $chars_count -gt ${max_chars:-0} ]] && max_chars=$chars_count;                                          \
                  done < <(git count-log && echo);                                                                             \
                  while IFS=+ read -r graph hash time branch message;do                                                        \
                    chars=$(sed -nl1000 \"l\" <<< \"$graph\" | grep -Eo \"\\\\\\\\\\\\\\\\|\\||\\/|\\ |\\*|_\" | wc -l);       \
                    whitespaces=$(($max_chars-$chars));                                                                        \
                    whitespaces=$(seq -s\" \" $whitespaces|tr -d \"[:digit:]\");                                               \
                    graph_all=\"$graph_all$graph$whitespaces\n\";                                                              \
                    hash_all=\"$hash_all$(printf \"%7s\" \"$hash\")  \n\";                                                     \
                    time_all=\"$time_all$(printf \"%12s\" \"$time\") \n\";                                                     \
                    branch_all=\"$branch_all$(printf \"%15s\" \"$branch\")\n\";                                                \
                    message_all=\"$message_all$message\n\";                                                                    \
                  done < <(git tably-log && echo);                                                                             \
                  paste -d\" \" <(echo -e \"$time_all\") <(echo -e \"$branch_all\") <(echo -e \"$graph_all\")                  \
                                <(echo -e \"$hash_all\") <(echo -e \"$message_all\");                                          \
                '"

Than just call git tably under any project path.

Git is so powerful that you can change head, tags, ... directly as shown above and taken from here.

Another fancy option is to select tree colors you prefer the most with

[log]
    graphColors = bold 160, blink 231 bold 239, bold 166, bold black 214, bold green, bold 24, cyan

that gives you crazy looking but always table-like git log outputs

fanciest_git_tree_tablelike_image

Too much blinking! Just to demonstrate what is possible. Too few specified colors leads to color repetitions.

A complete .gitconfig reference is just one click away.

EDIT 6: Due to your positive votes I improved the snippet. Now you can feed it with almost any git log command and don't have to adapt the code anymore. Try it!

How it works?

  • define your git log commands in your .gitconfig as always (formatted like below)
  • define a positive tree column number, where the git graph is shown (optional)

Then just call

    git tably YourLogAlias

under any git project path or

    git tably YourLogAlias TreeColNumber

where TreeColNumber overwrites an always defined value from above.

    git tably YourLogAlias | less -r

will pipe the output into less which is useful for huge histories.

Your git log alias must follow these format rules:

  • each column has to be indicated by a column delimiter which you have to choose and may cause problems if not unique

    i.e. ^ in ...format:'^%h^%cr^%s' results in a tree, a hash, a time and a commit column

  • before every commit placeholder in your log command you have to use
    %><(<N>[,ltrunc|mtrunc|trunc]) , with one of the trunc options

    (for syntax explanations see https://git-scm.com/docs/pretty-formats),

    however the last commit placeholder of any newline can be used without it

    i.e. ...format:'^%<(7,trunc)%h^%<(12,trunc)%cr^%s'

  • if extra characters are needed for decoration like (committer: , < and >) in

    ...%C(dim white)(committer: %cn% <%ce>)%C(reset)...

    to get a table-like output they must be written directly before and after the commit placeholder

    i.e. ...%C(dim white)%<(25,trunc)(committer: %cn%<(25,trunc) <%ce>)%C(reset)...

  • using column colors like %C(white)...%C(rest) needs the --color option for a colored output

    i.e. ...--color...format:'^%C(white)%<(7,trunc)%h%C(rest)...

  • if you use the --stat option or similar, add a newline %n at the end

    i.e. ...--stat...format:'...%n'...

  • you can place the git graph at every column as long as you use no newline or only empty ones format:'...%n'

    for non-empty newlines ...%n%CommitPlaceholder... you can place the git graph at every column n+1 only if all n-th columns of each line exist and use the same width

  • the name of your defined tree column number for a specific log alias have to be YourLogAlias-col

Compared to normal git log output this one is slow but nice.

Now the improved snippet to add to your .gitconfig

[color "decorate"]
    HEAD   = bold blink italic 196
    branch = 214
    tag    = bold 222
    
[alias]

    # delimiter used in every mylog alias as column seperator
    delim     = ^
    
    # short overview about the last hashes without graph
    mylog     = log --all --decorate=short --color --pretty=format:'^%C(dim white)%>(12,trunc)%cr%C(reset)^%C(bold 214)%<(7,trunc)%h%C(reset)' -5
    
    # log with hashes besides graph tree
    mylog2    = log --all --graph --decorate=short --color --pretty=format:'%C(bold 214)%<(7,trunc)%h%C(reset)^%C(dim white)%>(12,trunc)%cr%C(reset)^%C(auto)%>(15,trunc)%D%C(reset)^%C(white)%<(80,trunc)%s%C(reset)'
    mylog2-col= 3
    
    # log with hashes in an own column and more time data
    mylog3    = log --all --graph --decorate=short --color --pretty=format:'^%C(dim white)%>(12,trunc)%cr%C(reset)^%C(cyan)%<(10,trunc)%cs%C(reset)^%C(bold 214)%<(7,trunc)%h%C(reset)^%C(auto)%<(15,trunc)%D%C(reset)^%C(white)%s%C(reset)'
    mylog3-col= 4
    
    tably     = !bash -c '" \
                \
                \
                declare -A col_length; \
                apost=$(echo -e \"\\u0027\"); \
                delim=$(git config alias.delim); \
                git_log_cmd=$(git config alias.$1); \
                git_tre_col=${2:-$(git config alias.$1-col)}; \
                [[ -z "$git_tre_col" ]] && git_tre_col=1; \
                [[ -z "$git_log_cmd" ]] && { git $1;exit; }; \
                \
                \
                i=0; \
                n=0; \
                while IFS= read -r line;do \
                  ((n++)); \
                  while read -d\"$delim\" -r col_info;do \
                    ((i++)); \
                    [[ -z \"$col_info\" ]] && col_length[\"$n:$i\"]=${col_length[\"${last[$i]:-1}:$i\"]} && ((i--)) && continue; \
                    [[ $i -gt ${i_max:-0} ]] && i_max=$i; \
                    col_length[\"$n:$i\"]=$(grep -Eo \"\\([0-9]*,[lm]*trunc\\)\" <<< \"$col_info\" | grep -Eo \"[0-9]*\" | head -n 1); \
                    [[ -n \"${col_length[\"$n:$i\"]}\" ]] && last[$i]=$n; \
                    chars_extra=$(grep -Eo \"trunc\\).*\" <<< \"$col_info\"); \
                    chars_extra=${chars_extra#trunc)}; \
                    chars_begin=${chars_extra%%\\%*}; \
                    chars_extra=${chars_extra%$apost*}; \
                    chars_extra=${chars_extra#*\\%}; \
                    case \" ad aD ae aE ai aI al aL an aN ar as at b B cd cD ce cE ci cI cl cL cn cN cr \
                            cs ct d D e f G? gd gD ge gE GF GG GK gn gN GP gs GS GT h H N p P s S t T \" in \
                      *\" ${chars_extra:0:2} \"*) \
                        chars_extra=${chars_extra:2}; \
                        chars_after=${chars_extra%%\\%*}; \
                        ;; \
                      *\" ${chars_extra:0:1} \"*) \
                        chars_extra=${chars_extra:1}; \
                        chars_after=${chars_extra%%\\%*}; \
                        ;; \
                      *) \
                        echo \"No Placeholder found. Probably no tablelike output.\"; \
                        continue; \
                        ;; \
                    esac; \
                    if [[ -n \"$chars_begin$chars_after\" ]];then \
                      len_extra=$(echo \"$chars_begin$chars_after\" | wc -m); \
                      col_length["$n:$i"]=$((${col_length["$n:$i"]}+$len_extra-1)); \
                    fi; \
                  done <<< \"${line#*=format:}$delim\"; \
                  i=1; \
                done <<< \"$(echo -e \"${git_log_cmd//\\%n/\\\\n}\")\"; \
                \
                \
                git_log_fst_part=\"${git_log_cmd%%\"$apost\"*}\"; \
                git_log_lst_part=\"${git_log_cmd##*\"$apost\"}\"; \
                git_log_tre_part=\"${git_log_cmd%%\"$delim\"*}\"; \
                git_log_tre_part=\"${git_log_tre_part##*\"$apost\"}\"; \
                git_log_cmd_count=\"$git_log_fst_part$apost $git_log_tre_part$apost$git_log_lst_part\"; \
                col_length[\"1:1\"]=$(eval git \"${git_log_cmd_count// --color}\" | wc -L); \
                \
                \
                i=0; \
                while IFS=\"$delim\" read -r graph rest;do \
                  ((i++)); \
                  graph_line[$i]=\"$graph\"; \
                done < <(eval git \"${git_log_cmd/ --color}\" && echo); \
                \
                \
                i=0; \
                l=0; \
                while IFS= read -r line;do \
                  c=0; \
                  ((i++)); \
                  ((l++)); \
                  [[ $l -gt $n ]] && l=1; \
                  while IFS= read -d\"$delim\" -r col_content;do \
                    ((c++)); \
                    [[ $c -le $git_tre_col ]] && c_corr=-1 || c_corr=0; \
                    if [[ $c -eq 1 ]];then \
                      [[ \"${col_content/\\*}\" = \"$col_content\" ]] && [[ $l -eq 1 ]] && l=$n; \
                      count=$(wc -L <<< \"${graph_line[$i]}\"); \
                      whitespaces=$(seq -s\" \" $((${col_length[\"1:1\"]}-$count))|tr -d \"[:digit:]\"); \
                      col_content[$git_tre_col]=\"${col_content}$whitespaces\"; \
                    else \
                      col_content[$c+$c_corr]=\"$(printf \"%-${col_length[\"$l:$c\"]}s\" \"${col_content:-\"\"}\")\"; \
                    fi; \
                  done <<< \"$line$delim\"; \
                  for ((k=$c+1;k<=$i_max;k++));do \
                    [[ $k -le $git_tre_col ]] && c_corr=-1 || c_corr=0; \
                    col_content[$k+$c_corr]=\"$(printf \"%-${col_length[\"$l:$k\"]:-${col_length[\"${last[$k]:-1}:$k\"]:-0}}s\" \"\")\"; \
                  done; \
                  unset col_content[0]; \
                  echo -e \"${col_content[*]}\"; \
                  unset col_content[*]; \
                done < <(eval git \"$git_log_cmd\" && echo); \
                "' "git-tably"

where in tably

  • the first paragraph loads the delim(iter), YourLogAlias and YourLogAlias-col into shell variables
  • the second reads out the length for each column
  • the third counts the max. length of the tree
  • the fourth loads the tree into an array
  • the fifth organizes and print the table-like output

Results:

enter image description here

enter image description here

enter image description here

or with new TreeColNumber on the fly

enter image description here

AGAIN: Have fun to style your own clean table-like looking output to your needs.

You can also share your prefered formatted git log alias in the comments. From time to time I will include the most rated ones in the text above and add images too.

Reading a text file with SQL Server

BULK INSERT dbo.temp 

FROM 'c:\temp\file.txt' --- path file in db server 

WITH 

  (
     ROWTERMINATOR ='\n'
  )

it work for me but save as by editplus to ansi encoding for multilanguage

HTML Input="file" Accept Attribute File Type (CSV)

These days you can just use the file extension

<input type="file" ID="fileSelect" accept=".xlsx, .xls, .csv"/>

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

Show/hide image with JavaScript

If you already have a JavaScript function called showImage defined to show the image, you can link as such:

<a href="javascript:showImage()">show image</a>

If you need help defining the function, I would try:

function showImage() {
    var img = document.getElementById('myImageId');
    img.style.visibility = 'visible';
}

Or, better yet,

function setImageVisible(id, visible) {
    var img = document.getElementById(id);
    img.style.visibility = (visible ? 'visible' : 'hidden');
}

Then, your links would be:

<a href="javascript:setImageVisible('myImageId', true)">show image</a>
<a href="javascript:setImageVisible('myImageId', false)">hide image</a>

How to fill Matrix with zeros in OpenCV?

You can choose filling zero data or create zero Mat.

  1. Filling zero data with setTo():

    img.setTo(Scalar::all(0));
    
  2. Create zero data with zeros():

    img = zeros(img.size(), img.type());
    

The img changes address of memory.

Stopping python using ctrl+c

If it is running in the Python shell use Ctrl + Z, otherwise locate the python process and kill it.

How to auto-indent code in the Atom editor?

I prefer using atom-beautify, CTRL+ALT+B (in linux, may be in windows also) handles better al kind of formats and it is also customizable per file format.

more details here: https://atom.io/packages/atom-beautify

How can I get query string values in JavaScript?

Here's my own take on this. This first function decodes a URL string into an object of name/value pairs:

url_args_decode = function (url) {
  var args_enc, el, i, nameval, ret;
  ret = {};
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  // strip off initial ? on search and split
  args_enc = el.search.substring(1).split('&');
  for (i = 0; i < args_enc.length; i++) {
    // convert + into space, split on =, and then decode 
    args_enc[i].replace(/\+/g, ' ');
    nameval = args_enc[i].split('=', 2);
    ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
  }
  return ret;
};

And as an added bonus, if you change some of the args, you can use this second function to put the array of args back into the URL string:

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};

How do I upgrade the Python installation in Windows 10?

Installing/Upgrading Python Using the Chocolatey Windows Package Manager

Let's say you have Python 2.7.16:

    C:\Windows\system32>python --version
    python2 2.7.16

...and you want to upgrade to the (now current) 3.x.y version. There is a simple way to install a parallel installation of Python 3.x.y using a Windows package management tool.

Now that modern Windows has package management, just like Debian Linux distributions have apt-get, and RedHat has dnf: we can put it to work for us! It's called Chocolatey.

What's Chocolatey?

Chocolatey is a scriptable, command line tool that is based on .NET 4.0 and the nuget package manager baked into Visual Studio.

If you want to learn about Chocolatey and why to use it, which some here reading this might find particularly useful, go to https://chocolatey.org/docs/why

Installing Chocolatey

To get the Chocolatey Package Manager, you follow a process that is described at https://chocolatey.org/docs/installation#installing-chocolatey,

I'll summarize it for you here. There are basically two options: using the cmd prompt, or using the PowerShell prompt.

CMD Prompt Chocolatey Installation

Launch an administrative command prompt. On Windows 10, to do this:

  • Windows+R
  • Type cmd
  • Press ctrl+shift+Enter

If you don't have administrator rights on the system, go to the Chocolatey website. You may not be completely out of luck and can perform a limited local install, but I won't cover that here.

  • Copy the string below into your command prompt and type Enter:
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

Chocolatey will be downloaded and installed for you as below:

Getting latest version of the Chocolatey package for download.
Getting Chocolatey from https://chocolatey.org/api/v2/package/chocolatey/0.10.11.
Downloading 7-Zip commandline tool prior to extraction.
Extracting C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall\chocolatey.zip to C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall...
Installing chocolatey on this machine
Creating ChocolateyInstall as an environment variable (targeting 'Machine')
  Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'
WARNING: It's very likely you will need to close and reopen your shell
  before you can use choco.
Restricting write permissions to Administrators
We are setting up the Chocolatey package repository.
The packages themselves go to 'C:\ProgramData\chocolatey\lib'
  (i.e. C:\ProgramData\chocolatey\lib\yourPackageName).
A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'
  and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.

Creating Chocolatey folders if they do not already exist.

WARNING: You can safely ignore errors related to missing log files when
  upgrading from a version of Chocolatey less than 0.9.9.
  'Batch file could not be found' is also safe to ignore.
  'The system cannot find the file specified' - also safe.
chocolatey.nupkg file not installed in lib.
 Attempting to locate it from bootstrapper.
PATH environment variable does not have C:\ProgramData\chocolatey\bin in it. Adding...
WARNING: Not setting tab completion: Profile file does not exist at 'C:\Users\blahblahblah\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'.
Chocolatey (choco.exe) is now ready.
You can call choco from anywhere, command line or powershell by typing choco.
Run choco /? for a list of functions.
You may need to shut down and restart powershell and/or consoles
 first prior to using choco.
Ensuring chocolatey commands are on the path
Ensuring chocolatey.nupkg is in the lib folder

Either Exit the CMD prompt or type the following command to reload the environment variables:

refreshenv

PowerShell Chocolatey Installation

If you prefer PowerShell to the cmd prompt, you can do this directly from there, however you will have to tell PowerShell to run with a proper script execution policy to get it to work. On Windows 10, the simplest way I have found to do this is to type the following into the Cortana search bar next to the Windows button:

PowerShell.exe

Next, right click on the 'Best Match' choice in the menu that pops up and select 'Run as Administrator'

Now that you're in PowerShell, hopefully running with Administrator privileges, execute the following to install Chocolatey:

Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

PowerShell will download Chocolatey for you and launch the installation. It only takes a few moments. It looks exactly like the CMD installation, save perhaps some fancy colored text.

Either Exit PowerShell or type the following command to reload the environment variables:

refreshenv

Upgrading Python

The choco command is the same whether you use PowerShell or the cmd prompt. Launch your favorite using the instructions as above. I'll use the administrator cmd prompt:

C:\WINDOWS\system32>choco upgrade python -y

Essentially, chocolatey will tell you "Hey, Python isn't installed" since you're coming from 2.7.x and it treats the 2.7 version as completely separate. It is only going to give you the most current version, 3.x.y (as of this writing, 3.7.2, but that will change in a few months):

Chocolatey v0.10.11
Upgrading the following packages:
python
By upgrading you accept licenses for the packages.
python is not installed. Installing...

python3 v3.x.y [Approved]
python3 package files upgrade completed. Performing other installation steps.
Installing 64-bit python3...
python3 has been installed.
Installed to: 'C:\Python37' 
  python3 can be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The upgrade of python3 was successful.
  Software installed as 'exe', install location is likely default.

python v3.x.y [Approved]
python package files upgrade completed. Performing other installation steps.
 The upgrade of python was successful.
  Software install location not explicitly set, could be in package or
  default install location if installer.

Chocolatey upgraded 2/2 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

Either exit out of the cmd/Powershell prompt and re-enter it, or use refreshenv then type py --version

C:\Windows\System32>refreshenv
Refreshing environment variables from registry for cmd.exe. Please wait...Finished..

C:\Windows\system32>py --version
Python 3.7.2

Note that the most recent Python install will now take over when you type Python at the command line. You can run either version by using the following commands:

py -2
Python 2.7.16 (v2.7.16:413a49145e, Mar  4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

C:\>py -3
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>exit()
C:\>

From here I suggest you use the Python pip utility to install whatever packages you need. For example, let's say you wanted to install Flask. The commands below first upgrade pip, then install Flask

C:\>py -3 -m pip install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.4MB 1.6MB/s
Installing collected packages: pip
  Found existing installation: pip 18.1
    Uninstalling pip-18.1:
      Successfully uninstalled pip-18.1
Successfully installed pip-19.0.3

c:\>py -3 -m pip install Flask

...will do the trick. Happy Pythoning!

Are list-comprehensions and functional functions faster than "for loops"?

I modified @Alisa's code and used cProfile to show why list comprehension is faster:

from functools import reduce
import datetime

def reduce_(numbers):
    return reduce(lambda sum, next: sum + next * next, numbers, 0)

def for_loop(numbers):
    a = []
    for i in numbers:
        a.append(i*2)
    a = sum(a)
    return a

def map_(numbers):
    sqrt = lambda x: x*x
    return sum(map(sqrt, numbers))

def list_comp(numbers):
    return(sum([i*i for i in numbers]))

funcs = [
        reduce_,
        for_loop,
        map_,
        list_comp
        ]

if __name__ == "__main__":
    # [1, 2, 5, 3, 1, 2, 5, 3]
    import cProfile
    for f in funcs:
        print('=' * 25)
        print("Profiling:", f.__name__)
        print('=' * 25)
        pr = cProfile.Profile()
        for i in range(10**6):
            pr.runcall(f, [1, 2, 5, 3, 1, 2, 5, 3])
        pr.create_stats()
        pr.print_stats()

Here's the results:

=========================
Profiling: reduce_
=========================
         11000000 function calls in 1.501 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.162    0.000    1.473    0.000 profiling.py:4(reduce_)
  8000000    0.461    0.000    0.461    0.000 profiling.py:5(<lambda>)
  1000000    0.850    0.000    1.311    0.000 {built-in method _functools.reduce}
  1000000    0.028    0.000    0.028    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: for_loop
=========================
         11000000 function calls in 1.372 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.879    0.000    1.344    0.000 profiling.py:7(for_loop)
  1000000    0.145    0.000    0.145    0.000 {built-in method builtins.sum}
  8000000    0.320    0.000    0.320    0.000 {method 'append' of 'list' objects}
  1000000    0.027    0.000    0.027    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: map_
=========================
         11000000 function calls in 1.470 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.264    0.000    1.442    0.000 profiling.py:14(map_)
  8000000    0.387    0.000    0.387    0.000 profiling.py:15(<lambda>)
  1000000    0.791    0.000    1.178    0.000 {built-in method builtins.sum}
  1000000    0.028    0.000    0.028    0.000 {method 'disable' of '_lsprof.Profiler' objects}


=========================
Profiling: list_comp
=========================
         4000000 function calls in 0.737 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000    0.318    0.000    0.709    0.000 profiling.py:18(list_comp)
  1000000    0.261    0.000    0.261    0.000 profiling.py:19(<listcomp>)
  1000000    0.131    0.000    0.131    0.000 {built-in method builtins.sum}
  1000000    0.027    0.000    0.027    0.000 {method 'disable' of '_lsprof.Profiler' objects}

IMHO:

  • reduce and map are in general pretty slow. Not only that, using sum on the iterators that map returned is slow, compared to suming a list
  • for_loop uses append, which is of course slow to some extent
  • list-comprehension not only spent the least time building the list, it also makes sum much quicker, in contrast to map

What is the Windows equivalent of the diff command?

I've found a lightweight graphical software for windows that seems to be useful in lack of diff command. It could solve all of my problems.

WinDiff http://www.grigsoft.com/download-windiff.htm

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

How to list imported modules?

print [key for key in locals().keys()
       if isinstance(locals()[key], type(sys)) and not key.startswith('__')]

MySQL - SELECT * INTO OUTFILE LOCAL ?

Try setting path to /var/lib/mysql-files/filename.csv (MySQL 8). Determine what files directory is yours by typping SHOW VARIABLES LIKE "secure_file_priv"; in mysql client command line.

See answer about here: (...) --secure-file-priv in MySQL answered in 2015 by vhu user

Display Parameter(Multi-value) in Report

I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:

Public Function ShowParmValues(ByVal parm as Parameter) as string
   Dim s as String 

      For i as integer = 0 to parm.Count-1
         s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
      Next
  Return s
End Function  

Programmatically check Play Store for app updates

Apart from using JSoup, we can alternatively do pattern matching for getting the app version from playStore.

To match the latest pattern from google playstore ie <div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div> we first have to match the above node sequence and then from above sequence get the version value. Below is the code snippet for same:

    private String getAppVersion(String patternString, String inputString) {
        try{
            //Create a pattern
            Pattern pattern = Pattern.compile(patternString);
            if (null == pattern) {
                return null;
            }

            //Match the pattern string in provided string
            Matcher matcher = pattern.matcher(inputString);
            if (null != matcher && matcher.find()) {
                return matcher.group(1);
            }

        }catch (PatternSyntaxException ex) {

            ex.printStackTrace();
        }

        return null;
    }


    private String getPlayStoreAppVersion(String appUrlString) {
        final String currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>";
        final String appVersion_PatternSeq = "htlgb\">([^<]*)</s";
        String playStoreAppVersion = null;

        BufferedReader inReader = null;
        URLConnection uc = null;
        StringBuilder urlData = new StringBuilder();

        final URL url = new URL(appUrlString);
        uc = url.openConnection();
        if(uc == null) {
           return null;
        }
        uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
        inReader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        if (null != inReader) {
            String str = "";
            while ((str = inReader.readLine()) != null) {
                           urlData.append(str);
            }
        }

        // Get the current version pattern sequence 
        String versionString = getAppVersion (currentVersion_PatternSeq, urlData.toString());
        if(null == versionString){ 
            return null;
        }else{
            // get version from "htlgb">X.X.X</span>
            playStoreAppVersion = getAppVersion (appVersion_PatternSeq, versionString);
        }

        return playStoreAppVersion;
    }

I got it solved through this, as this works for latest Google playstore changes also. Hope that helps.

VBA copy cells value and format

Instead of setting the value directly you can try using copy/paste, so instead of:

Worksheets(2).Cells(a, 15) = Worksheets(1).Cells(i, 3).Value

Try this:

Worksheets(1).Cells(i, 3).Copy
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteFormats
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteValues

To just set the font to bold you can keep your existing assignment and add this:

If Worksheets(1).Cells(i, 3).Font.Bold = True Then
  Worksheets(2).Cells(a, 15).Font.Bold = True
End If

How to add http:// if it doesn't exist in the URL

Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.

if (false === strpos($url, '://')) {
    $url = 'http://' . $url;
}

Note: This may be a simple and straightforward solution, but Jack's answer using parse_url is almost as simple and much more robust. You should probably use that one.

symfony2 : failed to write cache directory

if symfony version less than 2.8

_x000D_
_x000D_
sudo chmod -R 777 app/cache/*
_x000D_
_x000D_
_x000D_

if symfony version great than or equal 3.0

_x000D_
_x000D_
sudo chmod -R 777 var/cache/*
_x000D_
_x000D_
_x000D_

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Ignoring the check results in a corrupted install. This is the only solution that worked for me:

  1. Create a C# console app with the following code: Console.WriteLine(string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0"));

  2. Run the app and get the 3 digit code.

  3. Run > Regedit, open the following path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib

Now, if you don't have a folder underneath that path with the 3 digit code from step 2, create it. If you do have the folder, check that it has the "Counter" and "Help" values set under that path. It probably doesn't -- which is why the check fails.

Create the missing Counter and Help keys (REG_MULTI_SZ). For the values, copy them from the existing path above (probably 009).

The check should now pass.

How to revert to origin's master branch's version of file

Assuming you did not commit the file, or add it to the index, then:

git checkout -- filename

Assuming you added it to the index, but did not commit it, then:

git reset HEAD filename
git checkout -- filename

Assuming you did commit it, then:

git checkout origin/master filename

Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):

git reset --hard origin/master

Android. WebView and loadData

As I understand it, loadData() simply generates a data: URL with the data provide it.

Read the javadocs for loadData():

If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.

The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):

String data = ...;  // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");

How to sum array of numbers in Ruby?

array.reduce(0, :+)

While equivalent to array.inject(0, :+), the term reduce is entering a more common vernacular with the rise of MapReduce programming models.

inject, reduce, fold, accumulate, and compress are all synonymous as a class of folding functions. I find consistency across your code base most important, but since various communities tend to prefer one word over another, it’s nonetheless useful to know the alternatives.

To emphasize the map-reduce verbiage, here’s a version that is a little bit more forgiving on what ends up in that array.

array.map(&:to_i).reduce(0, :+)

Some additional relevant reading:

What is the maximum length of a Push Notification alert text?

Apple push will reject a string for a variety of reasons. I tested a variety of scenarios for push delivery, and this was my working fix (in python):

#  Apple rejects push payloads > 256 bytes (truncate msg to < 120 bytes to be safe)
if len(push_str) > 120:
    push_str = push_str[0:120-3] + '...'

# Apple push rejects all quotes, remove them
import re
push_str = re.sub("[\"']", '', push_str)

# Apple push needs to newlines escaped
import MySQLdb
push_str = MySQLdb.escape_string(push_str)

# send it
import APNSWrapper
wrapper = APNSWrapper.APNSNotificationWrapper(certificate=...)
message = APNSWrapper.APNSNotification()
message.token(...)
message.badge(1)
message.alert(push_str)
message.sound("default")
wrapper.append(message)
wrapper.notify()

Importing json file in TypeScript

With TypeScript 2.9.+ you can simply import JSON files with typesafety and intellisense like this:

import colorsJson from '../colors.json'; // This import style requires "esModuleInterop", see "side notes"
console.log(colorsJson.primaryBright);

Make sure to add these settings in the compilerOptions section of your tsconfig.json (documentation):

"resolveJsonModule": true,
"esModuleInterop": true,

Side notes:

  • Typescript 2.9.0 has a bug with this JSON feature, it was fixed with 2.9.2
  • The esModuleInterop is only necessary for the default import of the colorsJson. If you leave it set to false then you have to import it with import * as colorsJson from '../colors.json'

MySQL set current date in a DATETIME field on insert

Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.

See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html

How can I add an item to a ListBox in C# and WinForms?

In WinForms, ValueMember and DisplayMember are used when data-binding the list. If you're not data-binding, then you can add any arbitrary object as a ListItem.

The catch to that is that, in order to display the item, ToString() will be called on it. Thus, it is highly recommended that you only add objects to the ListBox where calling ToString() will result in meaningful output.

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

Accessing the index in 'for' loops?

In your question, you write "how do I access the loop index, from 1 to 5 in this case?"

However, the index for a list runs from zero. So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in Python, it is easy to do either or both.

First, to clarify, the enumerate function iteratively returns the index and corresponding item for each item in a list.

alist = [1, 2, 3, 4, 5]

for n, a in enumerate(alist):
    print("%d %d" % (n, a))

The output for the above is then,

0 1
1 2
2 3
3 4
4 5

Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.

If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use

for n, a in enumerate(alist[1:-1]):
    print("%d %d" % (n, a))

Note that once again, the output index runs from 0,

0 2
1 3
2 4

That brings us to the start=n switch for enumerate(). This simply offsets the index, you can equivalently simply add a number to the index inside the loop.

for n, a in enumerate(alist, start=1):
    print("%d %d" % (n, a))

for which the output is

1 1
2 2
3 3
4 4
5 5

Get unique values from arraylist in java

If you have an array of a some kind of object (bean) you can do this:

List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);

like said Mathias Schwarz above, but you have to provide your aBean with the methods hashCode() and equals(Object obj) that can be done easily in Eclipse by dedicated menu 'Generate hashCode() and equals()' (while in the bean Class). Set will evaluate the overridden methods to discriminate equals objects.

In Subversion can I be a user other than my login name?

Go to ~/.subversion/auth/svn.simple/*, and you will see a list of files that contains the information about your svn user account. Just delete all others that you don't need.

After that, when you do anything that regards to SVN operation, such as commit, rm, etc,. You will be prompt again to enter username or passwords.

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

If you are using springboot then jackson is added by default,

So the version of jackson you are adding manualy is probably conflicting with the one spring boot adds,

Try to delete the jackson dependencies from your pom,

If you need to override the version spring boots add, then you need to exclude it first and then add your own

Should I learn C before learning C++?

I'm going to disagree with the majority here. I think you should learn C before learning C++. It's definitely not necessary, but I think it makes learning C++ a lot easier. C is at the heart of C++. Anything you learn about C is applicable to C++, but C is a lot smaller and easier to learn.

Pick up K&R and read through that. It is short and will give you a sufficient sense of the language. Once you have the basics of pointers and function calls down, you can move on to C++ a little easier.

Read file line by line in PowerShell

Not much documentation on PowerShell loops.

Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For, about_ForEach, about_Do, about_While.

foreach($line in Get-Content .\file.txt) {
    if($line -match $regex){
        # Work here
    }
}

Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object cmdlet:

Get-Content .\file.txt | ForEach-Object {
    if($_ -match $regex){
        # Work here
    }
}

Instead of regex matching inside the loop, you could pipe the lines through Where-Object to filter just those you're interested in:

Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
    # Work here
}

How to replace special characters in a string?

Following the example of the Andrzej Doyle's answer, I think the better solution is to use org.apache.commons.lang3.StringUtils.stripAccents():

package bla.bla.utility;

import org.apache.commons.lang3.StringUtils;

public class UriUtility {
    public static String normalizeUri(String s) {
        String r = StringUtils.stripAccents(s);
        r = r.replace(" ", "_");
        r = r.replaceAll("[^\\.A-Za-z0-9_]", "");
        return r;
    }
}

Create SQL identity as primary key?

If you're using T-SQL, the only thing wrong with your code is that you used braces {} instead of parentheses ().

PS: Both IDENTITY and PRIMARY KEY imply NOT NULL, so you can omit that if you wish.

What happened to console.log in IE8?

I'm using Walter's approach from above (see: https://stackoverflow.com/a/14246240/3076102)

I mix in a solution I found here https://stackoverflow.com/a/7967670 to properly show Objects.

This means the trap function becomes:

function trap(){
    if(debugging){
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var index;
        for (index = 0; index < args.length; ++index) {
            //fix for objects
            if(typeof args[index] === 'object'){ 
                args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
            }
        }
        var message = args.join(' ');
        console.messages.push(message);
        // instead of a fallback function we use the next few lines to output logs
        // at the bottom of the page with jQuery
        if($){
            if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
            $('#_console_log').append(message).append($('<br />'));
        }
    }
} 

I hope this is helpful:-)

How to display count of notifications in app launcher icon

Android ("vanilla" android without custom launchers and touch interfaces) does not allow changing of the application icon, because it is sealed in the .apk tightly once the program is compiled. There is no way to change it to a 'drawable' programmatically using standard APIs. You may achieve your goal by using a widget instead of an icon. Widgets are customisable. Please read this :http://www.cnet.com/8301-19736_1-10278814-251.html and this http://developer.android.com/guide/topics/appwidgets/index.html. Also look here: https://github.com/jgilfelt/android-viewbadger. It can help you.

As for badge numbers. As I said before - there is no standard way for doing this. But we all know that Android is an open operating system and we can do everything we want with it, so the only way to add a badge number - is either to use some 3-rd party apps or custom launchers, or front-end touch interfaces: Samsung TouchWiz or Sony Xperia's interface. Other answers use this capabilities and you can search for this on stackoverflow, e.g. here. But I will repeat one more time: there is no standard API for this and I want to say it is a bad practice. App's icon notification badge is an iOS pattern and it should not be used in Android apps anyway. In Andrioid there is a status bar notifications for these purposes:http://developer.android.com/guide/topics/ui/notifiers/notifications.html So, if Facebook or someone other use this - it is not a common pattern or trend we should consider. But if you insist anyway and don't want to use home screen widgets then look here, please:

How does Facebook add badge numbers on app icon in Android?

As you see this is not an actual Facebook app it's TouchWiz. In vanilla android this can be achieved with Nova Launcher http://forums.androidcentral.com/android-applications/199709-how-guide-global-badge-notifications.html So if you will see icon badges somewhere, be sure it is either a 3-rd party launcher or touch interface (frontend wrapper). May be sometime Google will add this capability to the standard Android API.

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

How do you change library location in R?

I've used this successfully inside R script:

library("reshape2",lib.loc="/path/to/R-packages/")

useful if for whatever reason libraries are in more than one place.

How to delete object from array inside foreach loop?

You can also use references on foreach values:

foreach($array as $elementKey => &$element) {
    // $element is the same than &$array[$elementKey]
    if (isset($element['id']) and $element['id'] == 'searched_value') {
        unset($element);
    }
}

Adding header for HttpURLConnection

Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes variable is a byte[] and not a String value. If you pass the byte[] to a new String() as below, the code snippet works perfectly.

encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);

How to download Google Play Services in an Android emulator?

Check out Setting Up Google Play Services which says:

To develop an app using the Google Play services APIs, you need to set up your project with the Google Play services SDK.

If you haven't installed the Google Play services SDK yet, go get it now by following the guide to Adding SDK Packages.

To test your app when using the Google Play services SDK, you must use either:

  • A compatible Android device that runs Android 2.3 or higher and includes Google Play Store.
  • The Android emulator with an AVD that runs the Google APIs platform based on Android 4.2.2 or higher.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

Use window.confirm() instead of window.alert().

HTML:

<input type="submit" onclick="return clicked();" value="Button" />

JavaScript:

function clicked() {
    return confirm('clicked');
}

Python Anaconda - How to Safely Uninstall

In my case Anaconda3 was not installed in home directory. Instead, it was installed in root. Therefore, I had to do the following to get it uninstalled:

sudo rm -rf /anaconda3/bin/python

How can I get the current directory name in Javascript?

For both / and \:

window.location.pathname.replace(/[^\\\/]*$/, '');

To return without the trailing slash, do:

window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');

How to clear a data grid view

YourGrid.Items.Clear();
YourGrid.Items.Refresh();

Git for beginners: The definitive practical guide

Here's a copy of PJ Hyett's post, as it is not available anymore:

Git Isn't Hard

Nov 23, 2008

When we tell people why they should use Git over Subversion, the go-to line is, “Git does Subversion better than Subversion, but it does a lot more than that.”

The “lot more” is comprised of a bunch of stuff that makes Git really shine, but it can be pretty overwhelming for those coming from other SCM’s like Subversion.

That said, there’s nothing stopping you from using Git just like you use Subversion while you’re making the transition.

Assuming you’ve installed the necessary software and have a remote repository somewhere, this is how you would grab the code and push your changes back with Subversion:

$ svn checkout svn://foo.googlecode.com/svn/trunk foo
# make your changes
$ svn commit -m "my first commit"

And how would you do it in Git:

$ git clone [email protected]:pjhyett/foo.git
# make your changes
$ git commit -a -m "my first commit"
$ git push

One more command to make it happen in Git. That extra command has large implications, but for the purposes of this post, that’s all we’re talking about, one extra command.

See, it really isn’t that hard.

Update: I’d be remiss to not also mention that the equivalent of updating your local copy in Subversion compared to Git is svn update and git pull, respectively. Only one command in both cases.

Update Angular model after setting input value with jQuery

Hope this is useful for someone.

I was unable to get the jQuery('#myInputElement').trigger('input') event to be picked up my angular app.

I was however, able to get angular.element(jQuery('#myInputElement')).triggerHandler('input') to be picked up.

how to change the dist-folder path in angular-cli after 'ng build'

For Angular 6+ things have changed a little.

Define where ng build generates app files

Cli setup is now done in angular.json (replaced .angular-cli.json) in your workspace root directory. The output path in default angular.json should look like this (irrelevant lines removed):

{
  "projects": {
    "my-app-name": {
    "architect": {
      "options": {
         "outputPath": "dist/my-app-name",

Obviously, this will generate your app in WORKSPACE/dist/my-app-name. Modify outputPath if you prefer another directory.

You can overwrite the output path using command line arguments (e.g. for CI jobs):

ng build -op dist/example
ng build --output-path=dist/example

S.a. https://github.com/angular/angular-cli/wiki/build

Hosting angular app in subdirectory

Setting the output path, will tell angular where to place the "compiled" files but however you change the output path, when running the app, angular will still assume that the app is hosted in the webserver's document root.

To make it work in a sub directory, you'll have to set the base href.

In angular.json:

{
  "projects": {
    "my-app-name": {
    "architect": {
      "options": {
         "baseHref": "/my-folder/",

Cli:

ng build --base-href=/my-folder/

If you don't know where the app will be hosted on build time, you can change base tag in generated index.html.

Here's an example how we do it in our docker container:

entrypoint.sh

if [ -n "${BASE_PATH}" ]
then
  files=( $(find . -name "index.html") )
  cp -n "${files[0]}" "${files[0]}.org"
  cp "${files[0]}.org" "${files[0]}"
  sed -i "s*<base href=\"/\">*<base href=\"${BASE_PATH}\">*g" "${files[0]}"
fi

how to assign a block of html code to a javascript variable

we can use backticks (``) without any error.. eg: <div>"test"<div>

we can store large template(HTML) inside the backticks which was introduced in ES6 javascript standard

No need to escape any special characters

if no backticks.. we need to escape characters by appending backslash() eg:" \"test\""

MINGW64 "make build" error: "bash: make: command not found"

You can also use Chocolatey.

Having it installed, just run:

choco install make

When it finishes, it is installed and available in Git for Bash / MinGW.

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

Convert UTC/GMT time to local time

In answer to Dana's suggestion:

The code sample now looks like:

string date = "Web service date"..ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            
DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(convertedDate);

The original date was 20/08/08; the kind was UTC.

Both "convertedDate" and "dt" are the same:

21/08/08 10:00:26; the kind was local

Adding data attribute to DOM

Using .data() will only add data to the jQuery object for that element. In order to add the information to the element itself you need to access that element using jQuery's .attr or native .setAttribute

$('div').attr('data-info', 1);
$('div')[0].setAttribute('data-info',1);

In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ($('div[data-info="1"]')), but when you use .data() you cannot. In order to select based on the .data() setting, you would need to use jQuery's filter function.

jsFiddle Demo

_x000D_
_x000D_
$('div').data('info', 1);_x000D_
//alert($('div').data('info'));//1_x000D_
_x000D_
$('div').filter(function(){_x000D_
   return $(this).data('info') == 1; _x000D_
}).text('222');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>1</div>
_x000D_
_x000D_
_x000D_

How to calculate rolling / moving average using NumPy / SciPy?

This answer using Pandas is adapted from above, as rolling_mean is not part of Pandas anymore

# the recommended syntax to import pandas
import pandas as pd
import numpy as np

# prepare some fake data:
# the date-time indices:
t = pd.date_range('1/1/2010', '12/31/2012', freq='D')

# the data:
x = np.arange(0, t.shape[0])

# combine the data & index into a Pandas 'Series' object
D = pd.Series(x, t)

Now, just call the function rolling on the dataframe with a window size, which in my example below is 10 days.

d_mva10 = D.rolling(10).mean()

# d_mva is the same size as the original Series
# though obviously the first w values are NaN where w is the window size
d_mva10[:11]

2010-01-01    NaN
2010-01-02    NaN
2010-01-03    NaN
2010-01-04    NaN
2010-01-05    NaN
2010-01-06    NaN
2010-01-07    NaN
2010-01-08    NaN
2010-01-09    NaN
2010-01-10    4.5
2010-01-11    5.5
Freq: D, dtype: float64

Delete specific line number(s) from a text file using sed?

$ cat foo
1
2
3
4
5
$ sed -e '2d;4d' foo
1
3
5
$ 

How to create a table from select query result in SQL Server 2008

Select [Column Name] into [New Table] from [Source Table]

Convert Data URI to File then append to FormData

Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer

function dataURItoBlob(dataURI) {
    'use strict'
    var byteString, 
        mimestring 

    if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
        byteString = atob(dataURI.split(',')[1])
    } else {
        byteString = decodeURI(dataURI.split(',')[1])
    }

    mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

    var content = new Array();
    for (var i = 0; i < byteString.length; i++) {
        content[i] = byteString.charCodeAt(i)
    }

    return new Blob([new Uint8Array(content)], {type: mimestring});
}

Pylint "unresolved import" error in Visual Studio Code

This issue has already been opened on GitHub:

Python unresolved import issue #3840

There are two very useful answers, by MagnuesBrzenk and SpenHouet.

The best solution for now is to create a .env file in your project root folder. Then add a PYTHONPATH to it like this:

PYTHONPATH=YOUR/MODULES/PATH

And in your settings.json add:

"python.envFile": ".env"

What is the difference between a token and a lexeme?

Lexeme is basically the unit of a token and it is basically sequence of characters that matches the token and helps to break the source code into tokens.

For example: If the source is x=b, then the lexemes would be x, =, b and the tokens would be <id, 0>, <=>, <id, 1>.

open resource with relative path in Java

In Order to obtain real path to the file you can try this:

URL fileUrl = Resourceloader.class.getResource("resources/repository/SSL-Key/cert.jks");
String pathToClass = fileUrl.getPath;    

Resourceloader is classname here. "resources/repository/SSL-Key/cert.jks" is relative path to the file. If you had your guiclass in ./package1/java with rest of folder structure remaining, you would take "../resources/repository/SSL-Key/cert.jks" as relative path because of rules defining relative path.

This way you can read your file with BufferedReader. DO NOT USE THE STRING to identify the path to the file, because if you have spaces or some characters from not english alphabet in your path, you will get problems and the file will not be found.

BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(fileUrl.openStream()));

How to represent multiple conditions in a shell if statement?

In bash for string comparison, you can use the following technique.

if [ $var OP "val" ]; then
    echo "statements"
fi

Example:

var="something"
if [ $var != "otherthing" ] && [ $var != "everything" ] && [ $var != "allthings" ]; then
    echo "this will be printed"
else
    echo "this will not be printed"
fi

How to do an array of hashmaps?

Java doesn't want you to make an array of HashMaps, but it will let you make an array of Objects. So, just write up a class declaration as a shell around your HashMap, and make an array of that class. This lets you store some extra data about the HashMaps if you so choose--which can be a benefit, given that you already have a somewhat complex data structure.

What this looks like:

private static someClass[] arr = new someClass[someNum];

and

public class someClass {

private static int dataFoo;
private static int dataBar;
private static HashMap<String, String> yourArray;

...

}

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

How can I make a program wait for a variable change in javascript?

JavaScript is one of the worst program\scripting language ever!

"Wait" seems to be impossible in JavaScript! (Yes, like in the real life, sometimes waiting is the best option!)

I tried "while" loop and "Recursion" (a function calls itself repeatedly until ...), but JavaScript refuses to work anyway! (This is unbelievable, but anyway, see the codes below:)

while loop:

<!DOCTYPE html>

<script>

var Continue = "no";
setTimeout(function(){Continue = "yes";}, 5000);    //after 5 seconds, "Continue" is changed to "yes"

while(Continue === 'no'){};    //"while" loop will stop when "Continue" is changed to "yes" 5 seconds later

    //the problem here is that "while" loop prevents the "setTimeout()" to change "Continue" to "yes" 5 seconds later
    //worse, the "while" loop will freeze the entire browser for a brief time until you click the "stop" script execution button

</script>

Recursion:

<!DOCTYPE html>

1234

<script>

function Wait_If(v,c){
if (window[v] === c){Wait_If(v,c)};
};

Continue_Code = "no"
setTimeout(function(){Continue_Code = "yes";}, 5000);    //after 5 seconds, "Continue_Code" is changed to "yes"

Wait_If('Continue_Code', 'no');

    //the problem here, the javascript console trows the "too much recursion" error, because "Wait_If()" function calls itself repeatedly!

document.write('<br>5678');     //this line will not be executed because of the "too much recursion" error above!

</script>

How to check whether java is installed on the computer

Go to this link and wait for a while to load.

http://www.java.com/en/download/testjava.jsp

You will see the below image: enter image description here

You can alternatively open command window and type java -version

Error handling in AngularJS http get then construct

I could not really work with the above. So this might help someone.

$http.get(url)
  .then(
    function(response) {
        console.log('get',response)
    }
  ).catch(
    function(response) {
    console.log('return code: ' + response.status);
    }
  )

See also the $http response parameter.

Reset local repository branch to be just like remote repository HEAD

The question mixes two issues here:

  1. how to reset a local branch to the point where the remote is
  2. how to clear your staging area (and possibly the working directory), so that git status says nothing to commit, working directory clean.

The one-stop-answer is:

  1. git fetch --prune (optional) Updates the local snapshot of the remote repo. Further commands are local only.
    git reset --hard @{upstream}Puts the local branch pointer to where the snapshot of the remote is, as well as set the index and the working directory to the files of that commit.
  2. git clean -d --force Removes untracked files and directories which hinder git to say “working directory clean”.

How to use css style in php

I didn't understood this Im new to php css but as you've defined your CSS at element level, already your styles are applied to your PHP code

Your PHP code is to be used with HTML like this

<!DOCTYPE html>
<html>
  <head>
    <style>
    /* Styles Go Here */
    </style>
  </head>
  <body>
  <?php
   echo 'Whatever'; 
  ?>
  </body>
</html>

Also remember, you did not need to echo HTML using php, simply separate them out like this

<table>
  <tr>
    <td><?php echo 'Blah'; ?></td>
  </tr>
</table>

Mismatched anonymous define() module

Per the docs:

If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.

Also seen if you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.

Finally, if you use the loader plugins or anonymous modules (modules that call define() with no string ID) but do not use the RequireJS optimizer to combine files together, this error can occur. The optimizer knows how to name anonymous modules correctly so that they can be combined with other modules in an optimized file.

To avoid the error:

  • Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.

  • If you manually code an HTML script tag, be sure it only includes named modules, and that an anonymous module that will have the same name as one of the modules in that file is not loaded.

  • If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer.

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Make a number a percentage

Numeral.js is a library I created that can can format numbers, currency, percentages and has support for localization.

numeral(0.7523).format('0%') // returns string "75%"

Best way to compare 2 XML documents in Java

Building on Tom's answer, here's an example using XMLUnit v2.

It uses these maven dependencies

    <dependency>
        <groupId>org.xmlunit</groupId>
        <artifactId>xmlunit-core</artifactId>
        <version>2.0.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.xmlunit</groupId>
        <artifactId>xmlunit-matchers</artifactId>
        <version>2.0.0</version>
        <scope>test</scope>
    </dependency>

..and here's the test code

import static org.junit.Assert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
import org.xmlunit.builder.Input;
import org.xmlunit.input.WhitespaceStrippedSource;

public class SomeTest extends XMLTestCase {
    @Test
    public void test() {
        String result = "<root></root>";
        String expected = "<root>  </root>";

        // ignore whitespace differences
        // https://github.com/xmlunit/user-guide/wiki/Providing-Input-to-XMLUnit#whitespacestrippedsource
        assertThat(result, isIdenticalTo(new WhitespaceStrippedSource(Input.from(expected).build())));

        assertThat(result, isIdenticalTo(Input.from(expected).build())); // will fail due to whitespace differences
    }
}

The documentation that outlines this is https://github.com/xmlunit/xmlunit#comparing-two-documents

Github permission denied: ssh add agent has no identities

Full details in this answer.

In summary, when ssh-add -l returns “The agent has no identities”, it means that keys used by ssh (stored in files such as ~/.ssh/id_rsa, ~/.ssh/id_dsa, etc.) are either missing, they are not known to ssh-agent, which is the authentication agent, or that their permissions are set incorrectly (for example, world writable).

If your keys are missing or if you have not generated any, use ssh-keygen -t rsa, then ssh-add to add them.

If keys exist but are not known to ssh-agent (like if they are in a non-standard folder), use ssh-add /path/to/my-non-standard-ssh-folder/id_rsa to add them.

See this answer if you are having trouble with ssh-add or ssh-agent.

accepting HTTPS connections with self-signed certificates

Jan 19th, 2020 Self Signed Certificate ISSUE FIX:

To play video , image , calling webservice for any self signed certificate or connecting to any unsecured url just call this method before performing any action , it will fix your issue regarding certificate issue :

KOTLIN CODE

  private fun disableSSLCertificateChecking() {
        val hostnameVerifier = object: HostnameVerifier {
            override fun verify(s:String, sslSession: SSLSession):Boolean {
                return true
            }
        }
        val trustAllCerts = arrayOf<TrustManager>(object: X509TrustManager {
            override fun getAcceptedIssuers(): Array<X509Certificate> {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            //val acceptedIssuers:Array<X509Certificate> = null
            @Throws(CertificateException::class)
            override fun checkClientTrusted(arg0:Array<X509Certificate>, arg1:String) {// Not implemented
            }
            @Throws(CertificateException::class)
            override fun checkServerTrusted(arg0:Array<X509Certificate>, arg1:String) {// Not implemented
            }
        })
        try
        {
            val sc = SSLContext.getInstance("TLS")
            sc.init(null, trustAllCerts, java.security.SecureRandom())
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory())
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier)
        }
        catch (e: KeyManagementException) {
            e.printStackTrace()
        }
        catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
    }

What is the best way to generate a unique and short file name in Java

I'd use Apache Commons Lang library (http://commons.apache.org/lang).

There is a class org.apache.commons.lang.RandomStringUtils that can be used to generate random strings of given length. Very handy not only for filename generation!

Here is the example:

String ext = "dat";
File dir = new File("/home/pregzt");
String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext);
File file = new File(dir, name);

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

recyclerview No adapter attached; skipping layout

i have this problem , a few time problem is recycleView put in ScrollView object

After checking implementation, the reason appears to be the following. If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and, as a result, gets equal to minimum height (as per implementation) which is apparently zero.

You have couple of options for fixing this:

  1. Set a certain height to RecyclerView
  2. Set ScrollView.fillViewport to true
  3. Or keep RecyclerView outside of ScrollView. In my opinion, this is the best option by far. If RecyclerView height is not limited - which is the case when it's put into ScrollView - then all Adapter's views have enough place vertically and get created all at once. There is no view recycling anymore which kinda breaks the purpose of RecyclerView .

(Can be followed for android.support.v4.widget.NestedScrollView as well)

Git cli: get user info from username

git config user.name
git config user.email

I believe these are the commands you are looking for.

Here is where I found them: http://alvinalexander.com/git/git-show-change-username-email-address

How to quietly remove a directory with content in PowerShell

$LogPath = "E:\" # Your local of directories
$Folders = Get-Childitem $LogPath -dir -r | Where-Object {$_.name -like "*temp*"}
foreach ($Folder in $Folders) 
{
    $Item =  $Folder.FullName
    Write-Output $Item
    Remove-Item $Item -Force -Recurse
}

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

Spring MVC @PathVariable with dot (.) is getting truncated

As far as i know this issue appears only for the pathvariable at the end of the requestmapping.

We were able to solve that by defining the regex addon in the requestmapping.

 /somepath/{variable:.+}

What does "select count(1) from table_name" on any database tables mean?

in oracle i believe these have exactly the same meaning

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Believe or not, keytool does not provide such basic functionality like importing private key to keystore. You can try this workaround with merging PKSC12 file with private key to a keystore:

keytool -importkeystore \
  -deststorepass storepassword \
  -destkeypass keypassword \
  -destkeystore my-keystore.jks \
  -srckeystore cert-and-key.p12 \
  -srcstoretype PKCS12 \
  -srcstorepass p12password \
  -alias 1

Or just use more user-friendly KeyMan from IBM for keystore handling instead of keytool.

Is true == 1 and false == 0 in JavaScript?

Use === to equate the variables instead of ==.

== checks if the value of the variables is similar

=== checks if the value of the variables and the type of the variables are similar

Notice how

if(0===false) {
    document.write("oh!!! that's true");
}?

and

if(0==false) {
    document.write("oh!!! that's true");
}?

give different results