Programs & Examples On #Nsnumberformatter

A Cocoa class for formatting and parsing numerical values. Use this tag for questions about using `NSNumberFormatter`.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

Getting char from string at specified index

char = split_string_to_char(text)(index)

------

Function split_string_to_char(text) As String()

   Dim chars() As String
   For char_count = 1 To Len(text)
      ReDim Preserve chars(char_count - 1)
      chars(char_count - 1) = Mid(text, char_count, 1)
   Next
   split_string_to_char = chars
End Function

git-diff to ignore ^M

Why do you get these ^M in your git diff?

In my case I was working on a project which was developed in Windows and I used OS X. When I changed some code, I saw ^M at the end of the lines I added in git diff. I think the ^M were showing up because they were different line endings than the rest of the file. Because the rest of the file was developed in Windows it used CR line endings, and in OS X it uses LF line endings.

Apparently, the Windows developer didn't use the option "Checkout Windows-style, commit Unix-style line endings" during the installation of Git.

So what should we do about this?

You can have the Windows users reinstall git and use the "Checkout Windows-style, commit Unix-style line endings" option. This is what I would prefer, because I see Windows as an exception in its line ending characters and Windows fixes its own issue this way.

If you go for this option, you should however fix the current files (because they're still using the CR line endings). I did this by following these steps:

  1. Remove all files from the repository, but not from your filesystem.

    git rm --cached -r .
    
  2. Add a .gitattributes file that enforces certain files to use a LF as line endings. Put this in the file:

    *.ext text eol=crlf
    

    Replace .ext with the file extensions you want to match.

  3. Add all the files again.

    git add .
    

    This will show messages like this:

    warning: CRLF will be replaced by LF in <filename>.
    The file will have its original line endings in your working directory.
    
  4. You could remove the .gitattributes file unless you have stubborn Windows users that don't want to use the "Checkout Windows-style, commit Unix-style line endings" option.

  5. Commit and push it all.

  6. Remove and checkout the applicable files on all the systems where they're used. On the Windows systems, make sure they now use the "Checkout Windows-style, commit Unix-style line endings" option. You should also do this on the system where you executed these tasks because when you added the files git said:

    The file will have its original line endings in your working directory.
    

    You can do something like this to remove the files:

    git ls | grep ".ext$" | xargs rm -f
    

    And then this to get them back with the correct line endings:

    git ls | grep ".ext$" | xargs git checkout
    

    Of course replacing .ext with the extension you want.

Now your project only uses LF characters for the line endings, and the nasty CR characters won't ever come back :).

The other option is to enforce windows style line endings. You can also use the .gitattributes file for this.

More info: https://help.github.com/articles/dealing-with-line-endings/#platform-all

read subprocess stdout line by line

I tried this with python3 and it worked, source

def output_reader(proc):
    for line in iter(proc.stdout.readline, b''):
        print('got line: {0}'.format(line.decode('utf-8')), end='')


def main():
    proc = subprocess.Popen(['python', 'fake_utility.py'],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

    t = threading.Thread(target=output_reader, args=(proc,))
    t.start()

    try:
        time.sleep(0.2)
        import time
        i = 0

        while True:
        print (hex(i)*512)
        i += 1
        time.sleep(0.5)
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=0.2)
            print('== subprocess exited with rc =', proc.returncode)
        except subprocess.TimeoutExpired:
            print('subprocess did not terminate in time')
    t.join()

Does Git Add have a verbose switch

You can use git add -i to get an interactive version of git add, although that's not exactly what you're after. The simplest thing to do is, after having git added, use git status to see what is staged or not.

Using git add . isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).

How to create a pulse effect using -webkit-animation - outward rings

You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.

Here is a solution that cleans up a lot of code and makes the animation start from the center:

.gps_ring {
    border: 3px solid #999;
    -webkit-border-radius: 30px;
    height: 18px;
    width: 18px;
    position: absolute;
    left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

You can see it in action here: http://jsfiddle.net/Fy8vD/

Incorrect syntax near ''

The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.

To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.

I need to get all the cookies from the browser

You can only access cookies for a specific site. Using document.cookie you will get a list of escaped key=value pairs seperated by a semicolon.

secret=do%20not%20tell%you;last_visit=1225445171794

To simplify the access, you have to parse the string and unescape all entries:

var getCookies = function(){
  var pairs = document.cookie.split(";");
  var cookies = {};
  for (var i=0; i<pairs.length; i++){
    var pair = pairs[i].split("=");
    cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
  }
  return cookies;
}

So you might later write:

var myCookies = getCookies();
alert(myCookies.secret); // "do not tell you"

How to run a python script from IDLE interactive shell?

You can use this in python3:

exec(open(filename).read())

How to get JavaScript variable value in PHP

PHP runs on the server. It outputs some text. Then it stops running.

The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.

If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.

You can make an HTTP request from JavaScript by using a form or Ajax.

CSS for the "down arrow" on a <select> element?

Try this

   <div style='position:relative;left:0px;top:0px;
        onMouseOver=document.getElementById('visible').style.visibility='visible' 
        id='hidden'>10
   <select style='position:absolute;left:0px;top:0px;cursor:pointer;visibility:hidden;'
        onMouseOut=document.getElementById('visible').style.visibility='hidden'
        onChange='this.form.submit()' 
        id='visible' multiple size='3'>";
   <option selected value=10>10</option>
   <option value=20>20</option>
   <option value=50>50</option>
   </select>
   </div>

Pandas Merge - How to avoid duplicating columns

I'm freshly new with Pandas but I wanted to achieve the same thing, automatically avoiding column names with _x or _y and removing duplicate data. I finally did it by using this answer and this one from Stackoverflow

sales.csv

    city;state;units
    Mendocino;CA;1
    Denver;CO;4
    Austin;TX;2

revenue.csv

    branch_id;city;revenue;state_id
    10;Austin;100;TX
    20;Austin;83;TX
    30;Austin;4;TX
    47;Austin;200;TX
    20;Denver;83;CO
    30;Springfield;4;I

merge.py import pandas

def drop_y(df):
    # list comprehension of the cols that end with '_y'
    to_drop = [x for x in df if x.endswith('_y')]
    df.drop(to_drop, axis=1, inplace=True)


sales = pandas.read_csv('data/sales.csv', delimiter=';')
revenue = pandas.read_csv('data/revenue.csv', delimiter=';')

result = pandas.merge(sales, revenue,  how='inner', left_on=['state'], right_on=['state_id'], suffixes=('', '_y'))
drop_y(result)
result.to_csv('results/output.csv', index=True, index_label='id', sep=';')

When executing the merge command I replace the _x suffix with an empty string and them I can remove columns ending with _y

output.csv

    id;city;state;units;branch_id;revenue;state_id
    0;Denver;CO;4;20;83;CO
    1;Austin;TX;2;10;100;TX
    2;Austin;TX;2;20;83;TX
    3;Austin;TX;2;30;4;TX
    4;Austin;TX;2;47;200;TX

Visual Studio Code: format is not using indent settings

I think vscode is using autopep8 to format .py by default.

"PEP 8 -- Style Guide for Python Code | Python.org"

According to this website, the following may explain why vscode always use 4 spaces.

Use 4 spaces per indentation level.

How do I disable fail_on_empty_beans in Jackson?

You can also probably annotate the class with @JsonIgnoreProperties(ignoreUnknown=true) to ignore the fields undefined in the class

Adding whitespace in Java

String text = "text";
text += new String(" ");

how to generate web service out of wsdl

How about using the wsdl /server or wsdl /serverinterface switches? As far as I understand the wsdl.exe command line properties, that's what you're looking for.

- ADVANCED -

/server

Server switch has been deprecated. Please use /serverInterface instead.
Generate an abstract class for an xml web service implementation using
ASP.NET based on the contracts. The default is to generate client proxy
classes.

On the other hand: why do you want to create obsolete technology solutions? Why not create this web service as a WCF service. That's the current and more modern, much more flexible way to do this!

Marc


UPDATE:

When I use wsdl /server on a WSDL file, I get this file created:

[WebService(Namespace="http://.......")]
public abstract partial class OneCrmServiceType : System.Web.Services.WebService 
{
    /// <remarks/>
    [WebMethod]
    public abstract void OrderCreated(......);
}

This is basically almost exactly the same code that gets generated when you add an ASMX file to your solution (in the code behind file - "yourservice.asmx.cs"). I don't think you can get any closer to creating an ASMX file from a WSDL file.

You can always add the "yourservice.asmx" manually - it doesn't really contain much:

<%@ WebService Language="C#" CodeBehind="YourService.asmx.cs" 
      Class="YourServiceNamespace.YourServiceClass" %>

git add, commit and push commands in one?

define function in .bashrc

function gitall() {
    file=${1:-.}
    comment=${2:-update}
    echo $file
    echo $comment
    git add $file && git commit -m '$comment' && git push origin master
}

in your terminal

gitall

default gitall will add all in current git repo

gitall some-file-to-add 'update file'

will add certain file to change, and use custom commit message

How to change text color of simple list item

In simple word "you can't do it through simple setListAdapter" . you must used custom listview for freely changes in text color or in any other views

for Custom Listview you can go with this link

Command to get time in milliseconds

A Python script like this:

import time
cur_time = int(time.time()*1000)

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

If you use Ctrl-F5 (start without debugging) it will leave the console window open with a message "Press any key to continue". That's the easiest way to keep the console window from closing so you can see the console output.

Use of min and max functions in C++

As Richard Corden pointed, use C++ functions min and max defined in std namespace. They provide type safety, and help to avoid comparing mixed types (i.e. float point vs integer) what sometimes may be undesirable.

If you find that C++ library you use defines min/max as macros as well, it may cause conflicts, then you can prevent unwanted macro substitution calling the min/max functions this way (notice extra brackets):

(std::min)(x, y)
(std::max)(x, y)

Remember, this will effectively disable Argument Dependant Lookup (ADL, also called Koenig lookup), in case you want to rely on ADL.

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

no, you can't do that, but you can use event handlers to change the title:

<img src="foo.jpg" onmouseover="this.title='it is now ' + new Date()" /> 

how to use LIKE with column name

You're close.

The LIKE operator works with strings (CHAR, NVARCHAR, etc). so you need to concattenate the '%' symbol to the string...


MS SQL Server:

SELECT * FROM table1,table2 WHERE table1.x LIKE table2.y + '%'


Use of LIKE, however, is often slower than other operations. It's useful, powerful, flexible, but has performance considerations. I'll leave those for another topic though :)


EDIT:

I don't use MySQL, but this may work...

SELECT * FROM table1,table2 WHERE table1.x LIKE CONCAT(table2.y, '%')

Sorting a Python list by two fields

Python has a stable sort, so provided that performance isn't an issue the simplest way is to sort it by field 2 and then sort it again by field 1.

That will give you the result you want, the only catch is that if it is a big list (or you want to sort it often) calling sort twice might be an unacceptable overhead.

list1 = sorted(csv1, key=operator.itemgetter(2))
list1 = sorted(list1, key=operator.itemgetter(1))

Doing it this way also makes it easy to handle the situation where you want some of the columns reverse sorted, just include the 'reverse=True' parameter when necessary.

Otherwise you can pass multiple parameters to itemgetter or manually build a tuple. That is probably going to be faster, but has the problem that it doesn't generalise well if some of the columns want to be reverse sorted (numeric columns can still be reversed by negating them but that stops the sort being stable).

So if you don't need any columns reverse sorted, go for multiple arguments to itemgetter, if you might, and the columns aren't numeric or you want to keep the sort stable go for multiple consecutive sorts.

Edit: For the commenters who have problems understanding how this answers the original question, here is an example that shows exactly how the stable nature of the sorting ensures we can do separate sorts on each key and end up with data sorted on multiple criteria:

DATA = [
    ('Jones', 'Jane', 58),
    ('Smith', 'Anne', 30),
    ('Jones', 'Fred', 30),
    ('Smith', 'John', 60),
    ('Smith', 'Fred', 30),
    ('Jones', 'Anne', 30),
    ('Smith', 'Jane', 58),
    ('Smith', 'Twin2', 3),
    ('Jones', 'John', 60),
    ('Smith', 'Twin1', 3),
    ('Jones', 'Twin1', 3),
    ('Jones', 'Twin2', 3)
]

# Sort by Surname, Age DESCENDING, Firstname
print("Initial data in random order")
for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

print('''
First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred''')
DATA.sort(key=lambda row: row[1])

for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

print('''
Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.''')
DATA.sort(key=lambda row: row[2], reverse=True)
for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

print('''
Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.
''')
DATA.sort(key=lambda row: row[0])
for d in DATA:
    print("{:10s} {:10s} {}".format(*d))

This is a runnable example, but to save people running it the output is:

Initial data in random order
Jones      Jane       58
Smith      Anne       30
Jones      Fred       30
Smith      John       60
Smith      Fred       30
Jones      Anne       30
Smith      Jane       58
Smith      Twin2      3
Jones      John       60
Smith      Twin1      3
Jones      Twin1      3
Jones      Twin2      3

First we sort by first name, after this pass all
Twin1 come before Twin2 and Anne comes before Fred
Smith      Anne       30
Jones      Anne       30
Jones      Fred       30
Smith      Fred       30
Jones      Jane       58
Smith      Jane       58
Smith      John       60
Jones      John       60
Smith      Twin1      3
Jones      Twin1      3
Smith      Twin2      3
Jones      Twin2      3

Second pass: sort by age in descending order.
Note that after this pass rows are sorted by age but
Twin1/Twin2 and Anne/Fred pairs are still in correct
firstname order.
Smith      John       60
Jones      John       60
Jones      Jane       58
Smith      Jane       58
Smith      Anne       30
Jones      Anne       30
Jones      Fred       30
Smith      Fred       30
Smith      Twin1      3
Jones      Twin1      3
Smith      Twin2      3
Jones      Twin2      3

Final pass sorts the Jones from the Smiths.
Within each family members are sorted by age but equal
age members are sorted by first name.

Jones      John       60
Jones      Jane       58
Jones      Anne       30
Jones      Fred       30
Jones      Twin1      3
Jones      Twin2      3
Smith      John       60
Smith      Jane       58
Smith      Anne       30
Smith      Fred       30
Smith      Twin1      3
Smith      Twin2      3

Note in particular how in the second step the reverse=True parameter keeps the firstnames in order whereas simply sorting then reversing the list would lose the desired order for the third sort key.

Select subset of columns in data.table R

Another alternative is to use .SDcols

cols = paste0("V", c(1,2,3,5))
dt[, .SD, .SDcols=-cols]

How to create a new text file using Python

    file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
    any_string = "Hello\nWorld"
    file.write(any_string)
    file.close()

How to change password using TortoiseSVN?

On the server.. In our environment, we're running Apache2 on Windows Server 2003.
Suppose Apache is serving our repository from C:\repo\MyProject

The actual repository is in C:\repo\MyProject\db

and the configuration is in C:\repo\MyProject\conf

So the passwords are in: C:\repo\MyProject.htaccess

They're encrypted, a tool similar to this: http://tools.dynamicdrive.com/password/

How do you split a list into evenly sized chunks?

If you had a chunk size of 3 for example, you could do:

zip(*[iterable[i::3] for i in range(3)]) 

source: http://code.activestate.com/recipes/303060-group-a-list-into-sequential-n-tuples/

I would use this when my chunk size is fixed number I can type, e.g. '3', and would never change.

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

How do I determine the current operating system with Node.js

Works fine for me

if (/^win/i.test(process.platform)) {
    // TODO: Windows
} else {
    // TODO: Linux, Mac or something else
}

The i modifier is used to perform case-insensitive matching.

Decode JSON with unknown structure

package main

import "encoding/json"

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

https://play.golang.org/p/o8ZwvgsQmoO

how to get current datetime in SQL?

I always just use NOW():

INSERT INTO table (lastModifiedTime) VALUES (NOW())

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_now

How to auto-size an iFrame?

I just happened to come by your question and i have a solution. But its in jquery. Its too simple.

$('iframe').contents().find('body').css({"min-height": "100", "overflow" : "hidden"});
setInterval( "$('iframe').height($('iframe').contents().find('body').height() + 20)", 1 );

There you go!

Cheers! :)

Edit: If you have a Rich Text Editor based on the iframe method and not the div method and want it to expand every new line then this code will do the needful.

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

This prevents the default parameter-less constructor from being used elsewhere in your code.

How to send email from Terminal?

For SMTP hosts and Gmail I like to use Swaks -> https://easyengine.io/tutorials/mail/swaks-smtp-test-tool/

On a Mac:

  1. brew install swaks
  2. swaks --to [email protected] --server smtp.example.com

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I've updated com.google.gms:google-services from 3.2.0 to 3.2.1 and the warning stopped appearing.

 buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        classpath 'com.google.gms:google-services:3.2.1'

    }
}

How can I make PHP display the error instead of giving me 500 Internal Server Error

Enabling error displaying from PHP code doesn't work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don't know which line. From the console, I use this:

/var/log/php-fpm# cat www-error.log | grep mycode.php

And I have the output:

[04-Apr-2016 06:58:27] PHP Parse error:  syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458

This helps me find the line where I have the typo.

Call PHP function from Twig template

There is already a Twig extension that lets you call PHP functions form your Twig templates like:

Hi, I am unique: {{ uniqid() }}.

And {{ floor(7.7) }} is floor of 7.7.

See official extension repository.

How to put a jar in classpath in Eclipse?

Right click on the project in which you want to put jar file. A window will open like this

enter image description here

Click on the AddExternal Jars there you can give the path to that jar file

How to get the number of threads in a Java process

Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed.

ps -o nlwp <pid>

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

String delimiter in string.split method

There is no need to set the delimiter by breaking it up in pieces like you have done.

Here is a complete program you can compile and run:

import java.util.Arrays;
public class SplitExample {
    public static final String PLAYER = "1||1||Abdul-Jabbar||Karim||1996||1974";
    public static void main(String[] args) {
        String[] data = PLAYER.split("\\|\\|");
        System.out.println(Arrays.toString(data));
    }
}

If you want to use split with a pattern, you can use Pattern.compile or Pattern.quote.

To see compile and quote in action, here is an example using all three approaches:

import java.util.Arrays;
import java.util.regex.Pattern;
public class SplitExample {
    public static final String PLAYER = "1||1||Abdul-Jabbar||Karim||1996||1974";
    public static void main(String[] args) {
        String[] data = PLAYER.split("\\|\\|");
        System.out.println(Arrays.toString(data));

        Pattern pattern = Pattern.compile("\\|\\|");
        data = pattern.split(PLAYER);
        System.out.println(Arrays.toString(data));

        pattern = Pattern.compile(Pattern.quote("||"));
        data = pattern.split(PLAYER);
        System.out.println(Arrays.toString(data));
    }
}

The use of patterns is recommended if you are going to split often using the same pattern. BTW the output is:

[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]
[1, 1, Abdul-Jabbar, Karim, 1996, 1974]

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

Why doesn't file_get_contents work?

If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).

I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.

Heatmap in matplotlib with pcolor?

This is late, but here is my python implementation of the flowingdata NBA heatmap.

updated:1/4/2014: thanks everyone

# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# ------------------------------------------------------------------------
# Filename   : heatmap.py
# Date       : 2013-04-19
# Updated    : 2014-01-04
# Author     : @LotzJoe >> Joe Lotz
# Description: My attempt at reproducing the FlowingData graphic in Python
# Source     : http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/
#
# Other Links:
#     http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor
#
# ------------------------------------------------------------------------

import matplotlib.pyplot as plt
import pandas as pd
from urllib2 import urlopen
import numpy as np
%pylab inline

page = urlopen("http://datasets.flowingdata.com/ppg2008.csv")
nba = pd.read_csv(page, index_col=0)

# Normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())

# Sort data according to Points, lowest to highest
# This was just a design choice made by Yau
# inplace=False (default) ->thanks SO user d1337
nba_sort = nba_norm.sort('PTS', ascending=True)

nba_sort['PTS'].head(10)

# Plot it out
fig, ax = plt.subplots()
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)

# Format
fig = plt.gcf()
fig.set_size_inches(8, 11)

# turn off the frame
ax.set_frame_on(False)

# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(nba_sort.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(nba_sort.shape[1]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

# Set the labels

# label source:https://en.wikipedia.org/wiki/Basketball_statistics
labels = [
    'Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 'Free throws attempts', 'Free throws percentage',
    'Three-pointers made', 'Three-point attempt', 'Three-point percentage', 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']

# note I could have used nba_sort.columns but made "labels" instead
ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(nba_sort.index, minor=False)

# rotate the
plt.xticks(rotation=90)

ax.grid(False)

# Turn off all the ticks
ax = plt.gca()

for t in ax.xaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False
for t in ax.yaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False

The output looks like this: flowingdata-like nba heatmap

There's an ipython notebook with all this code here. I've learned a lot from 'overflow so hopefully someone will find this useful.

mailto link multiple body lines

To get body lines use escape()

body_line =  escape("\n");

so

href = "mailto:[email protected]?body=hello,"+body_line+"I like this.";

How to test abstract class in Java with JUnit?

With the example class you posted it doesn't seem to make much sense to test getFuel() and getSpeed() since they can only return 0 (there are no setters).

However, assuming that this was just a simplified example for illustrative purposes, and that you have legitimate reasons to test methods in the abstract base class (others have already pointed out the implications), you could setup your test code so that it creates an anonymous subclass of the base class that just provides dummy (no-op) implementations for the abstract methods.

For example, in your TestCase you could do this:

c = new Car() {
       void drive() { };
   };

Then test the rest of the methods, e.g.:

public class CarTest extends TestCase
{
    private Car c;

    public void setUp()
    {
        c = new Car() {
            void drive() { };
        };
    }

    public void testGetFuel() 
    {
        assertEquals(c.getFuel(), 0);
    }

    [...]
}

(This example is based on JUnit3 syntax. For JUnit4, the code would be slightly different, but the idea is the same.)

How to fix warning from date() in PHP"

error_reporting(E_ALL ^ E_WARNING);

:)

You should change subject to "How to fix warning from date() in PHP"...

IOException: The process cannot access the file 'file path' because it is being used by another process

As other answers in this thread have pointed out, to resolve this error you need to carefully inspect the code, to understand where the file is getting locked.

In my case, I was sending out the file as an email attachment before performing the move operation.

So the file got locked for couple of seconds until SMTP client finished sending the email.

The solution I adopted was to move the file first, and then send the email. This solved the problem for me.

Another possible solution, as pointed out earlier by Hudson, would've been to dispose the object after use.

public static SendEmail()
{
           MailMessage mMailMessage = new MailMessage();
           //setup other email stuff

            if (File.Exists(attachmentPath))
            {
                Attachment attachment = new Attachment(attachmentPath);
                mMailMessage.Attachments.Add(attachment);
                attachment.Dispose(); //disposing the Attachment object
            }
} 

Question mark and colon in JavaScript

? : isn't this the ternary operator?

var x= expression ? true:false

Can't run Curl command inside my Docker Container

curl: command not found

is a big hint, you have to install it with :

apt-get update; apt-get install curl

Show Error on the tip of the Edit Text Android

You have written your code in onClick event. This will call when you click on EditText. But this is something like you are checking it before entering.

So what my suggestion is, you should use focus changed. When any view get focus, you are setting no error and when focus changed, you check whether there is valid input or not like below.

firstName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View arg0, boolean arg1) {
        firstName.setError(null);
        if (firstName.getText().toString().trim().equalsIgnoreCase("")) {
            firstName.setError("Enter FirstName");
        }
    }
});

Mockito, JUnit and Spring

The difference in whether you have to instantiate your @InjectMocks annotated field is in the version of Mockito, not in whether you use the MockitoJunitRunner or MockitoAnnotations.initMocks. In 1.9, which will also handle some constructor injection of your @Mock fields, it will do the instantiation for you. In earlier versions, you have to instantiate it yourself.

This is how I do unit testing of my Spring beans. There is no problem. People run into confusion when they want to use Spring configuration files to actually do the injection of the mocks, which is crossing up the point of unit tests and integration tests.

And of course the unit under test is an Impl. You need to test a real concrete thing, right? Even if you declared it as an interface you would have to instantiate the real thing to test it. Now, you could get into spies, which are stub/mock wrappers around real objects, but that should be for corner cases.

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

How to enable external request in IIS Express?

I did all of these steps and nothing helped me. And what I need, it's just to run my app via IIS Express...

enter image description here

Hope it helps.

Difference between PACKETS and FRAMES

Packet

A packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network. When any file (e-mail message, HTML file, Graphics Interchange Format file, Uniform Resource Locator request, and so forth) is sent from one place to another on the Internet, the Transmission Control Protocol (TCP) layer of TCP/IP divides the file into "chunks" of an efficient size for routing. Each of these packets is separately numbered and includes the Internet address of the destination. The individual packets for a given file may travel different routes through the Internet. When they have all arrived, they are reassembled into the original file (by the TCP layer at the receiving end).

Frame

1) In telecommunications, a frame is data that is transmitted between network points as a unit complete with addressing and necessary protocol control information. A frame is usually transmitted serial bit by bit and contains a header field and a trailer field that "frame" the data. (Some control frames contain no data.)

2) In time-division multiplexing (TDM), a frame is a complete cycle of events within the time division period.

3) In film and video recording and playback, a frame is a single image in a sequence of images that are recorded and played back.

4) In computer video display technology, a frame is the image that is sent to the display image rendering devices. It is continuously updated or refreshed from a frame buffer, a highly accessible part of video RAM.

5) In artificial intelligence (AI) applications, a frame is a set of data with information about a particular object, process, or image. An example is the iris-print visual recognition system used to identify users of certain bank automated teller machines. This system compares the frame of data for a potential user with the frames in its database of authorized users.

commands not found on zsh

For me just restarting my terminal seemed to fix the issue.

How to access List elements

It's simple

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:
        print(a)

How do I set browser width and height in Selenium WebDriver?

Try something like this:

IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);

Not sure if it'll resize after being launched though, so maybe it's not what you want

Cleanest way to build an SQL string in Java

I second the recommendations for using an ORM like Hibernate. However, there are certainly situations where that doesn't work, so I'll take this opportunity to tout some stuff that i've helped to write: SqlBuilder is a java library for dynamically building sql statements using the "builder" style. it's fairly powerful and fairly flexible.

Function to get yesterday's date in Javascript in format DD/MM/YYYY

The problem here seems to be that you're reassigning $today by assigning a string to it:

$today = $dd+'/'+$mm+'/'+$yyyy;

Strings don't have getDate.

Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:

$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.

Then just apply the formatting code you wrote:

var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;

Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.

PHP - define constant inside a class

This is a pretty old question, but perhaps this answer can still help someone else.

You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:

class Foo {

    // This is a private constant
    final public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.

To get nearly exactly what Alex was looking for the following code can be used:

final class Constants {

    public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

class Foo {

    static public app()
    {
        return new Constants();
    }
}

The emulated constant value would be accessible like this:

Foo::app()->MYCONSTANT();

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

[Updated to adapt to modern pandas, which has isnull as a method of DataFrames..]

You can use isnull and any to build a boolean Series and use that to index into your frame:

>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False
>>> df.isnull().any(axis=1)
0    False
1     True
2     True
3    False
4    False
dtype: bool
>>> df[df.isnull().any(axis=1)]
   0   1   2
1  0 NaN   0
2  0   0 NaN

[For older pandas:]

You could use the function isnull instead of the method:

In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])

In [57]: df
Out[57]: 
   0   1   2
0  0   1   2
1  0 NaN   0
2  0   0 NaN
3  0   1   2
4  0   1   2

In [58]: pd.isnull(df)
Out[58]: 
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False

In [59]: pd.isnull(df).any(axis=1)
Out[59]: 
0    False
1     True
2     True
3    False
4    False

leading to the rather compact:

In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]: 
   0   1   2
1  0 NaN   0
2  0   0 NaN

Populating a ListView using an ArrayList?

Here's an example of how you could implement a list view:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //We have our list view
    final ListView dynamic = findViewById(R.id.dynamic);

    //Create an array of elements
    final ArrayList<String> classes = new ArrayList<>();
    classes.add("Data Structures");
    classes.add("Assembly Language");
    classes.add("Calculus 3");
    classes.add("Switching Systems");
    classes.add("Analysis Tools");

    //Create adapter for ArrayList
    final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, classes);

    //Insert Adapter into List
    dynamic.setAdapter(adapter);

    //set click functionality for each list item
    dynamic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("User clicked ", classes.get(position));
        }
    });



}

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

How to count certain elements in array?

It is better to wrap it into function:

let countNumber = (array,specificNumber) => {
    return array.filter(n => n == specificNumber).length
}

countNumber([1,2,3,4,5],3) // returns 1

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

I was able to trigger an SDK download like this:

  1. Close Android Studio
  2. Open android studio, but be ready
  3. Once you see "loading project", click cancel. (this will only appear for seconds on a fast machine)
  4. The SDK download window appeared!

How to get the path of current worksheet in VBA?

If you want to get the path of the workbook from where the macro is being executed - use Application.ThisWorkbook.Path.
Application.ActiveWorkbook.Path can sometimes produce unexpected results (e.g. if your macro switches between multiple workbooks).

How do I create an .exe for a Java program?

If you really want an exe Excelsior JET is a professional level product that compiles to native code:

http://www.excelsior-usa.com/jet.html

You can also look at JSMooth:

http://jsmooth.sourceforge.net/

And if your application is compatible with its compatible with AWT/Apache classpath then GCJ compiles to native exe.

How to create/read/write JSON files in Qt5

Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.

So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:

value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;

and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL as needed):

value x(ctx);
std::cin >> x;
if (x.soap->error)
  exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
  if (x["appDesc"].has("description"))
    USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
  if (x["appDesc"].has("message"))
    USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
  if (x["appName"].has("description"))
    USE_VAL("$.appName.description", x["appName"]["description"]);
  if (x["appName"].has("message"))
    USE_VAL("$.appName.message", x["appName"]["message"]);
  if (x["appName"].has("imp"))
  {
    for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
      USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
  }
}

This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.

"No such file or directory" error when executing a binary

The answer is in this line of the output of readelf -a in the original question

  [Requesting program interpreter: /lib/ld-linux.so.2]

I was missing the /lib/ld-linux.so.2 file, which is needed to run 32-bit apps. The Ubuntu package that has this file is libc6-i386.

Is there a built-in function to print all the current properties and values of an object?

from pprint import pprint

def print_r(the_object):
    print ("CLASS: ", the_object.__class__.__name__, " (BASE CLASS: ", the_object.__class__.__bases__,")")
    pprint(vars(the_object))

Get custom product attributes in Woocommerce

Although @airdrumz solutions works, you will get lots of errors about you doing it wrong by accessing ID directly, this is not good for future compatibility.

But it lead me to inspect the object and create this OOP approach:

function myplug_get_prod_attrs() {
    // Enqueue scripts happens very early, global $product has not been created yet, neither has the post/loop
    global $product;
    $wc_attr_objs = $product->get_attributes();
    $prod_attrs = [];
    foreach ($wc_attr_objs as $wc_attr => $wc_term_objs) {
        $prod_attrs[$wc_attr] = [];
        $wc_terms = $wc_term_objs->get_terms();
        foreach ($wc_terms as $wc_term) {
            array_push($prod_attrs[$wc_attr], $wc_term->slug);
        }
    }
    return $prod_attrs;
}

Bonus, if you are performing the above early before the global $product item is created (e.g. during enqueue scripts), you can make it yourself with:

    $product = wc_get_product(get_queried_object_id());

Invert "if" statement to reduce nesting

This is a bit of a religious argument, but I agree with ReSharper that you should prefer less nesting. I believe that this outweighs the negatives of having multiple return paths from a function.

The key reason for having less nesting is to improve code readability and maintainability. Remember that many other developers will need to read your code in the future, and code with less indentation is generally much easier to read.

Preconditions are a great example of where it is okay to return early at the start of the function. Why should the readability of the rest of the function be affected by the presence of a precondition check?

As for the negatives about returning multiple times from a method - debuggers are pretty powerful now, and it's very easy to find out exactly where and when a particular function is returning.

Having multiple returns in a function is not going to affect the maintainance programmer's job.

Poor code readability will.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

Swift 5.2, 4 and later

Main and Background Queues

let main = DispatchQueue.main
let background = DispatchQueue.global()
let helper = DispatchQueue(label: "another_thread") 

Working with async and sync threads!

 background.async { //async tasks here } 
 background.sync { //sync tasks here } 

Async threads will work along with the main thread.

Sync threads will block the main thread while executing.

Java 8 - Difference between Optional.flatMap and Optional.map

You can refer below link to understand in detail (best explanation which I could find):

https://www.programmergirl.com/java-8-map-flatmap-difference/

Both map and flatMap - accept Function. The return type of map() is a single value whereas flatMap is returning stream of values

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

Open Facebook page from Android app?

To do this we need the "Facebook page id", you can get it :

  • from the page go to "About".
  • go to "More Info" section.

introducir la descripción de la imagen aquí

To opening facebook app on specified profile page,

you can do this:

 String facebookId = "fb://page/<Facebook Page ID>";
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookId)));

Or you can validate when the facebook app is not installed, then open the facebook web page.

String facebookId = "fb://page/<Facebook Page ID>";
String urlPage = "http://www.facebook.com/mypage";

     try {
          startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookId )));
        } catch (Exception e) {
         Log.e(TAG, "Application not intalled.");
         //Open url web page.
         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlPage)));
        }

Unable to ping vmware guest from another vmware guest

  1. Check the firewall on all the windows system. If it's enabled, disable it.
  2. If you still are unable to ping, Open the virtual network editor and check if you are using the same VMnet adapter for both the VM's, this adapter should be present in the host machine's network adapters as well. Share a screenshot of what you are seeing in the virtual network editor.

How can I remove the last character of a string in python?

For a path use os.path.abspath

import os    
print os.path.abspath(my_file_path)

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

TextView bold via xml file?

use textstyle property as bold

android:textStyle = "bold";

Using onBackPressed() in Android Fragments

In the fragment where you would like to handle your back button you should attach stuff to your view in the oncreateview

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_fragment, container, false);
    v.setOnKeyListener(pressed);
    return v;
}



@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if( keyCode == KeyEvent.KEYCODE_BACK ){
            // back to previous fragment by tag
            myfragmentclass fragment = (myfragmentclass) getActivity().getSupportFragmentManager().findFragmentByTag(TAG);
            if(fragment != null){
                (getActivity().getSupportFragmentManager().beginTransaction()).replace(R.id.cf_g1_mainframe_fm, fragment).commit();
            }
            return true;
        }
        return false;
    }
};

How can I convert a Word document to PDF?

It's already 2019, I can't believe still no easiest and conveniencest way to convert the most popular Micro$oft Word document to Adobe PDF format in Java world.

I almost tried every method the above answers mentioned, and I found the best and the only way can satisfy my requirement is by using OpenOffice or LibreOffice. Actually I am not exactly know the difference between them, seems both of them provide soffice command line.

My requirement is:

  1. It must run on Linux, more specifically CentOS, not on Windows, thus we cannot install Microsoft Office on it;
  2. It must support Chinese character, so ISO-8859-1 character encoding is not a choice, it must support Unicode.

First thing came in mind is doc-to-pdf-converter, but it lacks of maintenance, last update happened 4 years ago, I will not use a nobody-maintain-solution. Xdocreport seems a promising choice, but it can only convert docx, but not doc binary file which is mandatory for me. Using Java to call OpenOffice API seems good, but too complicated for such a simple requirement.

Finally I found the best solution: use OpenOffice command line to finish the job:

Runtime.getRuntime().exec("soffice --convert-to pdf -outdir . /path/some.doc");

I always believe the shortest code is the best code (of course it should be understandable), that's it.

Connecting to MySQL from Android with JDBC

If u need to connect your application to a server you can do it through PHP/MySQL and JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ .Mysql Connection code should be in AsynTask class. Dont run it in Main Thread.

How do you convert a byte array to a hexadecimal string, and vice versa?

In terms of speed, this seems to be better than anything here:

  public static string ToHexString(byte[] data) {
    byte b;
    int i, j, k;
    int l = data.Length;
    char[] r = new char[l * 2];
    for (i = 0, j = 0; i < l; ++i) {
      b = data[i];
      k = b >> 4;
      r[j++] = (char)(k > 9 ? k + 0x37 : k + 0x30);
      k = b & 15;
      r[j++] = (char)(k > 9 ? k + 0x37 : k + 0x30);
    }
    return new string(r);
  }

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

mutable does exist as you infer to allow one to modify data in an otherwise constant function.

The intent is that you might have a function that "does nothing" to the internal state of the object, and so you mark the function const, but you might really need to modify some of the objects state in ways that don't affect its correct functionality.

The keyword may act as a hint to the compiler -- a theoretical compiler could place a constant object (such as a global) in memory that was marked read-only. The presence of mutable hints that this should not be done.

Here are some valid reasons to declare and use mutable data:

  • Thread safety. Declaring a mutable boost::mutex is perfectly reasonable.
  • Statistics. Counting the number of calls to a function, given some or all of its arguments.
  • Memoization. Computing some expensive answer, and then storing it for future reference rather than recomputing it again.

Jquery each - Stop loop and return object

Try this ...

  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';  

  var test =  findXX('o322'); 
  console.log(test);



function findXX(word)
{  
  for(var i in someArray){


    if(someArray[i] == word)
    {
      return someArray[i]; //<---  stop the loop!
    }   
  }
}

remove all variables except functions

I wrote this to remove all objects apart from functions from the current environment (Programming language used is R with IDE R-Studio):

    remove_list=c()                             # create a vector

      for(i in 1:NROW(ls())){                   # repeat over all objects in environment
        if(class(get(ls()[i]))!="function"){    # if object is *not* a function
         remove_list=c(remove_list,ls()[i])     # ..add to vector remove_list
         }    
      }

    rm(list=remove_list)                        # remove all objects named in remove_list

Notes-

The argument "list" in rm(list=) must be a character vector.

The name of an object in position i of the current environment is returned from ls()[i] and the object itself from get(ls()[i]). Therefore the class of an object is returned from class(get(ls()[i]))

TLS 1.2 in .NET Framework 4.0

I code in VB and was able to add the following line to my Global.asax.vb file inside of Application_Start

ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)    'TLS 1.2

Rebasing a Git merge commit

  • From your merge commit
  • Cherry-pick the new change which should be easy
  • copy your stuff
  • redo the merge and resolve the conflicts by just copying the files from your local copy ;)

read word by word from file in C++

If I may I could give you some new code for the same task, in my code you can create a so called 'document'(not really)and it is saved, and can be opened up again. It is also stored as a string file though(not a document). Here is the code:

#include "iostream"

#include "windows.h"

#include "string"

#include "fstream"

using namespace std;

int main() {

string saveload;


cout << "---------------------------" << endl;
cout << "|enter 'text' to write your document    |" << endl;
cout << "|enter 'open file' to open the document |" << endl;
cout << "----------------------------------------" << endl;
while (true){
    getline(cin, saveload);

    if (saveload == "open file"){
        string filenamet;
        cout << "file name? " << endl;
        getline(cin, filenamet, '*');
        ifstream loadFile;

        loadFile.open(filenamet, ifstream::in);

        cout << "the text you entered was: ";

        while (loadFile.good()){

            cout << (char)loadFile.get();

            Sleep(100);
        }

        cout << "" << endl;

        loadFile.close();

    }

    if (saveload == "text") {
        string filename;
        cout << "file name: " << endl;
        getline(cin, filename,'*');
        string textToSave;
        cout << "Enter your text: " << endl;
        getline(cin, textToSave,'*');

        ofstream saveFile(filename);

        saveFile << textToSave;

        saveFile.close();

    }
}
return 0;
}

Just take this code and change it to serve your purpose. DREAM BIG,THINK BIG, DO BIG

Difference between JOIN and INNER JOIN

Similarly with OUTER JOINs, the word "OUTER" is optional. It's the LEFT or RIGHT keyword that makes the JOIN an "OUTER" JOIN.

However for some reason I always use "OUTER" as in LEFT OUTER JOIN and never LEFT JOIN, but I never use INNER JOIN, but rather I just use "JOIN":

SELECT ColA, ColB, ...
FROM MyTable AS T1
     JOIN MyOtherTable AS T2
         ON T2.ID = T1.ID
     LEFT OUTER JOIN MyOptionalTable AS T3
         ON T3.ID = T1.ID

Which programming language for cloud computing?

This is always fascinating. I am not a cloud developer, but based on my research there is nothing significantly different than what many of us have been doing off and on for decades. The server is platform specific. If you want to write platform agnostic code for your server that is fine, but unnecessary based on whoever your cloud server provider is. I think the biggest difference I've seen so far is the concept of providing a large set of services for the front end client to process. the front end, I'm assuming is predominantly web or web app development. As most browsers can handle LAMP vs Microsoft stack well enough, then you are still back to whatever your flavor of the month is. The only difference I truly am seeing from what I did 20 years ago in a highly distributed network environment are higher level protocol (HTTP vs. TCP/UDP). Maybe I am wrong and would welcome the education, but then again I've been doing this a long time and still have not seen anything I would consider revolutionary or significantly different, though languages like Java, C#, Python, Ruby, etc are significantly simpler to program in which is a mixed bag as the bar is lowered for those are are not familiar with writing optimized code. PAAS and SAAS to me seem to be some of the keys in the new technology, but been doing some of this to off and on for 20 years :)

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

You don't need to down grade. You can run more than one version of Java on MacOS. You can set the version of your terminal with this command in MacOS.

# List Java versions installed
/usr/libexec/java_home -V

# Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)

# Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

# Java 1.7
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

# Java 1.6
export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)

You can set the default value in the .bashrc, .profile, or .zprofile

Could not create the Java virtual machine

I had this issue today, and for me the problem was that I had allocated too much memory:

-Xmx1024M -XX:MaxPermSize=1024m

Once I reduced the PermGen space, everything worked fine:

-Xmx1024M -XX:MaxPermSize=512m

I know that doesn't look like much of a difference, but my machine only has 4GB of RAM, and apparently that was the straw that broke the camel's back. The Java VM was failing immediately upon every action because it was failing to allocate the memory.

After installation of Gulp: “no command 'gulp' found”

if still not resolved try adding this to your package.js scripts

"scripts": { "gulp": "gulp" },

and run npm run gulp it will runt gulp scripts from gulpfile.js

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

Excel VBA - Sum up a column

I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell. rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:

dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))

or

dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))

The worksheet function sum will correctly ignore blank spaces.

Let me know if this helps!

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

Why is quicksort better than mergesort?

As many people have noted, the average case performance for quicksort is faster than mergesort. But this is only true if you are assuming constant time to access any piece of memory on demand.

In RAM this assumption is generally not too bad (it is not always true because of caches, but it is not too bad). However if your data structure is big enough to live on disk, then quicksort gets killed by the fact that your average disk does something like 200 random seeks per second. But that same disk has no trouble reading or writing megabytes per second of data sequentially. Which is exactly what mergesort does.

Therefore if data has to be sorted on disk, you really, really want to use some variation on mergesort. (Generally you quicksort sublists, then start merging them together above some size threshold.)

Furthermore if you have to do anything with datasets of that size, think hard about how to avoid seeks to disk. For instance this is why it is standard advice that you drop indexes before doing large data loads in databases, and then rebuild the index later. Maintaining the index during the load means constantly seeking to disk. By contrast if you drop the indexes, then the database can rebuild the index by first sorting the information to be dealt with (using a mergesort of course!) and then loading it into a BTREE datastructure for the index. (BTREEs are naturally kept in order, so you can load one from a sorted dataset with few seeks to disk.)

There have been a number of occasions where understanding how to avoid disk seeks has let me make data processing jobs take hours rather than days or weeks.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

This error can be received but be aware it can be a red herring to the real issue. In my case, there wasn't an issue with the JSON as the error states, but rather a 404 was occurring that it could not pull the JSON data to process in the 1st place thus resulting in this error.

The fix for this was that in order to use fetch on a .json file in a local project, the .json file must be accessible. This can be done by placing it in a folder such as the public folder in the root of the project. Once I moved the json file into that folder, the 404 turned into a 200, and the Unexpected token < in JSON at position 0 error was resolved.

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

Apache error: _default_ virtualhost overlap on port 443

It is highly unlikely that adding NameVirtualHost *:443 is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).

If you're running a relatively stock Apache configuration, you probably have this somewhere:

<VirtualHost _default_:443>

Your best bet is to either:

  • Place your additional SSL configuration into this existing VirtualHost container, or
  • Comment out this entire VirtualHost block and create a new one. Don't forget to include all the relevant SSL options.

Adding script tag to React/JSX

I tried to edit the accepted answer by @Alex McMillan but it won't let me so heres a separate answer where your able to get the value of the library your loading in. A very important distinction that people asked for and I needed for my implementation with stripe.js.

useScript.js

import { useState, useEffect } from 'react'

export const useScript = (url, name) => {

  const [lib, setLib] = useState({})

  useEffect(() => {
    const script = document.createElement('script')

    script.src = url
    script.async = true
    script.onload = () => setLib({ [name]: window[name] })

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])

  return lib

}

usage looks like

const PaymentCard = (props) => {
  const { Stripe } = useScript('https://js.stripe.com/v2/', 'Stripe')
}

NOTE: Saving the library inside an object because often times the library is a function and React will execute the function when storing in state to check for changes -- which will break libs (like Stripe) that expect to be called with specific args -- so we store that in an object to hide that from React and protect library functions from being called.

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

check this out no need for third party libraries you can simply export datatable data to excel file using this

var dt = "your code for getting data into datatable";
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd")));
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dataColumn in dt.Columns)
            {
                Response.Write(tab + dataColumn.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dataRow in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dataRow[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();

Resetting a multi-stage form with jQuery

Complementing the accepted answer, if you use SELECT2 plugin, you need to recall select2 script to make changes is all select2 fields:

function resetForm(formId){
        $('#'+formId).find('input:text, input:password, input:file, select, select2, textarea').val('');
        $('#'+formId).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
        $('.select2').select2();
    }

Labeling file upload button

To make a custom "browse button" solution simply try making a hidden browse button, a custom button or element and some Jquery. This way I'm not modifying the actual "browse button" which is dependent on each browser/version. Here's an example.

HTML:

<div id="import" type="file">My Custom Button</div>
<input id="browser" class="hideMe" type="file"></input>

CSS:

#import {
  margin: 0em 0em 0em .2em;
  content: 'Import Settings';
  display: inline-block;
  border: 1px solid;
  border-color: #ddd #bbb #999;
  border-radius: 3px;
  padding: 5px 8px;
  outline: none;
  white-space: nowrap;
  -webkit-user-select: none;
  cursor: pointer;
  font-weight: 700;
  font: bold 12px/1.2 Arial,sans-serif !important;
  /* fallback */
  background-color: #f9f9f9;
  /* Safari 4-5, Chrome 1-9 */
  background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#C2C1C1), to(#2F2727));
}

.hideMe{
    display: none;
}

JS:

$("#import").click(function() {
    $("#browser").trigger("click");
    $('#browser').change(function() {
            alert($("#browser").val());
    });
});

Bind a function to Twitter Bootstrap Modal Close

Starting Bootstrap 3 (edit: still the same in Bootstrap 4) there are 2 instances in which you can fire up events, being:

1. When modal "hide" event starts

$('#myModal').on('hide.bs.modal', function () { 
    console.log('Fired at start of hide event!');
});  

2. When modal "hide" event finished

$('#myModal').on('hidden.bs.modal', function () {
    console.log('Fired when hide event has finished!');
});

Ref: http://getbootstrap.com/javascript/#js-events

Calling async method on button click

This is what's killing you:

task.Wait();

That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...

There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:

private async void Button_Click(object sender, RoutedEventArgs 
{
    Task<List<MyObject>> task = GetResponse<MyObject>("my url");
    var items = await task;
    // Presumably use items here
}

Or just:

private async void Button_Click(object sender, RoutedEventArgs 
{
    var items = await GetResponse<MyObject>("my url");
    // Presumably use items here
}

Now instead of blocking until the task has completed, the Button_Click method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)

Note that I would also rename GetResponse to GetResponseAsync for clarity.

Removing black dots from li and ul

CSS :

ul{
list-style-type:none;
}

You can take a look at W3School

Getting value from a cell from a gridview on RowDataBound event

protected void gvbind_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";
        e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.gvbind, "Select$" + e.Row.RowIndex);
    }
}

Setting device orientation in Swift iOS

Hi for LandscapeLeft and LandscapeRight (Update Swift 2.0)

enter image description here And you have this in info

enter image description here

And UIController

override func shouldAutorotate() -> Bool {
    return true
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return [UIInterfaceOrientationMask.LandscapeLeft,UIInterfaceOrientationMask.LandscapeRight]
}

For PortraitUpsideDown and Portrait use that enter image description here

override func shouldAutorotate() -> Bool {
    if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
        UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
        UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
            return false
    }
    else {
        return true
    }
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return [UIInterfaceOrientationMask.Portrait ,UIInterfaceOrientationMask.PortraitUpsideDown]
}

Message from France, Merry Christmas !

Edit :

Other solution :

extension UINavigationController {
    public override func shouldAutorotate() -> Bool {
        if visibleViewController is MyViewController {
            return true   // rotation
        } else {
            return false  // no rotation
        }
    }

    public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return (visibleViewController?.supportedInterfaceOrientations())!
    }
}

Where does Console.WriteLine go in ASP.NET?

The TraceContext object in ASP.NET writes to the DefaultTraceListener which outputs to the host process’ standard output. Rather than using Console.Write(), if you use Trace.Write, output will go to the standard output of the process.

You could use the System.Diagnostics.Process object to get the ASP.NET process for your site and monitor standard output using the OutputDataRecieved event.

Save multiple sheets to .pdf

In Excel 2013 simply select multiple sheets and do a "Save As" and select PDF as the file type. The multiple pages will open in PDF when you click save.

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

Running python script inside ipython

from within the directory of "my_script.py" you can simply do:

%run ./my_script.py

c - warning: implicit declaration of function ‘printf’

You need to include a declaration of the printf() function.

#include <stdio.h>

Displaying better error message than "No JSON object could be decoded"

The accepted answer is the easiest one to fix the problem. But in case you are not allowed to install the simplejson due to your company policy, I propose below solution to fix the particular issue of "using comma on the last item in a list":

  1. Create a child class "JSONLintCheck" to inherite from class "JSONDecoder" and override the init method of the class "JSONDecoder" like below:

    def __init__(self, encoding=None, object_hook=None, parse_float=None,parse_int=None, parse_constant=None, strict=True,object_pairs_hook=None)        
            super(JSONLintCheck,self).__init__(encoding=None, object_hook=None,      parse_float=None,parse_int=None, parse_constant=None, strict=True,object_pairs_hook=None)
            self.scan_once = make_scanner(self)
    
  1. make_scanner is a new function that used to override the 'scan_once' method of the above class. And here is code for it:
  1 #!/usr/bin/env python
  2 from json import JSONDecoder
  3 from json import decoder
  4 import re
  5
  6 NUMBER_RE = re.compile(
  7     r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
  8     (re.VERBOSE | re.MULTILINE | re.DOTALL))
  9
 10 def py_make_scanner(context):
 11     parse_object = context.parse_object
 12     parse_array = context.parse_array
 13     parse_string = context.parse_string
 14     match_number = NUMBER_RE.match
 15     encoding = context.encoding
 16     strict = context.strict
 17     parse_float = context.parse_float
 18     parse_int = context.parse_int
 19     parse_constant = context.parse_constant
 20     object_hook = context.object_hook
 21     object_pairs_hook = context.object_pairs_hook
 22
 23     def _scan_once(string, idx):
 24         try:
 25             nextchar = string[idx]
 26         except IndexError:
 27             raise ValueError(decoder.errmsg("Could not get the next character",string,idx))
 28             #raise StopIteration
 29
 30         if nextchar == '"':
 31             return parse_string(string, idx + 1, encoding, strict)
 32         elif nextchar == '{':
 33             return parse_object((string, idx + 1), encoding, strict,
 34                 _scan_once, object_hook, object_pairs_hook)
 35         elif nextchar == '[':
 36             return parse_array((string, idx + 1), _scan_once)
 37         elif nextchar == 'n' and string[idx:idx + 4] == 'null':
 38             return None, idx + 4
 39         elif nextchar == 't' and string[idx:idx + 4] == 'true':
 40             return True, idx + 4
 41         elif nextchar == 'f' and string[idx:idx + 5] == 'false':
 42             return False, idx + 5
 43
 44         m = match_number(string, idx)
 45         if m is not None:
 46             integer, frac, exp = m.groups()
 47             if frac or exp:
 48                 res = parse_float(integer + (frac or '') + (exp or ''))
 49             else:
 50                 res = parse_int(integer)
 51             return res, m.end()
 52         elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
 53             return parse_constant('NaN'), idx + 3
 54         elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
 55             return parse_constant('Infinity'), idx + 8
 56         elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
 57             return parse_constant('-Infinity'), idx + 9
 58         else:
 59             #raise StopIteration   # Here is where needs modification
 60             raise ValueError(decoder.errmsg("Expecting propert name enclosed in double quotes",string,idx))
 61     return _scan_once
 62
 63 make_scanner = py_make_scanner
  1. Better put the 'make_scanner' function together with the new child class into a same file.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

How do I make the first letter of a string uppercase in JavaScript?

Check out this solution:

var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master

Rethrowing exceptions in Java without losing the stack trace

In Java, you just throw the exception you caught, so throw e rather than just throw. Java maintains the stack trace.

How to continue a Docker container which has exited

by name

sudo docker start bob_the_container

or by Id

sudo docker start aa3f365f0f4e

this restarts stopped container, use -i to attach container's STDIN or instead of -i you can attach to container session (if you run with -it)

sudo docker attach bob_the_container

How do I get only directories using Get-ChildItem?

To answer the original question specifically (using IO.FileAttributes):

Get-ChildItem c:\mypath -Recurse | Where-Object {$_.Attributes -and [IO.FileAttributes]::Directory}

I do prefer Marek's solution though (Where-Object { $_ -is [System.IO.DirectoryInfo] }).

Using OpenGl with C#?

SharpGL is a project that lets you use OpenGL in your Windows Forms or WPF applications.

Normalize data in pandas

In [92]: df
Out[92]:
           a         b          c         d
A  -0.488816  0.863769   4.325608 -4.721202
B -11.937097  2.993993 -12.916784 -1.086236
C  -5.569493  4.672679  -2.168464 -9.315900
D   8.892368  0.932785   4.535396  0.598124

In [93]: df_norm = (df - df.mean()) / (df.max() - df.min())

In [94]: df_norm
Out[94]:
          a         b         c         d
A  0.085789 -0.394348  0.337016 -0.109935
B -0.463830  0.164926 -0.650963  0.256714
C -0.158129  0.605652 -0.035090 -0.573389
D  0.536170 -0.376229  0.349037  0.426611

In [95]: df_norm.mean()
Out[95]:
a   -2.081668e-17
b    4.857226e-17
c    1.734723e-17
d   -1.040834e-17

In [96]: df_norm.max() - df_norm.min()
Out[96]:
a    1
b    1
c    1
d    1

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

Is there a way to break a list into columns?

I've found that (currently) Chrome (Version 52.0.2743.116 m) has tons of quirks and issues with css column-count regarding overflow items and absolute positioned elements inside items, especially with some dimensions transitions..

it's a total mess and cannot be fix, so I tried tackling this through simple javascript, and had created a library which does that - https://github.com/yairEO/listBreaker

Demo page

Regular expression which matches a pattern, or is an empty string

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use

^$|^[^@\s]+@[^@\s]+$

meaning

^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
@         
[^@\s]+
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

How to reset Jenkins security settings from the command line?

Jenkins over KUBENETES and Docker

In case of Jenkins over a container managed by a Kubernetes POD is a bit more complex since: kubectl exec PODID --namespace=jenkins -it -- /bin/bash will you allow to access directly to the container running Jenkins, but you will not have root access, sudo, vi and many commands are not available and therefore a workaround is needed.

Use kubectl describe pod [...] to find the node running your Pod and the container ID (docker://...)

  • SSH into the node
  • run docker exec -ti -u root -- /bin/bash to access the container with Root privileges
  • apt-get update
  • sudo apt-get install vim

The second difference is that the Jenkins configuration file are placed in a different path that corresponds to the mounting point of the persistent volume, i.e. /var/jenkins_home, this location might change in the future, check it running df.

Then disable security - change true to false in /var/jenkins_home/jenkins/config.xml file.

<useSecurity>false</useSecurity>

Now it is enough to restart the Jenkins, action that will cause the container and the Pod to die, it will created again in some seconds with the configuration updated (and all the chance like vi, update erased) thanks to the persistent volume.

The whole solution has been tested on Google Kubernetes Engine. UPDATE Notice that you can as well run ps -aux the password in plain text is shown even without root access.

jenkins@jenkins-87c47bbb8-g87nw:/$ps -aux
[...]
jenkins [..] -jar /usr/share/jenkins/jenkins.war --argumentsRealm.passwd.jenkins=password --argumentsRealm.roles.jenkins=admin
[...]

Converting Secret Key into a String and Vice Versa

You can convert the SecretKey to a byte array (byte[]), then Base64 encode that to a String. To convert back to a SecretKey, Base64 decode the String and use it in a SecretKeySpec to rebuild your original SecretKey.

For Java 8

SecretKey to String:

// create new key
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
// get base64 encoded version of the key
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());

String to SecretKey:

// decode the base64 encoded string
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); 

For Java 7 and before (including Android):

NOTE I: you can skip the Base64 encoding/decoding part and just store the byte[] in SQLite. That said, performing Base64 encoding/decoding is not an expensive operation and you can store strings in almost any DB without issues.

NOTE II: Earlier Java versions do not include a Base64 in one of the java.lang or java.util packages. It is however possible to use codecs from Apache Commons Codec, Bouncy Castle or Guava.

SecretKey to String:

// CREATE NEW KEY
// GET ENCODED VERSION OF KEY (THIS CAN BE STORED IN A DB)

    SecretKey secretKey;
    String stringKey;

    try {secretKey = KeyGenerator.getInstance("AES").generateKey();}
    catch (NoSuchAlgorithmException e) {/* LOG YOUR EXCEPTION */}

    if (secretKey != null) {stringKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT)}

String to SecretKey:

// DECODE YOUR BASE64 STRING
// REBUILD KEY USING SecretKeySpec

    byte[] encodedKey     = Base64.decode(stringKey, Base64.DEFAULT);
    SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");

Can't find how to use HttpContent

Just leaving the way using Microsoft.AspNet.WebApi.Client here.

Example:

var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());

An efficient way to Base64 encode a byte array?

Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[].

However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:

string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);

This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)

PHP error: Notice: Undefined index:

Assure you have used method="post" in the form you are sending data from.

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

In my projects, this piece of code always worked as a default serializer which serializes the specified value as if there was no special converter:

serializer.Serialize(writer, value);

Import SQL file into mysql

I have installed my wamp server in D: drive so u have to go to the following path from ur command line->(and if u have installed ur wamp in c: drive then just replace the d: wtih c: here)

D:\>cd wamp
D:\wamp>cd bin
D:\wamp\bin>cd mysql
D:\wamp\bin\mysql>cd mysql5.5.8 (whatever ur verserion will be displayed here use keyboard Tab button)
D:\wamp\bin\mysql\mysql5.5.8>cd bin
D:\wamp\bin\mysql\mysql5.5.8\bin>mysql -u root -p password db_name < "d:\backupfile.sql"

here root is user of my phpmyadmin password is the password for phpmyadmin so if u haven't set any password for root just nothing type at that place, db_name is the database (for which database u r taking the backup) ,backupfile.sql is the file from which u want ur backup of ur database and u can also change the backup file location(d:\backupfile.sql) from to any other place on your computer

How to install SQL Server Management Studio 2012 (SSMS) Express?

When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe

I had to choose the following options to get the management Tools:

  1. "New SQL Server stand-alone installation or add features to an existing installation."
  2. "Add features to an existing instance of SQL Server 2012"
  3. Accept the license.
  4. Check the box for "Management Tools - Basic".
  5. Wait a long time as it installs.

When I was done I had an option "SQL Server Management Studio" within my Start Menu.

Searching for "Management" pulled it up faster within the Start Menu.

When should use Readonly and Get only properties

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

How to get the integer value of day of week

Another way to get Monday with integer value 1 and Sunday with integer value 7

int day = ((int)DateTime.Now.DayOfWeek + 6) % 7 + 1;

Mongoose: Get full list of users

you can also do it by async function to get all the users

await User.find({},(err,users)=>{

    if (err){
    return  res.status(422).send(err)
    }

    if (!users){
        return res.status(422).send({error:"No data in the collection"})
    }

    res.send({Allusers:users})

})

Toggle Checkboxes on/off

You can write:

$(document).ready(function() {
    $("#select-all-teammembers").click(function() {
        var checkBoxes = $("input[name=recipients\\[\\]]");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    });                 
});

Before jQuery 1.6, when we only had attr() and not prop(), we used to write:

checkBoxes.attr("checked", !checkBoxes.attr("checked"));

But prop() has better semantics than attr() when applied to "boolean" HTML attributes, so it is usually preferred in this situation.

Android global variable

There are a few different ways you can achieve what you are asking for.

1.) Extend the application class and instantiate your controller and model objects there.

public class FavoriteColorsApplication extends Application {

    private static FavoriteColorsApplication application;
    private FavoriteColorsService service;

    public FavoriteColorsApplication getInstance() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        application.initialize();
    }

    private void initialize() {
        service = new FavoriteColorsService();
    }

    public FavoriteColorsService getService() {
        return service;
    }

}

Then you can call the your singleton from your custom Application object at any time:

public class FavoriteColorsActivity extends Activity {

private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_favorite_colors);

    service = ((FavoriteColorsApplication) getApplication()).getService();
    favoriteColors = service.findAllColors();

    ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
    adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
            favoriteColors);
    lv.setAdapter(adapter);
}

2.) You can have your controller just create a singleton instance of itself:

public class Controller {
    private static final String TAG = "Controller";
    private static sController sController;
    private Dao mDao;

    private Controller() {
        mDao = new Dao();    
    }

    public static Controller create() {
        if (sController == null) {
            sController = new Controller();
        }
        return sController;
    }
}

Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.

3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.

I hope I gave enough detail in regards to how you can do what you are hoping for.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The servlet API .jar file must not be embedded inside the webapp since, obviously, the container already has these classes in its classpath: it implements the interfaces contained in this jar.

The dependency should be in the provided scope, rather than the default compile scope, in your Maven pom:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Bootstrap: Collapse other sections when one is expanded

For Bootstrap v4.1

Add the data-parent attribute to the collapse elements instead on the button.

<div id="myGroup">
<button class="btn dropdown" data-toggle="collapse" data-target="#keys"><i class="icon-chevron-right"></i> Keys  <span class="badge badge-info pull-right">X</span></button>
<button class="btn dropdown" data-toggle="collapse" data-target="#attrs"><i class="icon-chevron-right"></i> Attributes</button>
<button class="btn dropdown" data-toggle="collapse" data-target="#edit"><i class="icon-chevron-right"></i> Edit Details</button>

<div class="accordion-group">
    <div class="collapse indent" id="keys"  data-parent="#myGroup">
        keys
    </div>

    <div class="collapse indent" id="attrs"  data-parent="#myGroup">
        attrs
    </div>

    <div class="collapse" id="edit"  data-parent="#myGroup">
        edit
    </div>
</div>

Curl Command to Repeat URL Request

You can use any bash looping constructs like FOR, with is compatible to Linux and Mac.

https://tiswww.case.edu/php/chet/bash/bashref.html#Looping-Constructs

In your specific case you can define N iterations, with N is a number defining how many curl executions you want.

for n in {1..N}; do curl <arguments>; done

ex:

for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done

How to redirect back to form with input - Laravel 5

You can use the following:

return Redirect::back()->withInput(Input::all());

If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.

Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:

return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

You need to add jaxb dependancies to maven. The glassfish implementation version 2.3.2 is perfectly compatible with new jakarta EE jaxb api version 2.3.2.

<!-- API -->
<dependency>
    <groupId>jakarta.xml.bind</groupId>
    <artifactId>jakarta.xml.bind-api</artifactId>
    <version>2.3.2</version>
</dependency>

<!-- Runtime -->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.2</version>
</dependency>

How to reset postgres' primary key sequence when it falls out of sync?

These functions are fraught with perils when sequence names, column names, table names or schema names have funny characters such as spaces, punctuation marks, and the like. I have written this:

CREATE OR REPLACE FUNCTION sequence_max_value(oid) RETURNS bigint
VOLATILE STRICT LANGUAGE plpgsql AS  $$
DECLARE
 tabrelid oid;
 colname name;
 r record;
 newmax bigint;
BEGIN
 FOR tabrelid, colname IN SELECT attrelid, attname
               FROM pg_attribute
              WHERE (attrelid, attnum) IN (
                      SELECT adrelid::regclass,adnum
                        FROM pg_attrdef
                       WHERE oid IN (SELECT objid
                                       FROM pg_depend
                                      WHERE refobjid = $1
                                            AND classid = 'pg_attrdef'::regclass
                                    )
          ) LOOP
      FOR r IN EXECUTE 'SELECT max(' || quote_ident(colname) || ') FROM ' || tabrelid::regclass LOOP
          IF newmax IS NULL OR r.max > newmax THEN
              newmax := r.max;
          END IF;
      END LOOP;
  END LOOP;
  RETURN newmax;
END; $$ ;

You can call it for a single sequence by passing it the OID and it will return the highest number used by any table that has the sequence as default; or you can run it with a query like this, to reset all the sequences in your database:

 select relname, setval(oid, sequence_max_value(oid))
   from pg_class
  where relkind = 'S';

Using a different qual you can reset only the sequence in a certain schema, and so on. For example, if you want to adjust sequences in the "public" schema:

select relname, setval(pg_class.oid, sequence_max_value(pg_class.oid))
  from pg_class, pg_namespace
 where pg_class.relnamespace = pg_namespace.oid and
       nspname = 'public' and
       relkind = 'S';

Note that due to how setval() works, you don't need to add 1 to the result.

As a closing note, I have to warn that some databases seem to have defaults linking to sequences in ways that do not let the system catalogs have full information of them. This happens when you see things like this in psql's \d:

alvherre=# \d baz
                     Tabla «public.baz»
 Columna |  Tipo   |                 Modificadores                  
---------+---------+------------------------------------------------
 a       | integer | default nextval(('foo_a_seq'::text)::regclass)

Note that the nextval() call in that default clause has a ::text cast in addition to the ::regclass cast. I think this is due to databases being pg_dump'ed from old PostgreSQL versions. What will happen is that the function sequence_max_value() above will ignore such a table. To fix the problem, you can redefine the DEFAULT clause to refer to the sequence directly without the cast:

alvherre=# alter table baz alter a set default nextval('foo_a_seq');
ALTER TABLE

Then psql displays it properly:

alvherre=# \d baz
                     Tabla «public.baz»
 Columna |  Tipo   |             Modificadores              
---------+---------+----------------------------------------
 a       | integer | default nextval('foo_a_seq'::regclass)

As soon as you've fixed that, the function works correctly for this table as well as all others that might use the same sequence.

Creating virtual directories in IIS express

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
   </application>
   <application path="/OffSiteStuff" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="d:\temp\SubFolderApp" />
   </application>
    <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Practically you need to add a new application tag in your site for each virtual directory. You get a lot of flexibility because you can set different configuration for the virtual directory (for example a different .Net Framework version)

EDIT Thanks to Fevzi Apaydin to point to a more elegant solution.

You can achieve same result by adding one or more virtualDirectory tag to the Application tag:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
   </application>
    <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Reference:

How can I get screen resolution in java?

You can get the screen size with the Toolkit.getScreenSize() method.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();

On a multi-monitor configuration you should use this :

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();

If you want to get the screen resolution in DPI you'll have to use the getScreenResolution() method on Toolkit.


Resources :

SQL to find the number of distinct values in a column

**

Using following SQL we can get the distinct column value count in Oracle 11g.

**

Select count(distinct(Column_Name)) from TableName

Close pre-existing figures in matplotlib when running from eclipse

You can close a figure by calling matplotlib.pyplot.close, for example:

from numpy import *
import matplotlib.pyplot as plt
from scipy import *

t = linspace(0, 0.1,1000)
w = 60*2*pi


fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)

You can also close all open figures by calling matplotlib.pyplot.close("all")

Best way to update an element in a generic List

You could do:

var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));

This will return the matching dog, else it will return null.

You can then set the property like follows:

if (matchingDog != null)
    matchingDog.Name = "New Dog Name";

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Using STS 3.9.1 I got the same problem. However, currently I do not require any new JUnit5 features, so I tried to force using an older version. If using maven, you can add following dependencies to your pom.xml:

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>${junit.platform.version}</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>${junit.jupiter.version}</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>${junit.vintage.version}</version>
    <scope>test</scope>
</dependency>

This did the trick for me (at least as long as I do not need JUnit5 explicitly).

multiple conditions for filter in spark data frames

You need to use filter

package dataframe

import org.apache.spark.sql.SparkSession
/**
 * @author [email protected]
 */
//

object DataFrameExample{
  //
  case class Employee(id: Integer, name: String, address: String, salary: Double, state: String,zip:Integer)
  //
  def main(args: Array[String]) {
    val spark =
      SparkSession.builder()
        .appName("DataFrame-Basic")
        .master("local[4]")
        .getOrCreate()

    import spark.implicits._

    // create a sequence of case class objects 

    // (we defined the case class above)

    val emp = Seq( 
    Employee(1, "vaquar khan", "111 algoinquin road chicago", 120000.00, "AZ",60173),
    Employee(2, "Firdos Pasha", "1300 algoinquin road chicago", 2500000.00, "IL",50112),
    Employee(3, "Zidan khan", "112 apt abcd timesqure NY", 50000.00, "NY",55490),
    Employee(4, "Anwars khan", "washington dc", 120000.00, "VA",33245),
    Employee(5, "Deepak sharma ", "rolling edows schumburg", 990090.00, "IL",60172),
    Employee(6, "afaq khan", "saeed colony Bhopal", 1000000.00, "AZ",60173)
    )

    val employee=spark.sparkContext.parallelize(emp, 4).toDF()

     employee.printSchema()

    employee.show()


    employee.select("state", "zip").show()

    println("*** use filter() to choose rows")

    employee.filter($"state".equalTo("IL")).show()

    println("*** multi contidtion in filer || ")

    employee.filter($"state".equalTo("IL") || $"state".equalTo("AZ")).show()

    println("*** multi contidtion in filer &&  ")

    employee.filter($"state".equalTo("AZ") && $"zip".equalTo("60173")).show()

  }
}

Repeating a function every few seconds

Use a timer. Keep in mind that .NET comes with a number of different timers. This article covers the differences.

How do I get the directory that a program is running from?

Maybe concatenate the current working directory with argv[0]? I'm not sure if that would work in Windows but it works in linux.

For example:

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv) {
    char the_path[256];

    getcwd(the_path, 255);
    strcat(the_path, "/");
    strcat(the_path, argv[0]);

    printf("%s\n", the_path);

    return 0;
}

When run, it outputs:

jeremy@jeremy-desktop:~/Desktop$ ./test
/home/jeremy/Desktop/./test

How to run an awk commands in Windows?

Quoting is an issue if you're running awk from the command line. You'll sometimes need to use \, e.g. to quote ", but most of the time you'll use ^:

w:\srv>dir | grep ".txt" | awk "{ printf(\"echo %s@%s ^> %s.tstamp^\n\", $1, $2, $4); }"
echo 2014-09-07@22:21 > requirements-dev.txt.tstamp
echo 2014-11-28@18:14 > syncspec.txt.tstamp

ModuleNotFoundError: What does it mean __main__ is not a package?

Remove the dot and import absolute_import in the beginning of your file

from __future__ import absolute_import

from p_02_paying_debt_off_in_a_year import compute_balance_after

How to jump back to NERDTree from file in tab?

All The Shortcuts And Functionality is At

press CTRL-?

CORS header 'Access-Control-Allow-Origin' missing

This happens generally when you try access another domain's resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

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

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the ressources:

Access-Control-Allow-Origin : *

OR

Access-Control-Allow-Origin : http://www.my-domain.com

Peace and code ;)

Oracle PL/SQL - How to create a simple array variable?

You can use VARRAY for a fixed-size array:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
   for i in 1..array.count loop
       dbms_output.put_line(array(i));
   end loop;
end;

Or TABLE for an unbounded array:

...
   type array_t is table of varchar2(10);
...

The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.

With either of these you need to both initialise and extend the collection before adding elements:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t(); -- Initialise it
begin
   for i in 1..3 loop
      array.extend(); -- Extend it
      array(i) := 'x';
   end loop;
end;

The first index is 1 not 0.

Smooth scroll to specific div on click

Ned Rockson basically answers this question. However there is a fatal flaw within his solution. When the targeted element is closer to the bottom of the page than the viewport-height, the function doesn't reach its exit statement and traps the user on the bottom of the page. This is simply solved by limiting the iteration count.

var smoothScroll = function(elementId) {
    var MIN_PIXELS_PER_STEP = 16;
    var MAX_SCROLL_STEPS = 30;
    var target = document.getElementById(elementId);
    var scrollContainer = target;
    do {
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do {
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
                                 (targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);

    var iterations = 0;
    var stepFunc = function() {
        if(iterations > MAX_SCROLL_STEPS){
            return;
        }
        scrollContainer.scrollTop =
            Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);

        if (scrollContainer.scrollTop >= targetY) {
            return;
        }

        window.requestAnimationFrame(stepFunc);
    };

    window.requestAnimationFrame(stepFunc);
}

How to remove an HTML element using Javascript?

Change the input type to "button". As T.J. and Pav said, the form is getting submitted. Your Javascript looks correct, and I commend you for trying it out the non-JQuery way :)

How to do a HTTP HEAD request from the windows command line?

There is a Win32 port of wget that works decently.

PowerShell's Invoke-WebRequest -Method Head would work as well.

How to fix the height of a <div> element?

If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:

overflow: hidden;

How to make a local variable (inside a function) global

Here are two methods to achieve the same thing:

Using parameters and return (recommended)

def other_function(parameter):
    return parameter + 5

def main_function():
    x = 10
    print(x)    
    x = other_function(x)
    print(x)

When you run main_function, you'll get the following output

>>> 10
>>> 15

Using globals (never do this)

x = 0   # The initial value of x, with global scope

def other_function():
    global x
    x = x + 5

def main_function():
    print(x)    # Just printing - no need to declare global yet
    global x   # So we can change the global x
    x = 10
    print(x)
    other_function()
    print(x)

Now you will get:

>>> 0    # Initial global value
>>> 10   # Now we've set it to 10 in `main_function()`
>>> 15   # Now we've added 5 in `other_function()`

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

Swift: declare an empty dictionary

You can simply declare it like this:

var emptyDict:NSMutableDictionary = [:]

Test if a property is available on a dynamic variable

Just in case it helps someone:

If the method GetDataThatLooksVerySimilarButNotTheSame() returns an ExpandoObject you can also cast to a IDictionary before checking.

dynamic test = new System.Dynamic.ExpandoObject();
test.foo = "bar";

if (((IDictionary<string, object>)test).ContainsKey("foo"))
{
    Console.WriteLine(test.foo);
}

How do I perform query filtering in django templates

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

Use jQuery to get the file input's selected filename without the path

Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.

To get just the filename portion of a string, you can use split()...

var file = path.split('\\').pop();

jsFiddle.

...or a regular expression...

var file = path.match(/\\([^\\]+)$/)[1];

jsFiddle.

...or lastIndexOf()...

var file = path.substr(path.lastIndexOf('\\') + 1);

jsFiddle.

How to hide a div with jQuery?

$("#myDiv").hide();

will set the css display to none. if you need to set visibility to hidden as well, could do this via

$("#myDiv").css("visibility", "hidden");

or combine both in a chain

$("#myDiv").hide().css("visibility", "hidden");

or write everything with one css() function

$("#myDiv").css({
  display: "none",
  visibility: "hidden"
});

Add JavaScript object to JavaScript object

As my first object is a native javascript object (used like a list of objects), push didn't work in my escenario, but I resolved it by adding new key as following:

MyObjList['newKey'] = obj;

In addition to this, may be usefull to know how to delete same object inserted before:

delete MyObjList['newKey'][id];

Hope it helps someone as it helped me;

Pattern matching using a wildcard

glob2rx() converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.

If you want to match "blue*" where * has the usual wildcard, not regular expression, meaning we use glob2rx() to convert the wildcard pattern into a useful regular expression:

> glob2rx("blue*")
[1] "^blue"

The returned object is a regular expression.

Given your data:

x <- c('red','blue1','blue2', 'red2')

we can pattern match using grep() or similar tools:

> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE  TRUE  TRUE FALSE

As for the selecting rows problem you posted

> a <- data.frame(x =  c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2

or via subset():

> with(a, subset(a, subset = grepl(grx, x)))
      x
2 blue1
3 blue2

Hope that explains what grob2rx() does and how to use it?

Construct pandas DataFrame from items in nested dictionary

In case someone wants to get the data frame in a "long format" (leaf values have the same type) without multiindex, you can do this:

pd.DataFrame.from_records(
    [
        (level1, level2, level3, leaf)
        for level1, level2_dict in user_dict.items()
        for level2, level3_dict in level2_dict.items()
        for level3, leaf in level3_dict.items()
    ],
    columns=['UserId', 'Category', 'Attribute', 'value']
)

    UserId    Category Attribute     value
0       12  Category 1     att_1         1
1       12  Category 1     att_2  whatever
2       12  Category 2     att_1        23
3       12  Category 2     att_2   another
4       15  Category 1     att_1        10
5       15  Category 1     att_2       foo
6       15  Category 2     att_1        30
7       15  Category 2     att_2       bar

(I know the original question probably wants (I.) to have Levels 1 and 2 as multiindex and Level 3 as columns and (II.) asks about other ways than iteration over values in the dict. But I hope this answer is still relevant and useful (I.): to people like me who have tried to find a way to get the nested dict into this shape and google only returns this question and (II.): because other answers involve some iteration as well and I find this approach flexible and easy to read; not sure about performance, though.)

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

How do I convert a Swift Array to a String?

if you have string array list , then convert to Int

let arrayList = list.map { Int($0)!} 
     arrayList.description

it will give you string value

Implementing Singleton with an Enum (in Java)

This,

public enum MySingleton {
  INSTANCE;   
}

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

If you then added another class with a main() method like

public static void main(String[] args) {
    System.out.println(MySingleton.INSTANCE);
}

You would see

Here
INSTANCE

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Multiple inputs with same name through POST in php

Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin"  />

<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />

The outcome would be

$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
          'city' => [ 'Berlin' , 'New York'] ];

To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin"  />

<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />

The outcome would be

$POST = [ 'address' => [ 
                 1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                 2 => ['street' => 'Wallstreet', 'city' => 'New York'],
              ]
        ]

Postgresql GROUP_CONCAT equivalent?

My sugestion in postgresql

SELECT cpf || ';' || nome || ';' || telefone  
FROM (
      SELECT cpf
            ,nome
            ,STRING_AGG(CONCAT_WS( ';' , DDD_1, TELEFONE_1),';') AS telefone 
      FROM (
            SELECT DISTINCT * 
            FROM temp_bd 
            ORDER BY cpf DESC ) AS y
      GROUP BY 1,2 ) AS x   

How can I trim beginning and ending double quotes from a string?

Also with Apache StringUtils.strip():

 StringUtils.strip(null, *)          = null
 StringUtils.strip("", *)            = ""
 StringUtils.strip("abc", null)      = "abc"
 StringUtils.strip("  abc", null)    = "abc"
 StringUtils.strip("abc  ", null)    = "abc"
 StringUtils.strip(" abc ", null)    = "abc"
 StringUtils.strip("  abcyx", "xyz") = "  abc"

So,

final String SchrodingersQuotedString = "may or may not be quoted";
StringUtils.strip(SchrodingersQuotedString, "\""); //quoted no more

This method works both with quoted and unquoted strings as shown in my example. The only downside is, it will not look for strictly matched quotes, only leading and trailing quote characters (ie. no distinction between "partially and "fully" quoted strings).

How to center the text in a JLabel?

String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              "...in an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
              "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

How to render an ASP.NET MVC view as a string?

This works for me:

public virtual string RenderView(ViewContext viewContext)
{
    var response = viewContext.HttpContext.Response;
    response.Flush();
    var oldFilter = response.Filter;
    Stream filter = null;
    try
    {
        filter = new MemoryStream();
        response.Filter = filter;
        viewContext.View.Render(viewContext, viewContext.HttpContext.Response.Output);
        response.Flush();
        filter.Position = 0;
        var reader = new StreamReader(filter, response.ContentEncoding);
        return reader.ReadToEnd();
    }
    finally
    {
        if (filter != null)
        {
            filter.Dispose();
        }
        response.Filter = oldFilter;
    }
}

How to remove new line characters from data rows in mysql?

UPDATE test SET log = REPLACE(REPLACE(log, '\r', ''), '\n', '');

worked for me.

while its similar, it'll also get rid of \r\n

http://lists.mysql.com/mysql/182689

'printf' vs. 'cout' in C++

More differences: "printf" returns an integer value (equal to the number of characters printed) and "cout" does not return anything

And.

cout << "y = " << 7; is not atomic.

printf("%s = %d", "y", 7); is atomic.

cout performs typechecking, printf doesn't.

There's no iostream equivalent of "% d"

How do I run a PowerShell script when the computer starts?

Try this. Create a shortcut in startup folder and iuput

PowerShell "&.'PathToFile\script.ps1'"

This is the easiest way.

Can I fade in a background image (CSS: background-image) with jQuery?

I know i'm late, but I found a way using jquery which works on every browser(i tested it on chrome, firefox and Ie 9)and th fore-ground elements are always displayed instead of css3 transition property.

create 2 absolute wrapper and using z-index.

First set the elements that have to be in the fore-ground with the highest z-index property value, and the other elemets(all included in the body, so: body{}) with a lower z-index property value than the fore-ground elements'one , at least of 2 number lower.

HTML part:

         <div class="wrapper" id="wrapper1"></div>
         <div class="wrapper" id="wrapper2"></div>

css part:

        .fore-groundElements{              //select all fore-ground elements
                  z-index:0;               //>=0
        }
       .wrapper{
                  background-size: cover;
                  width:100%;
                  height:100%;
                  background-size: 100% 100%;
                  position:absolute;
         }

        #wrapper1{
               z-index:-1; 
        }


        #wrapper2{
                 z-index:-2;
         }
         body{

              height:100%;
              width:100%;
              margin:0px;   
              display:cover;
              z-index:-3                          //<=-3
         }

than the javascript/jquery one:

i needed to change the background image every three second so i used a set timeout.

this is the code:

  $(document).ready(main);

  var main = function(){

             var imgPath=[imagesPath1,..,...];                 // the array in which store the image paths

             var newWrapper;                     // the wrapper to display 
             var currentWrapper;                 //the current displayed wrapper which has to be faded
             var l=2;                             // the next image index  to be displayed, it is set to 2 because the first two position of the array(first two images) start already setted up
             var imgNumber= imgPath.length;        //to know when the images are over and restart the carousel
             var currentImg;                       //the next image path to be displayed


             $('#wrapper1').css("background-image", 'url'+imgPath[0]);         //pre set the first wrapper background images
             $('#wrapper2').css("background-image", 'url'+imgPath[1]);          //pre set the first wrapper background images   

             setInterval(myfunction,3000);                //refresh the background image every three seconds

             function myfunction(){
                    if(l===imgNumber-1){               //restart the carousel if every single image has already been displayed                  
                         l=0;
                     };

             if(l%2==0||l%2==2){                    //set the wrapper that will be displaied after the fadeOut callback function
                  currentWrapper='#wrapper1';         
                  newWrapper='#wrapper2';
             }else{
                  currentWrapper='#wrapper2';
                  newWrapper='#wrapper1';
             };
             currentImg=imgPath[l];
            $(currentWrapper).fadeOut(1000,function(){               //fade out the current wrapper, so now the back-ground wrapper is fully displayed
                  $(newWrapper).css("z-index", "-1");                //move the shown wrapper in the fore-ground
                  $(currentWrapper).css("z-index","-2");             //move the hidden wrapper in the back ground
                  $(currentWrapper).css("background-image",'url'+currentImg);                   // sets up the next image that is now shown in the actually hidden background wrapper
                  $(currentWrapper).show();          //shows the background wrapper, which is not visible yet, and it will be shown the next time the setInterval event will be triggered
                  l++;                         //set the next image index that will be set the next time the setInterval event will be triggered 
             });


         };                   //end of myFunction
  }                          //end of main

i hope that my answer is clear,if you need more explanation comment it.

sorry for my english :)

How do you launch the JavaScript debugger in Google Chrome?

Windows: CTRL-SHIFT-J OR F12

Mac: ?-?-J

Also available through the wrench menu (Tools > JavaScript Console):

JavaScript Console Menu

Working with huge files in VIM

It's already late but if you just want to navigate through the file without editing it, cat can do the job too.

% cat filename | less

or alternatively simple:

% less filename

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

Try putting it in quotes -- you're running into the shell's wildcard expansion, so what you're acually passing to find will look like:

find . -name bobtest.c cattest.c snowtest.c

...causing the syntax error. So try this instead:

find . -name '*test.c'

Note the single quotes around your file expression -- these will stop the shell (bash) expanding your wildcards.

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

Add one year in current date PYTHON

It seems from your question that you would like to simply increment the year of your given date rather than worry about leap year implications. You can use the date class to do this by accessing its member year.

from datetime import date
startDate = date(2012, 12, 21)

# reconstruct date fully
endDate = date(startDate.year + 1, startDate.month, startDate.day)
# replace year only
endDate = startDate.replace(startDate.year + 1)

If you're having problems creating one given your format, let us know.

Force overwrite of local file with what's in origin repo?

Full sync has few tasks:

  • reverting changes
  • removing new files
  • get latest from remote repository

git reset HEAD --hard

git clean -f

git pull origin master

Or else, what I prefer is that, I may create a new branch with the latest from the remote using:

git checkout origin/master -b <new branch name>

origin is my remote repository reference, and master is my considered branch name. These may different from yours.