Merge remote-tracking branch 'origin/from-starter' into from-starter

This commit is contained in:
Angelos Chalaris
2019-08-20 11:08:52 +03:00
24 changed files with 29 additions and 2220 deletions

23
COLLABORATING.md Normal file
View File

@ -0,0 +1,23 @@
# Collaborator team rules and guidelines for community moderation
**As a contributor/member of the community, remember that you can always open issues about moderation and problems with how community moderation is done. We are always open to constructive criticism and feedback!**
## Responsibilities of a collaborator
As a member of the team that manages **30 seconds of python code**, you have the following responsibilities:
- **Be part of the conversation in the issue tracker.** That includes (but is not limited to) helping out new members, discussing new features and explaining decisions to people.
- **Review pull requests.** You do not have to read through all of the pull requests and review them, but taking the time each day to review a few can help a great deal.
- **Be civil and polite.** If you are about to lose your temper, take a step back and do something else. We want our interactions with the community to be polite so that more people can join the project and contribute in any way they can. Remember to always thank contributors for their help, even if it's minor changes or changes that did not make it into the project. This way we can reward and encourage people to keep being part of the community.
- **Contribute when you want, moderate when you can.** If you have a lot on your plate outside of this project, it's alright. It's better to take a break for a few days rather than hastily deal with issues and pull requests that might break things.
## Guidelines for merging pull requests and making changes to the project
- **[Usual guidelines](https://github.com/30-seconds/30-seconds-of-python-code/blob/master/CONTRIBUTING.md) apply.** Make sure to follow them, like everybody else.
- **For a pull request to be considered ready to merge, there should be at least 2 (preferably 3) reviews approving it for merge.** There are, however, certain exceptions:
- **If a pull request only fixes typos**, there is no need to wait for a second reviewer (unless you are not certain these were not typos in the first place).
- **If a pull request only clarifies a snippet's description or enforces the style guide for an existing snippet**, you might be able to merge it without getting a second reviewer to review it, but only if you are certain about it.
- **Make sure pull requests pass the Travis CI build**, otherwise try and find out what's wrong and inform the author of the pull request.
- **Changes to build scripts, guidelines and things that might break the processes we have in place need to be reviewed by [@Chalarangelo](https://github.com/Chalarangelo) or [@fejes713](https://github.com/fejes713)**.
- **If you make changes or additions to existing snippets or if you want to add your own snippets, you will go through the pull request process that everyone else goes.** Exceptions apply similarly to the ones mentioned above about merging pull requests (i.e. typos, description clarification and the way script and build process changes are handled). Pull requests suggested by collaborators should be reviewed by at least two other collaborators to be considered ready to merge.
- **Pull requests that are inactive for over a week should be closed or put on hold.**

View File

@ -4,11 +4,11 @@
Here's what you can do to help:
- [Open issues](https://github.com/kriadmin/30-seconds-of-python-code/issues/new) for things you want to see added or modified.
- Be part of the discussion by helping out with [existing issues](https://github.com/kriadmin/30-seconds-of-python-code/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-python-code/Lobby).
- Submit [pull requests](https://github.com/kriadmin/30-seconds-of-python-code/pulls) with snippets you have created (see below for guidelines).
- [Open issues](https://github.com/30-seconds/30-seconds-of-python-code/issues/new) for things you want to see added or modified.
- Be part of the discussion by helping out with [existing issues](https://github.com/30-seconds/30-seconds-of-python-code/issues) or talking on our [gitter channel](https://gitter.im/30-seconds-of-python-code/Lobby).
- Submit [pull requests](https://github.com/30-seconds/30-seconds-of-python-code/pulls) with snippets you have created (see below for guidelines).
- Fix typos in existing snippets, improve snippet descriptions and explanations or provide better examples.
- Before submitting a PR for any new snippets go through [this](https://github.com/kriadmin/30-seconds-of-python-code/projects/1) project. If your snippet is not there, then go ahead and submit a PR. Else if it is in the done column, sorry it has been already implemented. If it is in any other column submit a PR and give the card's link in the description section of PR.
- Before submitting a PR for any new snippets go through [this](https://github.com/30-seconds/30-seconds-of-python-code/projects/1) project. If your snippet is not there, then go ahead and submit a PR. Else if it is in the done column, sorry it has been already implemented. If it is in any other column submit a PR and give the card's link in the description section of PR.
- **Working on your first Pull Request?** You can learn how from this *free* series [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)
### Snippet submission and Pull request guidelines
@ -25,7 +25,7 @@ Here's what you can do to help:
- **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what **inbuilt** features/modules are used. Remember to include what functions you are using and why.
- Follow snippet descriptions with an empty line.
- **Snippets _CAN NOT_ use any external modules**. Only the modules and function inbuilt in `python 3.6` shall be used.
- **Snippet code** must be enclosed inside ` ```python ` and ` ``` `.
- **Snippet code** must be enclosed inside ` ```py ` and ` ``` `.
- Remember to start your snippet's code on a new line below the opening backticks.
- You can write the code in any style you like but eventually it will be formated by our prettifier so the formatting will change. Just make sure to have consistent spacing.
- Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting.
@ -38,32 +38,3 @@ Here's what you can do to help:
- It is not mandatory but highly appreciated if you provide **test cases** and/or performance tests.
- You can start creating a new snippet, by using the [snippet template](snippet_template.md) to format your snippets.
- Updating the README.md file should only be done by altering the scripts in the **scripts** folder or altering their relative static parts in the **static-parts** folder.
- You may tag your snippet in tag_databse although it is _not_ necessary.
- You may add your name as `[Name][@github_username]` to the contributor database. If the snippet already exists and you are making changes to it you can add your name at the last seperated by a comma.
<!--
### Additional guidelines and conventions regarding snippets
- If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is.
- If your snippet uses recursion, explain the base cases.
- If your variable is not changed anywhere in the code name it in uppercase.
- Use `camelCase` for function and variable names if they consist of more than one word.
- Try to give meaningful names to variables. For example use `letter`, instead of `lt`. Some exceptions to convention are:
- `arr` for lists (usually as the snippet function's argument).
- `str` for strings.
- `n` for a numeric value (usually as the snippet function's argument).
- `val` or `v` for value (usually when iterating a list, mapping, sorting etc.).
- `i` for indexes.
- `func` for function arguments.
- `nums` for lists of numbers.
- Use `()` if your function takes no arguments.
- Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to.
- If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name).
- Always use single quotes for string literals.
- Prefer using the ternary operator (`trueResult if condition else falseResult`) instead of `if else` statements whenever possible.
- Avoid nesting ternary operators (but you can do it if you feel like you should).
- You should define multiple variables on the same line (e.g. `x,y = 0,1`) on the same line whenever possible.
- Do not use trailing or leading underscores in variable names(unless it is a helper function).
- Use lambda functions as much as possible, except when you can't.
- Leave a single space after a comma (`,`) character.
- Try to strike a balance between readability, brevity, and performance.
- Never use `eval()`. Your snippet will be disqualified immediately.-->

View File

@ -1 +0,0 @@
web: gunicorn run:app

View File

@ -1,5 +0,0 @@
from flask import Flask
app = Flask(__name__)
from app import routes,vote

View File

@ -1,2 +0,0 @@
127.0.0.1 localwebsite
127.0.0.1 blog.localwebsite

View File

@ -1,124 +0,0 @@
/* PrismJS 1.10.0
http://prismjs.com/download.html?themes=prism-okaidia&languages=python */
/**
* okaidia theme for JavaScript, CSS and HTML
* Loosely based on Monokai textmate theme by http://www.monokai.nl/
* @author ocodia
*/
code[class*="language-"],
pre[class*="language-"] {
color: #f8f8f2;
background: none;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
border-radius: 0.3em;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
background: #272822;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #f8f8f2;
}
.namespace {
opacity: .7;
}
.token.property,
.token.tag,
.token.constant,
.token.symbol,
.token.deleted {
color: #f92672;
}
.token.boolean,
.token.number {
color: #ae81ff;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #a6e22e;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable {
color: #f8f8f2;
}
.token.atrule,
.token.attr-value,
.token.function {
color: #e6db74;
}
.token.keyword {
color: #66d9ef;
}
.token.regex,
.token.important {
color: #fd971f;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}

File diff suppressed because one or more lines are too long

View File

@ -1,23 +0,0 @@
from flask import render_template, redirect ,request, url_for
from app import app, vote, vote_data
@app.route('/')
@app.route('/index')
@app.route('/index/')
def index():
return render_template('index.html',vote={})
'''
For future when we have logins
@app.route('/',methods=['POST'])
@app.route('/index',methods=['POST'])
@app.route('/index/',methods=['POST'])
def post():
try:
vote.vote(request.form['submit'])
except Exception as e:
return render_template('index.html', vote=vote_data.vote_data(),err_400=True,message=e)
return redirect(f"/#{request.form['submit']}",code=302)
'''

View File

@ -1,3 +0,0 @@
keys_only
values_only
all_unique

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

File diff suppressed because one or more lines are too long

View File

@ -1,74 +0,0 @@
<html>
<head>
<link href="/static/css/prism.css" rel = "stylesheet"></link>
<script src="/static/js/prism.js"></script>
<meta charset="utf-8"><meta name="description" content=" Python implementation of 30-seconds-of-code "><meta name="keywords" content="python, javascript, snippets, code, programming"><meta name="author" content="Rohit Kumar Tanwar (mst10041967@gmail.com)"><meta name="viewport" content="width=device-width,initial-scale=1"><meta property="og:title" content="30 seconds of python code"><meta property="og:description" content="Python implementation of 30 seconds of code"><meta property="og:type" content="website"><meta property="og:image" content="static/favicon.png"><link rel="icon" type="image/ico" href="static/favicon.png">
<title>30 seconds of python code</title>
</head>
<body onload="loader()">
<a href="https://github.com/kriadmin/30-seconds-of-python-code" class="github-corner" aria-label="View source on Github"><svg width="90" height="90" viewBox="0 0 250 250" style="fill:#151513;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>
{% if err_400 %}
<div class="error">{{ message }}</div>
{% endif %}
<header style="height:5.5rem"><h1 class="logo"><img src="static/favicon.png" style="height:4rem" alt="logo"><span id="title">&nbsp;30 seconds of python code</span> <small>Python Implementation of 30 seconds of code</small></h1><label for="doc-drawer-checkbox" class="button drawer-toggle" id="menu-toggle"></label></header>
{% block content %}{% endblock %}
<script>
const search = (node) => {
let matchingTags = [];
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
let data = [x.innerText.toLowerCase(), ...x.getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
if(data.includes(true)){
x.style.display = '';
matchingTags.push(x.getAttribute('tags').split(',')[0]);
}
else x.style.display = 'none';
});
Array.from(node.parentElement.parentElement.getElementsByTagName('h3')).forEach(x => {
x.style.display = matchingTags.includes(x.innerText.toLowerCase()) ? '' : 'none';
})
}
function scrollToTop(){
const c = document.querySelector('main').scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
document.querySelector('main').scrollTo(0, c - c / 4);
}
};
function loader() {
registerClickListener();
}
function registerClickListener() {
document.addEventListener('click', function (event) {
if ( event.target.classList.contains('collapse') ) {
event.target.classList = event.target.classList.contains('toggled') ? 'collapse' : 'collapse toggled';
}
else if (event.target.classList.contains('clipboard-copy')) {
const text = event.target.parentElement.parentElement.querySelector(':not(pre) + pre').textContent;
const textArea = document.createElement("textarea");
textArea.value = text.trim();
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
document.body.removeChild(textArea);
let tst = document.createElement('div');
tst.classList = 'toast';
tst.innerHTML = 'Snippet copied to clipboard!';
document.body.appendChild(tst);
setTimeout(function() {
tst.style.opacity = 0;
setTimeout(function() {
document.body.removeChild(tst);
},300);
},1700);
}
else if (event.target.classList.contains('scroll-to-top')){
scrollToTop();
}
}, false);
}
</script>
<script>
[...document.getElementsByClassName("language-python")].forEach(el => Prism.highlightElement(el))
</script>
</body>

View File

@ -1,466 +0,0 @@
{% extends "base.html" %}
{% block content %}<div class="row" style="height:calc(100vh - 5.875rem);overflow:hidden"><input id="doc-drawer-checkbox" class="drawer" value="on" type="checkbox"><nav class="col-md-4 col-lg-3" style="border-top:0"><div class="group"><input class="search" id="searchInput" onkeyup="search(this)" type="text"><label id="search-label">Search for snippet...</label></div><label for="doc-drawer-checkbox" class="button drawer-close"></label><h3 style = "">Math</h3><a class="sublink-1" tags="math" href="#average" style="">average</a><a class="sublink-1" tags="math" href="#factorial" style="">factorial</a><a class="sublink-1" tags="math" href="#gcd" style="">gcd</a><a class="sublink-1" tags="math" href="#lcm" style="">lcm</a><a class="sublink-1" tags="math" href="#max_n" style="">max_n</a><a class="sublink-1" tags="math" href="#min_n" style="">min_n</a><h3 style = "">List</h3><a class="sublink-1" tags="list" href="#chunk" style="">chunk</a><a class="sublink-1" tags="list" href="#compact" style="">compact</a><a class="sublink-1" tags="list" href="#count_occurences" style="">count_occurences</a><a class="sublink-1" tags="list" href="#deep_flatten" style="">deep_flatten</a><a class="sublink-1" tags="list" href="#difference" style="">difference</a><a class="sublink-1" tags="list" href="#shuffle" style="">shuffle</a><a class="sublink-1" tags="list" href="#spread" style="">spread</a><a class="sublink-1" tags="list" href="#zip" style="">zip</a><a class="sublink-1" tags="list" href="#count_by" style="">count_by</a><a class="sublink-1" tags="list" href="#difference_by" style="">difference_by</a><a class="sublink-1" tags="list" href="#insertion_sort" style="">insertion_sort</a><a class="sublink-1" tags="list" href="#bubble_sort" style="">bubble_sort</a><a class="sublink-1" tags="list" href="#has_duplicates" style="">has_duplicates</a><h3 style = "">String</h3><a class="sublink-1" tags="string" href="#count_vowels" style="">count_vowels</a><a class="sublink-1" tags="string" href="#byte_size" style="">byte_size</a><a class="sublink-1" tags="string" href="#capitalize" style="">capitalize</a><a class="sublink-1" tags="string" href="#capitalize_every_word" style="">capitalize_every_word</a><a class="sublink-1" tags="string" href="#decapitalize" style="">decapitalize</a><a class="sublink-1" tags="string" href="#palindrome" style="">palindrome</a><a class="sublink-1" tags="string" href="#is_upper_case" style="">is_upper_case</a><a class="sublink-1" tags="string" href="#is_lower_case" style="">is_lower_case</a><h3 style = "">Object</h3><a class="sublink-1" tags="object" href="#keys_only" style="">keys_only</a><a class="sublink-1" tags="object" href="#values_only" style="">values_only</a><a class="sublink-1" tags="object" href="#all_unique" style="">all_unique</a></nav><main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top"></a><h2 style="text-align:center">Math</h2><div class="card fluid"><h3 id="average" class="section double-padded">average</h3><!--<form action="" method="post"><button type="submit" value="average" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p><emoji></emoji> Already implemented via <code>statistics.mean</code>. <code>statistics.mean</code> takes an array as an argument whereas this function takes variadic arguments.</p>
<p>Returns the average of two or more numbers.</p>
<p>Takes the sum of all the <code>args</code> and divides it by <code>len(args)</code>. The second argument <code>0.0</code> in sum is to handle floating point division in <code>python3</code>.</p>
<pre class="language-python">def average(*args):
return sum(args, 0.0) / len(args)</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">average(*[1, 2, 3]) # 2.0
average(1, 2, 3) # 2.0</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="factorial" class="section double-padded">factorial</h3><!--<form action="" method="post"><button type="submit" value="factorial" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Calculates the factorial of a number.</p>
<p>Use recursion. If <code>num</code> is less than or equal to <code>1</code>, return <code>1</code>. Otherwise, return the product of <code>num</code> and the factorial of <code>num - 1</code>. Throws an exception if <code>num</code> is a negative or a floating point number.</p>
<pre class="language-python">def factorial(num):
if not ((num &gt;= 0) &amp; (num % 1 == 0)):
raise Exception(
f"Number( {num} ) can't be floating point or negative ")
return 1 if num == 0 else num * factorial(num - 1)</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">factorial(6) # 720</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="gcd" class="section double-padded">gcd</h3><!--<form action="" method="post"><button type="submit" value="gcd" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p><emoji></emoji> <code>math.gcd</code> works with only two numbers</p>
<p>Calculates the greatest common divisor between two or more numbers/lists.</p>
<p>The <code>helperGcdfunction</code> uses recursion. Base case is when <code>y</code> equals <code>0</code>. In this case, return <code>x</code>. Otherwise, return the GCD of <code>y</code> and the remainder of the division <code>x/y</code>.</p>
<p>Uses the reduce function from the inbuilt module <code>functools</code>. Also defines a method <code>spread</code> for javascript like spreading of lists.</p>
<pre class="language-python">from functools import reduce
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def gcd(*args):
numbers = []
numbers.extend(spread(list(args)))
def _gcd(x, y):
return x if not y else gcd(y, x % y)
return reduce((lambda x, y: _gcd(x, y)), numbers)</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">gcd(8,36) # 4</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="lcm" class="section double-padded">lcm</h3><!--<form action="" method="post"><button type="submit" value="lcm" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Returns the least common multiple of two or more numbers.</p>
<p>Use the <code>greatest common divisor (GCD)</code> formula and the fact that <code>lcm(x,y) = x * y / gcd(x,y)</code> to determine the least common multiple. The GCD formula uses recursion.</p>
<p>Uses <code>reduce</code> function from the inbuilt module <code>functools</code>. Also defines a method <code>spread</code> for javascript like spreading of lists.</p>
<pre class="language-python">from functools import reduce
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def lcm(*args):
numbers = []
numbers.extend(spread(list(args)))
def _gcd(x, y):
return x if not y else _gcd(y, x % y)
def _lcm(x, y):
return x * y / _gcd(x, y)
return reduce((lambda x, y: _lcm(x, y)), numbers)</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">lcm(12, 7) # 84
lcm([1, 3, 4], 5) # 60</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="max_n" class="section double-padded">max_n</h3><!--<form action="" method="post"><button type="submit" value="max_n" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Returns the <code>n</code> maximum elements from the provided list. If <code>n</code> is greater than or equal to the provided list's length, then return the original list(sorted in descending order).</p>
<p>Use <code>list.sort()</code> combined with the <code>deepcopy</code> function from the inbuilt <code>copy</code> module to create a shallow clone of the list and sort it in ascending order and then use <code>list.reverse()</code> reverse it to make it descending order. Use <code>[:n]</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element list</p>
<pre class="language-python">def max_n(lst, n=1, reverse=True):
return sorted(lst, reverse=reverse)[:n]</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">max_n([1, 2, 3]) # [3]
max_n([1, 2, 3], 2) # [3,2]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="min_n" class="section double-padded">min_n</h3><!--<form action="" method="post"><button type="submit" value="min_n" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Returns the <code>n</code> minimum elements from the provided list. If <code>n</code> is greater than or equal to the provided list's length, then return the original list(sorted in ascending order).</p>
<p>Use <code>list.sort()</code> combined with the <code>deepcopy</code> function from the inbuilt <code>copy</code> module to create a shallow clone of the list and sort it in ascending order. Use <code>[:n]</code> to get the specified number of elements. Omit the second argument, <code>n</code>, to get a one-element list</p>
<pre class="language-python">from copy import deepcopy
def min_n(lst, n=1):
numbers = deepcopy(lst)
numbers.sort()
return numbers[:n]</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">min_n([1, 2, 3]) # [1]
min_n([1, 2, 3], 2) # [1,2]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><h2 style="text-align:center">List</h2><div class="card fluid"><h3 id="chunk" class="section double-padded">chunk</h3><!--<form action="" method="post"><button type="submit" value="chunk" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Chunks an list into smaller lists of a specified size.</p>
<p>Uses <code>range</code> to create a list of desired size. Then use <code>map</code> on this list and fill it with splices of <code>lst</code>.</p>
<pre class="language-python">from math import ceil
def chunk(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="compact" class="section double-padded">compact</h3><!--<form action="" method="post"><button type="submit" value="compact" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Removes falsey values from a list.</p>
<p>Use <code>filter()</code> to filter out falsey values (False, None, 0, and "").</p>
<pre class="language-python">def compact(lst):
return list(filter(bool, lst))</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="count_occurences" class="section double-padded">count_occurences</h3><!--<form action="" method="post"><button type="submit" value="count_occurences" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p><emoji></emoji> Already implemented via <code>list.count()</code>.</p>
<p>Counts the occurrences of a value in an list.</p>
<p>Uses the list comprehension to increment a counter each time you encounter the specific value inside the list.</p>
<pre class="language-python">def count_occurrences(lst, val):
return len([x for x in lst if x == val and type(x) == type(val)])</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="deep_flatten" class="section double-padded">deep_flatten</h3><!--<form action="" method="post"><button type="submit" value="deep_flatten" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Deep flattens a list.</p>
<p>Use recursion. Use <code>list.extend()</code> with an empty list (<code>result</code>) and the spread function to flatten a list. Recursively flatten each element that is a list.</p>
<pre class="language-python">def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result = []
result.extend(
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="difference" class="section double-padded">difference</h3><!--<form action="" method="post"><button type="submit" value="difference" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Returns the difference between two iterables.</p>
<p>Use list comprehension to only keep values not contained in <code>b</code></p>
<pre class="language-python">def difference(a, b):
return [item for item in a if item not in b]</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">difference([1, 2, 3], [1, 2, 4]) # [3]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="shuffle" class="section double-padded">shuffle</h3><!--<form action="" method="post"><button type="submit" value="shuffle" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p><emoji></emoji> The same algorithm is already implemented via <code>random.shuffle</code>.</p>
<p>Randomizes the order of the values of an list, returning a new list.</p>
<p>Uses the <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle">Fisher-Yates algorithm</a> to reorder the elements of the list.</p>
<pre class="language-python">from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="spread" class="section double-padded">spread</h3><!--<form action="" method="post"><button type="submit" value="spread" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Implements javascript's <code>[].concat(...arr)</code>. Flattens the list(non-deep) and returns an list.</p>
<pre class="language-python">def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="zip" class="section double-padded">zip</h3><!--<form action="" method="post"><button type="submit" value="zip" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p><emoji></emoji> Already implemented via <code>itertools.zip_longest()</code></p>
<p>Creates a list of elements, grouped based on the position in the original lists.</p>
<p>Use <code>max</code> combined with <code>list comprehension</code> to get the length of the longest list in the arguments. Loops for <code>max_length</code> times grouping elements. If lengths of <code>lists</code> vary <code>fill_value</code> is used. By default <code>fill_value</code> is <code>None</code>.</p>
<pre class="language-python">def zip(*args, fillvalue=None):
max_length = max([len(lst) for lst in args])
result = []
for i in range(max_length):
result.append([
args[k][i] if i &lt; len(args[k]) else None for k in range(len(args))
])
return result</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="count_by" class="section double-padded">count_by</h3><!--<form action="" method="post"><button type="submit" value="count_by" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p><emoji></emoji> Already implemented via <code>collections.Counter</code></p>
<p>Groups the elements of a list based on the given function and returns the count of elements in each group.</p>
<p>Use <code>map()</code> to map the values of the list using the given function. Iterate over the map and increase the the elements count each time it occurs.</p>
<pre class="language-python">def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 0 if el not in key else key[el]
key[el] += 1
return key</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">from math import floor
count_by([6.1, 4.2, 6.3], floor) # {4: 1, 6: 2}
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="difference_by" class="section double-padded">difference_by</h3><!--<form action="" method="post"><button type="submit" value="difference_by" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Returns the difference between two list, after applying the provided function to each list element of both.</p>
<p>Create a <code>set</code> by applying <code>fn</code> to each element in <code>b</code>, then use list comprehension in combination with fn on a to only keep values not contained in the previously created <code>set</code>.</p>
<pre class="language-python">def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="insertion_sort" class="section double-padded">insertion_sort</h3><!--<form action="" method="post"><button type="submit" value="insertion_sort" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>On a very basic level, an insertion sort algorithm contains the logic of shifting around and inserting elements in order to sort an unordered list of any size. The way that it goes about inserting elements, however, is what makes insertion sort so very interesting!</p>
<pre class="language-python">def insertion_sort(lst):
for i in range(1, len(lst)):
key = lst[i]
j = i - 1
while j &gt;= 0 and key &lt; lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">lst = [7,4,9,2,6,3]
insertionsort(lst)
print('Sorted %s' %lst) # sorted [2, 3, 4, 6, 7, 9]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="bubble_sort" class="section double-padded">bubble_sort</h3><!--<form action="" method="post"><button type="submit" value="bubble_sort" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Bubble_sort uses the technique of comparing and swapping</p>
<pre class="language-python">def bubble_sort(lst):
for passnum in range(len(lst) - 1, 0, -1):
for i in range(passnum):
if lst[i] &gt; lst[i + 1]:
temp = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = temp</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">lst = [54,26,93,17,77,31,44,55,20]
bubble_sort(lst)
print("sorted %s" %lst) # [17,20,26,31,44,54,55,77,91]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="has_duplicates" class="section double-padded">has_duplicates</h3><!--<form action="" method="post"><button type="submit" value="has_duplicates" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Checks a flat list for duplicate values. Returns True if duplicate values exist and False if values are all unique.</p>
<p>This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list.</p>
<pre class="language-python">def has_duplicates(lst):
return len(lst) != len(set(lst))</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><h2 style="text-align:center">String</h2><div class="card fluid"><h3 id="count_vowels" class="section double-padded">count_vowels</h3><!--<form action="" method="post"><button type="submit" value="count_vowels" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Retuns <code>number</code> of vowels in provided <code>string</code>.</p>
<p>Use a regular expression to count the number of vowels <code>(A, E, I, O, U)</code> in a string.</p>
<pre class="language-python">import re
def count_vowels(str):
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">count_vowels('foobar') # 3
count_vowels('gym') # 0</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="byte_size" class="section double-padded">byte_size</h3><!--<form action="" method="post"><button type="submit" value="byte_size" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Returns the length of a string in bytes.</p>
<p><code>utf-8</code> encodes a given string and find its length.</p>
<pre class="language-python">def byte_size(string):
return(len(string.encode('utf-8')))</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">byte_size('😀') # 4
byte_size('Hello World') # 11</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="capitalize" class="section double-padded">capitalize</h3><!--<form action="" method="post"><button type="submit" value="capitalize" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Capitalizes the first letter of a string.</p>
<p>Capitalizes the fist letter of the sring and then adds it with rest of the string. Omit the <code>lower_rest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to lowercase.</p>
<pre class="language-python">def capitalize(string, lower_rest=False):
return string[:1].upper() + (string[1:].lower() if lower_rest else string[1:])</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">capitalize('fooBar') # 'FooBar'
capitalize('fooBar', True) # 'Foobar'</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="capitalize_every_word" class="section double-padded">capitalize_every_word</h3><!--<form action="" method="post"><button type="submit" value="capitalize_every_word" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Capitalizes the first letter of every word in a string.</p>
<p>Uses <code>str.title</code> to capitalize first letter of evry word in the string.</p>
<pre class="language-python">def capitalize_every_word(string):
return string.title()</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">capitalize_every_word('hello world!') # 'Hello World!'</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="decapitalize" class="section double-padded">decapitalize</h3><!--<form action="" method="post"><button type="submit" value="decapitalize" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Decapitalizes the first letter of a string.</p>
<p>Decapitalizes the fist letter of the sring and then adds it with rest of the string. Omit the <code>upper_rest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to uppercase.</p>
<pre class="language-python">def decapitalize(string, upper_rest=False):
return str[:1].lower() + (str[1:].upper() if upper_rest else str[1:])</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar', True) # 'fOOBAR'</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="palindrome" class="section double-padded">palindrome</h3><!--<form action="" method="post"><button type="submit" value="palindrome" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Returns <code>True</code> if the given string is a palindrome, <code>False</code> otherwise.</p>
<p>Convert string <code>str.lower()</code> and use <code>re.sub</code> to remove non-alphanumeric characters from it. Then compare the new string to the reversed.</p>
<pre class="language-python">def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">palindrome('taco cat') # True</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="is_upper_case" class="section double-padded">is_upper_case</h3><!--<form action="" method="post"><button type="submit" value="is_upper_case" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Checks if a string is upper case.</p>
<p>Convert the given string to upper case, using <code>str.upper()</code> method and compare it to the original.</p>
<pre class="language-python">def is_upper_case(string):
return string == string.upper()</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">is_upper_case('ABC') # True
is_upper_case('a3@$') # True
is_upper_case('aB4') # False</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="is_lower_case" class="section double-padded">is_lower_case</h3><!--<form action="" method="post"><button type="submit" value="is_lower_case" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Checks if a string is lower case.</p>
<p>Convert the given string to lower case, using <code>str.lower()</code> method and compare it to the original.</p>
<pre class="language-python">def is_lower_case(string):
return string == string.lower()</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">is_lower_case('abc') # True
is_lower_case('a3@$') # True
is_lower_case('Ab4') # False</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><h2 style="text-align:center">Object</h2><div class="card fluid"><h3 id="keys_only" class="section double-padded">keys_only</h3><!--<form action="" method="post"><button type="submit" value="keys_only" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Function which accepts a dictionary of key value pairs and returns a new flat list of only the keys.</p>
<p>Uses the .items() function with a for loop on the dictionary to track both the key and value and returns a new list by appending the keys to it. Best used on 1 level-deep key:value pair dictionaries (a flat dictionary) and not nested data-structures which are also commonly used with dictionaries. (a flat dictionary resembles a json and a flat list an array for javascript people).</p>
<pre class="language-python">def keys_only(flat_dict):
lst = []
for k, v in flat_dict.items():
lst.append(k)
return lst</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">ages = {
"Peter": 10,
"Isabel": 11,
"Anna": 9,
}
keys_only(ages) # ['Peter', 'Isabel', 'Anna']</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="values_only" class="section double-padded">values_only</h3><!--<form action="" method="post"><button type="submit" value="values_only" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Function which accepts a dictionary of key value pairs and returns a new flat list of only the values.</p>
<p>Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and returns a new list by appending the values to it. Best used on 1 level-deep key:value pair dictionaries and not nested data-structures.</p>
<pre class="language-python">def values_only(dict):
lst = []
for k, v in dict.items():
lst.append(v)
return lst</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">ages = {
"Peter": 10,
"Isabel": 11,
"Anna": 9,
}
values_only(ages) # [10, 11, 9]</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><div class="card fluid"><h3 id="all_unique" class="section double-padded">all_unique</h3><!--<form action="" method="post"><button type="submit" value="all_unique" name="submit">Vote</button></form><p></p>--><div class="section double-padded">
<p>Checks a flat list for all unique values. Returns True if list values are all unique and False if list values aren't all unique.</p>
<p>This function compares the length of the list with length of the set() of the list. set() removes duplicate values from the list.</p>
<pre class="language-python">def all_unique(lst):
return len(lst) == len(set(lst))</pre>
<label class="collapse">Show examples</label>
<pre class="language-python">x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
all_unique(x) # True
all_unique(y) # False</pre>
<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>
</div><button class="scroll-to-top"></button>
<footer><p style="display:inline-block"><strong>30 seconds of python code</strong> is licensed under the <a href="https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE">GPL-3.0</a> license.<br>Icons made by <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="https://www.flaticon.com/">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a>.<br>Ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> is licensed by <a href="https://opensource.org/licenses/MIT">The MIT License</a><br>Built with the <a href="https://minicss.org">mini.css framework</a>.</p></footer>
</main></div>{% endblock %}

View File

@ -1,124 +0,0 @@
/* PrismJS 1.10.0
http://prismjs.com/download.html?themes=prism-okaidia&languages=python */
/**
* okaidia theme for JavaScript, CSS and HTML
* Loosely based on Monokai textmate theme by http://www.monokai.nl/
* @author ocodia
*/
code[class*="language-"],
pre[class*="language-"] {
color: #f8f8f2;
background: none;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
border-radius: 0.3em;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
background: #272822;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #f8f8f2;
}
.namespace {
opacity: .7;
}
.token.property,
.token.tag,
.token.constant,
.token.symbol,
.token.deleted {
color: #f92672;
}
.token.boolean,
.token.number {
color: #ae81ff;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #a6e22e;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable {
color: #f8f8f2;
}
.token.atrule,
.token.attr-value,
.token.function {
color: #e6db74;
}
.token.keyword {
color: #66d9ef;
}
.token.regex,
.token.important {
color: #fd971f;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}

File diff suppressed because one or more lines are too long

View File

@ -1,16 +0,0 @@
import json
def vote(snippet):
snippets = open('website/app/snippets').read().split('\n')
with open('website/app/votes.json', 'r') as f:
if snippet in snippets:
data = json.load(f)
try:
data[snippet]
except KeyError:
data[snippet] = 0
data[snippet] += 1
open('website/app/votes.json','w').write(str(data).replace("'",'"'))
else:
raise Exception(f'{snippet} does not exists ')

View File

@ -1,16 +0,0 @@
import json
def vote_data():
f = open('website/app/snippets')
snippets = f.read().split('\n')
f.close()
f = open('website/app/votes.json')
votes_data = json.load(f)
votes = {}
for snippet in snippets:
try:
votes[snippet] = votes_data[snippet]
except KeyError:
votes[snippet] = 0
return votes

View File

@ -1 +0,0 @@
{}

View File

@ -1,69 +0,0 @@
import os
import re
import emoji
import mistune
codeRe = "```\s*python([\s\S]*?)```"
def tagger():
tag_data = open('tag_database').read()
tag_dict = {}
tag_list = filter(lambda x:x.strip() != '',tag_data.split('\n'))
for tag in tag_list:
category = tag.split(':')[1]
snippet = tag.split(':')[0]
if category in tag_dict:
tag_dict[category].append(snippet)
else:
tag_dict[category] = [snippet]
return tag_dict
class MyRenderer(mistune.Renderer):
def block_code(self, code, lang):
if not lang:
return f'\n<pre>{mistune.escape(code.strip())}</pre>\n'
else:
return f'\n<pre class="language-{lang}">{mistune.escape(code.strip())}</pre>\n'
renderer = MyRenderer()
md = mistune.Markdown(renderer=renderer,escape=True)
def title_case(str):
return str[:1].upper() + str[1:].lower()
rendered = ''
tag_dict = tagger()
for category in tag_dict:
rendered += f'<h2 style="text-align:center">{title_case(category)}</h2>'
snippets = tag_dict[category]
for file in snippets:
content = open('snippets/'+file+'.md').read()
content = re.sub(':(\S+):',r'<emoji>:\1:</emoji>',content)
codeParts = re.split(codeRe,content)
codeParts[3] = f'\n\n<label class="collapse">Show examples</label>\n\n```python\n{codeParts[3].strip()}\n```\n'
content = codeParts[0] + '``` python' + codeParts[1] + '```' + codeParts[2] + codeParts[3]
content = f'<div class="card fluid">{emoji.emojize(md.render(content),use_aliases=True)}<button class="primary clipboard-copy">📋&nbsp;Copy to clipboard</button></div>'+'\n\n'
rendered += re.sub('<h3>(\S+)</h3>',r'<h3>\1</h3><div class="section double-padded">',content) + '</div>'
rendered = re.sub('<h3>(\S+)</h3>',r'<h3 id="\1" class="section double-padded">\1</h3><!--<form action="" method="post"><button type="submit" value="\1" name="submit">Vote</button></form>'+'<p></p>-->',rendered)
nav_string = '<input id="doc-drawer-checkbox" class="drawer" value="on" type="checkbox"><nav class="col-md-4 col-lg-3" style="border-top:0"><div class="group"><input class="search" id="searchInput" onkeyup="search(this)" type="text"><label id="search-label">Search for snippet...</label></div><label for="doc-drawer-checkbox" class="button drawer-close"></label>'
for category in tag_dict:
nav_string += f'<h3 style = "">{title_case(category)}</h3>'
for file in tag_dict[category]:
nav_string += f'<a class="sublink-1" tags="{category}" href="#{file}" style="">{file}</a>'
nav_string += '</nav>'
start = '''{% extends "base.html" %}
{% block content %}'''
end = '{% endblock %}'
footer = '''
<footer><p style="display:inline-block"><strong>30 seconds of python code</strong> is licensed under the <a href="https://github.com/kriadmin/30-seconds-of-python-code/blob/master/LICENSE">GPL-3.0</a> license.<br>Icons made by <a href="https://www.flaticon.com/authors/smashicons">Smashicons</a> from <a href="https://www.flaticon.com/">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/">CC 3.0 BY</a>.<br>Ribbon made by <a href="https://github.com/tholman/github-corners">Tim Holman</a> is licensed by <a href="https://opensource.org/licenses/MIT">The MIT License</a><br>Built with the <a href="https://minicss.org">mini.css framework</a>.</p></footer>
'''
rendered = f'<div class="row" style="height:calc(100vh - 5.875rem);overflow:hidden">{nav_string}<main class="col-sm-12 col-md-8 col-lg-9" style="height:100%;overflow-y:auto;background:#eceef2;padding:0"><a id="top"></a>' + rendered + f'<button class="scroll-to-top">↑</button>{footer}</main></div>'
rendered = re.sub('<code\s*class=" language-python">','',rendered)
open('website/app/templates/index.html','w',encoding='utf-8').write(start + rendered + end)
snippets = [snippet.replace('.md','') for snippet in snippets]
open('website/app/snippets','w').write('\n'.join(snippets))

View File

@ -1,16 +0,0 @@
cffi==1.11.4
click==6.7
emoji==0.4.5
flake8==3.5.0
Flask==1.0
Flask-OAuth==0.12
gunicorn==19.7.1
httplib2==0.10.3
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
misaka==2.1.0
mistune==0.8.3
oauth2==1.9.0.post1
pycparser==2.18
Werkzeug==0.14.1

View File

@ -1,6 +0,0 @@
from app import app
if __name__ == '__main__':
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.run(debug=True, host='0.0.0.0',port=80)