commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
91bb95fa8e481ffd4b1e083cc607f2fb8ce9a1f2 | scripts/remove_after_use/update_datacite_dois.py | scripts/remove_after_use/update_datacite_dois.py | """
Script to send updates to Datacite for projects that were updated
while the DISABLE_DATACITE_DOIS switch was active.
Start date:
Dec 14, 2018 @ 10:09 PM EST = Dec 15, 2018 @ 03:09 UTC
End date:
Dec 15, 2018 @ 12:34 PM EST = Dec 15, 2018 @ 17:34 UTC
"""
import datetime
import logging
import pytz
import waff... | Add script to send updated projects to Datacite. | Add script to send updated projects to Datacite.
[PLAT-1273]
| Python | apache-2.0 | adlius/osf.io,felliott/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,felliott/osf.io,baylee-d/osf.io,mattclark/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,mfraezz/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,baylee-d/osf.io,cslzchen/osf.io,saradbowman/osf.io,mattclark/osf.... | ---
+++
@@ -0,0 +1,46 @@
+"""
+Script to send updates to Datacite for projects that were updated
+while the DISABLE_DATACITE_DOIS switch was active.
+
+Start date:
+ Dec 14, 2018 @ 10:09 PM EST = Dec 15, 2018 @ 03:09 UTC
+End date:
+ Dec 15, 2018 @ 12:34 PM EST = Dec 15, 2018 @ 17:34 UTC
+"""
+import datetime
+... | |
1eb40936310828fe353ea4c4dd902fabea235f77 | Python/112_PathSum.py | Python/112_PathSum.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
... | Add solution for 112 Path Sum. | Add solution for 112 Path Sum.
| Python | mit | comicxmz001/LeetCode,comicxmz001/LeetCode | ---
+++
@@ -0,0 +1,27 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ def hasPathSum(self, root, sum):
+ """
+ :type root: TreeNode
+ ... | |
115c62e6a9a9167633eff93ef0f1a355505a0e5d | tests/test_python33_bdist_egg.py | tests/test_python33_bdist_egg.py | import sys
import os
import tempfile
import unittest
import shutil
import copy
CURDIR = os.path.abspath(os.path.dirname(__file__))
TOPDIR = os.path.split(CURDIR)[0]
sys.path.insert(0, TOPDIR)
from distribute_setup import (use_setuptools, _build_egg, _python_cmd,
_do_download, _install, D... | Add a test for Python 3.3 bdist_egg issue | Add a test for Python 3.3 bdist_egg issue
--HG--
branch : distribute
extra : rebase_source : e83ee69c3b15e4a75780811a7bb3612b8f7f54d1
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -0,0 +1,25 @@
+import sys
+import os
+import tempfile
+import unittest
+import shutil
+import copy
+
+CURDIR = os.path.abspath(os.path.dirname(__file__))
+TOPDIR = os.path.split(CURDIR)[0]
+sys.path.insert(0, TOPDIR)
+
+from distribute_setup import (use_setuptools, _build_egg, _python_cmd,
+ ... | |
962472ab094ec6a5d9bc70628ceb98c48cf803ac | add_liwc_entities.py | add_liwc_entities.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Add LIWC words as entities in FoLiA XML file.
Usage: python add_liwc_entities.py <file in>
"""
from lxml import etree
from bs4 import BeautifulSoup
from emotools import bs4_helpers
import argparse
import json
def add_entity(soup, sentence, cls, word_ids):
# bevat s... | Add script for adding LIWC entities to FoLiA XML file | Add script for adding LIWC entities to FoLiA XML file
Added a script that checks whether a word in the FoLiA file also occurs
in the historic LIWC dictionary. If it does, and the word has certain
categories (at this time the script checks for posemo and negemo
words), an entity is added to the FoLiA XML file.
What nee... | Python | apache-2.0 | NLeSC/embodied-emotions-scripts,NLeSC/embodied-emotions-scripts | ---
+++
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Add LIWC words as entities in FoLiA XML file.
+Usage: python add_liwc_entities.py <file in>
+"""
+from lxml import etree
+from bs4 import BeautifulSoup
+from emotools import bs4_helpers
+import argparse
+import json
+
+
+def add_entity(soup,... | |
e15d982ec3ef0dba52af67ce5b7b448eb8914767 | benchmark_pencode.py | benchmark_pencode.py | #!/usr/bin/env python
import perf
from chopsticks.pencode import pencode, pdecode
def setup():
return [[
1000+i,
str(1000+i),
42,
42.0,
10121071034790721094712093712037123,
None,
True,
b'qwertyuiop',
u'qwertyuiop',
['q', 'w', 'e', '... | Add benchmark script for pencode.pencode() | Add benchmark script for pencode.pencode()
Baseline on a MBP A1389, i7-4750HQ CPU @ 2.00GHz, Ubuntu 17.10 x64,
Python 2.7.14, kernel 4.13.0-36-generic
pencode: Mean +- std dev: 95.8 ms +- 1.2 ms
| Python | apache-2.0 | lordmauve/chopsticks,lordmauve/chopsticks | ---
+++
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+
+import perf
+
+from chopsticks.pencode import pencode, pdecode
+
+
+def setup():
+ return [[
+ 1000+i,
+ str(1000+i),
+ 42,
+ 42.0,
+ 10121071034790721094712093712037123,
+ None,
+ True,
+ b'qwertyuiop',
+ ... | |
f93c9592de5dfcc8968f06cbc692cbee455ebf47 | lintcode/Medium/004_Ugly_Number_II.py | lintcode/Medium/004_Ugly_Number_II.py | class Solution:
"""
@param {int} n an integer.
@return {int} the nth prime number as description.
"""
def nthUglyNumber(self, n):
# write your code here
uglies = [1]
index0, index1, index2 = 0, 0, 0
while(len(uglies) < n):
nextNum = min(uglies[index0] * 2,... | Add solution to lintcode question 004 | Add solution to lintcode question 004
| Python | mit | Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode,Rhadow/leetcode | ---
+++
@@ -0,0 +1,19 @@
+class Solution:
+ """
+ @param {int} n an integer.
+ @return {int} the nth prime number as description.
+ """
+ def nthUglyNumber(self, n):
+ # write your code here
+ uglies = [1]
+ index0, index1, index2 = 0, 0, 0
+ while(len(uglies) < n):
+ ... | |
b9ed7e58e54536d761fe5658e50dcbbd3d1b4d3f | py/arithmetic-slices.py | py/arithmetic-slices.py | class Solution(object):
def numberOfArithmeticSlices(self, A):
"""
:type A: List[int]
:rtype: int
"""
lA = len(A)
if lA < 3:
return 0
p, q = 0, 0
ans = 0
while p < lA - 2:
if A[p + 1] * 2 != A[p] + A[p + 2]:
... | Add py solution for 413. Arithmetic Slices | Add py solution for 413. Arithmetic Slices
413. Arithmetic Slices: https://leetcode.com/problems/arithmetic-slices/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,22 @@
+class Solution(object):
+ def numberOfArithmeticSlices(self, A):
+ """
+ :type A: List[int]
+ :rtype: int
+ """
+ lA = len(A)
+ if lA < 3:
+ return 0
+ p, q = 0, 0
+ ans = 0
+ while p < lA - 2:
+ if A[p +... | |
bfcccf63d0ce17bc91efec6aa66196f1353a1eb7 | scripts/lowercase_log_nids.py | scripts/lowercase_log_nids.py | import sys
from framework.mongo import database as db
from framework.transactions.context import TokuTransaction
from website.app import init_app
def lowercase_nids():
for log in db.nodelog.find({'$or': [
{'params.node': {'$regex': '[A-Z]'}},
{'params.project': {'$regex': '[A-Z]'}},
{'pa... | Add a script to fix mixcased backrefs and params | Add a script to fix mixcased backrefs and params
| Python | apache-2.0 | SSJohns/osf.io,SSJohns/osf.io,icereval/osf.io,acshi/osf.io,leb2dg/osf.io,sloria/osf.io,samchrisinger/osf.io,caneruguz/osf.io,rdhyee/osf.io,laurenrevere/osf.io,RomanZWang/osf.io,emetsger/osf.io,RomanZWang/osf.io,pattisdr/osf.io,acshi/osf.io,amyshi188/osf.io,laurenrevere/osf.io,mfraezz/osf.io,mluo613/osf.io,mluke93/osf.i... | ---
+++
@@ -0,0 +1,45 @@
+import sys
+
+from framework.mongo import database as db
+from framework.transactions.context import TokuTransaction
+
+from website.app import init_app
+
+
+def lowercase_nids():
+ for log in db.nodelog.find({'$or': [
+ {'params.node': {'$regex': '[A-Z]'}},
+ {'params.proje... | |
84b984fc96dbea18cb3272d4ac9f8185c7df1d3b | froide/document/migrations/0006_auto_20180522_0114.py | froide/document/migrations/0006_auto_20180522_0114.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-05-21 23:14
from __future__ import unicode_literals
from django.db import migrations, models
import froide.document.models
import froide.helper.storage
import functools
class Migration(migrations.Migration):
dependencies = [
('document', '000... | Add storage to document image fields | Add storage to document image fields | Python | mit | fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide | ---
+++
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.12 on 2018-05-21 23:14
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import froide.document.models
+import froide.helper.storage
+import functools
+
+
+class Migration(migrations.Migration):
+
+ de... | |
3e7a99967c68d8d5f516889f62cec6a9e2de66aa | category_test.py | category_test.py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2015 Pascual Martinez-Gomez
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | Add test for category class | Add test for category class
| Python | apache-2.0 | mynlp/ccg2lambda,mynlp/ccg2lambda,mynlp/ccg2lambda | ---
+++
@@ -0,0 +1,69 @@
+#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+#
+# Copyright 2015 Pascual Martinez-Gomez
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://w... | |
362d339d39c9e5303cd8f5a99c475c7a68fe1324 | app/process_tweets.py | app/process_tweets.py | # -*- coding: utf-8 -*-
from string import punctuation
from test import _writeJSON, _readJSON
tweetData = _readJSON('var/tweet_test.json')
# Punctuation to be removed.
mySymbols = punctuation.replace(u'#', u'').replace(u'@', u'')
wordsDict = {}
for t in tweetData:
# case?
# apostrophes in words? ' vs ’?
... | Extend test for processing words of tweets. | Extend test for processing words of tweets.
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse | ---
+++
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+from string import punctuation
+
+from test import _writeJSON, _readJSON
+
+tweetData = _readJSON('var/tweet_test.json')
+
+# Punctuation to be removed.
+mySymbols = punctuation.replace(u'#', u'').replace(u'@', u'')
+
+wordsDict = {}
+
+for t in tweetData:
+ # cas... | |
45e9e53bfb857e9658e2c42dc9fd8542da6fbf8e | scripts/sync_local_file_with_swift.py | scripts/sync_local_file_with_swift.py | #!/usr/bin/env python
import os
import io
import tqdm
from dci import dci_config
from dci.db import models
from sqlalchemy import sql
conf = dci_config.generate_conf()
swift = dci_config.get_store()
engine = dci_config.get_engine(conf).connect()
_TABLE = models.FILES
# Calculate the total files to sync
file_list =... | Add a script to sync FS files to Swift | Add a script to sync FS files to Swift
Change-Id: I7a475177dd008040582943f7924a3f26df1df638
| Python | apache-2.0 | redhat-cip/dci-control-server,enovance/dci-control-server,redhat-cip/dci-control-server,enovance/dci-control-server | ---
+++
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+
+import os
+import io
+import tqdm
+from dci import dci_config
+from dci.db import models
+from sqlalchemy import sql
+
+
+conf = dci_config.generate_conf()
+swift = dci_config.get_store()
+engine = dci_config.get_engine(conf).connect()
+
+_TABLE = models.FILES
+
+# C... | |
7cee0a3ac98ecde609cb6077a4b1490b1751838b | cardbox/card_forms.py | cardbox/card_forms.py | from django.forms import Textarea, ModelForm
from card_model import Card
class CardForm(ModelForm):
"""The basic form for updating or editing cards"""
class Meta:
model = Card
fields = ('front', 'back')
widgets = {
'front': Textarea(attrs={'class': "form-control"}),
... | Add custom card model form for edit and create | Add custom card model form for edit and create
| Python | mit | DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune | ---
+++
@@ -0,0 +1,15 @@
+from django.forms import Textarea, ModelForm
+from card_model import Card
+
+
+class CardForm(ModelForm):
+ """The basic form for updating or editing cards"""
+
+ class Meta:
+ model = Card
+ fields = ('front', 'back')
+ widgets = {
+ 'front': Textarea(a... | |
b2b62818345f8062e42b4cfdc19e389cbc430efb | regscrape/sec_cftc/commands/sec_cftc_name_dockets.py | regscrape/sec_cftc/commands/sec_cftc_name_dockets.py | GEVENT = False
from regs_models import *
import datetime
def run():
for docket in Docket.objects(source="sec_cftc", scraped="no"):
now = datetime.datetime.now()
if not docket.title:
candidates = list(Doc.objects(docket_id=docket.id, type__in=("rule", "proposed_rule", "notice")))
... | Add docket namer for SEC/CFTC. | Add docket namer for SEC/CFTC.
| Python | bsd-3-clause | sunlightlabs/regulations-scraper,sunlightlabs/regulations-scraper,sunlightlabs/regulations-scraper | ---
+++
@@ -0,0 +1,23 @@
+GEVENT = False
+
+from regs_models import *
+import datetime
+
+def run():
+ for docket in Docket.objects(source="sec_cftc", scraped="no"):
+ now = datetime.datetime.now()
+ if not docket.title:
+ candidates = list(Doc.objects(docket_id=docket.id, type__in=("rule"... | |
eb804fbf08822053c8d891ece3ebf206cad8a8b8 | es_synonyms/utils.py | es_synonyms/utils.py | import requests
from codecs import open
from requests.exceptions import MissingSchema, InvalidSchema, InvalidURL
from .parser import SynParser
def load_synonyms(path):
try:
r = requests.get(path)
content = r.text
except (MissingSchema, InvalidSchema, InvalidURL):
try:
with open(path, encoding='... | Add utility for quickly loading the synonym file | Add utility for quickly loading the synonym file
| Python | mit | prashnts/elasticsearch-synonyms,prashnts/elasticsearch-synonyms | ---
+++
@@ -0,0 +1,19 @@
+import requests
+
+from codecs import open
+from requests.exceptions import MissingSchema, InvalidSchema, InvalidURL
+
+from .parser import SynParser
+
+def load_synonyms(path):
+ try:
+ r = requests.get(path)
+ content = r.text
+ except (MissingSchema, InvalidSchema, InvalidURL):
+ ... | |
575580d005802d1920402b385bfe963bb4390fac | data/Crumb_data/Crumb_data_loading.py | data/Crumb_data/Crumb_data_loading.py |
# coding: utf-8
# In[ ]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#import sys #(just for version number)
#import matplotlib #(just for version number)
#print('Python version ' + sys.version)
#print('Pandas version ' + pd.__version__)
#print('Matplotlib version ' + matplotlib.__ve... | Add an example python code for loading the resulting data | Add an example python code for loading the resulting data
| Python | bsd-3-clause | mirams/PyHillFit,mirams/PyHillFit,mirams/PyHillFit | ---
+++
@@ -0,0 +1,56 @@
+
+# coding: utf-8
+
+# In[ ]:
+
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+#import sys #(just for version number)
+#import matplotlib #(just for version number)
+#print('Python version ' + sys.version)
+#print('Pandas version ' + pd.__version__)
+#print... | |
4665b59415138e900f46b176cd44f20f23eddf2a | django-mserve/settings-prestoprime.py | django-mserve/settings-prestoprime.py | # Do PrestoPRIME setup
PRESTOPRIME = True
DEFAULT_DELIVERY_SUCCESS_CONSTANT_MIN = 15.0
DEFAULT_DELIVERY_SUCCESS_MULTIPLIER_GB = 1.0
DELIVERY_SUCCESS_METRIC = "http://mserve/deliverySuccess"
if PRESTOPRIME:
CELERY_IMPORTS += ("prestoprime.tasks",)
INSTALLED_APPS += ('prestoprime',)
| Add prestoprime specific settings file. | Add prestoprime specific settings file.
| Python | lgpl-2.1 | it-innovation/MServe-PrestoPRIME | ---
+++
@@ -0,0 +1,9 @@
+# Do PrestoPRIME setup
+PRESTOPRIME = True
+DEFAULT_DELIVERY_SUCCESS_CONSTANT_MIN = 15.0
+DEFAULT_DELIVERY_SUCCESS_MULTIPLIER_GB = 1.0
+DELIVERY_SUCCESS_METRIC = "http://mserve/deliverySuccess"
+if PRESTOPRIME:
+ CELERY_IMPORTS += ("prestoprime.tasks",)
+ INSTALLED_APPS += ('prestoprime... | |
a47c591b77720d342721e3ff3672145d574c65b6 | tests/test_cli.py | tests/test_cli.py | # coding: utf-8
""" Tests for pypel.cli.
THIS SOFTWARE IS UNDER BSD LICENSE.
Copyright (c) 2012-2015 Daniele Tricoli <eriol@mornie.org>
Read LICENSE for more informations.
"""
import unittest
from pypel.cli import Row
class RowTestCase(unittest.TestCase):
def test_empty(self):
row = Row()
se... | Add tests for Row class | Add tests for Row class
| Python | bsd-3-clause | eriol/pypel | ---
+++
@@ -0,0 +1,41 @@
+# coding: utf-8
+""" Tests for pypel.cli.
+
+THIS SOFTWARE IS UNDER BSD LICENSE.
+Copyright (c) 2012-2015 Daniele Tricoli <eriol@mornie.org>
+
+Read LICENSE for more informations.
+"""
+
+import unittest
+
+from pypel.cli import Row
+
+
+class RowTestCase(unittest.TestCase):
+
+ def test_... | |
39df7991e3e305fb54b79012a9d4ec9719deed6c | tests/test_set.py | tests/test_set.py | from thingstance import Thing
def test_tags_are_a_set():
thing = Thing(fields={'latitude', 'longitude'})
assert thing.fields == {'latitude', 'longitude'}
thing = Thing(fields={'latitude', 'longitude', 'altitude'})
assert thing.fields == {'altitude', 'latitude', 'longitude'}
thing = Thing(fields=... | Test fields property is a set | Test fields property is a set
| Python | mit | openregister/openregister-python,openregister/entry,byrondover/entry | ---
+++
@@ -0,0 +1,19 @@
+from thingstance import Thing
+
+
+def test_tags_are_a_set():
+ thing = Thing(fields={'latitude', 'longitude'})
+ assert thing.fields == {'latitude', 'longitude'}
+
+ thing = Thing(fields={'latitude', 'longitude', 'altitude'})
+ assert thing.fields == {'altitude', 'latitude', 'lo... | |
89cb0388c513f01f3dc00829bf21d50feed7ba27 | rest/utils.py | rest/utils.py | from django.http import HttpResponse
from rest_framework.views import exception_handler
from rest_framework.renderers import JSONRenderer
# Initially taken from
# http://www.django-rest-framework.org/tutorial/1-serialization/
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into J... | Add custom exception handler for API. | Add custom exception handler for API.
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project | ---
+++
@@ -0,0 +1,78 @@
+from django.http import HttpResponse
+from rest_framework.views import exception_handler
+from rest_framework.renderers import JSONRenderer
+
+# Initially taken from
+# http://www.django-rest-framework.org/tutorial/1-serialization/
+class JSONResponse(HttpResponse):
+ """
+ An HttpResp... | |
b1354f4b5f59706bbf8a0f6e39457564c5949a9c | samples/_create_webmap.py | samples/_create_webmap.py | """
create a webmap from code,
add a dynamic layer, with dynamiclayer option for changing the symbols
"""
import arcrest
import arcrest.webmap
import arcrest.agol
import json
USER = "XXXXX"
PASSWORD = "xxxxxx"
ORGANISATION = "xxxxxx"
wm = arcrest.webmap.layers.AGSMapServiceLayer("http://sa... | Add a sample on WebMap Serialization | Add a sample on WebMap Serialization
| Python | apache-2.0 | Esri/ArcREST,pLeBlanc93/ArcREST,jgravois/ArcREST,BrunoCaimar/ArcREST,DShokes/ArcREST,adegwerth/ArcREST,achapkowski/ArcREST | ---
+++
@@ -0,0 +1,36 @@
+"""
+ create a webmap from code,
+ add a dynamic layer, with dynamiclayer option for changing the symbols
+
+"""
+
+
+import arcrest
+import arcrest.webmap
+import arcrest.agol
+import json
+
+USER = "XXXXX"
+PASSWORD = "xxxxxx"
+ORGANISATION = "xxxxxx"
+
+wm = arcrest.webmap.layers.A... | |
12d922665ad1bba8a696ea35a1c0ced45fccd907 | pylibofp/__main__.py | pylibofp/__main__.py | from .ofp_app import ofp_run
import importlib
import argparse
import sys
def main():
args = parse_args()
for module in args.modules:
import_module(module)
ofp_run()
def parse_args():
parser = argparse.ArgumentParser(
prog='ofp_app',
description='ofp_app runner',
epilog... | Add support for python -m. | Add support for python -m.
| Python | mit | byllyfish/pylibofp,byllyfish/pylibofp | ---
+++
@@ -0,0 +1,41 @@
+from .ofp_app import ofp_run
+import importlib
+import argparse
+import sys
+
+def main():
+ args = parse_args()
+ for module in args.modules:
+ import_module(module)
+ ofp_run()
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(
+ prog='ofp_app',
+ d... | |
71b80cbf4b519823ecc72f1f38196c738ccf7c11 | registration/urls.py | registration/urls.py | # created by Chirath R, chirath.02@gmail.com
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from registration.views import UserSignUpView, login, UserUpdateView, ProfileDetailView, ProfileListView
urlpatterns = [
url(r'^login... | # created by Chirath R, chirath.02@gmail.com
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from registration.views import UserSignUpView, login, UserUpdateView, ProfileDetailView, ProfileListView
urlpatterns = [
url(r'^login... | Change the default no of users from 9 | Change the default no of users from 9 | Python | mit | akshaya9/fosswebsite,Sparker0i/fosswebsite,akshayharidas/fosswebsite,csriharsha/fosswebsite,akshaya9/fosswebsite,csriharsha/fosswebsite,amfoss/fosswebsite,rahulk98/fosswebsite,akshayharidas/fosswebsite,navisk13/fosswebsite,akshayharidas/fosswebsite,amfoss/fosswebsite,Sparker0i/fosswebsite,manikishan/fosswebsite,csrihar... | ---
+++
@@ -8,8 +8,8 @@
url(r'^login/$', login, name="login"),
url(r'^signup/$', UserSignUpView.as_view(), name="signup"),
url(r'^$', ProfileListView.as_view(), name="profile_list"),
- url(r'^(?P<pk>[0-9])/$', ProfileDetailView.as_view(), name="profile"),
- url(r'^(?P<pk>[0-9])/update/$', login_r... |
f4160538b9e55fa2f886a5b6e2a93a26ceb3d5da | tests/GIR/test_940_content_manager.py | tests/GIR/test_940_content_manager.py | # coding=utf-8
import sys
import struct
import unittest
import time
from test_000_config import TestConfig
from test_020_connection import TestConnection
from gi.repository import Midgard
from gi.repository import GObject
class TestContentManagerJobCreate(unittest.TestCase):
mgd = None
bookstore = None
referen... | Test sql content manager. Refs gh-168 | Test sql content manager. Refs gh-168
| Python | lgpl-2.1 | midgardproject/midgard-core,midgardproject/midgard-core,midgardproject/midgard-core,midgardproject/midgard-core | ---
+++
@@ -0,0 +1,66 @@
+# coding=utf-8
+
+import sys
+import struct
+import unittest
+import time
+from test_000_config import TestConfig
+from test_020_connection import TestConnection
+
+from gi.repository import Midgard
+from gi.repository import GObject
+
+class TestContentManagerJobCreate(unittest.TestCase):
+... | |
35c264819bac12fcb3baf8a2a33d63dd916f5f86 | mezzanine_fluent_pages/mezzanine_layout_page/widgets.py | mezzanine_fluent_pages/mezzanine_layout_page/widgets.py | from django.forms.widgets import Select
class LayoutSelector(Select):
"""
Modified `Select` class to select the original value.
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
"""
def render(self, name, value, attrs=None, choices=()):
... | from django.forms.widgets import Select
class LayoutSelector(Select):
"""
Modified `Select` class to select the original value.
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
"""
def render(self, name, value, attrs=None, *args, **kwar... | Remove keyword argument and allow generic argument passing. | Remove keyword argument and allow generic argument passing.
| Python | bsd-2-clause | sjdines/mezzanine-fluent-pages,sjdines/mezzanine-fluent-pages,sjdines/mezzanine-fluent-pages | ---
+++
@@ -8,16 +8,17 @@
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
"""
- def render(self, name, value, attrs=None, choices=()):
+ def render(self, name, value, attrs=None, *args, **kwargs):
"""
Modified render to s... |
62bace1f2a326ab6ab660a23bc1776a1895f5f3d | piper/abc.py | piper/abc.py | import abc
import logbook
import jsonschema
from piper.utils import DotDict
class DynamicItem(object):
"""
Dynamic base class that defines things all Piper classes need.
Many parts of the piper infrastructure is about being able to dynamically
choose which classes should execute actions. This class ... | Add abstract base class for dynamic items | Add abstract base class for dynamic items
| Python | mit | thiderman/piper | ---
+++
@@ -0,0 +1,47 @@
+import abc
+import logbook
+import jsonschema
+
+from piper.utils import DotDict
+
+
+class DynamicItem(object):
+ """
+ Dynamic base class that defines things all Piper classes need.
+
+ Many parts of the piper infrastructure is about being able to dynamically
+ choose which cla... | |
5616a5a3987106654ca0c15d73d1db6c1b8c7f3d | distribution/create_linux_shortcuts.py | distribution/create_linux_shortcuts.py | #!/usr/bin/env python3
import sys
import os
import os.path as op
try:
import picasso
except ImportError:
print("This script must be run within an environment "
"in which picasso is installed!", file=sys.stderr)
raise
SUBCMD = ("average", "design", "filter", "localize", "render", "simulate")
SCRIPT_PAT... | Add script for creating shortcuts in linux | Add script for creating shortcuts in linux
| Python | mit | jungmannlab/picasso,jungmannlab/picasso,jungmannlab/picasso | ---
+++
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+import sys
+import os
+import os.path as op
+
+try:
+ import picasso
+except ImportError:
+ print("This script must be run within an environment "
+ "in which picasso is installed!", file=sys.stderr)
+ raise
+
+SUBCMD = ("average", "design", "filter", "loc... | |
b8cd62385b904ba536642c68eedd9316344bf822 | authenticate_imgur.py | authenticate_imgur.py | #!/usr/bin/env python3
from imgurpython import ImgurClient
import config
CONFIG_FILE = "config.yaml"
def authenticate():
conf = config.read_file(CONFIG_FILE)
# Get client ID and secret from auth.ini
client = ImgurClient(conf.imgur.client_id, conf.imgur.client_secret)
# Authorization flow, pin exa... | Add script to generate refresh_token | Add script to generate refresh_token
https://github.com/Imgur/imgurpython/blob/master/examples/auth.py
| Python | mit | FichteFoll/CodetalkIRCBot,FichteFoll/TelegramIRCImageProxy,codetalkio/TelegramIRCImageProxy | ---
+++
@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+
+from imgurpython import ImgurClient
+
+import config
+
+CONFIG_FILE = "config.yaml"
+
+
+def authenticate():
+ conf = config.read_file(CONFIG_FILE)
+ # Get client ID and secret from auth.ini
+
+ client = ImgurClient(conf.imgur.client_id, conf.imgur.client_s... | |
9831af65019e245acd65ebd181d6936392d1d2ce | examples/dump_category.py | examples/dump_category.py | """dump_category.py - utility script for mps_edits."""
import sys
import json
import getopt
import urllib
import urllib2
class ArticleFetchError(Exception):
pass
def get_articles(base, category):
regular_params = [
('cmtitle', "Category:%s" % (category)),
('action', 'query'),
('list',... | Add example script that dumps a wikipedia category | Add example script that dumps a wikipedia category
| Python | mit | flexo/wikitweets | ---
+++
@@ -0,0 +1,84 @@
+"""dump_category.py - utility script for mps_edits."""
+
+import sys
+import json
+import getopt
+import urllib
+import urllib2
+
+class ArticleFetchError(Exception):
+ pass
+
+def get_articles(base, category):
+ regular_params = [
+ ('cmtitle', "Category:%s" % (category)),
+ ... | |
76c8a5ca367e2a22953cde9541f61d564de5f6ff | temba/channels/migrations/0007_auto_20150402_2103.py | temba/channels/migrations/0007_auto_20150402_2103.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('channels', '0006_channel_bod'),
]
operations = [
migrations.AlterField(
model_name='channel',
name='... | Add migration for HX channel type | Add migration for HX channel type
| Python | agpl-3.0 | reyrodrigues/EU-SMS,ewheeler/rapidpro,pulilab/rapidpro,ewheeler/rapidpro,Thapelo-Tsotetsi/rapidpro,tsotetsi/textily-web,harrissoerja/rapidpro,reyrodrigues/EU-SMS,harrissoerja/rapidpro,pulilab/rapidpro,praekelt/rapidpro,pulilab/rapidpro,ewheeler/rapidpro,tsotetsi/textily-web,praekelt/rapidpro,pulilab/rapidpro,harrissoer... | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('channels', '0006_channel_bod'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ ... | |
09bb45941583a126429e3cc27b2fb4bb6b01d56c | Car2know/analysis/QueryData.py | Car2know/analysis/QueryData.py | from urllib2 import Request, urlopen, URLError
from datetime import time
from datetime import date
import datetime
import time
import sys
import os
# Using request and urlopen to get data from car2go's API
# We need the city name and consumer_key
def querydata():
request = Request("http://www.car2go... | Move the file to correct path | Move the file to correct path
| Python | mit | gengho/Car2know,gengho/Car2know | ---
+++
@@ -0,0 +1,72 @@
+from urllib2 import Request, urlopen, URLError
+from datetime import time
+from datetime import date
+import datetime
+import time
+import sys
+import os
+
+
+# Using request and urlopen to get data from car2go's API
+# We need the city name and consumer_key
+def querydata():
+ request ... | |
ed7bbd2ed53a2b3009acace7b8399a35842a4532 | nameless/visitors.py | nameless/visitors.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
visitors.py
@author ejnp
"""
import ast
import lambda_calculus_ast
class FreeVariables(ast.NodeVisitor):
"""Visits each node of a lambda calculus abstract syntax tree and
determines which variables (if any) are unbound. Ultimately provides a set
of string v... | Add a visitor for determining free variables | Add a visitor for determining free variables
| Python | mit | ElliotPenson/nameless | ---
+++
@@ -0,0 +1,31 @@
+#!/usr/bin/python
+# -*- coding: UTF-8 -*-
+
+"""
+visitors.py
+
+@author ejnp
+"""
+
+import ast
+import lambda_calculus_ast
+
+
+class FreeVariables(ast.NodeVisitor):
+ """Visits each node of a lambda calculus abstract syntax tree and
+ determines which variables (if any) are unbound... | |
f5fb2f955843d802fb2a7225ee3aac98eac640e5 | output/pprint_json.py | output/pprint_json.py | #!/bin/env python3
import json
import pprint
import sys
json_string = ""
for line in sys.stdin.readlines():
json_string = "{}{}".format(json_string, line.strip())
item = json.loads(json_string)
pprint.pprint(item)
| Add pretty print json output | Add pretty print json output
| Python | mit | dgengtek/scripts,dgengtek/scripts | ---
+++
@@ -0,0 +1,9 @@
+#!/bin/env python3
+import json
+import pprint
+import sys
+json_string = ""
+for line in sys.stdin.readlines():
+ json_string = "{}{}".format(json_string, line.strip())
+item = json.loads(json_string)
+pprint.pprint(item) | |
f96d8119814488061c2bb6ef71bd8f054c69f082 | app/api_preferences.py | app/api_preferences.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import configuration
RPX_REALM = 'mils-alumni-secure'
rpxnow = {
'api_auth_url': 'https://rpxnow.com/api/v2/auth_info',
'api_key': 'b771106aa4e3ef377c359495f52f2c99120f36ac',
'auth_token_url': configuration.ROOT_URL + 'auth_token'
'realm': RPX_REALM,
'... | Add api preferences for rpxnow | Add api preferences for rpxnow
| Python | mit | yesudeep/old-milsalumni,yesudeep/old-milsalumni,yesudeep/old-milsalumni | ---
+++
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import configuration
+
+RPX_REALM = 'mils-alumni-secure'
+rpxnow = {
+ 'api_auth_url': 'https://rpxnow.com/api/v2/auth_info',
+ 'api_key': 'b771106aa4e3ef377c359495f52f2c99120f36ac',
+ 'auth_token_url': configuration.ROOT_URL + 'auth... | |
6072022e2debeb4dcd75e4969bd2beb16bac8827 | source/sqlserver_ado/fields.py | source/sqlserver_ado/fields.py | """This module provides SQL Server specific fields for Django models."""
from django.db.models import AutoField, ForeignKey, IntegerField
class BigAutoField(AutoField):
"""A bigint IDENTITY field"""
def get_internal_type(self):
return "BigAutoField"
def to_python(self, value):
if ... | """This module provides SQL Server specific fields for Django models."""
from django.db.models import AutoField, ForeignKey, IntegerField
from django.forms import ValidationError
class BigAutoField(AutoField):
"""A bigint IDENTITY field"""
def get_internal_type(self):
return "BigAutoField"
... | Fix import error for custom Field validation | Fix import error for custom Field validation
| Python | mit | theoriginalgri/django-mssql,theoriginalgri/django-mssql | ---
+++
@@ -1,5 +1,6 @@
"""This module provides SQL Server specific fields for Django models."""
from django.db.models import AutoField, ForeignKey, IntegerField
+from django.forms import ValidationError
class BigAutoField(AutoField):
"""A bigint IDENTITY field"""
@@ -12,7 +13,7 @@
try:
... |
1a0fe91b6ab9a90573b0f35d6ff81e7f0523acb4 | praw/util/__init__.py | praw/util/__init__.py | """Package imports for utilities."""
__all__ = ("cache",)
| """Package imports for utilities."""
import re
__all__ = ("cache", "camel_to_snake", "snake_case_keys")
_re_camel_to_snake = re.compile(r"([a-z0-9](?=[A-Z])|[A-Z](?=[A-Z][a-z]))")
def camel_to_snake(name):
"""Convert `name` from camelCase to snake_case."""
return _re_camel_to_snake.sub(r"\1_", name).lower(... | Add `camel_to_snake()` and `snake_case_keys()` to praw.util | Add `camel_to_snake()` and `snake_case_keys()` to praw.util
| Python | bsd-2-clause | praw-dev/praw,gschizas/praw,leviroth/praw,praw-dev/praw,gschizas/praw,leviroth/praw | ---
+++
@@ -1,3 +1,21 @@
"""Package imports for utilities."""
-__all__ = ("cache",)
+import re
+
+__all__ = ("cache", "camel_to_snake", "snake_case_keys")
+
+_re_camel_to_snake = re.compile(r"([a-z0-9](?=[A-Z])|[A-Z](?=[A-Z][a-z]))")
+
+
+def camel_to_snake(name):
+ """Convert `name` from camelCase to snake_cas... |
4b3eb563a50a601bcb24a358f6ea63690cffeb27 | raiden/network/nat.py | raiden/network/nat.py | import miniupnpc
from ethereum import slogging
MAX_PORT = 65535
RAIDEN_IDENTIFICATOR = "raiden-network udp service"
log = slogging.getLogger(__name__)
def connect():
"""Try to connect to the router.
Returns:
u (miniupnc.UPnP): the connected upnp-instance
router (string): the connection infor... | Add minimalistic UPnP NAT punching | Add minimalistic UPnP NAT punching
This is not in use yet.
| Python | mit | charles-cooper/raiden,hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,hackaugusto/raiden,tomaaron/raiden,tomaaron/raiden,tomaaron/raiden,tomashaber/raiden,tomaaron/raiden,charles-cooper/raiden | ---
+++
@@ -0,0 +1,92 @@
+import miniupnpc
+from ethereum import slogging
+
+MAX_PORT = 65535
+RAIDEN_IDENTIFICATOR = "raiden-network udp service"
+
+log = slogging.getLogger(__name__)
+
+
+def connect():
+ """Try to connect to the router.
+ Returns:
+ u (miniupnc.UPnP): the connected upnp-instance
+ ... | |
4ad58714dc0fd8dfd464f804ca356328beed1ff2 | Cloud.py | Cloud.py | from abc import ABCMeta, abstractmethod
class Cloud(object):
__metaclass__ = ABCMeta
def __init__(self):
self.driver = None
self.activeNode = None
@abstractmethod
def create(self):
raise Exception('Not implemented')
@abstractmethod
def destroy(self):
raise Ex... | Add a base class for OpenStack and Amazon. | Add a base class for OpenStack and Amazon.
| Python | mit | minidfx/Cloud-Python- | ---
+++
@@ -0,0 +1,17 @@
+from abc import ABCMeta, abstractmethod
+
+
+class Cloud(object):
+ __metaclass__ = ABCMeta
+
+ def __init__(self):
+ self.driver = None
+ self.activeNode = None
+
+ @abstractmethod
+ def create(self):
+ raise Exception('Not implemented')
+
+ @abstractmeth... | |
91417abaeb2cdc3cfafdc96a5b30f31d0ce8be80 | php4dvd/test_login.py | php4dvd/test_login.py | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import unittest
class Login(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox(capabilities={'native_events':True})
self.driver.implicitly_wait(10)
self.ba... | Move login test to a file by itself. | Move login test to a file by itself.
| Python | bsd-2-clause | bsamorodov/selenium-py-training-samorodov | ---
+++
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+from selenium import webdriver
+from selenium.common.exceptions import NoSuchElementException
+import unittest
+
+
+class Login(unittest.TestCase):
+ def setUp(self):
+ self.driver = webdriver.Firefox(capabilities={'native_events':True})
+ self.drive... | |
e835c8e1dd368d98eeb3d706983e803f1bb91a3a | 2018/CodingInterview/3주차/code_sc.py | 2018/CodingInterview/3주차/code_sc.py |
# input_data = """
# 10101111
# 01111101
# 11001110
# 00000010
# 2
# 3 -1
# 1 1
# """
# matrix_data = input_data.strip().split("\n")[:4]
#
# n_direction_data = input_data.strip().split("\n")[5:]
#
# matrix = [deque(list(line)) for line in matrix_data]
# step = int(input_data.strip().split("\n")[4])
# n, direction = zi... | Add 3rd week assignment of SC | Add 3rd week assignment of SC
| Python | mit | TeamLab/lab_study_group,kjihee/lab_study_group | ---
+++
@@ -0,0 +1,58 @@
+
+# input_data = """
+# 10101111
+# 01111101
+# 11001110
+# 00000010
+# 2
+# 3 -1
+# 1 1
+# """
+# matrix_data = input_data.strip().split("\n")[:4]
+#
+# n_direction_data = input_data.strip().split("\n")[5:]
+#
+# matrix = [deque(list(line)) for line in matrix_data]
+# step = int(input_data.... | |
a165962921ccdfbd6ba4eb4a6c7cbd38b57fdf47 | hackerrank_datatype.py | hackerrank_datatype.py | i=10
d=2.5
s="HackerRank"
# Declare second integer, double, and String variables.
ii=int(raw_input())
dd=float(raw_input())
ss=raw_input()
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print i+ii
# Print the sum of the double variables on a n... | Print sum of same data types on a different line | Print sum of same data types on a different line
| Python | mit | kumarisneha/practice_repo | ---
+++
@@ -0,0 +1,16 @@
+i=10
+d=2.5
+s="HackerRank"
+# Declare second integer, double, and String variables.
+ii=int(raw_input())
+dd=float(raw_input())
+ss=raw_input()
+# Read and save an integer, double, and String to your variables.
+
+# Print the sum of both integer variables on a new line.
+print i+ii
+# Print... | |
00f9a05f651c4c51c8c2a3c359f6eecc3faca699 | py/ones-and-zeroes.py | py/ones-and-zeroes.py | from collections import Counter
class Solution(object):
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
str_counter = []
for s in strs:
c0 = s.count('0')
str_counter.append(... | Add py solution for 474. Ones and Zeroes | Add py solution for 474. Ones and Zeroes
474. Ones and Zeroes: https://leetcode.com/problems/ones-and-zeroes/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,23 @@
+from collections import Counter
+class Solution(object):
+ def findMaxForm(self, strs, m, n):
+ """
+ :type strs: List[str]
+ :type m: int
+ :type n: int
+ :rtype: int
+ """
+ str_counter = []
+ for s in strs:
+ c0 = s.cou... | |
1874783a4626c0aaecaf1527b111ec3cd4e34c42 | examples/test_save_screenshots.py | examples/test_save_screenshots.py | import os
from seleniumbase import BaseCase
class ScreenshotTests(BaseCase):
def test_save_screenshot(self):
self.open("https://seleniumbase.io/demo_page")
# "./downloaded_files" is a special SeleniumBase folder for downloads
self.save_screenshot("demo_page.png", folder="./downlo... | Add a test for testing methods that save screenshots | Add a test for testing methods that save screenshots
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | ---
+++
@@ -0,0 +1,40 @@
+import os
+from seleniumbase import BaseCase
+
+
+class ScreenshotTests(BaseCase):
+
+ def test_save_screenshot(self):
+ self.open("https://seleniumbase.io/demo_page")
+ # "./downloaded_files" is a special SeleniumBase folder for downloads
+ self.save_screenshot("demo... | |
7088faefe52ecb69666fcc5c08398131dccf39df | rtorrent-interface.py | rtorrent-interface.py | #!./bin/python3
from functools import wraps
from rpc import RTorrentXMLRPCClient
import os
from flask import Flask, g, json, request
app = Flask(__name__)
RTORRENT_XMLRPC_CONFIG_PATH = './cfg/rtorrent-interface.cfg'
app.config.from_object(__name__)
@app.route('/')
def index():
return app.send_static_file('index.h... | Add small web backend serving static index.html and being api for getting torrent download info | Add small web backend serving static index.html and being api for getting torrent download info
| Python | mit | lfxgroove/rtorrent-interface,lfxgroove/rtorrent-interface | ---
+++
@@ -0,0 +1,68 @@
+#!./bin/python3
+from functools import wraps
+from rpc import RTorrentXMLRPCClient
+import os
+from flask import Flask, g, json, request
+app = Flask(__name__)
+
+RTORRENT_XMLRPC_CONFIG_PATH = './cfg/rtorrent-interface.cfg'
+app.config.from_object(__name__)
+
+@app.route('/')
+def index():
+... | |
5b8f125ca7a3c1b833105380316e325ce61b2c9d | test/test_priority.py | test/test_priority.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Simple test to send each priority level
import unittest
import logging
logging.basicConfig(level=logging.WARNING)
from gntp.notifier import GrowlNotifier
class TestHash(unittest.TestCase):
def setUp(self):
self.growl = GrowlNotifier('GNTP unittest', ['Testin... | Add a test for priority levels | Add a test for priority levels
| Python | mit | kfdm/gntp | ---
+++
@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Simple test to send each priority level
+import unittest
+import logging
+logging.basicConfig(level=logging.WARNING)
+from gntp.notifier import GrowlNotifier
+
+
+class TestHash(unittest.TestCase):
+ def setUp(self):
+ self.growl = ... | |
7300912727233500360a9e51f37161e04b04258b | util/hubget.py | util/hubget.py | #!/usr/bin/env python3
from cozify import hub, hub_api
import pprint, sys
def main(path):
hub.ping()
kwargs = {}
hub._fill_kwargs(kwargs)
response = hub_api.get(path, **kwargs)
pprint.pprint(response)
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1])
else:
... | Add a new utility for easily making arbitrary hub GET calls | Add a new utility for easily making arbitrary hub GET calls
Useful for exploring for undocumented endpoints without having to deal
with authentication, hub ip and so on.
| Python | mit | Artanicus/python-cozify,Artanicus/python-cozify | ---
+++
@@ -0,0 +1,18 @@
+#!/usr/bin/env python3
+from cozify import hub, hub_api
+import pprint, sys
+
+
+def main(path):
+ hub.ping()
+ kwargs = {}
+ hub._fill_kwargs(kwargs)
+ response = hub_api.get(path, **kwargs)
+ pprint.pprint(response)
+
+
+if __name__ == "__main__":
+ if len(sys.argv) > 1:
... | |
c58370b3e38f663ac361d82ea984ed5aa5e03318 | mecab_parsing.py | mecab_parsing.py | import operator
class WordInfo(object):
def __init__(self):
dictionary_form = ""
word_class = ""
spelling = ""
value = ""
features = []
def __str__(self):
return "{0},{1},{2},{3}".format(self.value, self.spelling, self.dictionary_form, self.word_cl... | Add mecab related utility function | Add mecab related utility function
| Python | mit | Deathhush/HushUtility,Deathhush/Hush | ---
+++
@@ -0,0 +1,51 @@
+import operator
+
+class WordInfo(object):
+ def __init__(self):
+ dictionary_form = ""
+ word_class = ""
+ spelling = ""
+ value = ""
+ features = []
+ def __str__(self):
+ return "{0},{1},{2},{3}".format(self.value, self.spelli... | |
c92d19ec8b689d63a95d3dc5f914c2e36d28daf6 | ipywidgets/widgets/tests/test_widget.py | ipywidgets/widgets/tests/test_widget.py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Test Widget."""
from IPython.utils.capture import capture_output
from IPython.display import display
from ..widget import Widget
def test_no_widget_view():
with capture_output() as cap:
w = Widget()
... | Test that Widget does not produce any view output | Test that Widget does not produce any view output
| Python | bsd-3-clause | jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets | ---
+++
@@ -0,0 +1,18 @@
+# Copyright (c) Jupyter Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+"""Test Widget."""
+
+from IPython.utils.capture import capture_output
+from IPython.display import display
+
+from ..widget import Widget
+
+
+def test_no_widget_view():
+ with captur... | |
3172aff3c1cc90a5e88d60d362cb73336b0dc646 | nettests/simpletest.py | nettests/simpletest.py | from ooni import nettest
class SimpleTest(nettest.TestCase):
inputs = range(1,100)
optParameters = [['asset', 'a', None, 'Asset file'],
['controlserver', 'c', 'google.com', 'Specify the control server'],
['resume', 'r', 0, 'Resume at this index'],
[... | Add a very simple test that *must* always pass. * Useful for testing the newstyle API | Add a very simple test that *must* always pass.
* Useful for testing the newstyle API
| Python | bsd-2-clause | 0xPoly/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,hackerberry/ooni-probe,0xPoly/ooni-probe,hackerberry/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,lordappsec/oon... | ---
+++
@@ -0,0 +1,19 @@
+from ooni import nettest
+class SimpleTest(nettest.TestCase):
+ inputs = range(1,100)
+ optParameters = [['asset', 'a', None, 'Asset file'],
+ ['controlserver', 'c', 'google.com', 'Specify the control server'],
+ ['resume', 'r', 0, 'Resume at thi... | |
a91f69e2c7618f1a0bcfd6b82004186ec949fbff | oneflow/settings/snippets/djdt.py | oneflow/settings/snippets/djdt.py | # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# leto.licorn.org
'82.236.133.193',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug... | # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# gurney.licorn.org
'109.190.93.141',
# my LAN
'192.168.111.23',
'192.168.111.111',
)
DEBUG_TOOLBAR_PANELS = (
'debug_to... | Fix the django debug toolbar not appearing and the user echo thing slowing my loadings in development. | Fix the django debug toolbar not appearing and the user echo thing slowing my loadings in development.
| Python | agpl-3.0 | 1flow/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow | ---
+++
@@ -6,8 +6,11 @@
INTERNAL_IPS = (
'127.0.0.1',
- # leto.licorn.org
- '82.236.133.193',
+ # gurney.licorn.org
+ '109.190.93.141',
+ # my LAN
+ '192.168.111.23',
+ '192.168.111.111',
)
DEBUG_TOOLBAR_PANELS = ( |
bda6a897511ab3312da30ab71b60797f53f7a73a | indico/modules/events/sessions/views.py | indico/modules/events/sessions/views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | Add view class for the sessions module | Add view class for the sessions module
| Python | mit | OmeGak/indico,mvidalgarcia/indico,DirkHoffmann/indico,pferreir/indico,pferreir/indico,mvidalgarcia/indico,ThiefMaster/indico,ThiefMaster/indico,OmeGak/indico,OmeGak/indico,mvidalgarcia/indico,mic4ael/indico,indico/indico,indico/indico,pferreir/indico,pferreir/indico,OmeGak/indico,ThiefMaster/indico,DirkHoffmann/indico,... | ---
+++
@@ -0,0 +1,31 @@
+# This file is part of Indico.
+# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
+#
+# Indico is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either ... | |
1aacd7d5e7403d3c3732a54e5f6111349436e00d | code/windingvstime.py | code/windingvstime.py | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy.ma as ma
fuz = 1/4.;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
fuz = float(sys.argv[2])
binfile = sy... | Make a plot as function of time for some datasets. | Make a plot as function of time for some datasets.
| Python | mit | TAdeJong/plasma-analysis,TAdeJong/plasma-analysis | ---
+++
@@ -0,0 +1,40 @@
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib
+from mpl_toolkits.mplot3d import Axes3D
+import sys
+
+import numpy.ma as ma
+
+fuz = 1/4.;
+if (len(sys.argv) < 2) :
+ print("Usage: \n dataplot.py path_to_binfile [clamp value]")
+ sys.exit()
+elif (len(sys.argv) > 2) ... | |
cf73f1c3ac17ca163cb7c930e3024ffd1994cef1 | odm/catalogs/CatalogReader.py | odm/catalogs/CatalogReader.py | class CatalogReader(object):
"""
Basic "interface" to the ODM catalog readers.
Resembles the structure of CKAN harvesters, for later CKAN imports.
"""
def info(self):
pass
def gather(self):
pass
def fetch(self, data_dict):
pass
def import_data(self, data_dict)... | Add outline for catalog readers | Add outline for catalog readers
| Python | mit | SebastianBerchtold/odm-catalogreaders,mattfullerton/odm-catalogreaders | ---
+++
@@ -0,0 +1,24 @@
+class CatalogReader(object):
+ """
+ Basic "interface" to the ODM catalog readers.
+ Resembles the structure of CKAN harvesters, for later CKAN imports.
+ """
+
+ def info(self):
+ pass
+
+ def gather(self):
+ pass
+
+ def fetch(self, data_dict):
+ p... | |
1b13a69b888d3cc925eae357f1959a6f420e5df5 | remap_authors.py | remap_authors.py | #!/usr/bin/python3
import sys
import json
if len(sys.argv) < 4:
print("Usage: ./remap_authors.py <input_journal> <old_authors.json> <new_authors.json>")
print("The input journal will have its author id's updated to the ids of the same authors in <new_authors.json>")
sys.exit(1)
# Build a map of author na... | Add author remapping script to merge different datasets | Add author remapping script to merge different datasets
| Python | mit | Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks | ---
+++
@@ -0,0 +1,40 @@
+#!/usr/bin/python3
+
+import sys
+import json
+
+if len(sys.argv) < 4:
+ print("Usage: ./remap_authors.py <input_journal> <old_authors.json> <new_authors.json>")
+ print("The input journal will have its author id's updated to the ids of the same authors in <new_authors.json>")
+ sys... | |
9bbdd657cddd9d56437d05ab9701aea305af3010 | embryo-interpolation.py | embryo-interpolation.py | # IPython log file
image = np.zeros((2048, 2048), dtype=float)
image[0, 0] = 1
np.percentile(image, [0.1, 99.9])
get_ipython().run_line_magic('pinfo', 'np.percentile')
np.stack([np.zeros((3, 2)), np.zeros(3)], axis=1)
from skimage import data
image = data.horse().astype(bool)
plt.imshow(image)
get_ipython().run_line_... | Add raw embryo interpolation code | Add raw embryo interpolation code
| Python | bsd-3-clause | jni/useful-histories | ---
+++
@@ -0,0 +1,47 @@
+# IPython log file
+
+
+image = np.zeros((2048, 2048), dtype=float)
+image[0, 0] = 1
+np.percentile(image, [0.1, 99.9])
+get_ipython().run_line_magic('pinfo', 'np.percentile')
+np.stack([np.zeros((3, 2)), np.zeros(3)], axis=1)
+from skimage import data
+image = data.horse().astype(bool)
+plt... | |
a42109b6992023dc31a3f77a173c19065e4c00d5 | jsonrpcclient/clients/socket_client.py | jsonrpcclient/clients/socket_client.py | """
Low-level socket client.
"""
import socket
from typing import Any
from ..client import Client
from ..response import Response
class SocketClient(Client):
"""
Args:
socket: Connected socket.
*args: Passed through to Client class.
**kwargs: Passed through to Client class.
"""
... | Add a low-level socket client | Add a low-level socket client
| Python | mit | bcb/jsonrpcclient | ---
+++
@@ -0,0 +1,34 @@
+"""
+Low-level socket client.
+"""
+import socket
+from typing import Any
+
+from ..client import Client
+from ..response import Response
+
+
+class SocketClient(Client):
+ """
+ Args:
+ socket: Connected socket.
+ *args: Passed through to Client class.
+ **kwargs:... | |
25743b9e5bc406d3f8f7713e5dca560d5bb4f82f | tests/xmi/test_xmi_serialization.py | tests/xmi/test_xmi_serialization.py | import pytest
import os
import pyecore.ecore as Ecore
from pyecore.resources import *
from pyecore.resources.xmi import XMIResource
def test_resource_createset(tmpdir):
f = tmpdir.mkdir('pyecore-tmp').join('test.xmi')
resource = XMIResource(URI(str(f)))
# we create a simple metamodel by script
package... | Add simple integration test for model serialization | Add simple integration test for model serialization
This test creates a new metamodel in memory (by code), create an
instance of the metamodel, serialize the instance model as XMI, then
re-read it again from another resource.
| Python | bsd-3-clause | aranega/pyecore,pyecore/pyecore | ---
+++
@@ -0,0 +1,38 @@
+import pytest
+import os
+import pyecore.ecore as Ecore
+from pyecore.resources import *
+from pyecore.resources.xmi import XMIResource
+
+def test_resource_createset(tmpdir):
+ f = tmpdir.mkdir('pyecore-tmp').join('test.xmi')
+ resource = XMIResource(URI(str(f)))
+
+ # we create a ... | |
f6dd64353c864f965bed0091dc1ab447ff29a2fd | src/ggrc_workflows/migrations/versions/20151107014837_18bdb0671010_update_invalid_task_dates.py | src/ggrc_workflows/migrations/versions/20151107014837_18bdb0671010_update_invalid_task_dates.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
"""Update invalid task dates
Revision ID: 18bdb0671010
Revises: e81da7a55e7
Cre... | Add a migration for fixing bad dates | Add a migration for fixing bad dates
This migration is for the case that some bad dates were imported before
the propper date validation was added.
| Python | apache-2.0 | AleksNeStu/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-cor... | ---
+++
@@ -0,0 +1,42 @@
+# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
+# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
+# Created By: miha@reciprocitylabs.com
+# Maintained By: miha@reciprocitylabs.com
+
+"""Update invalid task dates
+
+Revision ID: 18... | |
eaa125e7195f065c4ca74088d8f9a5eb6464e056 | basics/masking_utils.py | basics/masking_utils.py |
import skimage.morphology as mo
import scipy.ndimage as nd
import warnings
try:
import cv2
CV2_FLAG = True
except ImportError:
warnings.warn("Cannot import cv2. Computing with scipy.ndimage")
CV2_FLAG = False
from utils import eight_conn
def smooth_edges(mask, filter_size, min_pixels):
no_smal... | Split off masking utility functions | Split off masking utility functions
| Python | mit | e-koch/BaSiCs | ---
+++
@@ -0,0 +1,49 @@
+
+import skimage.morphology as mo
+import scipy.ndimage as nd
+import warnings
+
+try:
+ import cv2
+ CV2_FLAG = True
+except ImportError:
+ warnings.warn("Cannot import cv2. Computing with scipy.ndimage")
+ CV2_FLAG = False
+
+from utils import eight_conn
+
+
+def smooth_edges(m... | |
88fb0e30f50184641615bf70aa82ded6646854f3 | watcher.py | watcher.py | from threading import Thread
from werkzeug._reloader import ReloaderLoop
class Watcher(Thread, ReloaderLoop):
def __init__(self, dirname, interval=1, static, tasks, *args, **kwargs):
self.dirname = dirname
self.static = static
self.tasks = tasks
super(Watcher, self).__init__(*args,... | Add thread implementation to watch files | Add thread implementation to watch files
| Python | mit | rolurq/flask-gulp | ---
+++
@@ -0,0 +1,27 @@
+from threading import Thread
+from werkzeug._reloader import ReloaderLoop
+
+class Watcher(Thread, ReloaderLoop):
+
+ def __init__(self, dirname, interval=1, static, tasks, *args, **kwargs):
+ self.dirname = dirname
+ self.static = static
+ self.tasks = tasks
+ ... | |
769541b58b1b163197717ea4b84c5ce0cde293e0 | app/messaging_app.py | app/messaging_app.py | import os
import json
from .core.logger import configure_logging
from .core.messaging import MessageServer
def get_password():
if "REDIS_PASSWD" in os.environ:
return os.environ["REDIS_PASSWD"]
with open("/home/rpi/.variables") as f:
line = next(x.strip() for x in f if x.startswith("REDIS_PAS... | Add main for messaging server. | Add main for messaging server.
| Python | mit | supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer | ---
+++
@@ -0,0 +1,25 @@
+import os
+import json
+
+from .core.logger import configure_logging
+from .core.messaging import MessageServer
+
+
+def get_password():
+ if "REDIS_PASSWD" in os.environ:
+ return os.environ["REDIS_PASSWD"]
+ with open("/home/rpi/.variables") as f:
+ line = next(x.strip(... | |
53bbb9bfa6fdc1e946365e746b1acf4b03a0635e | regulations/templatetags/in_context.py | regulations/templatetags/in_context.py | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... | from django import template
register = template.Library()
class InContextNode(template.Node):
def __init__(self, nodelist, subcontext_names):
self.nodelist = nodelist
self.subcontext_names = subcontext_names
def render(self, context):
new_context = {}
for field in self.subcon... | Fix custom template tag to work with django 1.8 | Fix custom template tag to work with django 1.8
| Python | cc0-1.0 | willbarton/regulations-site,grapesmoker/regulations-site,willbarton/regulations-site,willbarton/regulations-site,grapesmoker/regulations-site,willbarton/regulations-site,ascott1/regulations-site,ascott1/regulations-site,grapesmoker/regulations-site,ascott1/regulations-site,grapesmoker/regulations-site,ascott1/regulatio... | ---
+++
@@ -16,7 +16,8 @@
new_context.update(context.get(field, {}))
else:
new_context[field] = value
- return self.nodelist.render(template.Context(new_context))
+ new_context = context.new(new_context)
+ return self.nodelist.render(new_context)
... |
f6c21d21964d5211ab9d157ca2eedbcc064cd3bd | scripts/generate_hamilton_input_UPL.py | scripts/generate_hamilton_input_UPL.py | #!/usr/bin/env python
from EPPs.common import StepEPP, step_argparser
class GenerateHamiltonInputUPL(StepEPP):
""""Generate a CSV containing the necessary information to batch up ot 9 User Prepared Library receipt
into one DCT plate. Requires input and output plate containers and well positions from LIMS. Volu... | Test updated for change to assign_to_workflow_receive_sample.py in last commit. | Test updated for change to assign_to_workflow_receive_sample.py in last commit.
| Python | mit | EdinburghGenomics/clarity_scripts,EdinburghGenomics/clarity_scripts | ---
+++
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+from EPPs.common import StepEPP, step_argparser
+
+class GenerateHamiltonInputUPL(StepEPP):
+ """"Generate a CSV containing the necessary information to batch up ot 9 User Prepared Library receipt
+ into one DCT plate. Requires input and output plate containers a... | |
9fe720e01de94a59f090c909b4659d2369cfea25 | stack/skyline.py | stack/skyline.py | from collections import deque
def solution(H):
levels = deque()
blocks = 0
for i in xrange(len(H)):
print H[i]
while len(levels) > 0 and levels[-1] > H[i]:
levels.pop()
print 'Going down, H: %s, levels: %s' % (H[i], levels)
blocks += 1
if len(leve... | Add min block wall algorithm. | Add min block wall algorithm.
| Python | apache-2.0 | isendel/algorithms | ---
+++
@@ -0,0 +1,16 @@
+from collections import deque
+
+def solution(H):
+ levels = deque()
+ blocks = 0
+ for i in xrange(len(H)):
+ print H[i]
+ while len(levels) > 0 and levels[-1] > H[i]:
+ levels.pop()
+ print 'Going down, H: %s, levels: %s' % (H[i], levels)
+ ... | |
ea17b8c990842290f4553374a51ebc223cf363bd | mnist_8by8_classifier.py | mnist_8by8_classifier.py | from __future__ import print_function
import time
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.datasets import load_digits
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.preprocessing import LabelBinarizer
from ann import ANN
# import the simpl... | Add mnist 8by8 classifier with scikit dataset | Add mnist 8by8 classifier with scikit dataset
| Python | mit | Razvy000/ANN-Intro | ---
+++
@@ -0,0 +1,71 @@
+from __future__ import print_function
+import time
+import numpy as np
+from sklearn.cross_validation import train_test_split
+from sklearn.datasets import load_digits
+from sklearn.metrics import confusion_matrix, classification_report
+from sklearn.preprocessing import LabelBinarizer
+from... | |
bb79f86e4eeadaf8a93ccceaee2936e248fea99e | server/removed_expired_data.py | server/removed_expired_data.py | #!/usr/bin/env python
# Standard Library
import os
import sqlite3
import ConfigParser as configparser
from datetime import datetime
# Third party
from dateutil.relativedelta import relativedelta
config = configparser.RawConfigParser()
if not config.read([os.path.expanduser('~/.ppupload.conf') or 'ppupload.conf', '/e... | Remove expired files from database and storage. | Remove expired files from database and storage. | Python | bsd-3-clause | jhaals/filebutler-upload,jhaals/python-filebutler | ---
+++
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+
+# Standard Library
+import os
+import sqlite3
+import ConfigParser as configparser
+from datetime import datetime
+
+# Third party
+from dateutil.relativedelta import relativedelta
+
+config = configparser.RawConfigParser()
+if not config.read([os.path.expanduser('~/... | |
9600746e27e8cd10cdb9ede05d1b341be903597f | gevent_tasks/utils.py | gevent_tasks/utils.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# >>
# gevent-tasks, 2017
# <<
import random
import string
ch_choices = string.ascii_letters + string.digits
def gen_uuid(length=4):
# type: (int) -> str
""" Generate a random ID of a given length. """
return ''.join(map(lambda c: random.choice(ch_choic... | Add simple uuid generator based on length and ASCII chars | Add simple uuid generator based on length and ASCII chars
| Python | mit | blakev/gevent-tasks | ---
+++
@@ -0,0 +1,16 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+# >>
+# gevent-tasks, 2017
+# <<
+
+import random
+import string
+
+ch_choices = string.ascii_letters + string.digits
+
+
+def gen_uuid(length=4):
+ # type: (int) -> str
+ """ Generate a random ID of a given length. """
+ return '... | |
7c2548f7f4cf01d0a5cf389c290a47cdf029a7ac | apps/explorer/tests/views/test_mixins.py | apps/explorer/tests/views/test_mixins.py | import pytest
from django.test import TestCase
from apps.explorer.views.mixins import DataTableMixin, SubsetSelectionMixin
class DataTableMixinTestCase(TestCase):
def test_get_omics_units_must_be_implemented(self):
class DataTableWithNoGetOmicsUnits(DataTableMixin):
pass
with pyte... | Add tests for explorer views mixins | Add tests for explorer views mixins
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel | ---
+++
@@ -0,0 +1,33 @@
+import pytest
+
+from django.test import TestCase
+
+from apps.explorer.views.mixins import DataTableMixin, SubsetSelectionMixin
+
+
+class DataTableMixinTestCase(TestCase):
+
+ def test_get_omics_units_must_be_implemented(self):
+
+ class DataTableWithNoGetOmicsUnits(DataTableMixi... | |
988481094bd34842e3ec186ec5c7daaff9663591 | examples/dots.py | examples/dots.py | from threading import Thread
from time import sleep
from nuimo import Controller, ControllerManager, ControllerListener, LedMatrix
MAC_ADDRESS = "c4:d7:54:71:e2:ce"
class NuimoListener(ControllerListener):
def __init__(self, controller):
self.controller = controller
self.stopping = False
... | Add an example how to write to the LED matrix from another thread | Add an example how to write to the LED matrix from another thread
| Python | mit | getsenic/nuimo-linux-python | ---
+++
@@ -0,0 +1,51 @@
+from threading import Thread
+from time import sleep
+
+from nuimo import Controller, ControllerManager, ControllerListener, LedMatrix
+
+
+MAC_ADDRESS = "c4:d7:54:71:e2:ce"
+
+
+class NuimoListener(ControllerListener):
+ def __init__(self, controller):
+ self.controller = controll... | |
5c167d35ea341e8ea33596f4174e16b9aafa041a | py/perfect-number.py | py/perfect-number.py | class Solution(object):
def checkPerfectNumber(self, num):
"""
:type num: int
:rtype: bool
"""
MersennePrime = [3, 7, 31, 127, 8191, 131071, 524287]
MPp = [2, 3, 5, 7, 13, 17, 19]
perfectnumbers = set(map(lambda a, b:a * (1 << (b - 1)), MersennePrime, MPp))
... | Add py solution for 507. Perfect Number | Add py solution for 507. Perfect Number
507. Perfect Number: https://leetcode.com/problems/perfect-number/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,10 @@
+class Solution(object):
+ def checkPerfectNumber(self, num):
+ """
+ :type num: int
+ :rtype: bool
+ """
+ MersennePrime = [3, 7, 31, 127, 8191, 131071, 524287]
+ MPp = [2, 3, 5, 7, 13, 17, 19]
+ perfectnumbers = set(map(lambda a, b:a * (1 ... | |
70b245f321bf542111929a1f1ba5460c46c067fc | python/gameOfLife.py | python/gameOfLife.py | # https://leetcode.com/problems/game-of-life/
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
dx = (-1, -1, -1, 0, 1, 1, 1, 0)
dy = (-1, 0, 1, 1, 1, 0, -1, -... | Add problem Game Of Life | Add problem Game Of Life
| Python | mit | guozengxin/myleetcode,guozengxin/myleetcode | ---
+++
@@ -0,0 +1,35 @@
+# https://leetcode.com/problems/game-of-life/
+
+class Solution(object):
+ def gameOfLife(self, board):
+ """
+ :type board: List[List[int]]
+ :rtype: void Do not return anything, modify board in-place instead.
+ """
+ dx = (-1, -1, -1, 0, 1, 1, 1, 0)
+ ... | |
0ab30d3f9b836db48b5e05614c5e1807d9189977 | sheldon/basic_classes.py | sheldon/basic_classes.py | # -*- coding: utf-8 -*-
"""
Declaration of classes needed for bot working:
Adapter class, Plugin class
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from time import sleep
class Adapter:
"""
Adapter class contains information about adapter:
name, ... | Add realization of adapter class | Add realization of adapter class
| Python | mit | lises/sheldon | ---
+++
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+
+"""
+Declaration of classes needed for bot working:
+Adapter class, Plugin class
+
+@author: Lises team
+@contact: zhidkovseva@gmail.com
+@license: The MIT license
+
+Copyright (C) 2015
+"""
+
+from time import sleep
+
+
+class Adapter:
+ """
+ Adapter class ... | |
12a2113453eb5ec6171d52a49948ea663609afbd | gutenbrowse/util.py | gutenbrowse/util.py | import urllib as _urllib
class HTTPError(IOError):
def __init__(self, code, msg, headers):
IOError.__init__(self, 'HTTP error', code, msg, headers)
def __str__(self):
return "HTTP: %d %s" % (self.args[1], self.args[2])
class MyURLOpener(_urllib.FancyURLopener):
def http_error_default(self,... | Add an exception-raising-on-http-error urlopen function | Add an exception-raising-on-http-error urlopen function
| Python | bsd-3-clause | pv/mgutenberg,pv/mgutenberg | ---
+++
@@ -0,0 +1,32 @@
+import urllib as _urllib
+
+class HTTPError(IOError):
+ def __init__(self, code, msg, headers):
+ IOError.__init__(self, 'HTTP error', code, msg, headers)
+ def __str__(self):
+ return "HTTP: %d %s" % (self.args[1], self.args[2])
+
+class MyURLOpener(_urllib.FancyURLopene... | |
c6480cad80a9c8eb93afdb3bd31a8c8c21eea8d9 | scripts/pubmedextract.py | scripts/pubmedextract.py | """
Extract a set of doc ids from the pubmed xml files.
"""
import argparse
import glob
import gzip
import multiprocessing
import os
from functools import partial
from multiprocessing import Pool
import sys
from lxml import etree
def parse_pubmeds(pmids: list, file: str) -> str:
"""
:param pmids:
:param... | Add script for extracting pmids out of pubmed data. | Add script for extracting pmids out of pubmed data.
| Python | apache-2.0 | leifos/lucene4ir,leifos/lucene4ir,leifos/lucene4ir,lucene4ir/lucene4ir,lucene4ir/lucene4ir,lucene4ir/lucene4ir | ---
+++
@@ -0,0 +1,58 @@
+"""
+Extract a set of doc ids from the pubmed xml files.
+"""
+import argparse
+import glob
+import gzip
+import multiprocessing
+import os
+from functools import partial
+from multiprocessing import Pool
+
+import sys
+from lxml import etree
+
+
+def parse_pubmeds(pmids: list, file: str) ->... | |
27b43cd5dd8c27afd8b7dbacd3024c222af909d0 | tests/test_int_vs_long.py | tests/test_int_vs_long.py | from __future__ import absolute_import, unicode_literals
import unittest
from jnius import autoclass, cast, PythonJavaClass, java_method
class TestImplemIterator(PythonJavaClass):
__javainterfaces__ = ['java/util/ListIterator']
class TestImplem(PythonJavaClass):
__javainterfaces__ = ['java/util/List']
... | Add test for INT vs LONG conversion on Py2 | Add test for INT vs LONG conversion on Py2
int and long are the same on py3, but we do care about the conversion from Python too which in case INT is >=2**31 then Java might have problem with that and it could cause issues for the users
| Python | mit | kivy/pyjnius,kivy/pyjnius,kivy/pyjnius | ---
+++
@@ -0,0 +1,58 @@
+from __future__ import absolute_import, unicode_literals
+import unittest
+from jnius import autoclass, cast, PythonJavaClass, java_method
+
+
+class TestImplemIterator(PythonJavaClass):
+ __javainterfaces__ = ['java/util/ListIterator']
+
+
+class TestImplem(PythonJavaClass):
+ __javai... | |
266eae5880b352783ca3cb31af8eae3fc40e5ea5 | snoboy/tests/test_cpu.py | snoboy/tests/test_cpu.py | from nose.tools import eq_, ok_
from snoboy import cpu
def test_BC():
cpu.registers.DE = 0xB060
cpu.registers.BC = 0xC005
eq_(cpu.registers.BC, 0xC005)
eq_(cpu.registers.DE, 0xB060)
| Add simple test case for cpu compound registers | Add simple test case for cpu compound registers
| Python | mit | Osmose/snoboy | ---
+++
@@ -0,0 +1,9 @@
+from nose.tools import eq_, ok_
+
+from snoboy import cpu
+
+def test_BC():
+ cpu.registers.DE = 0xB060
+ cpu.registers.BC = 0xC005
+ eq_(cpu.registers.BC, 0xC005)
+ eq_(cpu.registers.DE, 0xB060) | |
6bbde2294d1f5eeb4dde2ee76f6a874c6ed52ead | src/products/baseball.py | src/products/baseball.py | import numpy as np
import tensorflow.contrib.keras as keras
PWD = 'products'
MODEL = "{}/model.h5".format(PWD)
THRESHOLD = 0.75
# Load model.
model = keras.models.load_model(MODEL)
# Stream test photos.
test_datagen = keras.preprocessing.image.ImageDataGenerator(
rescale=1. / 255)
test_generator = tes... | Add script to only predict if above confidence threshold. | Add script to only predict if above confidence threshold.
| Python | mit | isaacanthony/tensorflow-playground,isaacanthony/tensorflow-playground | ---
+++
@@ -0,0 +1,39 @@
+import numpy as np
+import tensorflow.contrib.keras as keras
+
+PWD = 'products'
+MODEL = "{}/model.h5".format(PWD)
+THRESHOLD = 0.75
+
+# Load model.
+model = keras.models.load_model(MODEL)
+
+# Stream test photos.
+test_datagen = keras.preprocessing.image.ImageDataGenerator(
+ ... | |
9b6f703d65cfbf57cf5b4aee224b89c215f931eb | packaging/__init__.py | packaging/__init__.py | # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Use relative import to allow vendoring | Use relative import to allow vendoring
| Python | apache-2.0 | xavfernandez/packaging,nvie/packaging | ---
+++
@@ -13,7 +13,7 @@
# limitations under the License.
from __future__ import absolute_import, division, print_function
-from packaging.__about__ import (
+from .__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
) |
0c60ce6b4c816c080c56b44a0568c0b9520c3581 | lms/djangoapps/student_account/careersandenterprise.py | lms/djangoapps/student_account/careersandenterprise.py | from django.conf import settings
from social_core.backends.oauth import BaseOAuth2
import logging
import re
log = logging.getLogger(__name__)
class CareersAndEnterpriseOAuth2(BaseOAuth2):
"""Careers and Enterprise Company OAuth2 authentication backend."""
settings_dict = settings.CUSTOM_BACKENDS.get('careers... | Add initial version Careers and Enterprise Oauth2 backend. | Add initial version Careers and Enterprise Oauth2 backend.
| Python | agpl-3.0 | proversity-org/edx-platform,proversity-org/edx-platform,proversity-org/edx-platform,proversity-org/edx-platform | ---
+++
@@ -0,0 +1,62 @@
+from django.conf import settings
+from social_core.backends.oauth import BaseOAuth2
+import logging
+import re
+
+log = logging.getLogger(__name__)
+
+
+class CareersAndEnterpriseOAuth2(BaseOAuth2):
+ """Careers and Enterprise Company OAuth2 authentication backend."""
+ settings_dict =... | |
42a43d6594efc21ab29ea079f758df5bd2ec3c41 | Homeworks/HW1/Problem1.py | Homeworks/HW1/Problem1.py | """Problem 1: Break math
Break math using a computer. To be a bit more specific, demonstrate a
numerical calculation using the computer language of your choice where
the answer is demonstrably wrong. I'll want to see the code you used,
preferably something brief and punchy, and then the result. For full credit,
fix mat... | Add hw 1 problem 1 solution | Add hw 1 problem 1 solution
| Python | mit | dankolbman/NumericalAnalysis | ---
+++
@@ -0,0 +1,21 @@
+"""Problem 1: Break math
+Break math using a computer. To be a bit more specific, demonstrate a
+numerical calculation using the computer language of your choice where
+the answer is demonstrably wrong. I'll want to see the code you used,
+preferably something brief and punchy, and then the ... | |
d997f0aa51b20be8038e96bd6a79783b507aea08 | constantDraw.py | constantDraw.py | def draw_constant(res=10):
"""Re-draws a Read node using Constant nodes as pixels."""
# Checks that the user has selected a Read node.
try:
if nuke.selectedNode().Class() != "Read":
# Pushes pop up message to the user
nuke.message("No Read node selected to re-draw!")
... | Add .py file to repo. | Add .py file to repo.
| Python | mit | SurpriseTRex/node-draw | ---
+++
@@ -0,0 +1,40 @@
+def draw_constant(res=10):
+ """Re-draws a Read node using Constant nodes as pixels."""
+ # Checks that the user has selected a Read node.
+
+ try:
+ if nuke.selectedNode().Class() != "Read":
+ # Pushes pop up message to the user
+ nuke.message("No Read ... | |
0e899fabae552a33b7dfabe9908a0ad0279055b6 | tests/header_passthrough_tests.py | tests/header_passthrough_tests.py | from django.test.client import RequestFactory
from mock import Mock
from unittest2 import TestCase
from helpers import RequestPatchMixin
from test_views import TestProxy
class HttpProxyHeaderPassThrough(TestCase, RequestPatchMixin):
"""HttpProxy header pass through"""
def setUp(self):
self.proxy = Te... | Add header pass through tests | Add header pass through tests
| Python | mit | thomasw/djproxy | ---
+++
@@ -0,0 +1,41 @@
+from django.test.client import RequestFactory
+from mock import Mock
+from unittest2 import TestCase
+
+from helpers import RequestPatchMixin
+from test_views import TestProxy
+
+
+class HttpProxyHeaderPassThrough(TestCase, RequestPatchMixin):
+ """HttpProxy header pass through"""
+ de... | |
198fe89f055d2bdd1d8b0ea2a8df46f75a9ee21d | guessenc.py | guessenc.py | #!/usr/bin/env python
import sys
# common characters in GB
gb_cc = frozenset([
b"\xce\xd2", # 我
b"\xb5\xc4", # 的
b"\xc4\xe3", # 你
b"\xca\xc7", # 是
b"\xb2\xbb", # 不
b"\xc1\xcb", # 了
b"\xd2\xbb", # 一
b"\xc3\xc7", # 们
b"\xd5\xe2", # 这
b"\xd3\xd0" # 有
])
big5_cc = frozenset([
b"\xa7\xda", # 我
b"\xaa\xba", # 的
b"\xa7\x... | Add script to guess text encoding | Add script to guess text encoding
| Python | agpl-3.0 | erjiang/hanzidefs | ---
+++
@@ -0,0 +1,84 @@
+#!/usr/bin/env python
+
+
+import sys
+
+
+# common characters in GB
+gb_cc = frozenset([
+b"\xce\xd2", # 我
+b"\xb5\xc4", # 的
+b"\xc4\xe3", # 你
+b"\xca\xc7", # 是
+b"\xb2\xbb", # 不
+b"\xc1\xcb", # 了
+b"\xd2\xbb", # 一
+b"\xc3\xc7", # 们
+b"\xd5\xe2", # 这
+b"\xd3\xd0" # 有
+])
+
+big5_cc = frozen... | |
4b91050ddb5357970462d5a15fe0d1ed97d51178 | tests/variable_fields.py | tests/variable_fields.py | """Test cases for variable fields
"""
import unittest
from lighty.templates import Template
class VariableFieldTestCase(unittest.TestCase):
"""Test case for block template tag
"""
def setUp(self):
self.value = 'value'
self.variable_template = Template(name='base.html')
self.varia... | Add test for fields variables lookup | Add test for fields variables lookup
| Python | bsd-3-clause | GrAndSE/lighty,GrAndSE/lighty-template | ---
+++
@@ -0,0 +1,53 @@
+"""Test cases for variable fields
+"""
+import unittest
+
+from lighty.templates import Template
+
+
+class VariableFieldTestCase(unittest.TestCase):
+ """Test case for block template tag
+ """
+
+ def setUp(self):
+ self.value = 'value'
+ self.variable_template = Temp... | |
7d8164982754c86cc3fb90662795373845813c47 | myuw/management/commands/check_preference.py | myuw/management/commands/check_preference.py | #!/usr/bin/python
"""
Test all the links in the CSV for non-200 status codes (after redirects).
"""
import sys
from django.core.management.base import BaseCommand, CommandError
from myuw.models import UserMigrationPreference
class Command(BaseCommand):
args = "<user netid>"
help = "Find the Migration Prefere... | Add a management command to check legacy preference | Add a management command to check legacy preference
| Python | apache-2.0 | uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw | ---
+++
@@ -0,0 +1,29 @@
+#!/usr/bin/python
+"""
+Test all the links in the CSV for non-200 status codes (after redirects).
+"""
+
+import sys
+from django.core.management.base import BaseCommand, CommandError
+from myuw.models import UserMigrationPreference
+
+
+class Command(BaseCommand):
+ args = "<user netid>"... | |
5caf415a1517017271cbdce8e5bd3de3e552420e | test/unittests/skills/test_context.py | test/unittests/skills/test_context.py | from unittest import TestCase, mock
from mycroft.skills.context import adds_context, removes_context
"""
Tests for the adapt context decorators.
"""
class ContextSkillMock(mock.Mock):
"""Mock class to apply decorators on."""
@adds_context('DestroyContext')
def handler_adding_context(self):
pass
... | Add tests for context decorators | Add tests for context decorators
| Python | apache-2.0 | forslund/mycroft-core,MycroftAI/mycroft-core,MycroftAI/mycroft-core,forslund/mycroft-core | ---
+++
@@ -0,0 +1,42 @@
+from unittest import TestCase, mock
+
+from mycroft.skills.context import adds_context, removes_context
+"""
+Tests for the adapt context decorators.
+"""
+
+
+class ContextSkillMock(mock.Mock):
+ """Mock class to apply decorators on."""
+ @adds_context('DestroyContext')
+ def handl... | |
b0f3c0f8db69b7c4a141bd32680ed937b40d34c6 | util/item_name_gen.py | util/item_name_gen.py | '''Script to help generate item names.'''
def int_to_str(num, alphabet):
'''Convert integer to string.'''
# http://stackoverflow.com/a/1119769/1524507
if (num == 0):
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num = num // base
a... | Add util script to generate item names. | Add util script to generate item names.
| Python | unlicense | ArchiveTeam/twitpic-discovery,ArchiveTeam/twitpic-discovery | ---
+++
@@ -0,0 +1,37 @@
+'''Script to help generate item names.'''
+
+
+def int_to_str(num, alphabet):
+ '''Convert integer to string.'''
+ # http://stackoverflow.com/a/1119769/1524507
+ if (num == 0):
+ return alphabet[0]
+ arr = []
+ base = len(alphabet)
+ while num:
+ rem = num % b... | |
a4d312411cb125685291e81b8bb2204324fea34d | sandbox/order/migrations/0005_auto_20170502_1533.py | sandbox/order/migrations/0005_auto_20170502_1533.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-02 15:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0004_auto_20160111_1108'),
]
operations = [
migrations.AlterField(... | Add missing migration in sandbox | Add missing migration in sandbox
| Python | isc | thelabnyc/django-oscar-api-checkout | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.5 on 2017-05-02 15:33
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('order', '0004_auto_20160111_1108'),
+ ]
+
+ oper... | |
6bde05ad9c16be2677ab6c91444e793529a9fdd3 | comrade/core/models.py | comrade/core/models.py | from django.db import models
class ComradeBaseModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return self.__unicode__()
def __repr__(self):
return self.__unicode__()
class Meta:
abstr... | Add a base Django model to share common functionality. | Add a base Django model to share common functionality.
| Python | mit | bueda/django-comrade | ---
+++
@@ -0,0 +1,18 @@
+from django.db import models
+
+class ComradeBaseModel(models.Model):
+ created = models.DateTimeField(auto_now_add=True)
+ modified = models.DateTimeField(auto_now=True)
+
+ def __str__(self):
+ return self.__unicode__()
+
+ def __repr__(self):
+ return self.__unic... | |
b154468b085dad53de8fdef09ec42c8518475556 | tests/basics/string_format_modulo_int.py | tests/basics/string_format_modulo_int.py | # test string modulo formatting with int values
# test + option with various amount of padding
for pad in ('', ' ', '0'):
for n in (1, 2, 3):
for val in (-1, 0, 1):
print(('%+' + pad + str(n) + 'd') % val)
| Add test for string module formatting with int argument. | tests/basics: Add test for string module formatting with int argument.
| Python | mit | infinnovation/micropython,lowRISC/micropython,infinnovation/micropython,micropython/micropython-esp32,toolmacher/micropython,PappaPeppar/micropython,pfalcon/micropython,SHA2017-badge/micropython-esp32,AriZuu/micropython,lowRISC/micropython,tobbad/micropython,puuu/micropython,dmazzella/micropython,SHA2017-badge/micropyt... | ---
+++
@@ -0,0 +1,7 @@
+# test string modulo formatting with int values
+
+# test + option with various amount of padding
+for pad in ('', ' ', '0'):
+ for n in (1, 2, 3):
+ for val in (-1, 0, 1):
+ print(('%+' + pad + str(n) + 'd') % val) | |
b4f9b8d6c056224fc3728c6eecf511fecf6ac6d7 | tests/test_configuration/test_gateway.py | tests/test_configuration/test_gateway.py | '''
Test gateway creation
'''
import unittest
from wirecurly.configuration import gateway
from nose import tools
class testGatewayCreation(unittest.TestCase):
'''
Test gateway creation
'''
def setUp(self):
'''
gateway fixtures for tests
'''
self.gw = gateway.Gateway('name')
def test_gw_dict_ok(... | Add Tests for gateway creation | Add Tests for gateway creation
| Python | mpl-2.0 | IndiciumSRL/wirecurly | ---
+++
@@ -0,0 +1,45 @@
+'''
+ Test gateway creation
+'''
+
+import unittest
+from wirecurly.configuration import gateway
+from nose import tools
+
+
+class testGatewayCreation(unittest.TestCase):
+ '''
+ Test gateway creation
+ '''
+
+ def setUp(self):
+ '''
+ gateway fixtures for tests
+ '''
+
+ self.gw = ga... | |
6ba84140e5d7ddca2ee88e8ca6562a32a66a1d6b | tests/app/main/forms/test_govuk_text_input_field.py | tests/app/main/forms/test_govuk_text_input_field.py | from flask_wtf import FlaskForm as Form
from app.main.forms import GovukTextInputField
def test_GovukTextInputField_renders_zero(client_request):
class FakeForm(Form):
field = GovukTextInputField()
form = FakeForm(field=0)
html = form.field()
assert 'value="0"' in html
| Add test for rendering integer 0 in form input | Add test for rendering integer 0 in form input
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -0,0 +1,12 @@
+from flask_wtf import FlaskForm as Form
+
+from app.main.forms import GovukTextInputField
+
+
+def test_GovukTextInputField_renders_zero(client_request):
+ class FakeForm(Form):
+ field = GovukTextInputField()
+
+ form = FakeForm(field=0)
+ html = form.field()
+ assert 'va... | |
d9dd7214865130d2ccc31670bcbc1c1f6cc7596a | 02_task/sample_test.py | 02_task/sample_test.py | import unittest
import solution
class SampleTest(unittest.TestCase):
def test_five_plus_three(self):
plus = solution.create_operator('+', lambda lhs, rhs: lhs + rhs)
x = solution.create_variable('x')
y = solution.create_variable('y')
added_expression = solution.create_expression((... | Add 02-task sample test file. | Add 02-task sample test file.
| Python | mit | pepincho/Python-Course-FMI | ---
+++
@@ -0,0 +1,25 @@
+import unittest
+
+import solution
+
+
+class SampleTest(unittest.TestCase):
+ def test_five_plus_three(self):
+ plus = solution.create_operator('+', lambda lhs, rhs: lhs + rhs)
+ x = solution.create_variable('x')
+ y = solution.create_variable('y')
+ added_exp... | |
bac583e9b3849884aa9865a3d8d19796b0eedd70 | tap_dhcp.py | tap_dhcp.py | import re
import subprocess
def get_namespace_list():
"""Retrieve the list of DHCP namespaces."""
return subprocess(['ip', 'netns', 'list']).split()
def get_interfaces_for(namespace):
"""Retrieve the list of interfaces inside a namespace."""
return subprocess(['ip', 'netns', 'exec', namespace, 'ip',... | Add first pass at checking dhcp namespaces for taps | Add first pass at checking dhcp namespaces for taps
| Python | apache-2.0 | sigmavirus24/rpc-openstack,stevelle/rpc-openstack,git-harry/rpc-openstack,miguelgrinberg/rpc-openstack,git-harry/rpc-openstack,jacobwagner/rpc-openstack,mancdaz/rpc-openstack,mattt416/rpc-openstack,darrenchan/rpc-openstack,hughsaunders/rpc-openstack,galstrom21/rpc-openstack,darrenchan/rpc-openstack,rcbops/rpc-openstack... | ---
+++
@@ -0,0 +1,38 @@
+import re
+import subprocess
+
+
+def get_namespace_list():
+ """Retrieve the list of DHCP namespaces."""
+ return subprocess(['ip', 'netns', 'list']).split()
+
+
+def get_interfaces_for(namespace):
+ """Retrieve the list of interfaces inside a namespace."""
+ return subprocess([... | |
5d06524c8465064248cc3605c69dd32687ea7565 | wqflask/tests/wqflask/test_user_login.py | wqflask/tests/wqflask/test_user_login.py | """Test cases for some methods in login.py"""
import unittest
from wqflask.user_login import encode_password
class TestUserLogin(unittest.TestCase):
def test_encode_password(self):
"""
Test encode password
"""
pass_gen_fields = {
"salt": "salt",
"hashfunc":... | Add tests for encoding password | Add tests for encoding password
* wqflask/tests/wqflask/test_user_login.py: New tests.
| Python | agpl-3.0 | pjotrp/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2 | ---
+++
@@ -0,0 +1,21 @@
+"""Test cases for some methods in login.py"""
+
+import unittest
+from wqflask.user_login import encode_password
+
+
+class TestUserLogin(unittest.TestCase):
+ def test_encode_password(self):
+ """
+ Test encode password
+ """
+ pass_gen_fields = {
+ ... | |
e1914156c0d4085d35c88634c98c294e38faada5 | cryptchat/test/test_aes.py | cryptchat/test/test_aes.py | #/usr/bin/python
# -*- coding: utf-8 -*-
# Run from Cryptchat
# python -m unittest discover
import unittest
from ..crypto.aes import AESCipher
class testAESCipher(unittest.TestCase):
def test_encrypt_decrypt(self):
key = "TTTcPolAhIqZZJY0IOH7Orecb/EEaUx8/u/pQlCgma8="
cipher = AESCipher(key)
... | Add some tests for crypto/aes | Add some tests for crypto/aes
| Python | mit | djohsson/Cryptchat | ---
+++
@@ -0,0 +1,40 @@
+#/usr/bin/python
+# -*- coding: utf-8 -*-
+# Run from Cryptchat
+# python -m unittest discover
+
+import unittest
+from ..crypto.aes import AESCipher
+
+
+class testAESCipher(unittest.TestCase):
+
+ def test_encrypt_decrypt(self):
+ key = "TTTcPolAhIqZZJY0IOH7Orecb/EEaUx8/u/pQlCgma... | |
e9942aea9a2c11575d5abcfa33f2aef1d8d53c6a | modify-color.py | modify-color.py | #!/bin/python
"""modify-color
------------
"""
import sys
import colorsys
class Color(object):
def __init__(self, color_str, color_format="hex"):
pass
if __name__ == "__main__":
if len(sys.argv) == 1 or sys.argv[1] in ['help', '--help']:
print(__doc__)
sys.exit()
| Print doc on help or no args | Print doc on help or no args
| Python | bsd-3-clause | seenaburns/color-util,seenaburns/color-util | ---
+++
@@ -0,0 +1,16 @@
+#!/bin/python
+"""modify-color
+------------
+"""
+
+import sys
+import colorsys
+
+class Color(object):
+ def __init__(self, color_str, color_format="hex"):
+ pass
+
+if __name__ == "__main__":
+ if len(sys.argv) == 1 or sys.argv[1] in ['help', '--help']:
+ print(__doc__... | |
f2bb3b0ab09da5fc1c186765052aea8fd87a9b2b | setuptools/tests/test_find_packages.py | setuptools/tests/test_find_packages.py | """Tests for setuptools.find_packages()."""
import os
import shutil
import tempfile
import unittest
from setuptools import find_packages
class TestFindPackages(unittest.TestCase):
def setUp(self):
self.dist_dir = tempfile.mkdtemp()
self._make_pkg_structure()
def tearDown(self):
shut... | Add unit tests for find_packages | Add unit tests for find_packages
--HG--
extra : rebase_source : 75f5ce4d2fb9d0ccd7168739c23d9ea1eeeb9112
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -0,0 +1,72 @@
+"""Tests for setuptools.find_packages()."""
+import os
+import shutil
+import tempfile
+import unittest
+
+from setuptools import find_packages
+
+
+class TestFindPackages(unittest.TestCase):
+
+ def setUp(self):
+ self.dist_dir = tempfile.mkdtemp()
+ self._make_pkg_structur... | |
3e1a40ae2455dc6b1588451e9633efac0fd1ffaf | addons/account/report/account_journal_common_default.py | addons/account/report/account_journal_common_default.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | Add common report header default file (Tested with central journal only) => Need to improve it and work of all journals reports (Under development) | [ADD] Add common report header default file (Tested with central journal only) => Need to improve it and work of all journals reports (Under development)
bzr revid: mra@mra-laptop-20100710071957-ddp1dmz5ve9f5qdt | Python | agpl-3.0 | dgzurita/odoo,osvalr/odoo,massot/odoo,sadleader/odoo,pplatek/odoo,slevenhagen/odoo,Drooids/odoo,dgzurita/odoo,waytai/odoo,feroda/odoo,zchking/odoo,markeTIC/OCB,steedos/odoo,ClearCorp-dev/odoo,oliverhr/odoo,hifly/OpenUpgrade,odootr/odoo,mszewczy/odoo,patmcb/odoo,Danisan/odoo-1,hmen89/odoo,Daniel-CA/odoo,sv-dev1/odoo,Cat... | ---
+++
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+# OpenERP, Open Source Management Solution
+# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
+#
+# This program is free software: you can redistribute it and/or modify
... | |
4b7171ae794cc2ba5a4e668708c7cf424419e081 | tests/test_compare.py | tests/test_compare.py | import unittest
import pandas.util.testing as pdt
import recordlinkage
import numpy as np
import pandas as pd
class TestCompare(unittest.TestCase):
def test_exact_two_series(self):
comp = recordlinkage.Compare()
s1 = pd.Series(['mary ann', 'bob1', 'angel1', 'bob', 'mary ann', 'john', np.nan])
... | Add tests for compare module | Add tests for compare module
| Python | bsd-3-clause | J535D165/recordlinkage,J535D165/recordlinkage | ---
+++
@@ -0,0 +1,33 @@
+import unittest
+
+import pandas.util.testing as pdt
+import recordlinkage
+import numpy as np
+import pandas as pd
+
+class TestCompare(unittest.TestCase):
+
+ def test_exact_two_series(self):
+
+ comp = recordlinkage.Compare()
+
+ s1 = pd.Series(['mary ann', 'bob1', 'angel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.