Programs & Examples On #Text align

a property of CSS which determines the alignment of the text

How to dynamically add a style for text-align using jQuery

Is correct?

<script>
$( "#box" ).one( "click", function() {
  $( this ).css( "width", "+=200" );
});
</script>

Align printf output in Java

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.

Align contents inside a div

Just another example using HTML and CSS:

<div style="width: Auto; margin: 0 auto;">Hello</div>

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

CSS text-align: center; is not centering things

To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

How to center images on a web page for all screen sizes

In your specific case, you can set the containing a element to be:

a {
    display: block;
    text-align: center;
}

JS Bin demo.

Text-align class for inside a table

Just add a "custom" stylesheet which is loaded after Bootstrap´s stylesheet. So the class definitions are overloaded.

In this stylesheet declare the alignment as follows:

.table .text-right {text-align: right}
.table .text-left {text-align: left}
.table .text-center {text-align: center}

Now you are able to use the "common" alignment conventions for td and th elements.

Is there an easy way to return a string repeated X number of times?

You can create an ExtensionMethod to do that!

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    string ret = "";

    for (var x = 0; x < count; x++)
    {
      ret += str;
    }

    return ret;
  }
}

Or using @Dan Tao solution:

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    if (count == 0)
      return "";

    return string.Concat(Enumerable.Repeat(indent, N))
  }
}

Sorting an IList in C#

Convert your IList into List<T> or some other generic collection and then you can easily query/sort it using System.Linq namespace (it will supply bunch of extension methods)

Get domain name from given url

To get the actual domain name, without the subdomain, I use:

private String getDomainName(String url) throws URISyntaxException {
    String hostName = new URI(url).getHost();
    if (!hostName.contains(".")) {
        return hostName;
    }
    String[] host = hostName.split("\\.");
    return host[host.length - 2];
}

Note that this won't work with second-level domains (like .co.uk).

how do I change text in a label with swift?

use a simple formula: WHO.WHAT = VALUE

where,

WHO is the element in the storyboard you want to make changes to for eg. label

WHAT is the property of that element you wish to change for eg. text

VALUE is the change that you wish to be displayed

for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1

In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road

so our final code will be as follows: Final code

screenshot 1 changes to screenshot 2 once the above code is executed.

I hope this solution helps you solve your issue. Thank you!

How to find files that match a wildcard string in Java?

The wildcard library efficiently does both glob and regex filename matching:

http://code.google.com/p/wildcard/

The implementation is succinct -- JAR is only 12.9 kilobytes.

Creating a node class in Java

Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:

public class ItemLinkedList {
    private ItemInfoNode head;
    private ItemInfoNode tail;
    private int size = 0;

    public int getSize() {
        return size;
    }

    public void addBack(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, null, tail);
            this.tail.next =node;
            this.tail = node;
        }
    }

    public void addFront(ItemInfo info) {
        size++;
        if (head == null) {
            head = new ItemInfoNode(info, null, null);
            tail = head;
        } else {
            ItemInfoNode node = new ItemInfoNode(info, head, null);
            this.head.prev = node;
            this.head = node;
        }
    }

    public ItemInfo removeBack() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = tail.info;
            if (tail.prev != null) {
                tail.prev.next = null;
                tail = tail.prev;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public ItemInfo removeFront() {
        ItemInfo result = null;
        if (head != null) {
            size--;
            result = head.info;
            if (head.next != null) {
                head.next.prev = null;
                head = head.next;
            } else {
                head = null;
                tail = null;
            }
        }
        return result;
    }

    public class ItemInfoNode {

        private ItemInfoNode next;
        private ItemInfoNode prev;
        private ItemInfo info;

        public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
            this.info = info;
            this.next = next;
            this.prev = prev;
        }

        public void setInfo(ItemInfo info) {
            this.info = info;
        }

        public void setNext(ItemInfoNode node) {
            next = node;
        }

        public void setPrev(ItemInfoNode node) {
            prev = node;
        }

        public ItemInfo getInfo() {
            return info;
        }

        public ItemInfoNode getNext() {
            return next;
        }

        public ItemInfoNode getPrev() {
            return prev;
        }
    }
}

EDIT:

Declare ItemInfo as this:

public class ItemInfo {
    private String name;
    private String rfdNumber;
    private double price;
    private String originalPosition;

    public ItemInfo(){
    }

    public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
        this.name = name;
        this.rfdNumber = rfdNumber;
        this.price = price;
        this.originalPosition = originalPosition;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRfdNumber() {
        return rfdNumber;
    }

    public void setRfdNumber(String rfdNumber) {
        this.rfdNumber = rfdNumber;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getOriginalPosition() {
        return originalPosition;
    }

    public void setOriginalPosition(String originalPosition) {
        this.originalPosition = originalPosition;
    }
}

Then, You can use your nodes inside the linked list like this:

public static void main(String[] args) {
    ItemLinkedList list = new ItemLinkedList();
    for (int i = 1; i <= 10; i++) {
        list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));

    }
    while (list.size() > 0){
        System.out.println(list.removeFront().getName());
    }
}

How do I get the HTML code of a web page in PHP?

I tried this code and it's working for me .

$html = file_get_contents('www.google.com');
$myVar = htmlspecialchars($html, ENT_QUOTES);
echo($myVar);

How can I load Partial view inside the view?

If you do it with a @Html.ActionLink() then loading the PartialView is handled as a normal request when clicking a anchor-element, i.e. load new page with the reponse of the PartialViewResult method.
If you want to load it immedialty, then you use @Html.RenderPartial("_LoadView") or @Html.RenderAction("Load").
If you want to do it upon userinteraction (i.e. clicking a link) then you need to use AJAX --> @Ajax.ActionLink()

NullInjectorError: No provider for AngularFirestore

Change Your Import From :

import { AngularFirestore } from '@angular/fire/firestore/firestore';

To This :

import { AngularFirestore } from '@angular/fire/firestore';

This solve my problem.

Find the files existing in one directory but not in the other

Unsatisfied with all the replies, since most of them work very slowly and produce unnecessarily long output for large directories, I wrote my own Python script to compare two folders.

Unlike many other solutions, it doesn't compare contents of the files. Also it doesn't go inside subdirectories which are missing in another directory. So the output is quite concise and the script works fast.

#!/usr/bin/env python3

import os, sys

def compare_dirs(d1: "old directory name", d2: "new directory name"):
    def print_local(a, msg):
        print('DIR ' if a[2] else 'FILE', a[1], msg)
    # ensure validity
    for d in [d1,d2]:
        if not os.path.isdir(d):
            raise ValueError("not a directory: " + d)
    # get relative path
    l1 = [(x,os.path.join(d1,x)) for x in os.listdir(d1)]
    l2 = [(x,os.path.join(d2,x)) for x in os.listdir(d2)]
    # determine type: directory or file?
    l1 = sorted([(x,y,os.path.isdir(y)) for x,y in l1])
    l2 = sorted([(x,y,os.path.isdir(y)) for x,y in l2])
    i1 = i2 = 0
    common_dirs = []
    while i1<len(l1) and i2<len(l2):
        if l1[i1][0] == l2[i2][0]:      # same name
            if l1[i1][2] == l2[i2][2]:  # same type
                if l1[i1][2]:           # remember this folder for recursion
                    common_dirs.append((l1[i1][1], l2[i2][1]))
            else:
                print_local(l1[i1],'type changed')
            i1 += 1
            i2 += 1
        elif l1[i1][0]<l2[i2][0]:
            print_local(l1[i1],'removed')
            i1 += 1
        elif l1[i1][0]>l2[i2][0]:
            print_local(l2[i2],'added')
            i2 += 1
    while i1<len(l1):
        print_local(l1[i1],'removed')
        i1 += 1
    while i2<len(l2):
        print_local(l2[i2],'added')
        i2 += 1
    # compare subfolders recursively
    for sd1,sd2 in common_dirs:
        compare_dirs(sd1, sd2)

if __name__=="__main__":
    compare_dirs(sys.argv[1], sys.argv[2])

Sample usage:

user@laptop:~$ python3 compare_dirs.py dir1/ dir2/
DIR  dir1/out/flavor-domino removed
DIR  dir2/out/flavor-maxim2 added
DIR  dir1/target/vendor/flavor-domino removed
DIR  dir2/target/vendor/flavor-maxim2 added
FILE dir1/tmp/.kconfig-flavor_domino removed
FILE dir2/tmp/.kconfig-flavor_maxim2 added
DIR  dir2/tools/tools/LiveSuit_For_Linux64 added

Or if you want to see only files from the first directory:

user@laptop:~$ python3 compare_dirs.py dir2/ dir1/ | grep dir1
DIR  dir1/out/flavor-domino added
DIR  dir1/target/vendor/flavor-domino added
FILE dir1/tmp/.kconfig-flavor_domino added

P.S. If you need to compare file sizes and file hashes for potential changes, I published an updated script here: https://gist.github.com/amakukha/f489cbde2afd32817f8e866cf4abe779

Unsupported major.minor version 52.0 when rendering in Android Studio

This is bug in Android Studio. Usually you get error: Unsupported major.minor version 52.0

WORKAROUND: If you have installed Android N, change Android rendering version with older one and the problem will disappear.

SOLUTION: Install Android SDK Tools 25.1.3 (tools) or higher

enter image description here

How to set commands output as a variable in a batch file

If you don't want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:

FOR /F %i IN ('findstr testing') DO set VARIABLE=%i
echo %VARIABLE%

If you want to enclose search string in double quotes:

FOR /F %i IN ('findstr "testing"') DO set VARIABLE=%i

If you want to store this code in a batch file, add an extra % symbol:

FOR /F %%i IN ('findstr "testing"') DO set VARIABLE=%%i

A useful example to count the number of files in a directory & store in a variable: (illustrates piping)

FOR /F %i IN ('dir /b /a-d "%cd%" ^| find /v /c "?"') DO set /a count=%i

Note the use of single quotes instead of double quotes " or grave accent ` in the command brackets. This is cleaner alternative to delims, tokens or usebackq in for loop.

Tested on Win 10 CMD.

Properly close mongoose's connection once you're done

Probably you have this:

const db = mongoose.connect('mongodb://localhost:27017/db');

// Do some stuff

db.disconnect();

but you can also have something like this:

mongoose.connect('mongodb://localhost:27017/db');

const model = mongoose.model('Model', ModelSchema);

model.find().then(doc => {
  console.log(doc);
}

you cannot call db.disconnect() but you can close the connection after you use it.

model.find().then(doc => {
  console.log(doc);
}).then(() => {
  mongoose.connection.close();
});

How do I load an HTML page in a <div> using JavaScript?

If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash

For ex : <iframe src="home.html" width="100" height="100"/>

How to fill OpenCV image with one solid color?

Using the OpenCV C API with IplImage* img:

Use cvSet(): cvSet(img, CV_RGB(redVal,greenVal,blueVal));

Using the OpenCV C++ API with cv::Mat img, then use either:

cv::Mat::operator=(const Scalar& s) as in:

img = cv::Scalar(redVal,greenVal,blueVal);

or the more general, mask supporting, cv::Mat::setTo():

img.setTo(cv::Scalar(redVal,greenVal,blueVal));

How to pass an event object to a function in Javascript?

I would change your binding to be:

<button type="button" value="click me" onclick="check_me" />

I would then change your check_me() function declaration to be:

function check_me() {   
  //event.preventDefault();
  var hello = document.myForm.username.value;
  var err = '';

  if(hello == '' || hello == null) {
    err = 'User name required';
  }

  if(err != '') { 
     alert(err); 
     $('username').focus(); 
     event.preventDefault(); 
   } else { 
    return true; }
}

Add a summary row with totals

This is the more powerful grouping / rollup syntax you'll want to use in SQL Server 2008+. Always useful to specify the version you're using so we don't have to guess.

SELECT 
  [Type] = COALESCE([Type], 'Total'), 
  [Total Sales] = SUM([Total Sales])
FROM dbo.Before
GROUP BY GROUPING SETS(([Type]),());

Craig Freedman wrote a great blog post introducing GROUPING SETS.

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

How to copy files from host to Docker container?

I just started using docker to compile VLC, here's what you can do to copy files back and forth from containers:

su -
cd /var/lib/docker
ls -palR > /home/user/dockerfilelist.txt

Search for a familiar file in that txt and you'll have the folder, cd to it as root and voila! copy all you want.

There might be a path with "merged" in it, I guess you want the one with "diff" in it.

Also if you exit the container and want to be back where you left off:

docker ps -a
docker start -i containerid

I guess that's usefull when you didn't name anything with a command like

docker run -it registry.videolan.org:5000/vlc-debian-win64 /bin/bash

Sure the hacker method but so what!

https with WCF error: "Could not find base address that matches scheme https"

It turned out that my problem was that I was using a load balancer to handle the SSL, which then sent it over http to the actual server, which then complained.

Description of a fix is here: http://blog.hackedbrain.com/2006/09/26/how-to-ssl-passthrough-with-wcf-or-transportwithmessagecredential-over-plain-http/

Edit: I fixed my problem, which was slightly different, after talking to microsoft support.

My silverlight app had its endpoint address in code going over https to the load balancer. The load balancer then changed the endpoint address to http and to point to the actual server that it was going to. So on each server's web config I added a listenUri for the endpoint that was http instead of https

<endpoint address="" listenUri="http://[LOAD_BALANCER_ADDRESS]" ... />

change type of input field with jQuery

It's very likely this action is prevented as part of the browser's security model.

Edit: indeed, testing right now in Safari, I get the error type property cannot be changed.

Edit 2: that seems to be an error straight out of jQuery. Using the following straight DOM code works just fine:

var pass = document.createElement('input');
pass.type = 'password';
document.body.appendChild(pass);
pass.type = 'text';
pass.value = 'Password';

Edit 3: Straight from the jQuery source, this seems to be related to IE (and could either be a bug or part of their security model, but jQuery isn't specific):

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
    throw "type property can't be changed";

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Convert Text to Date?

To the OP... I also got a type mismatch error the first time I tried running your subroutine. In my case it was cause by non-date-like data in the first cell (i.e. a header). When I changed the contents of the header cell to date-style txt for testing, it ran just fine...

Hope this helps as well.

How to decode viewstate

Here's an online ViewState decoder:

http://ignatu.co.uk/ViewStateDecoder.aspx

Edit: Unfortunatey, the above link is dead - here's another ViewState decoder (from the comments):

http://viewstatedecoder.azurewebsites.net/

Setting the character encoding in form submit for Internet Explorer

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

How to conditionally take action if FINDSTR fails to find a string

I tried to get this working using FINDSTR, but for some reason my "debugging" command always output an error level of 0:

ECHO %ERRORLEVEL%

My workaround is to use Grep from Cygwin, which outputs the right errorlevel (it will give an errorlevel greater than 0) if a string is not found:

dir c:\*.tib >out 2>>&1
grep "1 File(s)" out
IF %ERRORLEVEL% NEQ 0 "Run other commands" ELSE "Run Errorlevel 0 commands"

Cygwin's grep will also output errorlevel 2 if the file is not found. Here's the hash from my version:

C:\temp\temp>grep --version grep (GNU grep) 2.4.2

C:\cygwin64\bin>md5sum grep.exe c0a50e9c731955628ab66235d10cea23 *grep.exe

C:\cygwin64\bin>sha1sum grep.exe ff43a335bbec71cfe99ce8d5cb4e7c1ecdb3db5c *grep.exe

.bashrc: Permission denied

If you want to edit that file (or any file in generally), you can't edit it simply writing its name in terminal. You must to use a command to a text editor to do this. For example:

nano ~/.bashrc

or

gedit ~/.bashrc

And in general, for any type of file:

xdg-open ~/.bashrc

Writing only ~/.bashrc in terminal, this will try to execute that file, but .bashrc file is not meant to be an executable file. If you want to execute the code inside of it, you can source it like follow:

source ~/.bashrc

or simple:

. ~/.bashrc 

How to define custom exception class in Java, the easiest way?

Reason for this is explained in the Inheritance article of the Java Platform which says:

"A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass."

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

Array.size() vs Array.length

array.length isn't necessarily the number of items in the array:

var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101

The length of the array is one more than the highest index.

As stated before Array.size() is not a valid method.

More information

How do I configure modprobe to find my module?

I think the key is to copy the module to the standard paths.

Once that is done, modprobe only accepts the module name, so leave off the path and ".ko" extension.

Is it correct to use alt tag for an anchor link?

You should use the title attribute for anchor tags if you wish to apply descriptive information similarly as you would for an alt attribute. The title attribute is valid on anchor tags and is serves no other purpose than providing information about the linked page.

W3C recommends that the value of the title attribute should match the value of the title of the linked document but it's not mandatory.

http://www.w3.org/MarkUp/1995-archive/Elements/A.html


Alternatively, and likely to be more beneficial, you can use the ARIA accessibility attribute aria-label (not to be confused with aria-labeledby). aria-label serves the same function as the alt attribute does for images but for non-image elements and includes some measure of optimization since your optimizing for screen readers.

http://www.w3.org/WAI/GL/wiki/Using_aria-label_to_provide_labels_for_objects


If you want to describe an anchor tag though, it's usually appropriate to use the rel or rev tag but your limited to specific values, they should not be used for human readable descriptions.

Rel serves to describe the relationship of the linked page to the current page. (e.g. if the linked page is next in a logical series it would be rel=next)

The rev attribute is essentially the reverse relationship of the rel attribute. Rev describes the relationship of the current page to the linked page.

You can find a list of valid values here: http://microformats.org/wiki/existing-rel-values

How to copy data from one table to another new table in MySQL?

This will do what you want:

INSERT INTO table2 (st_id,uid,changed,status,assign_status)
SELECT st_id,from_uid,now(),'Pending','Assigned'
FROM table1

If you want to include all rows from table1. Otherwise you can add a WHERE statement to the end if you want to add only a subset of table1.

I hope this helps.

How to add white spaces in HTML paragraph

If you really need then you can use i.e. &nbsp; entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.

Rename multiple columns by names

Building on @user3114046's answer:

x <- data.frame(q=1,w=2,e=3)
x
#  q w e
#1 1 2 3

names(x)[match(oldnames,names(x))] <- newnames

x
#  A w B
#1 1 2 3

This won't be reliant on a specific ordering of columns in the x dataset.

Can I catch multiple Java exceptions in the same catch clause?

It is very simple:

try { 
  // Your code here.
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
            NoSuchFieldException e) { 
  // Handle exception here.
}

CSS table td width - fixed, not flexible

This workaround worked for me...

<td style="white-space: normal; width:300px;">

How can you strip non-ASCII characters from a string? (in C#)

Necromancing.
Also, the method by bzlm can be used to remove characters that are not in an arbitrary charset, not just ASCII:

// https://en.wikipedia.org/wiki/Code_page#EBCDIC-based_code_pages
// https://en.wikipedia.org/wiki/Windows_code_page#East_Asian_multi-byte_code_pages
// https://en.wikipedia.org/wiki/Chinese_character_encoding
System.Text.Encoding encRemoveAllBut = System.Text.Encoding.ASCII;
encRemoveAllBut = System.Text.Encoding.GetEncoding(System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage); // System-encoding
encRemoveAllBut = System.Text.Encoding.GetEncoding(1252); // Western European (iso-8859-1)
encRemoveAllBut = System.Text.Encoding.GetEncoding(1251); // Windows-1251/KOI8-R
encRemoveAllBut = System.Text.Encoding.GetEncoding("ISO-8859-5"); // used by less than 0.1% of websites
encRemoveAllBut = System.Text.Encoding.GetEncoding(37); // IBM EBCDIC US-Canada
encRemoveAllBut = System.Text.Encoding.GetEncoding(500); // IBM EBCDIC Latin 1
encRemoveAllBut = System.Text.Encoding.GetEncoding(936); // Chinese Simplified
encRemoveAllBut = System.Text.Encoding.GetEncoding(950); // Chinese Traditional
encRemoveAllBut = System.Text.Encoding.ASCII; // putting ASCII again, as to answer the question 

// https://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c
string inputString = "Räksmör??????, ???gås";
string asAscii = encRemoveAllBut.GetString(
    System.Text.Encoding.Convert(
        System.Text.Encoding.UTF8,
        System.Text.Encoding.GetEncoding(
            encRemoveAllBut.CodePage,
            new System.Text.EncoderReplacementFallback(string.Empty),
            new System.Text.DecoderExceptionFallback()
            ),
        System.Text.Encoding.UTF8.GetBytes(inputString)
    )
);

System.Console.WriteLine(asAscii);

AND for those that just want to remote the accents:
(caution, because Normalize != Latinize != Romanize)

// string str = Latinize("(æøå âôû?aè");
public static string Latinize(string stIn)
{
    // Special treatment for German Umlauts
    stIn = stIn.Replace("ä", "ae");
    stIn = stIn.Replace("ö", "oe");
    stIn = stIn.Replace("ü", "ue");

    stIn = stIn.Replace("Ä", "Ae");
    stIn = stIn.Replace("Ö", "Oe");
    stIn = stIn.Replace("Ü", "Ue");
    // End special treatment for German Umlauts

    string stFormD = stIn.Normalize(System.Text.NormalizationForm.FormD);
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    for (int ich = 0; ich < stFormD.Length; ich++)
    {
        System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);

        if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)
        {
            sb.Append(stFormD[ich]);
        } // End if (uc != System.Globalization.UnicodeCategory.NonSpacingMark)

    } // Next ich


    //return (sb.ToString().Normalize(System.Text.NormalizationForm.FormC));
    return (sb.ToString().Normalize(System.Text.NormalizationForm.FormKC));
} // End Function Latinize

Auto-loading lib files in Rails 4

I think this may solve your problem:

  1. in config/application.rb:

    config.autoload_paths << Rails.root.join('lib')
    

    and keep the right naming convention in lib.

    in lib/foo.rb:

    class Foo
    end
    

    in lib/foo/bar.rb:

    class Foo::Bar
    end
    
  2. if you really wanna do some monkey patches in file like lib/extensions.rb, you may manually require it:

    in config/initializers/require.rb:

    require "#{Rails.root}/lib/extensions" 
    

P.S.

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

Taking multiple inputs from user in python

How about making the input a list. Then you may use standard list operations.

a=list(input("Enter the numbers"))

Can a unit test project load the target application's app.config file?

Whether you're using Team System Test or NUnit, the best practice is to create a separate Class Library for your tests. Simply adding an App.config to your Test project will automatically get copied to your bin folder when you compile.

If your code is reliant on specific configuration tests, the very first test I would write validates that the configuration file is available (so that I know I'm not insane) :

<configuration>
   <appSettings>
       <add key="TestValue" value="true" />
   </appSettings>
</configuration>

And the test:

[TestFixture]
public class GeneralFixture
{
     [Test]
     public void VerifyAppDomainHasConfigurationSettings()
     {
          string value = ConfigurationManager.AppSettings["TestValue"];
          Assert.IsFalse(String.IsNullOrEmpty(value), "No App.Config found.");
     }
}

Ideally, you should be writing code such that your configuration objects are passed into your classes. This not only separates you from the configuration file issue, but it also allows you to write tests for different configuration scenarios.

public class MyObject
{
     public void Configure(MyConfigurationObject config)
     {
          _enabled = config.Enabled;
     }

     public string Foo()
     {
         if (_enabled)
         {
             return "foo!";
         }
         return String.Empty;
     }

     private bool _enabled;
}

[TestFixture]
public class MyObjectTestFixture
{
     [Test]
     public void CanInitializeWithProperConfig()
     {
         MyConfigurationObject config = new MyConfigurationObject();
         config.Enabled = true;

         MyObject myObj = new MyObject();
         myObj.Configure(config);

         Assert.AreEqual("foo!", myObj.Foo());
     }
}

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

The "illegal instruction" message is simply telling you that your binaries contain instructions the version of the OS that you are attempting to run them under does not understand. I can't give you the precise meaning of 4 but I expect that is internal to Apple.

Otherwise take a look at these... they are a little old, but probably tell you what you need to know

How does 64 bit code work on OS-X 10.5?
what does macosx-version-min imply?

Why can't I set text to an Android TextView?

Or you can do this way :

((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

I had the same issue "Cannot create a connection to data source...Login failed for user.." on Windows 8.1, SQL Server 2014 Developer Edition and Visual Studio 2013 Pro. All solutions offered above by other Stackoverflow Community members did not work for me.

So, I did the next steps (running all Windows applications as Administrator):

  1. VS2013 SSRS: I converted my Data Source to Shared Data Source (.rds) with Windows Authentication (Integrated Security) on the Right Pane "Solution Explorer".

  2. Original (non-shared) Data Source (on the Left Pane "Report Data") got "Don't Use Credentials".

  3. On the Project Properties, I set for "Deployment" "Overwrite DataSources" to "True" and redeployed the Project.

enter image description here

After that, I could run my report without further requirements to enter Credentials. All Shared DataSources were deployed in a separate Directory "DataSources".

enter image description here

enter image description here

How to pass a PHP variable using the URL

just put

$a='Link1';
$b='Link2';

in your pass.php and you will get your answer and do a double quotation in your link.php:

echo '<a href="pass.php?link=' . $a . '">Link 1</a>';

Catch an exception thrown by an async void method

The exception can be caught in the async function.

public async void Foo()
{
    try
    {
        var x = await DoSomethingAsync();
        /* Handle the result, but sometimes an exception might be thrown
           For example, DoSomethingAsync get's data from the network
           and the data is invalid... a ProtocolException might be thrown */
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught here */
    }
}

public void DoFoo()
{
    Foo();
}

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

Python vs. Java performance (runtime speed)

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

For example:

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

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

How to convert column with string type to int form in pyspark data frame?

from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))

You can run loop for each column but this is the simplest way to convert string column into integer.

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

Zabbix server is not running: the information displayed may not be current

Never had the problem until it suddenly appeared once, for me, the solution was to add (uncomment) the following line in /etc/zabbix/zabbix_server.conf

 ListenIP=0.0.0.0

How to restart adb from root to user mode?

i've been with this issue using elementary OS loki. For like one day and i solved it restarting the adb using this command:

./adb kill-server

and

./adb start-server

You need to be in the Sdk folder >Platform Tools

Now, restart your phone this will restart all the process in your phone.

And that's how i fixed it.

Set Jackson Timezone for Date deserialization

Your date object is probably ok, since you sent your date encoded in ISO format with GMT timezone and you are in EST when you print your date.

Note that Date objects perform timezone translation at the moment they are printed. You can check if your date object is correct with:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
System.out.println (cal);

Logging POST data from $request_body

I had a similar problem. GET requests worked and their (empty) request bodies got written to the the log file. POST requests failed with a 404. Experimenting a bit, I found that all POST requests were failing. I found a forum posting asking about POST requests and the solution there worked for me. That solution? Add a proxy_header line right before the proxy_pass line, exactly like the one in the example below.

server {
    listen       192.168.0.1:45080;
    server_name  foo.example.org;

    access_log  /path/to/log/nginx/post_bodies.log post_bodies;
    location / {
      ### add the following proxy_header line to get POSTs to work
      proxy_set_header Host $http_host;
      proxy_pass   http://10.1.2.3;
    }
}

(This is with nginx 1.2.1 for what it is worth.)

How can I get client information such as OS and browser

You can use browscap-java to get browser's information.

For Example:

UserAgentParser parser = new UserAgentService().loadParser(Arrays.asList(BrowsCapField.BROWSER));
    Capabilities capabilities = parser.parse(user_agent);

    String browser = capabilities.getBrowser();

How to compare 2 files fast using .NET?

My answer is a derivative of @lars but fixes the bug in the call to Stream.Read. I also add some fast path checking that other answers had, and input validation. In short, this should be the answer:

using System;
using System.IO;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var fi1 = new FileInfo(args[0]);
            var fi2 = new FileInfo(args[1]);
            Console.WriteLine(FilesContentsAreEqual(fi1, fi2));
        }

        public static bool FilesContentsAreEqual(FileInfo fileInfo1, FileInfo fileInfo2)
        {
            if (fileInfo1 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo1));
            }

            if (fileInfo2 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo2));
            }

            if (string.Equals(fileInfo1.FullName, fileInfo2.FullName, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (fileInfo1.Length != fileInfo2.Length)
            {
                return false;
            }
            else
            {
                using (var file1 = fileInfo1.OpenRead())
                {
                    using (var file2 = fileInfo2.OpenRead())
                    {
                        return StreamsContentsAreEqual(file1, file2);
                    }
                }
            }
        }

        private static int ReadFullBuffer(Stream stream, byte[] buffer)
        {
            int bytesRead = 0;
            while (bytesRead < buffer.Length)
            {
                int read = stream.Read(buffer, bytesRead, buffer.Length - bytesRead);
                if (read == 0)
                {
                    // Reached end of stream.
                    return bytesRead;
                }

                bytesRead += read;
            }

            return bytesRead;
        }

        private static bool StreamsContentsAreEqual(Stream stream1, Stream stream2)
        {
            const int bufferSize = 1024 * sizeof(Int64);
            var buffer1 = new byte[bufferSize];
            var buffer2 = new byte[bufferSize];

            while (true)
            {
                int count1 = ReadFullBuffer(stream1, buffer1);
                int count2 = ReadFullBuffer(stream2, buffer2);

                if (count1 != count2)
                {
                    return false;
                }

                if (count1 == 0)
                {
                    return true;
                }

                int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
                for (int i = 0; i < iterations; i++)
                {
                    if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
                    {
                        return false;
                    }
                }
            }
        }
    }
}

Or if you want to be super-awesome, you can use the async variant:

using System;
using System.IO;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var fi1 = new FileInfo(args[0]);
            var fi2 = new FileInfo(args[1]);
            Console.WriteLine(FilesContentsAreEqualAsync(fi1, fi2).GetAwaiter().GetResult());
        }

        public static async Task<bool> FilesContentsAreEqualAsync(FileInfo fileInfo1, FileInfo fileInfo2)
        {
            if (fileInfo1 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo1));
            }

            if (fileInfo2 == null)
            {
                throw new ArgumentNullException(nameof(fileInfo2));
            }

            if (string.Equals(fileInfo1.FullName, fileInfo2.FullName, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (fileInfo1.Length != fileInfo2.Length)
            {
                return false;
            }
            else
            {
                using (var file1 = fileInfo1.OpenRead())
                {
                    using (var file2 = fileInfo2.OpenRead())
                    {
                        return await StreamsContentsAreEqualAsync(file1, file2).ConfigureAwait(false);
                    }
                }
            }
        }

        private static async Task<int> ReadFullBufferAsync(Stream stream, byte[] buffer)
        {
            int bytesRead = 0;
            while (bytesRead < buffer.Length)
            {
                int read = await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead).ConfigureAwait(false);
                if (read == 0)
                {
                    // Reached end of stream.
                    return bytesRead;
                }

                bytesRead += read;
            }

            return bytesRead;
        }

        private static async Task<bool> StreamsContentsAreEqualAsync(Stream stream1, Stream stream2)
        {
            const int bufferSize = 1024 * sizeof(Int64);
            var buffer1 = new byte[bufferSize];
            var buffer2 = new byte[bufferSize];

            while (true)
            {
                int count1 = await ReadFullBufferAsync(stream1, buffer1).ConfigureAwait(false);
                int count2 = await ReadFullBufferAsync(stream2, buffer2).ConfigureAwait(false);

                if (count1 != count2)
                {
                    return false;
                }

                if (count1 == 0)
                {
                    return true;
                }

                int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
                for (int i = 0; i < iterations; i++)
                {
                    if (BitConverter.ToInt64(buffer1, i * sizeof(Int64)) != BitConverter.ToInt64(buffer2, i * sizeof(Int64)))
                    {
                        return false;
                    }
                }
            }
        }
    }
}

Using the "animated circle" in an ImageView while loading stuff

You can do this by using the following xml

<RelativeLayout
    style="@style/GenericProgressBackground"
    android:id="@+id/loadingPanel"
    >
    <ProgressBar
        style="@style/GenericProgressIndicator"/>
</RelativeLayout>

With this style

<style name="GenericProgressBackground" parent="android:Theme">
    <item name="android:layout_width">fill_parent</item>    
    <item name="android:layout_height">fill_parent</item>
    <item name="android:background">#DD111111</item>    
    <item name="android:gravity">center</item>  
</style>
<style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Small">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:indeterminate">true</item> 
</style>

To use this, you must hide your UI elements by setting the visibility value to GONE and whenever the data is loaded, call setVisibility(View.VISIBLE) on all your views to restore them. Don't forget to call findViewById(R.id.loadingPanel).setVisiblity(View.GONE) to hide the loading animation.

If you dont have a loading event/function but just want the loading panel to disappear after x seconds use a Handle to trigger the hiding/showing.

XPath with multiple conditions

question is not clear, but what i understand you need to select a catagory that has name attribute and should have child author with value specified , correct me if i am worng

here is a xpath

//category[@name='Required value'][./author[contains(.,'Required value')]]
e.g
//category[@name='Sport'][./author[contains(.,'James Small')]]

fatal: git-write-tree: error building trees

I used:

 git reset --hard

I lost some changes, but this is ok.

PHP 7 simpleXML

For Ubuntu 18.04 and php7.3, install php7.3-xml sudo apt-get install php7.3-xml

this will installl the required simplexml

Commit empty folder structure (with git)

Just add a file .gitkeep in every folder you want committed.

On windows do so by right clicking when in the folder and select: Git bash from here. Then type: touch .gitkeep

How to use LINQ to select object with minimum or maximum property value

People.OrderBy(p => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue)).First()

Would do the trick

How to reload a page using JavaScript

You can perform this task using window.location.reload();. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation

JavaScript window.location object can be used

  • to get current page address (URL)
  • to redirect the browser to another page
  • to reload the same page

window: in JavaScript represents an open window in a browser.

location: in JavaScript holds information about current URL.

The location object is like a fragment of the window object and is called up through the window.location property.

location object has three methods:

  1. assign(): used to load a new document
  2. reload(): used to reload current document
  3. replace(): used to replace current document with a new one

So here we need to use reload(), because it can help us in reloading the same document.

So use it like window.location.reload();.

Online demo on jsfiddle

To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true parameter to location.reload(). This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.

Multiple lines of text in UILabel

These things helped me

Change these properties of UILabel

label.numberOfLines = 0;
label.adjustsFontSizeToFitWidth = NO;
label.lineBreakMode = NSLineBreakByWordWrapping;

And while giving input String use \n to display different words in different lines.

Example :

 NSString *message = @"This \n is \n a demo \n message for \n stackoverflow" ;

How to extract the first two characters of a string in shell scripting?

You've gotten several good answers and I'd go with the Bash builtin myself, but since you asked about sed and awk and (almost) no one else offered solutions based on them, I offer you these:

echo "USCAGoleta9311734.5021-120.1287855805" | awk '{print substr($0,0,2)}'

and

echo "USCAGoleta9311734.5021-120.1287855805" | sed 's/\(^..\).*/\1/'

The awk one ought to be fairly obvious, but here's an explanation of the sed one:

  • substitute "s/"
  • the group "()" of two of any characters ".." starting at the beginning of the line "^" and followed by any character "." repeated zero or more times "*" (the backslashes are needed to escape some of the special characters)
  • by "/" the contents of the first (and only, in this case) group (here the backslash is a special escape referring to a matching sub-expression)
  • done "/"

Does bootstrap 4 have a built in horizontal divider?

Here are some custom utility classes:

_x000D_
_x000D_
hr.dashed {
    border-top: 2px dashed #999;
}

hr.dotted {
    border-top: 2px dotted #999;
}

hr.solid {
    border-top: 2px solid #999;
}


hr.hr-text {
  position: relative;
    border: none;
    height: 1px;
    background: #999;
}

hr.hr-text::before {
    content: attr(data-content);
    display: inline-block;
    background: #fff;
    font-weight: bold;
    font-size: 0.85rem;
    color: #999;
    border-radius: 30rem;
    padding: 0.2rem 2rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}



/*
*
* ==========================================
* FOR DEMO PURPOSES
* ==========================================
*
*/

body {
    min-height: 100vh;
    background-color: #fff; 
    color: #333;
}
.text-uppercase {
  letter-spacing: .1em;
}
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">

<div class="container py-5">
    <!-- For Demo Purpose -->
    <header class="py-5 text-center">
        <h1 class="display-4">Bootstrap Divider</h1>
        <p class="lead mb-0">Some divider variants using &lt;hr&gt; element.    </p>
    </header>


    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="mb-4">
                <h6 class=" text-uppercase">Dashed</h6>
                <!-- Dashed divider -->
                <hr class="dashed">
            </div>
            <div class="mb-4">
                <h6 class=" text-uppercase">Dotted</h6>
                <!-- Dotted divider -->
                <hr class="dotted">
            </div>
            <div class="mb-4">
                <h6 class="text-uppercase">Solid</h6>
                <!-- Solid divider -->
                <hr class="solid">
            </div>
            <div class="mb-4">
                <h6 class=" text-uppercase">Text content</h6>
                <!-- Gradient divider -->
                <hr data-content="AND" class="hr-text">
            </div>
           
        </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

No Main class found in NetBeans

import java.util.Scanner;
public class FarenheitToCelsius{
    public static void main(String[]args){
     Scanner input= new Scanner(System.in);
     System.out.println("Enter Degree in Farenheit:");
     double Farenheit=input.nextDouble();
     //convert farenheit to celsius
     double celsuis=(5.0/9)*(farenheit 32);
     system.out.println("Farenheit"+farenheit+"is"+celsius+"in celsius")
             {

offsetting an html anchor to adjust for fixed header

I was looking for a solution to this as well. In my case, it was pretty easy.

I have a list menu with all the links:

<ul>
<li><a href="#one">one</a></li>
<li><a href="#two">two</a></li>
<li><a href="#three">three</a></li>
<li><a href="#four">four</a></li>
</ul>

And below that the headings where it should go to.

<h3>one</h3>
<p>text here</p>

<h3>two</h3>
<p>text here</p>

<h3>three</h3>
<p>text here</p>

<h3>four</h3>
<p>text here</p>

Now because I have a fixed menu at the top of my page I can't just make it go to my tag because that would be behind the menu.

Instead, I put a span tag inside my tag with the proper id.

<h3><span id="one"></span>one</h3>

Now use 2 lines of CSS to position them properly.

h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}

Change the top value to match the height of your fixed header (or more). Now I assume this would work with other elements as well.

How do I encode/decode HTML entities in Ruby?

If you don't want to add a new dependency just to do this (like HTMLEntities) and you're already using Hpricot, it can both escape and unescape for you. It handles much more than CGI:

Hpricot.uxs "foo&nbsp;b&auml;r"
=> "foo bär"

What is JavaScript garbage collection?

Reference types do not store the object directly into the variable to which it is assigned, so the object variable in the example below, doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory, where the object exists.

var object = new Object();

if you assign one reference typed variable to another, each variable gets a copy of the pointer, and both still reference to the same object in memory.

var object1 = new Object();
var object2 = object1;

Two variables pointing to one object

JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.

var object1 = new Object();
// do something
object1 = null; // dereference

Dereferencing objects is especially important in very large applications that use millions of objects.

from The Principles of Object-Oriented JavaScript - NICHOLAS C. ZAKAS

How to Install Font Awesome in Laravel Mix

To install font-awesome you first should install it with npm. So in your project root directory type:

npm install font-awesome --save

(Of course I assume you have node.js and npm already installed. And you've done npm install in your projects root directory)

Then edit the resources/assets/sass/app.scss file and add at the top this line:

@import "node_modules/font-awesome/scss/font-awesome.scss";

Now you can do for example:

npm run dev

This builds unminified versions of the resources in the correct folders. If you wanted to minify them, you would instead run:

npm run production

And then you can use the font.

Best Timer for using in a Windows service

Don't use a service for this. Create a normal application and create a scheduled task to run it.

This is the commonly held best practice. Jon Galloway agrees with me. Or maybe its the other way around. Either way, the fact is that it is not best practices to create a windows service to perform an intermittent task run off a timer.

"If you're writing a Windows Service that runs a timer, you should re-evaluate your solution."

–Jon Galloway, ASP.NET MVC community program manager, author, part time superhero

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Tooltips with Twitter Bootstrap

Add this into your header

<script>
    //tooltip
    $(function() {
        var tooltips = $( "[title]" ).tooltip();
        $(document)(function() {
            tooltips.tooltip( "open" );
        });
    });
</script>

Then just add the attribute title="your tooltip" to any element

How do I use extern to share variables between source files?

First off, the extern keyword is not used for defining a variable; rather it is used for declaring a variable. I can say extern is a storage class, not a data type.

extern is used to let other C files or external components know this variable is already defined somewhere. Example: if you are building a library, no need to define global variable mandatorily somewhere in library itself. The library will be compiled directly, but while linking the file, it checks for the definition.

How to display an activity indicator with text on iOS 8 with Swift?

For Swift 5

Indicator with label inside WKWebview

var strLabel = UILabel()
   let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    let loadingTextLabel = UILabel()
   
    @IBOutlet var indicator: UIActivityIndicatorView!
    @IBOutlet var webView: WKWebView!
    
    var refController:UIRefreshControl = UIRefreshControl()
    
    
    override func viewDidLoad() {
        webView = WKWebView(frame: CGRect.zero)
        webView.navigationDelegate = self
        webView.uiDelegate = self as? WKUIDelegate
        
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences
       
        
        webView.allowsBackForwardNavigationGestures = true
        
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
        setBackground()
        
    }
    

    
    func setBackground() {
        view.addSubview(webView)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    }
    
    func showActivityIndicator(show: Bool) {
        if show {
            
            
            strLabel = UILabel(frame: CGRect(x: 55, y: 0, width: 400, height: 66))
            strLabel.text = "Please Wait. Checking Internet Connection..."
            strLabel.font = UIFont(name: "Avenir Light", size: 12)
            
           
            strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
           
            effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 300, height: 66)
            effectView.layer.cornerRadius = 15
            effectView.layer.masksToBounds = true
            indicator = UIActivityIndicatorView(style: .white)
            indicator.frame = CGRect(x: 0, y: 0, width: 66, height: 66)
            indicator.startAnimating()
            effectView.contentView.addSubview(indicator)
            effectView.contentView.addSubview(strLabel)
            indicator.transform = CGAffineTransform(scaleX: 1.4, y: 1.4);
            effectView.center = webView.center
            view.addSubview(effectView)
            
            
        } else {
            strLabel.removeFromSuperview()
             effectView.removeFromSuperview()
            indicator.removeFromSuperview()
            indicator.stopAnimating()
        }
    }

Here is my screenshort

Converting a number with comma as decimal point to float

This function is compatible for numbers with dots or commas as decimals

function floatvalue($val){
            $val = str_replace(",",".",$val);
            $val = preg_replace('/\.(?=.*\.)/', '', $val);
            return floatval($val);
}

This works for all kind of inputs (American or european style)

echo floatvalue('1.325.125,54'); // The output is 1325125.54
echo floatvalue('1,325,125.54'); // The output is 1325125.54
echo floatvalue('59,95');        // The output is 59.95
echo floatvalue('12.000,30');    // The output is 12000.30
echo floatvalue('12,000.30');    // The output is 12000.30

How to configure postgresql for the first time?

EDIT: Warning: Please, read the answer posted by Evan Carroll. It seems that this solution is not safe and not recommended.

This worked for me in the standard Ubuntu 14.04 64 bits installation.

I followed the instructions, with small modifications, that I found in http://suite.opengeo.org/4.1/dataadmin/pgGettingStarted/firstconnect.html

  1. Install postgreSQL (if not already in your machine):

sudo apt-get install postgresql

  1. Run psql using the postgres user

sudo –u postgres psql postgres

  1. Set a new password for the postgres user:

\password postgres

  1. Exit psql

\q

  1. Edit /etc/postgresql/9.3/main/pg_hba.conf and change:

#Database administrative login by Unix domain socket local all postgres peer

To:

#Database administrative login by Unix domain socket local all postgres md5

  1. Restart postgreSQL:

sudo service postgresql restart

  1. Create a new database

sudo –u postgres createdb mytestdb

  1. Run psql with the postgres user again:

psql –U postgres –W

  1. List the existing databases (your new database should be there now):

\l

jquery's append not working with svg element?

When you pass a markup string into $, it's parsed as HTML using the browser's innerHTML property on a <div> (or other suitable container for special cases like <tr>). innerHTML can't parse SVG or other non-HTML content, and even if it could it wouldn't be able to tell that <circle> was supposed to be in the SVG namespace.

innerHTML is not available on SVGElement—it is a property of HTMLElement only. Neither is there currently an innerSVG property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn't give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn't designed for use with SVG at all and many operations may fail.

HTML5 promises to let you use <svg> without an xmlns inside a plain HTML (text/html) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you'll not be able to use innerHTML even though they look like part of an HTML document.

However, for today's browsers you must use XHTML (properly served as application/xhtml+xml; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you'd have to escape the < symbols inside your script block (or enclose in a CDATA section), and include the XHTML xmlns declaration. example:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
    <svg id="s" xmlns="http://www.w3.org/2000/svg"/>
    <script type="text/javascript">
        function makeSVG(tag, attrs) {
            var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;
        }

        var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
        document.getElementById('s').appendChild(circle);
        circle.onmousedown= function() {
            alert('hello');
        };
    </script>
</body></html>

*: well, there's DOM Level 3 LS's parseWithContext, but browser support is very poor. Edit to add: however, whilst you can't inject markup into an SVGElement, you could inject a new SVGElement into an HTMLElement using innerHTML, then transfer it to the desired target. It'll likely be a bit slower though:

<script type="text/javascript"><![CDATA[
    function parseSVG(s) {
        var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
        div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
        var frag= document.createDocumentFragment();
        while (div.firstChild.firstChild)
            frag.appendChild(div.firstChild.firstChild);
        return frag;
    }

    document.getElementById('s').appendChild(parseSVG(
        '<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
    ));
]]></script>

**: I hate the way the authors of HTML5 seem to be scared of XML and determined to shoehorn XML-based features into the crufty mess that is HTML. XHTML solved these problems years ago.

PHP mySQL - Insert new record into table with auto-increment on primary key

Use the DEFAULT keyword:

$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";

Also, you can specify the columns, (which is better practice):

$query = "INSERT INTO myTable
          (fname, lname, website)
          VALUES
          ('fname', 'lname', 'website')";

Reference:

How to make pylab.savefig() save image for 'maximized' window instead of default size

You set the size on initialization:

fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # in inches!

Edit:

If the problem is with x-axis ticks - You can set them "manually":

fig2.add_subplot(111).set_xticks(arange(1,3,0.5)) # You can actually compute the interval You need - and substitute here

And so on with other aspects of Your plot. You can configure it all. Here's an example:

from numpy import arange
import matplotlib
# import matplotlib as mpl
import matplotlib.pyplot
# import matplotlib.pyplot as plt

x1 = [1,2,3]
y1 = [4,5,6]
x2 = [1,2,3]
y2 = [5,5,5]

# initialization
fig2 = matplotlib.pyplot.figure(figsize=(8.0, 5.0)) # The size of the figure is specified as (width, height) in inches

# lines:
l1 = fig2.add_subplot(111).plot(x1,y1, label=r"Text $formula$", "r-", lw=2)
l2 = fig2.add_subplot(111).plot(x2,y2, label=r"$legend2$" ,"g--", lw=3)
fig2.add_subplot(111).legend((l1,l2), loc=0)

# axes:
fig2.add_subplot(111).grid(True)
fig2.add_subplot(111).set_xticks(arange(1,3,0.5))
fig2.add_subplot(111).axis(xmin=3, xmax=6) # there're also ymin, ymax
fig2.add_subplot(111).axis([0,4,3,6]) # all!
fig2.add_subplot(111).set_xlim([0,4])
fig2.add_subplot(111).set_ylim([3,6])

# labels:
fig2.add_subplot(111).set_xlabel(r"x $2^2$", fontsize=15, color = "r")
fig2.add_subplot(111).set_ylabel(r"y $2^2$")
fig2.add_subplot(111).set_title(r"title $6^4$")
fig2.add_subplot(111).text(2, 5.5, r"an equation: $E=mc^2$", fontsize=15, color = "y")
fig2.add_subplot(111).text(3, 2, unicode('f\374r', 'latin-1'))

# saving:
fig2.savefig("fig2.png")

So - what exactly do You want to be configured?

Why plt.imshow() doesn't display the image?

plt.imshow displays the image on the axes, but if you need to display multiple images you use show() to finish the figure. The next example shows two figures:

import numpy as np
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
plt.imshow(X_train[1])
plt.show()

In Google Colab, if you comment out the show() method from previous example just a single image will display (the later one connected with X_train[1]).

Here is the content from the help:

plt.show(*args, **kw)
        Display a figure.
        When running in ipython with its pylab mode, display all
        figures and return to the ipython prompt.

        In non-interactive mode, display all figures and block until
        the figures have been closed; in interactive mode it has no
        effect unless figures were created prior to a change from
        non-interactive to interactive mode (not recommended).  In
        that case it displays the figures but does not block.

        A single experimental keyword argument, *block*, may be
        set to True or False to override the blocking behavior
        described above.



plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
        Display an image on the axes.

Parameters
----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
    Display the image in `X` to current axes.  `X` may be an
    array or a PIL image. If `X` is an array, it
    can have the following shapes and types:

    - MxN -- values to be mapped (float or int)
    - MxNx3 -- RGB (float or uint8)
    - MxNx4 -- RGBA (float or uint8)

    The value for each component of MxNx3 and MxNx4 float arrays
    should be in the range 0.0 to 1.0. MxN arrays are mapped
    to colors based on the `norm` (mapping scalar to scalar)
    and the `cmap` (mapping the normed scalar to a color).

How do you create a yes/no boolean field in SQL server?

You can use the data type bit

Values inserted which are greater than 0 will be stored as '1'

Values inserted which are less than 0 will be stored as '1'

Values inserted as '0' will be stored as '0'

This holds true for MS SQL Server 2012 Express

Axios handling errors

You can go like this: error.response.data
In my case, I got error property from backend. So, I used error.response.data.error

My code:

axios
  .get(`${API_BASE_URL}/students`)
  .then(response => {
     return response.data
  })
  .then(data => {
     console.log(data)
  })
  .catch(error => {
     console.log(error.response.data.error)
  })

How to change scroll bar position with CSS?

Using CSS only:

Right/Left Flippiing: Working Fiddle

.Container
{
    height: 200px;
    overflow-x: auto;
}
.Content
{
    height: 300px;
}

.Flipped
{
    direction: rtl;
}
.Content
{
    direction: ltr;
}

Top/Bottom Flipping: Working Fiddle

.Container
{
    width: 200px;
    overflow-y: auto;
}
.Content
{
    width: 300px;
}

.Flipped, .Flipped .Content
{
    transform:rotateX(180deg);
    -ms-transform:rotateX(180deg); /* IE 9 */
    -webkit-transform:rotateX(180deg); /* Safari and Chrome */
}

encrypt and decrypt md5

This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.

$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);

var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);

Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.

But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

What is the C# equivalent of friend?

There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is InternalsVisibleTo. I've only ever used this attribute for testing - where it's very handy!

Example: To be placed in AssemblyInfo.cs

[assembly: InternalsVisibleTo("OtherAssembly")]

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

You can use mysqli_connect($mysql_hostname , $mysql_username) instead of mysql_connect($mysql_hostname , $mysql_username).

mysql_* functions were removed as of PHP 7. You now have two alternatives: MySQLi and PDO.

Using Mysql in the command line in osx - command not found?

So there are few places where terminal looks for commands. This places are stored in your $PATH variable. Think of it as a global variable where terminal iterates over to look up for any command. This are usually binaries look how /bin folder is usually referenced.

/bin folder has lots of executable files inside it. Turns out this are command. This different folder locations are stored inside one Global variable i.e. $PATH separated by :

Now usually programs upon installation takes care of updating PATH & telling your terminal that hey i can be all commands inside my bin folder.

Turns out MySql doesn't do it upon install so we manually have to do it.

We do it by following command,

export PATH=$PATH:/usr/local/mysql/bin

If you break it down, export is self explanatory. Think of it as an assignment. So export a variable PATH with value old $PATH concat with new bin i.e. /usr/local/mysql/bin

This way after executing it all the commands inside /usr/local/mysql/bin are available to us.

There is a small catch here. Think of one terminal window as one instance of program and maybe something like $PATH is class variable ( maybe ). Note this is pure assumption. So upon close we lose the new assignment. And if we reopen terminal we won't have access to our command again because last when we exported, it was stored in primary memory which is volatile.

Now we need to have our mysql binaries exported every-time we use terminal. So we have to persist concat in our path.

You might be aware that our terminal using something called dotfiles to load configuration on terminal initialisation. I like to think of it's as sets of thing passed to constructer every-time a new instance of terminal is created ( Again an assumption but close to what it might be doing ). So yes by now you get the point what we are going todo.

.bash_profile is one of the primary known dotfile.

So in following command,

echo 'export PATH=$PATH:/usr/local/mysql/bin' >> ~/.bash_profile

What we are doing is saving result of echo i.e. output string to ~/.bash_profile

So now as we noted above every-time we open terminal or instance of terminal our dotfiles are loaded. So .bash_profile is loaded respectively and export that we appended above is run & thus a our global $PATH gets updated and we get all the commands inside /usr/local/mysql/bin.

P.s.

if you are not running first command export directly but just running second in order to persist it? Than for current running instance of terminal you have to,

source ~/.bash_profile

This tells our terminal to reload that particular file.

Is there an exponent operator in C#?

Since no-one has yet wrote a function to do this with two integers, here's one way:

private long CalculatePower(int number, int powerOf)
{
    for (int i = powerOf; i > 1; i--)
        number *= number;
    return number;
}
CalculatePower(5, 3); // 125
CalculatePower(8, 4); // 4096
CalculatePower(6, 2); // 36

Alternatively in VB.NET:

Private Function CalculatePower(number As Integer, powerOf As Integer) As Long
    For i As Integer = powerOf To 2 Step -1
        number *= number
    Next
    Return number
End Function
CalculatePower(5, 3) ' 125
CalculatePower(8, 4) ' 4096
CalculatePower(6, 2) ' 36

What does it mean: The serializable class does not declare a static final serialVersionUID field?

The reasons for warning are documented here, and the simple fixes are to turn off the warning or put the following declaration in your code to supply the version UID. The actual value is not relevant, start with 999 if you like, but changing it when you make incompatible changes to the class is.

public class HelloWorldSwing extends JFrame {

        JTextArea m_resultArea = new JTextArea(6, 30);
        private static final long serialVersionUID = 1L;

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

If you're testing your app on a device > android 6.0 you have also to explicitely ask the user to grant the permission.

As you can see here READ_PHONE_STATE have a dangerous level.

If a permission have a dangerous level then the user have to accept or not this permission manually. You don't have the choice, you MUST do this

To do this from your activity execute the following code :

if the user use Android M and didn't grant the permission yet it will ask for it.

public static final int READ_PHONE_STATE_PERMISSION = 100;

  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, READ_PHONE_STATE_PERMISSION);
        }

then override onRequestPermissionsResult in your activity

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case READ_PHONE_STATE_PERMISSION: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    //Permission granted do what you want from this point
                }else {
                    //Permission denied, manage this usecase
                }
            }
        }
    }

You should read this article to know more about it

disable Bootstrap's Collapse open/close animation

If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...

Just add this somewhere in your code:

$(document).ready(
    $('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
        e.preventDefault();
    }),
    $('[data-toggle="collapse"]').on('click', function(e) {
        e.preventDefault();
        $($(this).data('target')).toggleClass('in');
    })
);

How to delete a column from a table in MySQL

ALTER TABLE `tablename` DROP `columnname`;

Or,

ALTER TABLE `tablename` DROP COLUMN `columnname`;

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

My quick solution was to close all opened files in text editor area and then reopen them again from Solution Explorer.

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

I think I know why you want to avoid that. But maybe try & catch !== try & catch. ;o) This came into my mind:

var json_verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

So you may also dirty clip to the JSON object, like:

JSON.verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

As this as encapsuled as possible, it may not break on error.

How to handle notification when app in background in Firebase

According to OAUTH 2.0:

There will be Auth problem for this case beacuse FCM now using OAUTH 2

So I read firebase documentation and according to documentation new way to post data message is;

POST: https://fcm.googleapis.com/v1/projects/YOUR_FIREBASEDB_ID/messages:send

Headers

Key: Content-Type, Value: application/json

Auth

Bearer YOUR_TOKEN 

Example Body

{
   "message":{
    "topic" : "xxx",
    "data" : {
         "body" : "This is a Firebase Cloud Messaging Topic Message!",
         "title" : "FCM Message"
          }
      }
 }

In the url there is Database Id which you can find it on your firebase console. (Go project setttings)

And now lets take our token (It will valid only 1 hr):

First in the Firebase console, open Settings > Service Accounts. Click Generate New Private Key, securely store the JSON file containing the key. I was need this JSON file to authorize server requests manually. I downloaded it.

Then I create a node.js project and used this function to get my token;

var PROJECT_ID = 'YOUR_PROJECT_ID';
var HOST = 'fcm.googleapis.com';
var PATH = '/v1/projects/' + PROJECT_ID + '/messages:send';
var MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
var SCOPES = [MESSAGING_SCOPE];

  router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
      getAccessToken().then(function(accessToken) {
        console.log("TOKEN: "+accessToken)
      })

    });

function getAccessToken() {
return new Promise(function(resolve, reject) {
    var key = require('./YOUR_DOWNLOADED_JSON_FILE.json');
    var jwtClient = new google.auth.JWT(
        key.client_email,
        null,
        key.private_key,
        SCOPES,
        null
    );
    jwtClient.authorize(function(err, tokens) {
        if (err) {
            reject(err);
            return;
        }
        resolve(tokens.access_token);
    });
});
}

Now I can use this token in my post request. Then I post my data message, and it is now handled by my apps onMessageReceived function.

Does VBA have Dictionary Structure?

Yes. For VB6, VBA (Excel), and VB.NET

How to convert timestamp to datetime in MySQL?

DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`

This is the ultimate solution if the given date is in encoded format like 1300464000

Python regex for integer?

You are apparently using Django.

You are probably better off just using models.IntegerField() instead of models.TextField(). Not only will it do the check for you, but it will give you the error message translated in several langs, and it will cast the value from it's type in the database to the type in your Python code transparently.

Print text in Oracle SQL Developer SQL Worksheet window

enter image description here

for simple comments:

set serveroutput on format wrapped;
begin
    DBMS_OUTPUT.put_line('simple comment');
end;
/

-- do something

begin
    DBMS_OUTPUT.put_line('second simple comment');
end;
/

you should get:

anonymous block completed
simple comment

anonymous block completed
second simple comment

if you want to print out the results of variables, here's another example:

set serveroutput on format wrapped;
declare
a_comment VARCHAR2(200) :='first comment';
begin
    DBMS_OUTPUT.put_line(a_comment);
end;

/

-- do something


declare
a_comment VARCHAR2(200) :='comment';
begin
    DBMS_OUTPUT.put_line(a_comment || 2);
end;

your output should be:

anonymous block completed
first comment

anonymous block completed
comment2

What are .NumberFormat Options In Excel VBA?

dovers gives us his great answer and based on it you can try use it like

public static class CellDataFormat
{
        public static string General { get { return "General"; } }
        public static string Number { get { return "0"; } }

        // Your custom format 
        public static string NumberDotTwoDigits { get { return "0.00"; } }

        public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
        public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
        public static string Date { get { return "m/d/yy"; } }
        public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
        public static string Percentage { get { return "0.00%"; } }
        public static string Fraction { get { return "# ?/?"; } }
        public static string Scientific { get { return "0.00E+00"; } }
        public static string Text { get { return "@"; } }
        public static string Special { get { return ";;"; } }
        public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}

ng if with angular for string contains

All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives

<li ng-repeat="select in Items">   
         <foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found

What's your most controversial programming opinion?

Most of programming job interview questions are pointless. Especially those figured out by programmers.

It is a common case, at least according to my & my friends experience, where a puffed up programmer, asks you some tricky wtf he spent weeks googling for. The funny thing about that is, you get home and google it within a minute. It's like they often try to beat you up with their sophisticated weapons, instead of checking if you'd be a comprehensive, pragmatic team player to work with.

Similar stupidity IMO is when you're being asked for highly accessible fundamentals, like: "Oh wait, let me see if you can pseudo-code that insert_name_here-algorithm on a sheet of paper (sic!)". Do I really need to remember it while applying for a high-level programming job? Should I efficiently solve problems or puzzles?

How do I create dynamic variable names inside a loop?

 var marker+i = "some stuff";

coudl be interpreted like this: create a variable named marker (undefined); then add to i; then try to assign a value to to the result of an expression, not possible. What firebug is saying is this: var marker; i = 'some stuff'; this is what firebug expects a comma after marker and before i; var is a statement and don't (apparently) accepts expressions. Not so good an explanation but i hope it helps.

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

Since the user asked for more than one timezone option, then you can make it generic.

Generic Function

function convertDateFromTimezone($date,$timezone,$timezone_to,$format){
 $date = new DateTime($date,new DateTimeZone($timezone));
 $date->setTimezone( new DateTimeZone($timezone_to) );
 return $date->format($format);
}

Usage:

echo  convertDateFromTimezone('2011-04-21 13:14','UTC','America/New_York','Y-m-d H:i:s');

Output:

2011-04-21 09:14:00

Disabling same-origin policy in Safari

If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.

C# Error: Parent does not contain a constructor that takes 0 arguments

By default compiler tries to call parameterless constructor of base class.

In case if the base class doesn't have a parameterless constructor, you have to explicitly call it yourself:

public child(int i) : base(i){
Console.WriteLine("child");}

Ref : Constructor calling hierarchy during inheritance

How to check if string contains Latin characters only?

You can use regex:

/[a-z]/i.test(str);

The i makes the regex case-insensitive. You could also do:

/[a-z]/.test(str.toLowerCase());

pip installs packages successfully, but executables not found from command line

I know the question asks about macOS, but here is a solution for Linux users who arrive here via Google.

I was having the issue described in this question, having installed the pdfx package via pip.

When I ran it however, nothing...

pip list | grep pdfx
pdfx (1.3.0)

Yet:

which pdfx
pdfx not found

The problem on Linux is that pip install ... drops scripts into ~/.local/bin and this is not on the default Debian/Ubuntu $PATH.

Here's a GitHub issue going into more detail: https://github.com/pypa/pip/issues/3813

To fix, just add ~/.local/bin to your $PATH, for example by adding the following line to your .bashrc file:

export PATH="$HOME/.local/bin:$PATH"

After that, restart your shell and things should work as expected.

Hibernate dialect for Oracle Database 11g?

We had a problem with the (deprecated) dialect org.hibernate.dialect.Oracledialect and Oracle 11g database using hibernate.hbm2ddl.auto = validate mode.

With this dialect Hibernate was unable to found the sequences (because the implementation of the getQuerySequencesString() method, that returns this query:

"select sequence_name from user_sequences;"

for which the execution returns an empty result from database).

Using the dialect org.hibernate.dialect.Oracle9iDialect , or greater, solves the problem, due to a different implementation of getQuerySequencesString() method:

"select sequence_name from all_sequences union select synonym_name from all_synonyms us, all_sequences asq where asq.sequence_name = us.table_name and asq.sequence_owner = us.table_owner;"

that returns all the sequences if executed, instead.

Getting multiple values with scanf()

int a,b,c,d;
if(scanf("%d %d %d %d",&a,&b,&c,&d) == 4) {
   //read the 4 integers
} else {
   puts("Error. Please supply 4 integers");
}

How do I add space between items in an ASP.NET RadioButtonList

<asp:RadioButtonList ID="rbn" runat="server" RepeatLayout="Table" RepeatColumns="2"
                        Width="100%" >
                        <asp:ListItem Text="1"></asp:ListItem>
                        <asp:ListItem Text="2"></asp:ListItem>
                        <asp:ListItem Text="3"></asp:ListItem>
                        <asp:ListItem Text="4"></asp:ListItem>
                    </asp:RadioButtonList>

lodash multi-column sortBy descending

In the documentation of the version 4.11.x, says: ` "This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, specify an order of "desc" for descending or "asc" for ascending sort order of corresponding values." (source https://lodash.com/docs/4.17.10#orderBy)

let sorted = _.orderBy(this.items, ['fieldFoo', 'fieldBar'], ['asc', 'desc'])

AngularJS: How to run additional code after AngularJS has rendered a template?

You can also create a directive that runs your code in the link function.

See that stackoverflow reply.

Determine the size of an InputStream

When explicitly dealing with a ByteArrayInputStream then contrary to some of the comments on this page you can use the .available() function to get the size. Just have to do it before you start reading from it.

From the JavaDocs:

Returns the number of remaining bytes that can be read (or skipped over) from this input stream. The value returned is count - pos, which is the number of bytes remaining to be read from the input buffer.

https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()

Angular 2 Cannot find control with unspecified name attribute on formArrays

Remove the brackets from

[formArrayName]="areas" 

and use only

formArrayName="areas"

This, because with [ ] you are trying to bind a variable, which this is not. Also notice your submit, it should be:

(ngSubmit)="onSubmit(areasForm.value)"

instead of areasForm.values.

Escape a string for a sed replace pattern

Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter)

Note that escaping everything is a bad idea. Sed needs many characters to be escaped to get their special meaning. For example, if you escape a digit in the replacement string, it will turn in to a backreference.

As Ben Blank said, there are only three characters that need to be escaped in the replacement string (escapes themselves, forward slash for end of statement and & for replace all):

ESCAPED_REPLACE=$(printf '%s\n' "$REPLACE" | sed -e 's/[\/&]/\\&/g')
# Now you can use ESCAPED_REPLACE in the original sed statement
sed "s/KEYWORD/$ESCAPED_REPLACE/g"

If you ever need to escape the KEYWORD string, the following is the one you need:

sed -e 's/[]\/$*.^[]/\\&/g'

And can be used by:

KEYWORD="The Keyword You Need";
ESCAPED_KEYWORD=$(printf '%s\n' "$KEYWORD" | sed -e 's/[]\/$*.^[]/\\&/g');

# Now you can use it inside the original sed statement to replace text
sed "s/$ESCAPED_KEYWORD/$ESCAPED_REPLACE/g"

Remember, if you use a character other than / as delimiter, you need replace the slash in the expressions above wih the character you are using. See PeterJCLaw's comment for explanation.

Edited: Due to some corner cases previously not accounted for, the commands above have changed several times. Check the edit history for details.

How to create a collapsing tree table in html/css/js?

HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link

Bitwise operation and usage

Whilst manipulating bits of an integer is useful, often for network protocols, which may be specified down to the bit, one can require manipulation of longer byte sequences (which aren't easily converted into one integer). In this case it is useful to employ the bitstring library which allows for bitwise operations on data - e.g. one can import the string 'ABCDEFGHIJKLMNOPQ' as a string or as hex and bit shift it (or perform other bitwise operations):

>>> import bitstring
>>> bitstring.BitArray(bytes='ABCDEFGHIJKLMNOPQ') << 4
BitArray('0x142434445464748494a4b4c4d4e4f50510')
>>> bitstring.BitArray(hex='0x4142434445464748494a4b4c4d4e4f5051') << 4
BitArray('0x142434445464748494a4b4c4d4e4f50510')

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

As it allows to install more than one version of java, I had install many 3 versions unknowingly but it was point to latest version "11.0.2"

I could able to solve this issue with below steps to move to "1.8"

$java -version

openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment 18.9 (build 11.0.2+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

cd /Library/Java/JavaVirtualMachines
ls

jdk1.8.0_201.jdk jdk1.8.0_202.jdk openjdk-11.0.2.jdk

sudo rm -rf openjdk-11.0.2.jdk
sudo rm -rf jdk1.8.0_201.jdk
ls

jdk1.8.0_202.jdk

java -version

java version "1.8.0_202-ea" Java(TM) SE Runtime Environment (build 1.8.0_202-ea-b03) Java HotSpot(TM) 64-Bit Server VM (build 25.202-b03, mixed mode)

Disable-web-security in Chrome 48+

Update 2020-04-30

As of Chrome 81, it is mandatory to pass both --disable-site-isolation-trials and a non-empty profile path via --user-data-dir in order for --disable-web-security to take effect:

# MacOS
open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials

(Speculation) It is likely that Chrome requires a non-empty profile path to mitigate the high security risk of launching the browser with web security disabled on the default profile. See --user-data-dir= vs --user-data-dir=/some/path for more details below.

Thanks to @Snæbjørn for the Chrome 81 tip in the comments.


Update 2020-03-06

As of Chrome 80 (possibly even earlier), the combination of flags --user-data-dir=/tmp/some-path --disable-web-security --disable-site-isolation-trials no longer disables web security.

It is unclear when the Chromium codebase regressed, but downloading an older build of Chromium (following "Not-so-easy steps" on the Chromium download page) is the only workaround I found. I ended up using Version 77.0.3865.0, which properly disables web security with these flags.


Original Post 2019-11-01

In Chrome 67+, it is necessary to pass the --disable-site-isolation-trials flag alongside arguments --user-data-dir= and --disable-web-security to truly disable web security.

On MacOS, the full command becomes:

open -na Google\ Chrome --args --user-data-dir= --disable-web-security --disable-site-isolation-trials

Regarding --user-data-dir

Per David Amey's answer, it is still necessary to specify --user-data-dir= for Chrome to respect the --disable-web-security option.

--user-data-dir= vs --user-data-dir=/some/path

Though passing in an empty path via --user-data-dir= works with --disable-web-security, it is not recommended for security purposes as it uses your default Chrome profile, which has active login sessions to email, etc. With Chrome security disabled, your active sessions are thus vulnerable to additional in-browser exploits.

Thus, it is recommended to use an alternative directory for your Chrome profile with --user-data-dir=/tmp/chrome-sesh or equivalent. Credit to @James B for pointing this out in the comments.

Source

This fix was discoreved within the browser testing framework Cypress: https://github.com/cypress-io/cypress/issues/1951

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

Remove all html tags from php string

For my this is best solution.

function strip_tags_content($string) { 
    // ----- remove HTML TAGs ----- 
    $string = preg_replace ('/<[^>]*>/', ' ', $string); 
    // ----- remove control characters ----- 
    $string = str_replace("\r", '', $string);
    $string = str_replace("\n", ' ', $string);
    $string = str_replace("\t", ' ', $string);
    // ----- remove multiple spaces ----- 
    $string = trim(preg_replace('/ {2,}/', ' ', $string));
    return $string; 

}

SQL Server Pivot Table with multiple column aggregates

I used your own pivot as a nested query and came to this result:

SELECT
  [sub].[chardate],
  SUM(ISNULL([Australia], 0)) AS [Transactions Australia],
  SUM(CASE WHEN [Australia] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Australia],
  SUM(ISNULL([Austria], 0)) AS [Transactions Austria],
  SUM(CASE WHEN [Austria] IS NOT NULL THEN [TotalAmount] ELSE 0 END) AS [Amount Austria]
FROM
(
  select * 
  from  mytransactions
  pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
) AS [sub]
GROUP BY
  [sub].[chardate],
  [sub].[numericmonth]
ORDER BY 
  [sub].[numericmonth] ASC

Here is the Fiddle.

How do I get the coordinates of a mouse click on a canvas element?

ThreeJS r77

var x = event.offsetX == undefined ? event.layerX : event.offsetX;
var y = event.offsetY == undefined ? event.layerY : event.offsetY;

mouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;
mouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;

After trying many solutions. This worked for me. Might help someone else hence posting. Got it from here

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

Your JRE was probably defined in run configuration. Follow these steps in Eclipse to change the build JRE.

1) Right click on the project and select Run As > Run Configurations

2) From Run Configurations window, select your project build configuration on the left panel. On the right, you will see various tabs: Main, JRE, Refresh, Source,...

3) Click on JRE tab, you should see something like this

enter image description here

4) By default, Work Default JRE (The JRE you select as default under Preferences->Java->Installed JREs) will be used. If you want to use another installed JRE, tick the Alternate JRE checkbox and select your preferred JRE from the dropdown.

How do I delete rows in a data frame?

You can also work with a so called boolean vector, aka logical:

row_to_keep = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)
myData = myData[row_to_keep,]

Note that the ! operator acts as a NOT, i.e. !TRUE == FALSE:

myData = myData[!row_to_keep,]

This seems a bit cumbersome in comparison to @mrwab's answer (+1 btw :)), but a logical vector can be generated on the fly, e.g. where a column value exceeds a certain value:

myData = myData[myData$A > 4,]
myData = myData[!myData$A > 4,] # equal to myData[myData$A <= 4,]

You can transform a boolean vector to a vector of indices:

row_to_keep = which(myData$A > 4)

Finally, a very neat trick is that you can use this kind of subsetting not only for extraction, but also for assignment:

myData$A[myData$A > 4,] <- NA

where column A is assigned NA (not a number) where A exceeds 4.

Delete all local git branches

The below command will delete all the local branches except master branch.

git branch | grep -v "master" | xargs git branch -D

The above command

  1. list all the branches
  2. From the list ignore the master branch and take the rest of the branches
  3. delete the branch

get the titles of all open windows

you should use the EnumWindow API.

there are plenty of examples on how to use it from C#, I found something here:

Get Application's Window Handles

Issue with EnumWindows

filename and line number of Python script

In Python 3 you can use a variation on:

def Deb(msg = None):
  print(f"Debug {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")

In code, you can then use:

Deb("Some useful information")
Deb()

To produce:

123: Some useful information
124:

Where the 123 and 124 are the lines that the calls are made from.

How to Deserialize XML document

Kevin's anser is good, aside from the fact, that in the real world, you are often not able to alter the original XML to suit your needs.

There's a simple solution for the original XML, too:

[XmlRoot("Cars")]
public class XmlData
{
    [XmlElement("Car")]
    public List<Car> Cars{ get; set; }
}

public class Car
{
    public string StockNumber { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
}

And then you can simply call:

var ser = new XmlSerializer(typeof(XmlData));
XmlData data = (XmlData)ser.Deserialize(XmlReader.Create(PathToCarsXml));

Mongoose (mongodb) batch insert?

You can perform bulk insert using mongoDB shell using inserting the values in an array.

db.collection.insert([{values},{values},{values},{values}]);

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I encountered a similar behavior while running a malfunctioned transaction on the postgres terminal. Nothing went through after this, as the database is in a state of error. However, just as a quick fix, if you can afford to avoid rollback transaction. Following did the trick for me:

COMMIT;

Synchronization vs Lock

If you're simply locking an object, I'd prefer to use synchronized

Example:

Lock.acquire();
doSomethingNifty(); // Throws a NPE!
Lock.release(); // Oh noes, we never release the lock!

You have to explicitly do try{} finally{} everywhere.

Whereas with synchronized, it's super clear and impossible to get wrong:

synchronized(myObject) {
    doSomethingNifty();
}

That said, Locks may be more useful for more complicated things where you can't acquire and release in such a clean manner. I would honestly prefer to avoid using bare Locks in the first place, and just go with a more sophisticated concurrency control such as a CyclicBarrier or a LinkedBlockingQueue, if they meet your needs.

I've never had a reason to use wait() or notify() but there may be some good ones.

How exactly to use Notification.Builder

Self-contained example

Same technique as in this answer but:

  • self-contained: copy paste and it will compile and run
  • with a button for you to generated as many notifications as you like and play with intent and notification IDs

Source:

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("click me");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Notification notification = new Notification.Builder(Main.this)
                        /* Make app open when you click on the notification. */
                        .setContentIntent(PendingIntent.getActivity(
                                Main.this,
                                Main.this.i,
                                new Intent(Main.this, Main.class),
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setContentTitle("title")
                        .setAutoCancel(true)
                        .setContentText(String.format("id = %d", Main.this.i))
                        // Starting on Android 5, only the alpha channel of the image matters.
                        // https://stackoverflow.com/a/35278871/895245
                        // `android.R.drawable` resources all seem suitable.
                        .setSmallIcon(android.R.drawable.star_on)
                        // Color of the background on which the alpha image wil drawn white.
                        .setColor(Color.RED)
                        .build();
                final NotificationManager notificationManager =
                        (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(Main.this.i, notification);
                // If the same ID were used twice, the second notification would replace the first one. 
                //notificationManager.notify(0, notification);
                Main.this.i++;
            }
        });
        this.setContentView(button);
    }
}

Tested in Android 22.

Composer - the requested PHP extension mbstring is missing from your system

sudo apt-get install php-mbstring

# if your are using php 7.1
sudo apt-get install php7.1-mbstring

# if your are using php 7.2
sudo apt-get install php7.2-mbstring

What does "collect2: error: ld returned 1 exit status" mean?

The ld returned 1 exit status error is the consequence of previous errors. In your example there is an earlier error - undefined reference to 'clrscr' - and this is the real one. The exit status error just signals that the linking step in the build process encountered some errors. Normally exit status 0 means success, and exit status > 0 means errors.

When you build your program, multiple tools may be run as separate steps to create the final executable. In your case one of those tools is ld, which first reports the error it found (clrscr reference missing), and then it returns the exit status. Since the exit status is > 0, it means an error and is reported.

In many cases tools return as the exit status the number of errors they encountered. So if ld tool finds two errors, its exit status would be 2.

How to skip over an element in .map()?

Since 2019, Array.prototype.flatMap is a good option.

images.flatMap(({src}) => src.endsWith('.json') ? [] : src);

From MDN:

flatMap can be used as a way to add and remove items (modify the number of items) during a map. In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. In this sense, it works like the opposite of filter. Simply return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

How to update/refresh specific item in RecyclerView

A way that has worked for me personally, is using the recyclerview's adapter methods to deal with changes in it's items.

It would go in a way similar to this, create a method in your custom recycler's view somewhat like this:

public void modifyItem(final int position, final Model model) {
    mainModel.set(position, model);
    notifyItemChanged(position);
}

What's the difference between "static" and "static inline" function?

By default, an inline definition is only valid in the current translation unit.

If the storage class is extern, the identifier has external linkage and the inline definition also provides the external definition.

If the storage class is static, the identifier has internal linkage and the inline definition is invisible in other translation units.

If the storage class is unspecified, the inline definition is only visible in the current translation unit, but the identifier still has external linkage and an external definition must be provided in a different translation unit. The compiler is free to use either the inline or the external definition if the function is called within the current translation unit.

As the compiler is free to inline (and to not inline) any function whose definition is visible in the current translation unit (and, thanks to link-time optimizations, even in different translation units, though the C standard doesn't really account for that), for most practical purposes, there's no difference between static and static inline function definitions.

The inline specifier (like the register storage class) is only a compiler hint, and the compiler is free to completely ignore it. Standards-compliant non-optimizing compilers only have to honor their side-effects, and optimizing compilers will do these optimizations with or without explicit hints.

inline and register are not useless, though, as they instruct the compiler to throw errors when the programmer writes code that would make the optimizations impossible: An external inline definition can't reference identifiers with internal linkage (as these would be unavailable in a different translation unit) or define modifiable local variables with static storage duration (as these wouldn't share state accross translation units), and you can't take addresses of register-qualified variables.

Personally, I use the convention to mark static function definitions within headers also inline, as the main reason for putting function definitions in header files is to make them inlinable.

In general, I only use static inline function and static const object definitions in addition to extern declarations within headers.

I've never written an inline function with a storage class different from static.

MongoDB - admin user not authorized

For MongoDB shell version v4.2.8 I've tried different ways to back-up my database with auth, my winner solution is

mongodump -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password> --authenticationDatabase admin -o /path/to/where/i/want

SQL Server CASE .. WHEN .. IN statement

CASE AlarmEventTransactions.DeviceID should just be CASE.

You are mixing the 2 forms of the CASE expression.

How to zoom div content using jquery?

Used zoom-master/jquery.zoom.js. The zoom for the image worked perfectly. Here is a link to the page. http://www.jacklmoore.com/zoom/

 <script>
    $(document).ready(function(){
        $('#ex1').zoom();

    });
</script>

Set markers for individual points on a line in Matplotlib

A simple trick to change a particular point marker shape, size... is to first plot it with all the other data then plot one more plot only with that point (or set of points if you want to change the style of multiple points). Suppose we want to change the marker shape of second point:

x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, "-o")
x0 = [2]
y0 = [1]
plt.plot(x0, y0, "s")

plt.show()

Result is: Plot with multiple markers

enter image description here

How to set scope property with ng-init?

HTML:

<body ng-app="App">
    <div ng-controller="testController" >
        <input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" />
    </div>
    {{ testInput }}
</body>

JS:

angular.module('App', []);

testController = function ($scope) {
    console.log('test');
    $scope.$watch('testInput', testShow, true);
    function testShow() {
      console.log($scope.testInput);
    }
}

Fiddle

How to convert numpy arrays to standard TensorFlow format?

You can use tf.convert_to_tensor():

import tensorflow as tf
import numpy as np

data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)

data_tf = tf.convert_to_tensor(data_np, np.float32)

sess = tf.InteractiveSession()  
print(data_tf.eval())

sess.close()

Here's a link to the documentation for this method:

https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor

javascript filter array multiple conditions

This is an easily understandable functional solution

_x000D_
_x000D_
let filtersObject = {_x000D_
  address: "England",_x000D_
  name: "Mark"_x000D_
};_x000D_
_x000D_
let users = [{_x000D_
    name: 'John',_x000D_
    email: '[email protected]',_x000D_
    age: 25,_x000D_
    address: 'USA'_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    email: '[email protected]',_x000D_
    age: 35,_x000D_
    address: 'England'_x000D_
  },_x000D_
  {_x000D_
    name: 'Mark',_x000D_
    email: '[email protected]',_x000D_
    age: 28,_x000D_
    address: 'England'_x000D_
  }_x000D_
];_x000D_
_x000D_
function filterUsers(users, filtersObject) {_x000D_
  //Loop through all key-value pairs in filtersObject_x000D_
  Object.keys(filtersObject).forEach(function(key) {_x000D_
    //Loop through users array checking each userObject_x000D_
    users = users.filter(function(userObject) {_x000D_
      //If userObject's key:value is same as filtersObject's key:value, they stay in users array_x000D_
      return userObject[key] === filtersObject[key]_x000D_
    })_x000D_
  });_x000D_
  return users;_x000D_
}_x000D_
_x000D_
//ES6_x000D_
function filterUsersES(users, filtersObject) {_x000D_
  for (let key in filtersObject) {_x000D_
    users = users.filter((userObject) => userObject[key] === filtersObject[key]);_x000D_
  }_x000D_
  return users;_x000D_
}_x000D_
_x000D_
console.log(filterUsers(users, filtersObject));_x000D_
console.log(filterUsersES(users, filtersObject));
_x000D_
_x000D_
_x000D_

Javascript : calling function from another file

Why don't you take a look to this answer

Including javascript files inside javascript files

In short you can load the script file with AJAX or put a script tag on the HTML to include it( before the script that uses the functions of the other script). The link I posted is a great answer and has multiple examples and explanations of both methods.

Fetch: reject promise and catch the error if status is not OK?

Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren't network errors, there's nothing to catch. You'll need to throw an error yourself to use Promise#catch.

A fetch Response conveniently supplies an ok , which tells you whether the request succeeded. Something like this should do the trick:

fetch(url).then((response) => {
  if (response.ok) {
    return response.json();
  } else {
    throw new Error('Something went wrong');
  }
})
.then((responseJson) => {
  // Do something with the response
})
.catch((error) => {
  console.log(error)
});

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():

unset($arr[1]);

How does the @property decorator work in Python?

The first part is simple:

@property
def x(self): ...

is the same as

def x(self): ...
x = property(x)
  • which, in turn, is the simplified syntax for creating a property with just a getter.

The next step would be to extend this property with a setter and a deleter. And this happens with the appropriate methods:

@x.setter
def x(self, value): ...

returns a new property which inherits everything from the old x plus the given setter.

x.deleter works the same way.

jdk7 32 bit windows version to download

As detailed in the Oracle Java SE Support Roadmap

After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive

Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe (64-bit is named jdk-7u80-windows-x64.exe.

Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget to grab the file without signing in.

wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"

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

My problem was that I was using first prepare statement and then I was using mysqli query on the same page and was getting the error "Commands out of sync; you can't run this command now". The error was only then when I was using the code that had prepare statement.

What I did was to close the question. and it worked.

mysqli_stmt_close($stmt);

My code

get_category.php (here using prepare statement )

    <?php


    global $connection;
    $cat_to_delete =    mysqli_real_escape_string($connection, $_GET['get'] );

    $sql = "SELECT category_name FROM categories WHERE category_id = ? ;";


    $stmt = mysqli_stmt_init($connection);

    if (!mysqli_stmt_prepare($stmt, $sql))
        $_SESSION['error'] = "Error at preaparing for deleting query. mysqli_stmt_error($stmt) ." & redirect('../error.php');

    mysqli_stmt_bind_param($stmt, 's', $cat_to_delete);

    if (!mysqli_stmt_execute($stmt))
        $_SESSION['error'] = "ERror at executing delete category ".mysqli_stmt_error($stmt) &
            redirect('../error.php');


    mysqli_stmt_bind_result($stmt, $cat_name);

    if (!mysqli_stmt_fetch($stmt)) {
        mysqli_stmt_error($stmt);
    }



    mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);

admin_get_category_body.php (here mysqli)

        <?php

        if (isset($_GET['get']) && !empty($_GET['get']) )
        {
            include 'intodb/edit_category.php';
        }


        if (check_method('get') && isset($_GET['delete']) )
        {
            require 'intodb/delete_category.php';
        }


        if (check_method('get') && isset($_GET['get']) )
        {
            require 'intodb/get_category.php';
        }


        ?>

        <!--            start: cat body          -->

        <div     class="columns is-mobile is-centered is-vcentered">
            <div class="column is-half">
                <div   class="section has-background-white-ter box ">


                    <div class="has-text-centered column    " >
                        <h4 class="title is-4">Ctegories</h4>
                    </div>

                    <div class="column " >


                        <?php if (check_method('get') && isset($_GET['get'])) {?>
                        <form action="" method="post">
                            <?php } else {?>
                            <form action="intodb/add_category.php" method="post">
                                <?php } ?>

                                <label class="label" for="admin_add_category_bar">Add Category</label>
                                <div class="field is-grouped">

                                    <p class="control is-expanded">

                                        <?php if (check_method('get') && isset($_GET['get'])) {?>

                                            <input id="admin_add_category_bar" name="admin_add_category_bar_edit" class="input" type="text" placeholder="Add Your Category Here" value="<?php echo $cat_name; ?>">

                                            <?php


                                            ?>
                                        <?php } else {?>
                                            <input id="admin_add_category_bar" name="admin_add_category_bar" class="input" type="text" placeholder="Add Your Category Here">

                                        <?php } ?>
                                    </p>
                                    <p class="control">
                                        <input type="submit" name="admin_add_category_submit" class="button is-info my_fucking_hover_right_arrow" value="Add Category">
                                    </p>
                                </div>
                            </form>


                            <div class="">

                                <!--            start: body for all posts inside admin          -->


                                <table class="table is-bordered">
                                    <thead>
                                    <tr>
                                        <th><p>Category Name</p></th>
                                        <th><p>Edit</p></th>
                                        <th><p>Delete</p></th>
                                    </tr>
                                    </thead>

                                    <?php

                                    global $connection;
                                    $sql = "SELECT * FROM categories ;";

                                    $result = mysqli_query($connection, $sql);
                                    if (!$result) {
                                        echo mysqli_error($connection);
                                    }
                                    while($row = mysqli_fetch_assoc($result))
                                    {
                                        ?>
                                        <tbody>
                                        <tr>
                                            <td><p><?php echo $row['category_name']?></p></td>
                                            <td>
                                                <a href="admin_category.php?get=<?php echo $row['category_id']; ?>" class="button is-info my_fucking_hover_right_arrow" >Edit</a>

                                            </td>

                                            <td>
                                                <a href="admin_category.php?delete=<?php echo $row['category_id']; ?>" class="button is-danger my_fucking_hover_right_arrow" >Delete</a>

                                            </td>
                                        </tr>


                                        </tbody>
                                    <?php }?>
                                </table>

                                <!--           end: body for all posts inside admin             -->




                            </div>

                    </div>
                </div>


            </div>

        </div>
        </div>

Something that just crossed my mind, I am also again adding connection variable via global $connection;. So I think basically a whole new set of query system is being started after ending of prepare statement with mysqli_stmt_close($stmt); and also I am adding these files and other stuff via include

How do you read CSS rule values with JavaScript?

Based on @dude answer this should return relevant styles in a object, for instance:

.recurly-input {                                                                                                                                                                             
  display: block;                                                                                                                                                                            
  border-radius: 2px;                                                                                                                                                                        
  -webkit-border-radius: 2px;                                                                                                                                                                
  outline: 0;                                                                                                                                                                                
  box-shadow: none;                                                                                                                                                                          
  border: 1px solid #beb7b3;                                                                                                                                                                 
  padding: 0.6em;                                                                                                                                                                            
  background-color: #f7f7f7;                                                                                                                                                                 
  width:100%;                                                                                                                                                                                
}

This will return:

backgroundColor:
"rgb(247, 247, 247)"
border
:
"1px solid rgb(190, 183, 179)"
borderBottom
:
"1px solid rgb(190, 183, 179)"
borderBottomColor
:
"rgb(190, 183, 179)"
borderBottomLeftRadius
:
"2px"
borderBottomRightRadius
:
"2px"
borderBottomStyle
:
"solid"
borderBottomWidth
:
"1px"
borderColor
:
"rgb(190, 183, 179)"
borderLeft
:
"1px solid rgb(190, 183, 179)"
borderLeftColor
:
"rgb(190, 183, 179)"
borderLeftStyle
:
"solid"
borderLeftWidth
:
"1px"
borderRadius
:
"2px"
borderRight
:
"1px solid rgb(190, 183, 179)"
borderRightColor
:
"rgb(190, 183, 179)"
borderRightStyle
:
"solid"
borderRightWidth
:
"1px"
borderStyle
:
"solid"
borderTop
:
"1px solid rgb(190, 183, 179)"
borderTopColor
:
"rgb(190, 183, 179)"
borderTopLeftRadius
:
"2px"
borderTopRightRadius
:
"2px"
borderTopStyle
:
"solid"
borderTopWidth
:
"1px"
borderWidth
:
"1px"
boxShadow
:
"none"
display
:
"block"
outline
:
"0px"
outlineWidth
:
"0px"
padding
:
"0.6em"
paddingBottom
:
"0.6em"
paddingLeft
:
"0.6em"
paddingRight
:
"0.6em"
paddingTop
:
"0.6em"
width
:
"100%"

Code:

function getStyle(className_) {

    var styleSheets = window.document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        var classes = styleSheets[i].rules || styleSheets[i].cssRules;
        if (!classes)
            continue;
        var classesLength = classes.length;
        for (var x = 0; x < classesLength; x++) {
            if (classes[x].selectorText == className_) {
                return _.pickBy(classes[x].style, (v, k) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )
            }
        }
    }

}

Converting of Uri to String

You can use .toString method to convert Uri to String in java

Uri uri = Uri.parse("Http://www.google.com");

String url = uri.toString();

This method convert Uri to String easily

Can we make unsigned byte in Java

There is no unsigned byte in Java, but if you want to display a byte, you can do,

int myInt = 144;

byte myByte = (byte) myInt;

char myChar = (char) (myByte & 0xFF);

System.out.println("myChar :" + Integer.toHexString(myChar));

Output:

myChar : 90

For more information, please check, How to display a hex/byte value in Java.

Generate UML Class Diagram from Java Project

I wrote Class Visualizer, which does it. It's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post. For each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view. Class relations diagram allows to traverse through the whole structure. It has full support for annotations and generics plus special support for JPA entities. Works very well with big projects (thousands of classes).

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 

After

$_config[0] =& $config;
return $_config[0]; 

Update

Added by NikiC

In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).

Update

This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.

Get difference between two dates in months using Java

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

Sending JSON object to Web API

I believe you need quotes around the model:

JSON.stringify({ "model": source })

Align contents inside a div

Honestly, I hate all the solutions I've seen so far, and I'll tell you why: They just don't seem to ever align it right...so here's what I usually do:

I know what pixel values each div and their respective margins hold...so I do the following.

I'll create a wrapper div that has an absolute position and a left value of 50%...so this div now starts in the middle of the screen, and then I subtract half of all the content of the div's width...and I get BEAUTIFULLY scaling content...and I think this works across all browsers, too. Try it for yourself (this example assumes all content on your site is wrapped in a div tag that uses this wrapper class and all content in it is 200px in width):

.wrapper {
    position: absolute;
    left: 50%;
    margin-left: -100px;
}

EDIT: I forgot to add...you may also want to set width: 0px; on this wrapper div for some browsers to not show the scrollbars, and then you may use absolute positioning for all inner divs.

This also works AMAZING for vertically aligning your content as well using top: 50% and margin-top. Cheers!

How to Access Hive via Python?

None of the answers demonstrate how to fetch and print the table headers. Modified the standard example from PyHive which is widely used and actively maintained.

from pyhive import hive
cursor = hive.connect(host="localhost", 
                      port=10000, 
                      username="shadan", 
                      auth="KERBEROS", 
                      kerberos_service_name="hive"
                      ).cursor()
cursor.execute("SELECT * FROM my_dummy_table LIMIT 10")
columnList = [desc[0] for desc in cursor.description]
headerStr = ",".join(columnList)
headerTuple = tuple(headerStr.split (",")
print(headerTuple)
print(cursor.fetchone())
print(cursor.fetchall())

What is the fastest way to send 100,000 HTTP requests in Python?

A solution using tornado asynchronous networking library

from tornado import ioloop, httpclient

i = 0

def handle_request(response):
    print(response.code)
    global i
    i -= 1
    if i == 0:
        ioloop.IOLoop.instance().stop()

http_client = httpclient.AsyncHTTPClient()
for url in open('urls.txt'):
    i += 1
    http_client.fetch(url.strip(), handle_request, method='HEAD')
ioloop.IOLoop.instance().start()

How to create an android app using HTML 5

Try Sencha Touch. It is a HTML5 compliant framework to build application for touch devices.

How can I output the value of an enum class in C++11

Unlike an unscoped enumeration, a scoped enumeration is not implicitly convertible to its integer value. You need to explicitly convert it to an integer using a cast:

std::cout << static_cast<std::underlying_type<A>::type>(a) << std::endl;

You may want to encapsulate the logic into a function template:

template <typename Enumeration>
auto as_integer(Enumeration const value)
    -> typename std::underlying_type<Enumeration>::type
{
    return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}

used as:

std::cout << as_integer(a) << std::endl;

HTML table with 100% width, with vertical scroll inside tbody

try below approach, very simple easy to implement

Below is the jsfiddle link

http://jsfiddle.net/v2t2k8ke/2/

HTML:

<table border='1' id='tbl_cnt'>
<thead><tr></tr></thead><tbody></tbody>

CSS:

 #tbl_cnt{
 border-collapse: collapse; width: 100%;word-break:break-all;
 }
 #tbl_cnt thead, #tbl_cnt tbody{
 display: block;
 }
 #tbl_cnt thead tr{
 background-color: #8C8787; text-align: center;width:100%;display:block;
 }
 #tbl_cnt tbody {
 height: 100px;overflow-y: auto;overflow-x: hidden;
 }

Jquery:

 var data = [
    {
    "status":"moving","vehno":"tr544","loc":"bng","dri":"ttt"
    }, {
    "status":"stop","vehno":"tr54","loc":"che", "dri":"ttt"
    },{    "status":"idle","vehno":"yy5499999999999994","loc":"bng","dri":"ttt"
    },{
    "status":"moving","vehno":"tr544","loc":"bng", "dri":"ttt"
    }, {
    "status":"stop","vehno":"tr54","loc":"che","dri":"ttt"
    },{
    "status":"idle","vehno":"yy544","loc":"bng","dri":"ttt"
    }
    ];
   var sth = '';
   $.each(data[0], function (key, value) {
     sth += '<td>' + key + '</td>';
   });
   var stb = '';        
   $.each(data, function (key, value) {
       stb += '<tr>';
       $.each(value, function (key, value) {
       stb += '<td>' + value + '</td>';
       });
       stb += '</tr>';
    });
      $('#tbl_cnt thead tr').append(sth);
      $('#tbl_cnt tbody').append(stb);
      setTimeout(function () {
      var col_cnt=0 
      $.each(data[0], function (key, value) {col_cnt++;});    
      $('#tbl_cnt thead tr').css('width', ($("#tbl_cnt tbody") [0].scrollWidth)+ 'px');
      $('#tbl_cnt thead tr td,#tbl_cnt tbody tr td').css('width',  ($('#tbl_cnt thead tr ').width()/Number(col_cnt)) + 'px');}, 100)

Android Studio : unmappable character for encoding UTF-8

If above answeres did not work, then you can try my answer because it worked for me.
Here's what worked for me.

  1. Close Android Studio
  2. Go to C:\Usersyour username
  3. Locate the Android Studio settings directory named .AndroidStudioX.X (X.X being the version)
  4. C:\Users\my_user_name.AndroidStudio4.0\system\caches
  5. Delete the caches folder and open android studio

This should fix the issue.

vertical align middle in <div>

This Code Is for Vertical Middle and Horizontal Center Align without specify fixed height:

_x000D_
_x000D_
.parent-class-name {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.className {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  margin: 0 auto;_x000D_
  transform: translateY(-50%);_x000D_
  -moz-transform: translateY(-50%);_x000D_
  -webkit-transform: translateY(-50%);_x000D_
}
_x000D_
_x000D_
_x000D_

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

Although I didn't use this exact function I got this same error.

In my case I just had to remove the protocol.

Instead of $uri = "http://api.hostip.info/?ip=$ip&position=true";

Use $uri = "api.hostip.info/?ip=$ip&position=true";

And it worked fine afterwards

Error in MySQL when setting default value for DATE or DATETIME

It works for 5.7.8:

mysql> create table t1(updated datetime NOT NULL DEFAULT '0000-00-00 00:00:00');
Query OK, 0 rows affected (0.01 sec)

mysql> show create table t1;
+-------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                            |
+-------+-------------------------------------------------------------------------------------------------------------------------+
| t1    | CREATE TABLE `t1` (
  `updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
+-------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.8-rc  |
+-----------+
1 row in set (0.00 sec)

You can create a SQLFiddle to recreate your issue.

http://sqlfiddle.com/

If it works for MySQL 5.6 and 5.7.8, but fails on 5.7.11. Then it probably is a regression bug for 5.7.11.

php - push array into array - key issue

Don't use array_values on your $row

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       array_push($res_arr_values, $row);
   }

Also, the preferred way to add a value to an array is writing $array[] = $value;, not using array_push

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       $res_arr_values[] = $row;
   }

And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC) but to use mysql_fetch_assoc($result) directly.

$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
   {
       $res_arr_values[] = $row;
   }

CSS selector - element with a given child

Is it possible to select an element if it contains a specific child element?

Unfortunately not yet.

The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.


A Note About Specification Changes

This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.


An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.

The subject was going to be the element in the selector chain that would have styles applied to it.

Example HTML
<p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>

This selector would style the span element

p span {
    color: red;
}

This selector would style the p element

!p span {
    color: red;
}

A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()"

:has() would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has() pseudo-selector*.

In any event, continuing the example from above, to select the p element that contains a span one could use:

p:has(span) {
    color: red;
}

* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.

What is the difference between T(n) and O(n)?

Short explanation:

If an algorithm is of T(g(n)), it means that the running time of the algorithm as n (input size) gets larger is proportional to g(n).

If an algorithm is of O(g(n)), it means that the running time of the algorithm as n gets larger is at most proportional to g(n).

Normally, even when people talk about O(g(n)) they actually mean T(g(n)) but technically, there is a difference.


More technically:

O(n) represents upper bound. T(n) means tight bound. O(n) represents lower bound.

f(x) = T(g(x)) iff f(x) = O(g(x)) and f(x) = O(g(x))

Basically when we say an algorithm is of O(n), it's also O(n2), O(n1000000), O(2n), ... but a T(n) algorithm is not T(n2).

In fact, since f(n) = T(g(n)) means for sufficiently large values of n, f(n) can be bound within c1g(n) and c2g(n) for some values of c1 and c2, i.e. the growth rate of f is asymptotically equal to g: g can be a lower bound and and an upper bound of f. This directly implies f can be a lower bound and an upper bound of g as well. Consequently,

f(x) = T(g(x)) iff g(x) = T(f(x))

Similarly, to show f(n) = T(g(n)), it's enough to show g is an upper bound of f (i.e. f(n) = O(g(n))) and f is a lower bound of g (i.e. f(n) = O(g(n)) which is the exact same thing as g(n) = O(f(n))). Concisely,

f(x) = T(g(x)) iff f(x) = O(g(x)) and g(x) = O(f(x))


There are also little-oh and little-omega (?) notations representing loose upper and loose lower bounds of a function.

To summarize:

f(x) = O(g(x)) (big-oh) means that the growth rate of f(x) is asymptotically less than or equal to to the growth rate of g(x).

f(x) = O(g(x)) (big-omega) means that the growth rate of f(x) is asymptotically greater than or equal to the growth rate of g(x)

f(x) = o(g(x)) (little-oh) means that the growth rate of f(x) is asymptotically less than the growth rate of g(x).

f(x) = ?(g(x)) (little-omega) means that the growth rate of f(x) is asymptotically greater than the growth rate of g(x)

f(x) = T(g(x)) (theta) means that the growth rate of f(x) is asymptotically equal to the growth rate of g(x)

For a more detailed discussion, you can read the definition on Wikipedia or consult a classic textbook like Introduction to Algorithms by Cormen et al.

How to generate random positive and negative numbers in Java

Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables. It's done via "non standard" options. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

How to determine when a Git branch was created?

Pro Git § 3.1 Git Branching - What a Branch Is has a good explanation of what a git branch really is

A branch in Git is simply a lightweight movable pointer to [a] commit.

Since a branch is just a lightweight pointer, git has no explicit notion of its history or creation date. "But hang on," I hear you say, "of course git knows my branch history!" Well, sort of.

If you run either of the following:

git log <branch> --not master
gitk <branch> --not master

you will see what looks like the "history of your branch", but is really a list of commits reachable from 'branch' that are not reachable from master. This gives you the information you want, but if and only if you have never merged 'branch' back to master, and have never merged master into 'branch' since you created it. If you have merged, then this history of differences will collapse.

Fortunately the reflog often contains the information you want, as explained in various other answers here. Use this:

git reflog --date=local <branch>

to show the history of the branch. The last entry in this list is (probably) the point at which you created the branch.

If the branch has been deleted then 'branch' is no longer a valid git identifier, but you can use this instead, which may find what you want:

git reflog --date=local | grep <branch>

Or in a Windows cmd shell:

git reflog --date=local | find "<branch>"

Note that reflog won't work effectively on remote branches, only ones you have worked on locally.

Incrementing a date in JavaScript

You first need to parse your string before following the other people's suggestion:

var dateString = "2010-09-11";
var myDate = new Date(dateString);

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

If you want it back in the same format again you will have to do that "manually":

var y = myDate.getFullYear(),
    m = myDate.getMonth() + 1, // january is month 0 in javascript
    d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");

But I suggest getting Date.js as mentioned in other replies, that will help you alot.

Tainted canvases may not be exported

I also solved this error by adding useCORS : true, in my code like -

html2canvas($("#chart-section")[0], {
        useCORS : true,
        allowTaint : true,
        scale : 0.98,
        dpi : 500,
        width: 1400, height: 900
    }).then();

Clear data in MySQL table with PHP?

TRUNCATE TABLE `table`

unless you need to preserve the current value of the AUTO_INCREMENT sequence, in which case you'd probably prefer

DELETE FROM `table`

though if the time of the operation matters, saving the AUTO_INCREMENT value, truncating the table, and then restoring the value using

ALTER TABLE `table` AUTO_INCREMENT = value

will happen a lot faster.

How do I enable MSDTC on SQL Server?

I've found that the best way to debug is to use the microsoft tool called DTCPing

  1. Copy the file to both the server (DB) and the client (Application server/client pc)
    • Start it at the server and the client
    • At the server: fill in the client netbios computer name and try to setup a DTC connection
    • Restart both applications.
    • At the client: fill in the server netbios computer name and try to setup a DTC connection

I've had my fare deal of problems in our old company network, and I've got a few tips:

  • if you get the error message "Gethostbyname failed" it means the computer can not find the other computer by its netbios name. The server could for instance resolve and ping the client, but that works on a DNS level. Not on a netbios lookup level. Using WINS servers or changing the LMHOST (dirty) will solve this problem.
  • if you get an error "Acces Denied", the security settings don't match. You should compare the security tab for the msdtc and get the server and client to match. One other thing to look at is the RestrictRemoteClients value. Depending on your OS version and more importantly the Service Pack, this value can be different.
  • Other connection problems:
    • The firewall between the server and the client must allow communication over port 135. And more importantly the connection can be initiated from both sites (I had a lot of problems with the firewall people in my company because they assumed only the server would open an connection on to that port)
    • The protocol returns a random port to connect to for the real transaction communication. Firewall people don't like that, they like to restrict the ports to a certain range. You can restrict the RPC dynamic port generation to a certain range using the keys as described in How to configure RPC dynamic port allocation to work with firewalls.

In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.

Strtotime() doesn't work with dd/mm/YYYY format

This is a good solution to many problems:

function datetotime ($date, $format = 'YYYY-MM-DD') {

    if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $date);
    if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $date);
    if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $date);

    if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $date);
    if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $date);
    if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $date);

    if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $date);
    if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $date);
    if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $date);

    return mktime(0, 0, 0, $month, $day, $year);

}

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

python list in sql query as parameter

l = [1] # or [1,2,3]

query = "SELECT * FROM table WHERE id IN :l"
params = {'l' : tuple(l)}
cursor.execute(query, params)

The :var notation seems simpler. (Python 3.7)

How to get post slug from post in WordPress?

You can do this is in many ways like:

1- You can use Wordpress global variable $post :

<?php 
global $post;
$post_slug=$post->post_name;
?>

2- Or you can get use:

$slug = get_post_field( 'post_name', get_post() );

3- Or get full url and then use the PHP function parse_url:

$url      = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url( $url, PHP_URL_PATH );
$slug = pathinfo( $url_path, PATHINFO_BASENAME );

I hope above methods will help you.

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:

float distance = (float) loc.distanceTo(loc2);

Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?

String array initialization in Java

You mean like:

String names[] = {"Ankit","Bohra","Xyz"};

But you can only do this in the same statement when you declare it

How can I convert an HTML element to a canvas element?

the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.

this code work with the library: https://github.com/tsayen/dom-to-image

*the "id_div" is the id of the element html that you want to transform.

**the "canvas_out" is the id of the div that will contain the canvas so try this code. :

   function Guardardiv(id_div){

      var mode = 2 // default 1 (save to image), mode 2 = save to canvas
      console.log("Process start");
      var node = document.getElementById(id_div);
      // get the div that will contain the canvas
      var canvas_out = document.getElementById('canvas_out');
      var canvas = document.createElement('canvas');
      canvas.width = node.scrollWidth;
      canvas.height = node.scrollHeight;

      domtoimage.toPng(node).then(function (pngDataUrl) {
          var img = new Image();
          img.onload = function () {
          var context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
        };

        if (mode == 1){ // save to image
             downloadURI(pngDataUrl, "salida.png");
        }else if (mode == 2){ // save to canvas
          img.src = pngDataUrl;
          canvas_out.appendChild(img);

        }
      console.log("Process finish");
    });

    }

so, if you want to save to image just add this function:

    function downloadURI(uri, name) {
        var link = document.createElement("a");

        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();   
    }

Example of use:

 <html>
 <head>
 </script src="/dom-to-image.js"></script>
 </head> 
 <body>
 <div id="container">
   All content that want to transform
  </div>
  <button onclick="Guardardiv('container');">Convert<button> 

 <!-- if use mode 2 -->
 <div id="canvas_out"></div>
 </html>

Comment if that work. Comenten si les sirvio :)

Reading column names alone in a csv file

Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-

An implementation could be as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    #get fieldnames from DictReader object and store in list
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...

>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']

If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:

import csv

with open('C:/mypath/to/csvfile.csv', 'r') as f:
    #you can eat the first line before creating DictReader.
    #if no "fieldnames" param is passed into
    #DictReader object upon creation, DictReader
    #will read the upper-most line as the headers
    f.readline()

    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames

    for line in d_reader:
        #print value in MyCol1 for each row
        print(line['MyCol1'])

What can MATLAB do that R cannot do?

I have used both R and MATLAB to solve problems and construct models related to Environmental Engineering and there is a lot of overlap between the two systems. In my opinion, the advantages of MATLAB lie in specialized domain-specific applications. Some examples are:

  • Functions such as streamline that aid in fluid dynamics investigations.

  • Toolboxes such as the image processing toolset. I have not found a R package that provides an equivalent implementation of tools like the watershed algorithm.

In my opinion MATLAB provides far better interactive graphics capabilities. However, I think R produces better static print-quality graphics, depending on the application. MATLAB's symbolic math toolbox is also better integrated and more capable than R equivalents such as Ryacas or rSymPy. The existence of the MATLAB compiler also allows systems based on MATLAB code to be deployed independently of the MATLAB environment-- although it's availability will depend on how much money you have to throw around.

Another thing I should note is that the MATLAB debugger is one of the best I have worked with.

The principle advantage I see with R is the openness of the system and the ease with which it can be extended. This has resulted in an incredible diversity of packages on CRAN. I know Mathworks also maintains a repository of user-contributed toolboxes and I can't make a fair comparison as I have not used it that much.

The openness of R also extends to linking in compiled code. A while back I had a model written in Fortran and I was trying to decide between using R or MATLAB as a front-end to help prepare input and process results. I spent an hour reading about the MEX interface to compiled code. When I found that I would have to write and maintain a separate Fortran routine that did some intricate pointer juggling in order to manage the interface, I shelved MATLAB.

The R interface consists of calling .Fortran( [subroutine name], [argument list]) and is simply quicker and cleaner.

How to decide when to use Node.js?

The most important reasons to start your next project using Node ...

  • All the coolest dudes are into it ... so it must be fun.
  • You can hangout at the cooler and have lots of Node adventures to brag about.
  • You're a penny pincher when it comes to cloud hosting costs.
  • Been there done that with Rails
  • You hate IIS deployments
  • Your old IT job is getting rather dull and you wish you were in a shiny new Start Up.

What to expect ...

  • You'll feel safe and secure with Express without all the server bloatware you never needed.
  • Runs like a rocket and scales well.
  • You dream it. You installed it. The node package repo npmjs.org is the largest ecosystem of open source libraries in the world.
  • Your brain will get time warped in the land of nested callbacks ...
  • ... until you learn to keep your Promises.
  • Sequelize and Passport are your new API friends.
  • Debugging mostly async code will get umm ... interesting .
  • Time for all Noders to master Typescript.

Who uses it?

  • PayPal, Netflix, Walmart, LinkedIn, Groupon, Uber, GoDaddy, Dow Jones
  • Here's why they switched to Node.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Syntax errors is not checked easily in external servers, just runtime errors.

What I do? Just like you, I use

ini_set('display_errors', 'On');
error_reporting(E_ALL);

However, before run I check syntax errors in a PHP file using an online PHP syntax checker.

The best, IMHO is PHP Code Checker

I copy all the source code, paste inside the main box and click the Analyze button.

It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely

Initializing a list to a known number of elements in Python

This:

 lst = [8 for i in range(9)]

creates a list, elements are initialized 8

but this:

lst = [0] * 7

would create 7 lists which have one element