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 |
|---|---|---|---|---|---|---|---|---|---|---|
986c0401da5247cd5021432ba6392df9034ee21c | pombola/south_africa/migrations/0002_add_parliamentary_sessions.py | pombola/south_africa/migrations/0002_add_parliamentary_sessions.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def add_parliamentary_sessions(apps, schema_editor):
ParliamentarySession = apps.get_model('core', 'ParliamentarySession')
Organisation = apps.get_model('core', 'Organisation')
PositionTitle = apps.get_model(... | Add a data migration to add ParliamentarySession objects | ZA: Add a data migration to add ParliamentarySession objects
For Kenya, we've created instances of a `ParliamentarySession` model
to represent a term of a particular house of parliament. (The name is
a bit misleading - it should probably be `Term` instead.) This was
introduced primarily so that we could distinguish pl... | Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | ---
+++
@@ -0,0 +1,76 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+def add_parliamentary_sessions(apps, schema_editor):
+ ParliamentarySession = apps.get_model('core', 'ParliamentarySession')
+ Organisation = apps.get_model('core', 'Organisation')... | |
c0f0164612b2cfe1e3728c81956fc93ec1a50101 | python/misc/format-json.py | python/misc/format-json.py | #!/usr/bin/env python
import json
import sys
def main():
if len(sys.argv) < 3:
print('Usage: {} INFILE OUTFILE'.format(sys.argv[0]))
sys.exit()
with open(sys.argv[1], 'r') as infile, open(sys.argv[2], 'w') as outfile:
outfile.write(
json.dumps(
json.lo... | Add quick script for formatting a flat json file | Add quick script for formatting a flat json file
| Python | mit | bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile | ---
+++
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+
+import json
+import sys
+
+
+def main():
+ if len(sys.argv) < 3:
+ print('Usage: {} INFILE OUTFILE'.format(sys.argv[0]))
+ sys.exit()
+
+ with open(sys.argv[1], 'r') as infile, open(sys.argv[2], 'w') as outfile:
+ outfile.write(
+ ... | |
85728e993f6573054f8a6fa9475ea387957aae5d | tests/rules_tests/isValid_tests/__init__.py | tests/rules_tests/isValid_tests/__init__.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
""" | Add directory for Rule.is_valid tests | Add directory for Rule.is_valid tests
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -0,0 +1,8 @@
+#!/usr/bin/env python
+"""
+:Author Patrik Valkovic
+:Created 23.06.2017 16:39
+:Licence GNUv3
+Part of grammpy
+
+""" | |
439b98cc221d29e25b3b5383e90e846a5c4968ac | users/migrations/0002_auto_20140922_0843.py | users/migrations/0002_auto_20140922_0843.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def add_echonest_forward(apps, schema_editor):
"""Create echonest user."""
User = apps.get_model("users", "User")
User.objects.update_or_create(email='echonest')
def add_echonest_backward(apps, sche... | Add migration to create echonest user | Add migration to create echonest user
| Python | bsd-3-clause | FreeMusicNinja/api.freemusic.ninja | ---
+++
@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+def add_echonest_forward(apps, schema_editor):
+ """Create echonest user."""
+ User = apps.get_model("users", "User")
+ User.objects.update_or_create(email='echonest')
+... | |
de1dbde3914ceb9e684df025063c44bc3a0e65da | ceph_deploy/tests/parser/test_purgedata.py | ceph_deploy/tests/parser/test_purgedata.py | import pytest
from ceph_deploy.cli import get_parser
class TestParserPurgeData(object):
def setup(self):
self.parser = get_parser()
def test_purgedata_help(self, capsys):
with pytest.raises(SystemExit):
self.parser.parse_args('purgedata --help'.split())
out, err = capsys... | Add tests for argparse purgedata | [RM-11742] Add tests for argparse purgedata
Signed-off-by: Travis Rhoden <e5e44d6dbac12e32e01c3bb8b67940d8b42e225b@redhat.com>
| Python | mit | SUSE/ceph-deploy-to-be-deleted,zhouyuan/ceph-deploy,ceph/ceph-deploy,isyippee/ceph-deploy,Vicente-Cheng/ceph-deploy,branto1/ceph-deploy,SUSE/ceph-deploy-to-be-deleted,SUSE/ceph-deploy,ghxandsky/ceph-deploy,branto1/ceph-deploy,trhoden/ceph-deploy,codenrhoden/ceph-deploy,osynge/ceph-deploy,Vicente-Cheng/ceph-deploy,isyip... | ---
+++
@@ -0,0 +1,32 @@
+import pytest
+
+from ceph_deploy.cli import get_parser
+
+
+class TestParserPurgeData(object):
+
+ def setup(self):
+ self.parser = get_parser()
+
+ def test_purgedata_help(self, capsys):
+ with pytest.raises(SystemExit):
+ self.parser.parse_args('purgedata --... | |
6a08d2b6b5f7989b3a8aea5ac292e7baf1ed94e2 | salt/grains/philips_hue.py | salt/grains/philips_hue.py | # -*- coding: utf-8 -*-
'''
Generate baseline proxy minion grains
'''
__proxyenabled__ = ['philips_hue']
__virtualname__ = 'hue'
def __virtual__():
if 'proxy' not in __opts__:
return False
else:
return __virtualname__
def kernel():
return {'kernel': 'RTOS'}
def os():
return {'os':... | Implement static grains for the Philips HUE | Implement static grains for the Philips HUE
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+'''
+Generate baseline proxy minion grains
+'''
+__proxyenabled__ = ['philips_hue']
+
+__virtualname__ = 'hue'
+
+
+def __virtual__():
+ if 'proxy' not in __opts__:
+ return False
+ else:
+ return __virtualname__
+
+
+def kernel():
+ return {'k... | |
3d0f20cbcebc5e29a00c65ce51b2204f562a0a21 | tests/app/soc/views/models/test_sponsor.py | tests/app/soc/views/models/test_sponsor.py | #!/usr/bin/env python2.5
#
# Copyright 2010 the Melange authors.
#
# 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 applic... | Add test for the sponsor views | Add test for the sponsor views
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -0,0 +1,35 @@
+#!/usr/bin/env python2.5
+#
+# Copyright 2010 the Melange authors.
+#
+# 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/LICEN... | |
eb109a55bc1d4c3be961257d9713b23a5916f5ef | tests/monitoring/test_check_mesos_quorum.py | tests/monitoring/test_check_mesos_quorum.py | # Copyright 2015-2016 Yelp Inc.
#
# 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 writin... | Add last metastatus check test | Add last metastatus check test
| Python | apache-2.0 | somic/paasta,Yelp/paasta,Yelp/paasta,somic/paasta | ---
+++
@@ -0,0 +1,47 @@
+# Copyright 2015-2016 Yelp Inc.
+#
+# 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 a... | |
c9137bdaf551d0e1203120a9c00af60541e3597f | scikits/talkbox/lpc/lpc.py | scikits/talkbox/lpc/lpc.py | #! /usr/bin/env python
# Last Change: Sun Sep 14 03:00 PM 2008 J
import numpy as np
from c_lpc import levinson as c_levinson
def levinson(r, order, axis = -1):
"""Levinson-Durbin recursion, to efficiently solve symmetric linear systems
with toeplitz structure.
Arguments
---------
r : array-... | Add python interface around C implementation of levinson. | Add python interface around C implementation of levinson.
| Python | mit | cournape/talkbox,cournape/talkbox | ---
+++
@@ -0,0 +1,57 @@
+#! /usr/bin/env python
+
+# Last Change: Sun Sep 14 03:00 PM 2008 J
+
+import numpy as np
+
+from c_lpc import levinson as c_levinson
+
+def levinson(r, order, axis = -1):
+ """Levinson-Durbin recursion, to efficiently solve symmetric linear systems
+ with toeplitz structure.
+
+ Ar... | |
0cb717548ee0f9086226c842dc4a5f16862f3f8e | apps/offlineevents/migrations/0002_require_date.py | apps/offlineevents/migrations/0002_require_date.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('meinberlin_offlineevents', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='... | Add offlineevent migration to require dates | Add offlineevent migration to require dates
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import datetime
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('meinberlin_offlineevents', '0001_initial'),
+ ]
+
+ operations = [
+ migra... | |
b2791d86aadde7fd0edb1d9e61ceece0cd47ba14 | scripts/backup-database.py | scripts/backup-database.py | #!/usr/bin/python
# This is a small helper script to back up a CATMAID
# database.
# For example, I'm calling this script from cron with the following
# crontab entry, which will cause a backup to happen every 8 hours at
# 20 past the hour:
#
# 20 0-23/8 * * * CATMAID_CONFIGURATION=$HOME/.catmaid-db.whatever $HOME/ca... | Add a script for easy backups of CATMAID's database | Add a script for easy backups of CATMAID's database
| Python | agpl-3.0 | htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID | ---
+++
@@ -0,0 +1,54 @@
+#!/usr/bin/python
+
+# This is a small helper script to back up a CATMAID
+# database.
+
+# For example, I'm calling this script from cron with the following
+# crontab entry, which will cause a backup to happen every 8 hours at
+# 20 past the hour:
+#
+# 20 0-23/8 * * * CATMAID_CONFIGURATIO... | |
40212c8cea43e5adfc2ba30f18182480dea481b2 | txircd/modules/core/channel_defaultmodes.py | txircd/modules/core/channel_defaultmodes.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class DefaultModes(ModuleData):
implements(IPlugin, IModuleData)
name = "DefaultModes"
core = True
def hookIRCd(self, ircd):
... | Support setting default modes in channels | Support setting default modes in channels
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | ---
+++
@@ -0,0 +1,35 @@
+from twisted.plugin import IPlugin
+from txircd.module_interface import IModuleData, ModuleData
+from txircd.utils import ModeType
+from zope.interface import implements
+
+class DefaultModes(ModuleData):
+ implements(IPlugin, IModuleData)
+
+ name = "DefaultModes"
+ core = True... | |
11717529ab66290464e34925b08a1b792ac00cd7 | cms/migrations/0002_auto_20190507_1532.py | cms/migrations/0002_auto_20190507_1532.py | # Generated by Django 2.1.8 on 2019-05-07 13:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='contentpage',
options={'verbose_name': 'Eine Sei... | Add outstanding migrations from wagtail | Add outstanding migrations from wagtail
| Python | mit | meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent | ---
+++
@@ -0,0 +1,25 @@
+# Generated by Django 2.1.8 on 2019-05-07 13:32
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('cms', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+ name='contentpage',
+ ... | |
81c307848af0bf1a32253d67a1bbc279990e917b | myuw/management/commands/flush_memcache.py | myuw/management/commands/flush_memcache.py | import logging
from rc_django.cache_implementation.memcache import MemcachedCache
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
client = MyUWMemcachedCache().client
logger.info("Stats before flush: {}".format(client.stats()))
logger.... | Add a command to flush memcache | Add a command to flush memcache
| Python | apache-2.0 | uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw,uw-it-aca/myuw | ---
+++
@@ -0,0 +1,13 @@
+import logging
+from rc_django.cache_implementation.memcache import MemcachedCache
+
+
+logger = logging.getLogger(__name__)
+
+class Command(BaseCommand):
+
+ def handle(self, *args, **options):
+ client = MyUWMemcachedCache().client
+ logger.info("Stats before flush: {}".f... | |
64d74b5f059323fc81d5d4938d1ede8dc34c7c9a | sujmarkov/from_file.py | sujmarkov/from_file.py | """Read lines from a file, feed them into the markov generator, and then
generate a few lines.
Usage:
python from_file.py <input_filename> <num_lines_to_generate>
"""
import sys
import sujmarkov
def extract_sentences(input_file):
# Each line is a sentence.
#
for raw_line in input_file:
line = ... | Add a util to generate sentences from a file | Add a util to generate sentences from a file
| Python | bsd-2-clause | sujaymansingh/sujmarkov | ---
+++
@@ -0,0 +1,43 @@
+"""Read lines from a file, feed them into the markov generator, and then
+generate a few lines.
+
+Usage:
+ python from_file.py <input_filename> <num_lines_to_generate>
+"""
+import sys
+
+import sujmarkov
+
+
+def extract_sentences(input_file):
+ # Each line is a sentence.
+ #
+ f... | |
8085c063ffcdfa60e24f17a8cd961d25f116a5d5 | tests/test_lightgbm.py | tests/test_lightgbm.py | import unittest
import lightgbm as lgb
from sklearn.datasets import load_iris
class TestLightgbm(unittest.TestCase):
# Based on the "simple_example" from their documentation:
# https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/simple_example.py
def test_simple(self):
# Load ... | Add test for the lightgbm package | Add test for the lightgbm package
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python | ---
+++
@@ -0,0 +1,33 @@
+import unittest
+
+import lightgbm as lgb
+
+from sklearn.datasets import load_iris
+
+class TestLightgbm(unittest.TestCase):
+ # Based on the "simple_example" from their documentation:
+ # https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/simple_example.py
+ d... | |
270724a7d6a6de7de092cab9c0bb8ac98e66b898 | unity_setup.py | unity_setup.py | #!/usr/bin/env python
import os
import os.path
import subprocess
from subprocess import Popen, PIPE
def _set_value(plist_path, key, value):
subprocess.call(['plutil', '-replace', key, '-string', value, plist_path])
def _get_jdk_home():
proc = Popen(['/usr/libexec/java_home'], stdout=PIPE)
return proc.com... | Add script for configuring unity settings | Add script for configuring unity settings
| Python | mit | akhosravian/laptop,akhosravian/laptop | ---
+++
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+import os
+import os.path
+import subprocess
+
+from subprocess import Popen, PIPE
+
+def _set_value(plist_path, key, value):
+ subprocess.call(['plutil', '-replace', key, '-string', value, plist_path])
+
+def _get_jdk_home():
+ proc = Popen(['/usr/libexec/java_h... | |
83dfa6581eec1b9d32d519592c4212e6195998a3 | taskflow/persistence/backends/sqlalchemy/alembic/versions/40fc8c914bd2_fix_atomdetails_failure_size.py | taskflow/persistence/backends/sqlalchemy/alembic/versions/40fc8c914bd2_fix_atomdetails_failure_size.py | # 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, software
# d... | Fix atomdetails failure column size | Fix atomdetails failure column size
failure and revert_failure fields in atomdetails is defined as a JSON type,
but its data type is 'text' in mysql, which is limited to 64kbytes.
JSON data type should have the same size as a LONGTEXT.
Closes-Bug: #1959243
Change-Id: I65b6a6d896d3e8aad871dc19b0f8d0eddf48bdd6
| Python | apache-2.0 | openstack/taskflow,openstack/taskflow | ---
+++
@@ -0,0 +1,36 @@
+# 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 agr... | |
fd747b412b7ba4e9b685ef6a9043272cdb3e41ab | 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', )
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'deb... | # 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... | Add my own public IP address to INTERNAL_IPS for `obi` testing. | Add my own public IP address to INTERNAL_IPS for `obi` testing. | Python | agpl-3.0 | 1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow | ---
+++
@@ -1,8 +1,14 @@
# Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
+
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
-INTERNAL_IPS = ('127.0.0.1', )
+
+INTERNAL_IPS = (
+ '127.0.0.1',
+ # leto.licorn.org
+ '82.236.133.193',
+)
DEBUG_TOOLBAR_PANELS = (
... |
574cd304e39b74ee4dbd7a7902d0e941d899351f | tests/lbrynet_test_bot.py | tests/lbrynet_test_bot.py | import xmlrpclib
import json
from datetime import datetime
from time import sleep
from slackclient import SlackClient
def get_conf():
f = open('testbot.conf', 'r')
token = f.readline().replace('\n', '')
channel = f.readline().replace('\n', '')
f.close()
return token, channel
def test_lbrynet(lbry,... | Test ability to download from lbrynet | Test ability to download from lbrynet
This tries to download a small image with a five minute timeout. After this, the bot waits ten minutes and tries again. Any failures get posted to slack. | Python | mit | lbryio/lbry,DaveA50/lbry,zestyr/lbry,lbryio/lbry,DaveA50/lbry,lbryio/lbry,zestyr/lbry,zestyr/lbry | ---
+++
@@ -0,0 +1,60 @@
+import xmlrpclib
+import json
+from datetime import datetime
+from time import sleep
+from slackclient import SlackClient
+
+def get_conf():
+ f = open('testbot.conf', 'r')
+ token = f.readline().replace('\n', '')
+ channel = f.readline().replace('\n', '')
+ f.close()
+ return... | |
9df652a5997404452e9598640a4151035fd409cf | tests/test_cme_agriculture_calendar.py | tests/test_cme_agriculture_calendar.py | import pandas as pd
import pytz
from pandas_market_calendars.exchange_calendar_cme_agriculture import CMEAgricultureExchangeCalendar
def test_time_zone():
assert CMEAgricultureExchangeCalendar().tz == pytz.timezone('America/Chicago')
assert CMEAgricultureExchangeCalendar().name == 'CME_Agriculture'
def tes... | Add test stub for agriculture | Add test stub for agriculture
| Python | mit | rsheftel/pandas_market_calendars,rsheftel/pandas_market_calendars | ---
+++
@@ -0,0 +1,48 @@
+import pandas as pd
+import pytz
+
+from pandas_market_calendars.exchange_calendar_cme_agriculture import CMEAgricultureExchangeCalendar
+
+
+def test_time_zone():
+ assert CMEAgricultureExchangeCalendar().tz == pytz.timezone('America/Chicago')
+ assert CMEAgricultureExchangeCalendar()... | |
e5ceeb4b17525acb730e7440bc5c56c79eb7c32d | thread_safe_print_test.py | thread_safe_print_test.py | import thread_safe_print
from six.moves import queue
import thread_pool
import io_expectation as expect
import sys
import unittest
class TestThreadSafePrint(unittest.TestCase):
def _thread1(self, thread1_turn, thread2_turn):
thread1_turn.get()
sys.stdout.write('Thread 1 starts, ')
thread2_turn.put(True... | Add a unit-test for thread_safe_print.py. | Add a unit-test for thread_safe_print.py.
| Python | mit | graveljp/smugcli | ---
+++
@@ -0,0 +1,51 @@
+import thread_safe_print
+
+from six.moves import queue
+import thread_pool
+import io_expectation as expect
+import sys
+import unittest
+
+class TestThreadSafePrint(unittest.TestCase):
+
+ def _thread1(self, thread1_turn, thread2_turn):
+ thread1_turn.get()
+ sys.stdout.write('Threa... | |
abac33bc2c8713f5187529e13557ea6b58472079 | Problems/shapeAreaCF.py | Problems/shapeAreaCF.py | def shapeArea(n):
if n < 1 or n > 10**4:
raise ValueError
if n == 1:
return 1
else:
innerArea = shapeArea(n - 1)
return innerArea + (n - 1) * 4
def main():
tests = [-1, 10**5, 1, 2, 3, 4]
results = [False, False, 1, 5, 13, 25]
for i, t in enumerate(tests):
... | Add code fight shape area solution | Add code fight shape area solution
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,27 @@
+def shapeArea(n):
+ if n < 1 or n > 10**4:
+ raise ValueError
+ if n == 1:
+ return 1
+ else:
+ innerArea = shapeArea(n - 1)
+ return innerArea + (n - 1) * 4
+
+
+def main():
+ tests = [-1, 10**5, 1, 2, 3, 4]
+ results = [False, False, 1, 5, 13, 25]... | |
1bb3a5276e46363cbf2ad88a5f97868f65a99b30 | tutorials/dataframe/tdf003_profiles.py | tutorials/dataframe/tdf003_profiles.py | ## \file
## \ingroup tutorial_tdataframe
## \notebook -nodraw
## This tutorial illustrates how to use TProfiles in combination with the
## TDataFrame. See the documentation of TProfile and TProfile2D to better
## understand the analogy of this code with the example one.
##
## \macro_code
##
## \date February 2017
## \a... | Add a profiles tutorial in Python | [TDF] Add a profiles tutorial in Python
| Python | lgpl-2.1 | olifre/root,karies/root,olifre/root,karies/root,zzxuanyuan/root,olifre/root,karies/root,karies/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,karies/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,karies/root,zzxuanyuan/root,olifre/root,karies/root,olifre/root,karie... | ---
+++
@@ -0,0 +1,49 @@
+## \file
+## \ingroup tutorial_tdataframe
+## \notebook -nodraw
+## This tutorial illustrates how to use TProfiles in combination with the
+## TDataFrame. See the documentation of TProfile and TProfile2D to better
+## understand the analogy of this code with the example one.
+##
+## \macro_c... | |
adc17c25b6602818defec29c10c862a73a2a23bf | python/src/singleNumber/testSingleNumber.py | python/src/singleNumber/testSingleNumber.py | import unittest
from singleNumber import Solution
class TestSingleNumber(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def testArrayOfSingleIntReturnsOnlyValue(self):
A = [1]
self.assertEqual(self.solution.singleNumber(A), 1)
def testArrayOfTwoTypesOfNumbersRetur... | Add 3 test cases for singleNumber problem. | Add 3 test cases for singleNumber problem.
| Python | mit | TheGhostHuCodes/leetCode | ---
+++
@@ -0,0 +1,21 @@
+import unittest
+from singleNumber import Solution
+
+class TestSingleNumber(unittest.TestCase):
+ def setUp(self):
+ self.solution = Solution()
+
+ def testArrayOfSingleIntReturnsOnlyValue(self):
+ A = [1]
+ self.assertEqual(self.solution.singleNumber(A), 1)
+
+ ... | |
f9537e9d38d50d3fbe95132629577d07f961b1c7 | scikits/image/io/_plugins/test_freeimage.py | scikits/image/io/_plugins/test_freeimage.py | import os
import scikits.image as si
import scikits.image.io as sio
sio.use_plugin('matplotlib', 'imshow')
sio.use_plugin('freeimage', 'imread')
img = sio.imread(os.path.join(si.data_dir, 'color.png'))
sio.imshow(img)
sio.show()
| Add a free standing test for freeimage. | ENH: Add a free standing test for freeimage.
| Python | bsd-3-clause | SamHames/scikit-image,Britefury/scikit-image,warmspringwinds/scikit-image,newville/scikit-image,ofgulban/scikit-image,emmanuelle/scikits.image,pratapvardhan/scikit-image,rjeli/scikit-image,robintw/scikit-image,robintw/scikit-image,Midafi/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,michaelay... | ---
+++
@@ -0,0 +1,13 @@
+import os
+
+import scikits.image as si
+import scikits.image.io as sio
+
+sio.use_plugin('matplotlib', 'imshow')
+sio.use_plugin('freeimage', 'imread')
+
+img = sio.imread(os.path.join(si.data_dir, 'color.png'))
+
+sio.imshow(img)
+sio.show()
+ | |
feb2dd41d4a7368f2a056375b9e9a867a3d5b42e | vsub/settings/gunicorn.py | vsub/settings/gunicorn.py | """gunicorn WSGI server configuration."""
# Based on https://github.com/rdegges/django-skel/blob/master/gunicorn.py.ini.
import os
from multiprocessing import cpu_count
def max_workers():
return cpu_count()
bind = '0.0.0.0:' + os.environ.get('PORT', '8000')
max_requests = 1000
worker_class = 'gevent'
workers =... | Add a configuration file for Gunicorn. | Add a configuration file for Gunicorn.
| Python | mit | PrecisionMojo/pm-www,PrecisionMojo/pm-www | ---
+++
@@ -0,0 +1,15 @@
+"""gunicorn WSGI server configuration."""
+
+# Based on https://github.com/rdegges/django-skel/blob/master/gunicorn.py.ini.
+
+import os
+from multiprocessing import cpu_count
+
+
+def max_workers():
+ return cpu_count()
+
+bind = '0.0.0.0:' + os.environ.get('PORT', '8000')
+max_requests ... | |
26b9157f2c8c7eb490b5fa712908c70dcf51f6d0 | cli/commands/cmd_routes.py | cli/commands/cmd_routes.py | import logging
import click
from catwatch.app import create_app
app = create_app()
@click.command()
def cli():
""" List all of the available routes. """
output = {}
for rule in app.url_map.iter_rules():
route = {
'path': rule.rule,
'methods': '({0})'.format(', '.join(rul... | Add CLI command 'run routes' to list all of the routes | Add CLI command 'run routes' to list all of the routes
| Python | mit | nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask | ---
+++
@@ -0,0 +1,27 @@
+import logging
+import click
+
+from catwatch.app import create_app
+
+app = create_app()
+
+
+@click.command()
+def cli():
+ """ List all of the available routes. """
+ output = {}
+
+ for rule in app.url_map.iter_rules():
+ route = {
+ 'path': rule.rule,
+ ... | |
94d99ba174ba38f00d4198b8d45e9471bf9a32e5 | apps/profile/management/commands/startup.py | apps/profile/management/commands/startup.py | #add homepage user from settings
#add popular user
from settings import HOMEPAGE_USERNAME
from apps.profile.models import create_profile
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
instance ... | Add management command to create homepage user | Add management command to create homepage user
| Python | mit | samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur,samuelclay/NewsBlur | ---
+++
@@ -0,0 +1,14 @@
+#add homepage user from settings
+#add popular user
+from settings import HOMEPAGE_USERNAME
+from apps.profile.models import create_profile
+from django.contrib.auth.models import User
+from django.core.management.base import BaseCommand
+
+class Command(BaseCommand):
+
+ def handle(self,... | |
9b2ef4cf70e9895b96ca2d0213dc0d08c0703831 | comics/comics/hjalmarbt.py | comics/comics/hjalmarbt.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Hjalmar (bt.no)"
language = "no"
url = "https://www.bt.no/kultur/tegneserier/"
rights = "Nils Axle Kanten"
class Crawler(CrawlerBase):
history_... | Add crawler for "Hjalmar" from bt.no | Add crawler for "Hjalmar" from bt.no
| Python | agpl-3.0 | jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics | ---
+++
@@ -0,0 +1,20 @@
+from comics.aggregator.crawler import CrawlerBase, CrawlerImage
+from comics.core.comic_data import ComicDataBase
+
+
+class ComicData(ComicDataBase):
+ name = "Hjalmar (bt.no)"
+ language = "no"
+ url = "https://www.bt.no/kultur/tegneserier/"
+ rights = "Nils Axle Kanten"
+
+
+c... | |
57f2fde877f00a726d204734e01b86805ae3ed81 | pombola/core/management/commands/core_render_template.py | pombola/core/management/commands/core_render_template.py | from django.core.management.base import LabelCommand
from django.template.loader import render_to_string
from django.template import RequestContext
from django.http import HttpRequest
class Command(LabelCommand):
help = 'Render a template to STDOUT'
args = '<template path>'
def handle_label(self, template... | Create a management command to output a given template | Create a management command to output a given template
| Python | agpl-3.0 | mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola,patricmutwiri/pombola,geoffkilpin/pombola,ken-muturi/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/po... | ---
+++
@@ -0,0 +1,21 @@
+from django.core.management.base import LabelCommand
+from django.template.loader import render_to_string
+from django.template import RequestContext
+from django.http import HttpRequest
+
+class Command(LabelCommand):
+ help = 'Render a template to STDOUT'
+ args = '<template path>'
+... | |
6c56f9bc68950c4fa6ab2fe4bbdc5700654eb604 | misc/utils/LSL_Tests/RecieveGaitStream.py | misc/utils/LSL_Tests/RecieveGaitStream.py | """Example program to show how to read a marker time series from LSL."""
from pylsl import StreamInlet, resolve_stream
import sys
import os
from collections import deque
os.system('cls' if os.name == 'nt' else 'clear')
MAX_ELEMENTS_IN_QUEUE = 5
# first resolve an EEG stream on the lab network
print("looking for an ... | Add an test script for recieving a custom Gait stream | Add an test script for recieving a custom Gait stream
| Python | mit | xfleckx/BeMoBI,xfleckx/BeMoBI | ---
+++
@@ -0,0 +1,40 @@
+"""Example program to show how to read a marker time series from LSL."""
+
+from pylsl import StreamInlet, resolve_stream
+import sys
+import os
+from collections import deque
+
+os.system('cls' if os.name == 'nt' else 'clear')
+
+MAX_ELEMENTS_IN_QUEUE = 5
+
+# first resolve an EEG stream on... | |
c44db3982db1a0ea163bdb29589c8ac546c7038c | test/read_output_test.py | test/read_output_test.py | '''Unit tests for Aronnax'''
from contextlib import contextmanager
import os.path as p
import re
import numpy as np
from scipy.io import FortranFile
import aronnax as aro
from aronnax.utils import working_directory
import pytest
import glob
self_path = p.dirname(p.abspath(__file__))
def test_open_mfdataarray():
... | Test for new function for reading output | Test for new function for reading output
| Python | mit | edoddridge/MIM,edoddridge/aronnax | ---
+++
@@ -0,0 +1,50 @@
+'''Unit tests for Aronnax'''
+
+from contextlib import contextmanager
+import os.path as p
+import re
+
+import numpy as np
+from scipy.io import FortranFile
+
+import aronnax as aro
+from aronnax.utils import working_directory
+
+import pytest
+import glob
+
+self_path = p.dirname(p.abspath... | |
06e1357ac6b14a26dda72a6080f6228226e8ed91 | rubix.py | rubix.py | #!/usr/bin/python
import re
import argparse
import time
# Let's time the execution for display in -v
start_time = time.time()
# String to hold regex
regex = ''
# Create a storage area for sorting words by size
sortedDict = {}
# For comparison, let's keep record of the sorted string of characters that was input
sor... | Change file name. Add timing and verbose flag. Still using letters more times than possible. | Change file name. Add timing and verbose flag. Still using letters more times than possible.
| Python | mit | chaseconey/rubix | ---
+++
@@ -0,0 +1,61 @@
+#!/usr/bin/python
+
+import re
+import argparse
+import time
+
+# Let's time the execution for display in -v
+start_time = time.time()
+
+# String to hold regex
+regex = ''
+
+# Create a storage area for sorting words by size
+sortedDict = {}
+
+# For comparison, let's keep record of the sor... | |
45bea73cecaee8f18fc7519066dc8ec51b53f13b | tests/functional/test_api_v1.py | tests/functional/test_api_v1.py | import pytest
from decimal import Decimal
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
from wightinvoices.invoice import factories
pytestmark = pytest.mark.django_db
def test_get_invoice():
test_client = APIClient()
owner = factories.User.create(password="clear$abc$... | Test to get the invoice. | Test to get the invoice.
| Python | mit | linovia/wight-invoices | ---
+++
@@ -0,0 +1,35 @@
+import pytest
+from decimal import Decimal
+from django.core.urlresolvers import reverse
+from rest_framework.test import APIClient
+from wightinvoices.invoice import factories
+
+
+pytestmark = pytest.mark.django_db
+
+
+def test_get_invoice():
+ test_client = APIClient()
+ owner = fa... | |
5adaa6ec7b1c379d0fcbf7b488cc48e183739f0e | timed/tests/test_serializers.py | timed/tests/test_serializers.py | from datetime import timedelta
import pytest
from rest_framework_json_api.serializers import DurationField, IntegerField
from timed.serializers import PkDictSerializer
class MyPkDictSerializer(PkDictSerializer):
test_duration = DurationField()
test_nr = IntegerField()
class Meta:
pk_key = 'test... | Add unit test for pk dict serializer | Add unit test for pk dict serializer
| Python | agpl-3.0 | adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend | ---
+++
@@ -0,0 +1,56 @@
+from datetime import timedelta
+
+import pytest
+from rest_framework_json_api.serializers import DurationField, IntegerField
+
+from timed.serializers import PkDictSerializer
+
+
+class MyPkDictSerializer(PkDictSerializer):
+ test_duration = DurationField()
+ test_nr = IntegerField()
+... | |
717b3ec17b76d347894591f813d45e5e56bba0b2 | staging_settings.py | staging_settings.py | # To activate these settings as the current local_settings, create a symlink
# called local_settings.py pointing to this file.
from secret_settings import STAGING_DB_PASSWORD
import os
DEBUG = False
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT),
... | Add settings override for staging environment | Add settings override for staging environment
| Python | mit | amarandon/smeuhsocial,fgirault/smeuhsocial,amarandon/smeuhsocial,amarandon/smeuhsocial,fgirault/smeuhsocial,fgirault/smeuhsocial | ---
+++
@@ -0,0 +1,35 @@
+# To activate these settings as the current local_settings, create a symlink
+# called local_settings.py pointing to this file.
+
+from secret_settings import STAGING_DB_PASSWORD
+
+import os
+
+DEBUG = False
+
+PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
+MEDIA_ROOT = os.path.... | |
be4a40ce2e1977aa349e02cf639cd663ec32b8dd | autopush/tests/test_protocol.py | autopush/tests/test_protocol.py | from mock import Mock
from nose.tools import eq_
from twisted.trial import unittest
from twisted.web.client import Response
from autopush.protocol import IgnoreBody
class ProtocolTestCase(unittest.TestCase):
def test_ignore(self):
mock_reason = Mock()
mock_reason.check.return_value = True
... | Add 100% unit test for IgnorBody protocol. | Add 100% unit test for IgnorBody protocol.
| Python | mpl-2.0 | mozilla-services/autopush,mozilla-services/autopush | ---
+++
@@ -0,0 +1,44 @@
+from mock import Mock
+from nose.tools import eq_
+from twisted.trial import unittest
+from twisted.web.client import Response
+
+from autopush.protocol import IgnoreBody
+
+
+class ProtocolTestCase(unittest.TestCase):
+ def test_ignore(self):
+ mock_reason = Mock()
+ mock_r... | |
be0639d7f7904c9e8c54883f51a36ad834f1a635 | thinc/tests/unit/test_linear.py | thinc/tests/unit/test_linear.py | # coding: utf8
from __future__ import unicode_literals
import numpy
from ...linear.linear import LinearModel
def test_init():
model = LinearModel(3)
keys = numpy.ones((5,), dtype="uint64")
values = numpy.ones((5,), dtype="f")
lengths = numpy.zeros((2,), dtype="long")
lengths[0] = 3
lengths[1... | Add basic test for LinearModel | Add basic test for LinearModel
| Python | mit | spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc | ---
+++
@@ -0,0 +1,19 @@
+# coding: utf8
+from __future__ import unicode_literals
+
+import numpy
+
+from ...linear.linear import LinearModel
+
+
+def test_init():
+ model = LinearModel(3)
+ keys = numpy.ones((5,), dtype="uint64")
+ values = numpy.ones((5,), dtype="f")
+ lengths = numpy.zeros((2,), dtype=... | |
82529522f6f281c5c647cbb8a79fcf5830bf6911 | setup.py | setup.py | import multiprocessing # noqa # stop tests breaking tox
from setuptools import setup
import tvrenamr
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online databases',
long_description=open('README.rst').read() + '\n\n' +
open('CHANGELOG.rst'... | import multiprocessing # noqa # stop tests breaking tox
from setuptools import find_packages, setup
import tvrenamr
setup(
name=tvrenamr.__title__,
version=tvrenamr.__version__,
description='Rename tv show files using online databases',
long_description=open('README.rst').read() + '\n\n' +
open(... | Use find_packages to deal with vendoring | Use find_packages to deal with vendoring
| Python | mit | ghickman/tvrenamr,wintersandroid/tvrenamr | ---
+++
@@ -1,5 +1,5 @@
import multiprocessing # noqa # stop tests breaking tox
-from setuptools import setup
+from setuptools import find_packages, setup
import tvrenamr
@@ -14,7 +14,7 @@
author_email='george@ghickman.co.uk',
url='http://tvrenamr.info',
license='MIT',
- packages=['tvrenamr']... |
972b6ad21509e313d7cfd901b12020135e202c51 | logos/migrations/0004_auto_20160518_2120.py | logos/migrations/0004_auto_20160518_2120.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('logos', '0003_auto_20160217_2158'),
]
operations = [
migrations.DeleteModel(
name='CapturedUrls',
),
... | Add some old models deleted in logos/ migration | Add some old models deleted in logos/ migration
| Python | apache-2.0 | kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2 | ---
+++
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('logos', '0003_auto_20160217_2158'),
+ ]
+
+ operations = [
+ migrations.DeleteModel(
+ ... | |
efad39e0932b60000e89e486fc16239833ea4d98 | copy/opt/core/bin/core-ns-download.py | copy/opt/core/bin/core-ns-download.py | #!/usr/bin/env python
# core-ns-download
# Check and download zip archive with zone information but only
# if required.
import requests
import os, zipfile
import argparse
from io import BytesIO
import json
# Parse arguments
parser = argparse.ArgumentParser(description='Download multible zip archives with zone informa... | Add our awesome core-ns download script | Add our awesome core-ns download script
| Python | mit | skylime/mi-core-ns,skylime/mi-core-ns | ---
+++
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+# core-ns-download
+# Check and download zip archive with zone information but only
+# if required.
+
+import requests
+import os, zipfile
+import argparse
+from io import BytesIO
+import json
+
+# Parse arguments
+parser = argparse.ArgumentParser(description='Download... | |
d3fd0d4f2220cee440f0af1a9ed3efd5cfd9444c | sale_exception_nostock_by_line/__init__.py | sale_exception_nostock_by_line/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# ... | Correct author (../trunk-generic/ rev 29.1.22) | [FIX] Correct author
(../trunk-generic/ rev 29.1.22)
| Python | agpl-3.0 | jabibi/sale-workflow,anas-taji/sale-workflow,brain-tec/sale-workflow,alexsandrohaag/sale-workflow,richard-willowit/sale-workflow,kittiu/sale-workflow,BT-fgarbely/sale-workflow,jjscarafia/sale-workflow,Endika/sale-workflow,BT-jmichaud/sale-workflow,luistorresm/sale-workflow,fevxie/sale-workflow,adhoc-dev/sale-workflow,E... | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
##############################################################################
#
-# Author: Guewen Baconnier
+# Author: Joel Grand-Guillaume
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify |
0e5a6019f88093691724532221fd1f4b24ad84d6 | app.py | app.py | def app(env, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World"]
if __name__ == '__main__':
try:
from wsgiref.simple_server import make_server
httpd = make_server('', 8080, app)
print('Serving on port 8080...')
httpd.serve_foreve... | Return 'Hello World' by wsgiref | Return 'Hello World' by wsgiref
| Python | mit | c-bata/kobin,kobinpy/kobin,kobinpy/kobin,c-bata/kobin | ---
+++
@@ -0,0 +1,12 @@
+def app(env, start_response):
+ start_response('200 OK', [('Content-Type','text/html')])
+ return [b"Hello World"]
+
+if __name__ == '__main__':
+ try:
+ from wsgiref.simple_server import make_server
+ httpd = make_server('', 8080, app)
+ print('Serving on port ... | |
6b940e8d0f4ae4deac7a71b133e0c9e863f324d7 | stars/middleware.py | stars/middleware.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class StarFilterMiddleware(object):
"""
Stores star filter data in user's session.
"""
def process_request(self, request):
assert hasattr(request, 'session'), "StarFilterMiddleware requires session middleware to be installed."
... | Store limiting magnitude in session, if requested from filter. | Store limiting magnitude in session, if requested from filter.
| Python | mit | zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net | ---
+++
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+
+class StarFilterMiddleware(object):
+ """
+ Stores star filter data in user's session.
+ """
+ def process_request(self, request):
+ assert hasattr(request, 'session'), "StarFilterMiddleware requires ses... | |
010f1b9526c666986e2557f6b693efe5a194d30f | scrapi/harvesters/lshtm.py | scrapi/harvesters/lshtm.py | '''
Harvester for the LSHTM Research Online for the SHARE project
Example API call: http://researchonline.lshtm.ac.uk/cgi/oai2?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class LshtmHarvester(OAIHarvester):
short_name = 'lshtm'
long... | Add harvester for the London School of Hygene and Tropical Medicine | Add harvester for the London School of Hygene and Tropical Medicine
Closes [#SHARE-123]
| Python | apache-2.0 | CenterForOpenScience/scrapi,erinspace/scrapi,erinspace/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi | ---
+++
@@ -0,0 +1,18 @@
+'''
+Harvester for the LSHTM Research Online for the SHARE project
+
+Example API call: http://researchonline.lshtm.ac.uk/cgi/oai2?verb=ListRecords&metadataPrefix=oai_dc
+'''
+from __future__ import unicode_literals
+
+from scrapi.base import OAIHarvester
+
+
+class LshtmHarvester(OAIHarvest... | |
317aeeec2279f68daf70d0b7bf8e14ee1859f599 | examples/remote_cluster.py | examples/remote_cluster.py | # Copyright 2016 The Kubernetes Authors.
#
# 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 ... | Add example for remote cluster without kube client on server | Add example for remote cluster without kube client on server
| Python | apache-2.0 | kubernetes-client/python,kubernetes-client/python | ---
+++
@@ -0,0 +1,58 @@
+# Copyright 2016 The Kubernetes Authors.
+#
+# 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 requ... | |
163434cb3d1dfd9774def6de9c3b005f9130504b | tests/cupy_tests/random_tests/test_random.py | tests/cupy_tests/random_tests/test_random.py | import unittest
from cupy import random
from cupy import testing
class TestResetSeed(unittest.TestCase):
@testing.for_float_dtypes(no_float16=True)
def test_reset_seed(self, dtype):
rs = random.get_random_state()
rs.seed(0)
l1 = rs.rand(10, dtype=dtype)
rs = random.get_rando... | Write functional test for seed | Write functional test for seed
| Python | mit | hvy/chainer,wkentaro/chainer,benob/chainer,jnishi/chainer,AlpacaDB/chainer,ronekko/chainer,wkentaro/chainer,cupy/cupy,keisuke-umezawa/chainer,kikusu/chainer,wkentaro/chainer,niboshi/chainer,muupan/chainer,jnishi/chainer,cupy/cupy,jnishi/chainer,sinhrks/chainer,wkentaro/chainer,kashif/chainer,ktnyt/chainer,chainer/chain... | ---
+++
@@ -0,0 +1,19 @@
+import unittest
+
+from cupy import random
+from cupy import testing
+
+
+class TestResetSeed(unittest.TestCase):
+
+ @testing.for_float_dtypes(no_float16=True)
+ def test_reset_seed(self, dtype):
+ rs = random.get_random_state()
+ rs.seed(0)
+ l1 = rs.rand(10, dty... | |
4e99176621f81b9f115613fe87f8036d07a80ddc | encryptit/tests/packets/test_generic_packet_body.py | encryptit/tests/packets/test_generic_packet_body.py | from io import BytesIO
from nose.tools import assert_equal, assert_raises
from encryptit.packets import GenericPacketBody
from encryptit.exceptions import MalformedPacketError
BODY = bytearray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
TESTS = [
(0, 10, bytearray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])),
(1, 9, bytearray([1, ... | Add (failing!) tests for GenericPacketBody | Add (failing!) tests for GenericPacketBody
See #40
| Python | agpl-3.0 | paulfurley/encryptit,paulfurley/encryptit | ---
+++
@@ -0,0 +1,55 @@
+from io import BytesIO
+from nose.tools import assert_equal, assert_raises
+
+from encryptit.packets import GenericPacketBody
+from encryptit.exceptions import MalformedPacketError
+
+
+BODY = bytearray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+
+TESTS = [
+ (0, 10, bytearray([0, 1, 2, 3, 4, 5, 6,... | |
5f8f44363cfa133b959e6aa3a4e284362eb53aa8 | plot_s_curve.py | plot_s_curve.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import sys
x = []
y = []
infile = open(sys.argv[1])
for line in infile:
data = line.replace('\n','').split()
print(data)
x.append(float(data[0]))
y.append(float(data[1]))
figManager = plt.get_current_fig_manager()
figMan... | Add python script to plot the S curve | Add python script to plot the S curve
Rudimentary version to help debugging
| Python | mit | M2-AAIS/BAD | ---
+++
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import matplotlib.pyplot as plt
+import sys
+
+x = []
+
+y = []
+
+infile = open(sys.argv[1])
+
+for line in infile:
+ data = line.replace('\n','').split()
+ print(data)
+ x.append(float(data[0]))
+ y.append(float(data[1]))
+
+fig... | |
94212e2b02e7e585e815bb659662253dceee9d55 | tensorflow/contrib/autograph/core/annos.py | tensorflow/contrib/autograph/core/annos.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | Add a set of annotations specific to AutoGraph. | Add a set of annotations specific to AutoGraph.
PiperOrigin-RevId: 202972265
| Python | apache-2.0 | davidzchen/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,Bismarrck/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gunan/tensorflow,karllessard/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,aldian/tensorflow,jbedorf/tensorflow,jart/tensorflow,jart/tensorflow,ghchin... | ---
+++
@@ -0,0 +1,39 @@
+# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
+#
+# 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-... | |
6315a38c01b001acd36ddd0a528138903e19ff80 | blox/compile.py | blox/compile.py | '''blox/compile.py
Creates an optimized programattically generated template from an html file
Copyright (C) 2015 Timothy Edmund Crosley
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without r... | Add initial file for template compilation | Add initial file for template compilation
| Python | mit | timothycrosley/blox,timothycrosley/blox,timothycrosley/blox | ---
+++
@@ -0,0 +1,48 @@
+'''blox/compile.py
+
+Creates an optimized programattically generated template from an html file
+
+Copyright (C) 2015 Timothy Edmund Crosley
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+documentation files (the "Software")... | |
133bb56417f2ac1080959c2e4d4db7012890d429 | sympy/categories/tests/test_baseclasses.py | sympy/categories/tests/test_baseclasses.py | from sympy.categories import Object, Morphism
def test_object():
A = Object("A")
assert A.name == "A"
def test_morphism():
A = Object("A")
B = Object("B")
C = Object("C")
D = Object("D")
f = Morphism(A, B, "f")
g = Morphism(B, C, "g")
h = Morphism(C, D, "h")
assert f.name ==... | Write the tests for categories.Object and categories.Morphism. | Write the tests for categories.Object and categories.Morphism.
The tests do not pass at the moment. The goal is to define the desired
behaviour of the methods in Morphism by means of tests.
| Python | bsd-3-clause | kaushik94/sympy,moble/sympy,dqnykamp/sympy,shipci/sympy,abhiii5459/sympy,emon10005/sympy,cccfran/sympy,vipulroxx/sympy,ChristinaZografou/sympy,madan96/sympy,vipulroxx/sympy,hrashk/sympy,lidavidm/sympy,madan96/sympy,mafiya69/sympy,atreyv/sympy,Sumith1896/sympy,pandeyadarsh/sympy,farhaanbukhsh/sympy,jamesblunt/sympy,skid... | ---
+++
@@ -0,0 +1,62 @@
+from sympy.categories import Object, Morphism
+
+def test_object():
+ A = Object("A")
+
+ assert A.name == "A"
+
+def test_morphism():
+ A = Object("A")
+ B = Object("B")
+ C = Object("C")
+ D = Object("D")
+
+ f = Morphism(A, B, "f")
+ g = Morphism(B, C, "g")
+ h ... | |
b27a76a70cc24c403fba85a0c205bd76de1468e4 | tutorials/pyroot/pyroot003_prettyPrinting.py | tutorials/pyroot/pyroot003_prettyPrinting.py | ## \file
## \ingroup tutorial_pyroot
## \notebook -nodraw
## This tutorial illustrates the pretty printing feature of PyROOT, which reveals
## the content of the object if a string representation is requested, e.g., by
## Python's print statement. The printing behaves similar to the ROOT prompt
## powered by the C++ in... | Add tutorial for pretty printing feature | [PyROOT] Add tutorial for pretty printing feature
| Python | lgpl-2.1 | karies/root,root-mirror/root,root-mirror/root,olifre/root,karies/root,olifre/root,root-mirror/root,karies/root,olifre/root,olifre/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,olifre/root,karies/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root... | ---
+++
@@ -0,0 +1,38 @@
+## \file
+## \ingroup tutorial_pyroot
+## \notebook -nodraw
+## This tutorial illustrates the pretty printing feature of PyROOT, which reveals
+## the content of the object if a string representation is requested, e.g., by
+## Python's print statement. The printing behaves similar to the ROO... | |
73b69c0205b29cda9107d71a88e94320be98d09e | tests/test_sqlite_db.py | tests/test_sqlite_db.py | '''
Module for testing the SQLite DB.
Fairly similar to the test_api tests...
'''
import os
import sys
import json
import unittest
CWD = os.path.dirname(os.path.abspath(__file__))
MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Allow import of sqlite_driver
if os.path.join(MS_WD, 'storage') not ... | Add first unit tests for sqlite db | Add first unit tests for sqlite db
| Python | mpl-2.0 | jmlong1027/multiscanner,awest1339/multiscanner,mitre/multiscanner,awest1339/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,mitre/multiscanner,mitre/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner | ---
+++
@@ -0,0 +1,50 @@
+'''
+Module for testing the SQLite DB.
+Fairly similar to the test_api tests...
+'''
+import os
+import sys
+import json
+import unittest
+
+CWD = os.path.dirname(os.path.abspath(__file__))
+MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+# Allow import of sqlite_drive... | |
2f0db51462a3d182602fe5c604afb3c9a31c811a | examples/leaderboard_example.py | examples/leaderboard_example.py | import requests
r = requests.get("https://stepic.org/api/leaders")
print "Current leaders:\n"
for leader in r.json()["leaders"]:
user = requests.get("https://stepic.org/api/users/" + str(leader["user"])).json()["users"][0]
print leader["score"], '\t', user['first_name'], user['last_name'] | Add a new example, showing the list of leaders | Add a new example, showing the list of leaders
| Python | mit | StepicOrg/Stepic-API | ---
+++
@@ -0,0 +1,9 @@
+import requests
+
+r = requests.get("https://stepic.org/api/leaders")
+
+print "Current leaders:\n"
+
+for leader in r.json()["leaders"]:
+ user = requests.get("https://stepic.org/api/users/" + str(leader["user"])).json()["users"][0]
+ print leader["score"], '\t', user['first_name'], us... | |
9a145fd5df247d1b018cc8cb66ce89659a39f874 | pygame/color.py | pygame/color.py |
class Color(object):
def __init__(self, *args):
if len(args) == 4:
r, g, b, a = args
else:
raise NotImplementedError("implement me")
self.r = r
self.g = g
self.b = b
self.a = a
| Make blitting work (the basics anyway) | Make blitting work (the basics anyway)
| Python | lgpl-2.1 | caseyc37/pygame_cffi,GertBurger/pygame_cffi,CTPUG/pygame_cffi,caseyc37/pygame_cffi,CTPUG/pygame_cffi,GertBurger/pygame_cffi,GertBurger/pygame_cffi,GertBurger/pygame_cffi,CTPUG/pygame_cffi,caseyc37/pygame_cffi | ---
+++
@@ -0,0 +1,11 @@
+
+class Color(object):
+ def __init__(self, *args):
+ if len(args) == 4:
+ r, g, b, a = args
+ else:
+ raise NotImplementedError("implement me")
+ self.r = r
+ self.g = g
+ self.b = b
+ self.a = a | |
9cb8d712798ca3fe8c0585b68995b14fd965a191 | tests/test_simpleflow/swf/test_helpers.py | tests/test_simpleflow/swf/test_helpers.py | import json
from mock import patch
import unittest
from sure import expect
from simpleflow.swf.helpers import swf_identity
@patch("socket.gethostname")
@patch("getpass.getuser")
@patch("os.getpid")
class TestSwfHelpers(unittest.TestCase):
def test_swf_identity_standard_case(self, mock_pid, mock_user, mock_host)... | Add basic tests for swf_identity() helper | Add basic tests for swf_identity() helper
| Python | mit | botify-labs/simpleflow,botify-labs/simpleflow | ---
+++
@@ -0,0 +1,37 @@
+import json
+from mock import patch
+import unittest
+
+from sure import expect
+
+from simpleflow.swf.helpers import swf_identity
+
+
+@patch("socket.gethostname")
+@patch("getpass.getuser")
+@patch("os.getpid")
+class TestSwfHelpers(unittest.TestCase):
+ def test_swf_identity_standard_c... | |
06260f50624068915ec84ba9e1e2993370a37471 | poradnia/events/migrations/0007_reminder.py | poradnia/events/migrations/0007_reminder.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-26 18:50
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... | Add migration with Reminder model | Add migration with Reminder model
| Python | mit | watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia | ---
+++
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.7 on 2016-07-26 18:50
+from __future__ import unicode_literals
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = ... | |
a8574ad9d7b7b933bb70fa47f84b3e396d058033 | src/escpos/capabilities.py | src/escpos/capabilities.py | import re
from os import path
import yaml
with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
PROFILES = yaml.load(f)
class Profile(object):
profile_data = {}
def __init__(self, columns=None):
self.default_columns = columns
def __getattr__(self, name):
return se... | Support loading capabilites YAML into Python classes. | Support loading capabilites YAML into Python classes.
| Python | mit | python-escpos/python-escpos,braveheuel/python-escpos,belono/python-escpos | ---
+++
@@ -0,0 +1,83 @@
+import re
+from os import path
+import yaml
+
+
+with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
+ PROFILES = yaml.load(f)
+
+
+class Profile(object):
+
+ profile_data = {}
+
+ def __init__(self, columns=None):
+ self.default_columns = columns
+
+ de... | |
df30466b43a765bc4771c7541cc8d99cae5f7932 | examples/safecast_logger.py | examples/safecast_logger.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Log measurements to Safecast open-data API (https://api.safecast.org).
Require the SafecastPy packages:
https://github.com/MonsieurV/SafecastPy
You'll also need a Safecast API key:
https://api.safecast.org/en-US/users/sign_up
Released under MIT Licen... | Add an example to publish data on the Safecast API | Add an example to publish data on the Safecast API
| Python | mit | MonsieurV/PiPocketGeiger | ---
+++
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+Log measurements to Safecast open-data API (https://api.safecast.org).
+
+Require the SafecastPy packages:
+ https://github.com/MonsieurV/SafecastPy
+You'll also need a Safecast API key:
+ https://api.safecast.org/en-US/users/sign_up... | |
79bf320f18db1b1dc89383a1c8e2f1080391c56c | tests/zeus/api/resources/test_revision_artifacts.py | tests/zeus/api/resources/test_revision_artifacts.py | from datetime import timedelta
from zeus import factories
from zeus.models import RepositoryAccess, RepositoryBackend, RepositoryProvider
from zeus.utils import timezone
def test_revision_artifacts(
client, db_session, default_login, default_user, git_repo_config
):
repo = factories.RepositoryFactory.create(... | Add coverage for revision artifacts endpoint | test: Add coverage for revision artifacts endpoint
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | ---
+++
@@ -0,0 +1,39 @@
+from datetime import timedelta
+
+from zeus import factories
+from zeus.models import RepositoryAccess, RepositoryBackend, RepositoryProvider
+from zeus.utils import timezone
+
+
+def test_revision_artifacts(
+ client, db_session, default_login, default_user, git_repo_config
+):
+ repo... | |
e738c5caa352f72419bb07ad7673ce1ed3f86039 | zivinetz/migrations/0002_auto_20140908_1116.py | zivinetz/migrations/0002_auto_20140908_1116.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('zivinetz', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='specification',
name... | Add a migration for the boolean field changes | Add a migration for the boolean field changes
| Python | mit | matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz | ---
+++
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('zivinetz', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ mo... | |
2011ca3e3b05591dfff3779a58e6ac21b4624be5 | cluster_viz/upload_data.py | cluster_viz/upload_data.py | import os, sys, subprocess, tempfile, gzip, cStringIO
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection()
bucket = conn.get_bucket("openinternet.widgets.sunlightfoundation.com")
base = sys.argv[1]
for j in os.listdir(base):
print "uploading", j
k = Key(bucket)
... | Add script for uploading tree_data. | Add script for uploading tree_data.
| Python | mit | sunlightlabs/fcc-net-neutrality-comments,sunlightlabs/fcc-net-neutrality-comments,sunlightlabs/fcc-net-neutrality-comments,sunlightlabs/fcc-net-neutrality-comments | ---
+++
@@ -0,0 +1,26 @@
+import os, sys, subprocess, tempfile, gzip, cStringIO
+from boto.s3.connection import S3Connection
+from boto.s3.key import Key
+
+conn = S3Connection()
+bucket = conn.get_bucket("openinternet.widgets.sunlightfoundation.com")
+
+base = sys.argv[1]
+for j in os.listdir(base):
+ print "up... | |
f7276ddf05c9775fb92706eedf1b1503f01b79e4 | src/url_json.py | src/url_json.py | from argparse import ArgumentParser
from time import time
from urllib.request import urlopen
import json
def parse_args():
parser = ArgumentParser()
parser.add_argument('--prefix', default='url_json')
parser.add_argument('--url', default='http://localhost/')
parser.add_argument(
'--key',
... | Add plugin to request data from JSON url endpoint | Add plugin to request data from JSON url endpoint
| Python | mit | innogames/igcollect | ---
+++
@@ -0,0 +1,32 @@
+from argparse import ArgumentParser
+from time import time
+from urllib.request import urlopen
+
+import json
+
+
+def parse_args():
+ parser = ArgumentParser()
+ parser.add_argument('--prefix', default='url_json')
+ parser.add_argument('--url', default='http://localhost/')
+ par... | |
655f8f319b3be348916731a424354dfc4a6cadab | utils/repl.py | utils/repl.py | from nex.state import GlobalState
from nex.reader import Reader, EndOfFile
from nex.lexer import Lexer
from nex.instructioner import Instructioner
from nex.banisher import Banisher
from nex.parsing.command_parser import command_parser
from nex.parsing.utils import ChunkGrabber
from nex.box_writer import write_to_file
f... | Add simple REPL to test commands | Add simple REPL to test commands
| Python | mit | eddiejessup/nex | ---
+++
@@ -0,0 +1,30 @@
+from nex.state import GlobalState
+from nex.reader import Reader, EndOfFile
+from nex.lexer import Lexer
+from nex.instructioner import Instructioner
+from nex.banisher import Banisher
+from nex.parsing.command_parser import command_parser
+from nex.parsing.utils import ChunkGrabber
+from ne... | |
4dfb5003994b45d01d451412d12fbf30051f68a8 | project_euler/library/number_theory/test_pells_equation.py | project_euler/library/number_theory/test_pells_equation.py | import pytest
from typing import Tuple
from .pells_equation import solve_pells_equation
from ..sqrt import is_square
PELLS_SOLUTIONS = [
(
2,
[
3,
2
]
),
(
3,
[
2,
1
]
),
(
5,
[
... | Add testing for Pells equation | Add testing for Pells equation
| Python | mit | cryvate/project-euler,cryvate/project-euler | ---
+++
@@ -0,0 +1,64 @@
+import pytest
+
+from typing import Tuple
+
+from .pells_equation import solve_pells_equation
+from ..sqrt import is_square
+
+
+PELLS_SOLUTIONS = [
+ (
+ 2,
+ [
+ 3,
+ 2
+ ]
+ ),
+ (
+ 3,
+ [
+ 2,
+ 1
+ ... | |
13ba3720f473ec5057a5da2ab804e7a99dcd9d95 | tools/client.py | tools/client.py | import hashlib
import RandomIO
# config vars
address = "1CutsncbjcCtZKeRfvQ7bnYFVj28zeU6fo"
byte_size = 1024*1024*10
# lib functions
def sha256(content):
"""Finds the sha256 hash of the content."""
content = content.encode('utf-8')
return hashlib.sha256(content).hexdigest()
def build_seed(height):
... | Add Sample Data Generating Client | Add Sample Data Generating Client
| Python | mit | Storj/dataserv,F483/dataserv,littleskunk/dataserv | ---
+++
@@ -0,0 +1,42 @@
+import hashlib
+import RandomIO
+
+# config vars
+address = "1CutsncbjcCtZKeRfvQ7bnYFVj28zeU6fo"
+byte_size = 1024*1024*10
+
+
+# lib functions
+def sha256(content):
+ """Finds the sha256 hash of the content."""
+ content = content.encode('utf-8')
+ return hashlib.sha256(content).he... | |
d8ae8c08324f428618639ef004388b42c27b3bdb | jsk_apc2016_common/scripts/list_objects.py | jsk_apc2016_common/scripts/list_objects.py | #!/usr/bin/env python
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--year', type=int, default=2016)
args = parser.parse_args()
if args.year == 2015:
import jsk_apc2015_common
cls_names = ['background'] + jsk_apc2015_common.get_object_list()
... | Add script to list object names | Add script to list object names
| Python | bsd-3-clause | pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc | ---
+++
@@ -0,0 +1,28 @@
+#!/usr/bin/env python
+
+import argparse
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--year', type=int, default=2016)
+ args = parser.parse_args()
+
+ if args.year == 2015:
+ import jsk_apc2015_common
+ cls_names = ['background'] + j... | |
f12334865233518fe128105834ef5fea59c500b2 | tests/test_web_listener.py | tests/test_web_listener.py | import pytest
@pytest.fixture
def test_flask_app():
from gitbot import web_listener
web_listener.app.config['TESTING'] = True
return web_listener.app.test_client()
expected_root_html_strings = [
(True, "<h1>GitHub issues bot index page</h1>"),
(True, "<!DOCTYPE html>"),
(True, "Set up the <c... | Add tests for web homepage | Add tests for web homepage
| Python | mit | melkamar/gitbot,melkamar/gitbot | ---
+++
@@ -0,0 +1,30 @@
+import pytest
+
+
+@pytest.fixture
+def test_flask_app():
+ from gitbot import web_listener
+ web_listener.app.config['TESTING'] = True
+ return web_listener.app.test_client()
+
+
+expected_root_html_strings = [
+ (True, "<h1>GitHub issues bot index page</h1>"),
+ (True, "<!DO... | |
c22fde851dc4e8f3c9c930e1f0151b677eeadb52 | tensorflow/python/platform/remote_utils.py | tensorflow/python/platform/remote_utils.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | Add `args` and `kwargs` to cloud-tpu version of `coordination_service_type()` function | Add `args` and `kwargs` to cloud-tpu version of `coordination_service_type()` function
PiperOrigin-RevId: 470776162
| Python | apache-2.0 | tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensor... | ---
+++
@@ -14,6 +14,7 @@
# ==============================================================================
"""Platform-specific helpers for connecting to remote servers."""
+
def get_default_communication_protocol():
return 'grpc'
@@ -26,5 +27,6 @@
return ''
-def coordination_service_type(_):
+def co... |
eb084516ceca0645024d41ae2a0ea7e04250b13f | bluebottle/time_based/migrations/0044_auto_20201224_1120.py | bluebottle/time_based/migrations/0044_auto_20201224_1120.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2020-12-24 10:20
from __future__ import unicode_literals
from django.db import migrations
def fix_wallpost_ctype(apps, schema_editor):
ContentType = apps.get_model('contenttypes', 'ContentType')
Assignment = apps.get_model('assignments', 'Assignment')
... | Migrate wallposts to right ctype | Migrate wallposts to right ctype
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.17 on 2020-12-24 10:20
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+def fix_wallpost_ctype(apps, schema_editor):
+ ContentType = apps.get_model('contenttypes', 'ContentType')
+ Assignment = apps.ge... | |
47bff9240beaa1214f945067310fbed32ee16b7c | scripts/revert-database.py | scripts/revert-database.py | #!/usr/bin/python
# This is a small helper script revert a CATMAID
# database from to a recent backup.
# For example, you might call this as:
# revert-database.py /mnt/catmaid-backups/2011-12-10T19-14-47.bz2
# You will need to create a .pgpass file so that your password can be
# found.
# You may need to install ps... | Add a script to revert the database from an earlier backup | Add a script to revert the database from an earlier backup
This scripts assumes that the database dump was done with
pg_dump --clean. If it wasn't done with the --clean option
you would need to do:
dropdb catmaid
sudo -u postgres psql < docs/createuser.sql
... before running revert-database.py backup.bz2
| Python | agpl-3.0 | fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID | ---
+++
@@ -0,0 +1,54 @@
+#!/usr/bin/python
+
+# This is a small helper script revert a CATMAID
+# database from to a recent backup.
+
+# For example, you might call this as:
+
+# revert-database.py /mnt/catmaid-backups/2011-12-10T19-14-47.bz2
+
+# You will need to create a .pgpass file so that your password can be
+... | |
605323fa8fa4dd8f447e7ba1b1a24cb791efe57e | thecut/authorship/views.py | thecut/authorship/views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
class AuthorshipViewMixin(object):
"""Add the request's ``User`` instance to the form kwargs."""
def get_form_kwargs(self, *args, **kwargs):
form_kwargs = super(AuthorshipViewMixin, self).get_form_kwargs(
*ar... | Add a view mixin to pass the ``User`` instance to the view's form. | Add a view mixin to pass the ``User`` instance to the view's form.
| Python | apache-2.0 | thecut/thecut-authorship | ---
+++
@@ -0,0 +1,12 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, unicode_literals
+
+
+class AuthorshipViewMixin(object):
+ """Add the request's ``User`` instance to the form kwargs."""
+
+ def get_form_kwargs(self, *args, **kwargs):
+ form_kwargs = super(AuthorshipViewMixin, se... | |
f73709f8a542a768c5a96e9f8ce7504a4c8f839f | coffin/template/response.py | coffin/template/response.py | from coffin.template import loader
from django.template import response as django_response
class SimpleTemplateResponse(django_response.SimpleTemplateResponse):
def resolve_template(self, template):
if isinstance(template, (list, tuple)):
return loader.select_template(template)
elif is... | Implement a wrapper for the SimpleTemplateResponse and the TemplateResponse which use jinja2 | Implement a wrapper for the SimpleTemplateResponse and the TemplateResponse which use jinja2 | Python | bsd-3-clause | rossowl/coffin,rossowl/coffin,akx/coffin | ---
+++
@@ -0,0 +1,16 @@
+from coffin.template import loader
+from django.template import response as django_response
+
+
+class SimpleTemplateResponse(django_response.SimpleTemplateResponse):
+ def resolve_template(self, template):
+ if isinstance(template, (list, tuple)):
+ return loader.select... | |
05952797e4be473bf68ba5f2f6710c35379b59f5 | scripts/stream_iss_data.py | scripts/stream_iss_data.py | #!/usr/bin/python
import socket
import logging
import json
import requests
import time
import datetime
logger = logging.getLogger(__name__)
class Socket(socket.socket):
def __init__(self, x=socket.AF_INET, y=socket.SOCK_DGRAM, *args, **kwargs):
super(Socket, self).__init__(x, y, *args, **kwargs)
if __na... | Add script to populate the database periodically with geocoordinates of the International Space Station | Add script to populate the database periodically with geocoordinates of the International Space Station
| Python | apache-2.0 | opentrv/iotlaunchpad,opentrv/iotlaunchpad | ---
+++
@@ -0,0 +1,24 @@
+#!/usr/bin/python
+import socket
+import logging
+import json
+import requests
+import time
+import datetime
+
+logger = logging.getLogger(__name__)
+
+class Socket(socket.socket):
+
+ def __init__(self, x=socket.AF_INET, y=socket.SOCK_DGRAM, *args, **kwargs):
+ super(Socket, self)... | |
5f3be583d945d04ef9f259ee77d21933756209bd | components/table_fetcher.py | components/table_fetcher.py | """Fetches data from GitHub API, store and return the data in a SgTable."""
import table
import inspect
class SgTableFetcher:
"""Fetches data from GitHub API, store and return the data in a SgTable."""
def __init__(self, github):
self._github = github
def _Parse(self, label):
tmp = labe... | Add SgTableFetcher - automatically infers keys/fields and values from object | Add SgTableFetcher - automatically infers keys/fields and values from object
| Python | mit | lnishan/SQLGitHub | ---
+++
@@ -0,0 +1,47 @@
+"""Fetches data from GitHub API, store and return the data in a SgTable."""
+
+import table
+import inspect
+
+
+class SgTableFetcher:
+ """Fetches data from GitHub API, store and return the data in a SgTable."""
+
+ def __init__(self, github):
+ self._github = github
+
+ def... | |
39848dcbaae0648e42108c720eeb008d23bf51e4 | import/bde-metadata-extractor.py | import/bde-metadata-extractor.py | from __future__ import print_function
import os
import sys
import yaml
# Scan the local directory (or one provided as the first command line argument)
# for directories that contain 'package' directories. Extract BDE metadata from
# these and print a YAML document.
def readDeps(filename):
f = open(filename, "rt")... | Add prototype BDE Metadata scanner in import/extract-yaml.pl | Add prototype BDE Metadata scanner in import/extract-yaml.pl
| Python | apache-2.0 | CodethinkLabs/software-dependency-visualizer,CodethinkLabs/software-dependency-visualizer,CodethinkLabs/software-dependency-visualizer,CodethinkLabs/software-dependency-visualizer | ---
+++
@@ -0,0 +1,75 @@
+from __future__ import print_function
+import os
+import sys
+import yaml
+
+# Scan the local directory (or one provided as the first command line argument)
+# for directories that contain 'package' directories. Extract BDE metadata from
+# these and print a YAML document.
+
+def readDeps(fi... | |
c44df13321a7f8b844b708ea90dbccc89579dc95 | examples/widgets/focus_behavior.py | examples/widgets/focus_behavior.py | from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.behaviors import FocusBehavior
class FocusButton(FocusBehavior, Button):
'''A button, which when focused, turns red and sets the keyboard
input to the t... | Add focus behavior example to examples. | Add focus behavior example to examples.
| Python | mit | matham/kivy,rnixx/kivy,Cheaterman/kivy,LogicalDash/kivy,angryrancor/kivy,angryrancor/kivy,bob-the-hamster/kivy,niavlys/kivy,ernstp/kivy,jegger/kivy,manthansharma/kivy,jegger/kivy,gonzafirewall/kivy,angryrancor/kivy,arcticshores/kivy,niavlys/kivy,janssen/kivy,JohnHowland/kivy,arlowhite/kivy,KeyWeeUsr/kivy,rafalo1333/kiv... | ---
+++
@@ -0,0 +1,66 @@
+from kivy.app import App
+from kivy.uix.gridlayout import GridLayout
+from kivy.uix.boxlayout import BoxLayout
+from kivy.uix.button import Button
+from kivy.uix.behaviors import FocusBehavior
+
+
+class FocusButton(FocusBehavior, Button):
+ '''A button, which when focused, turns red and ... | |
9b870f8a94cd232ecc5fddc155f9056fdcdfe9b1 | runreport.py | runreport.py | import os
import json
import saulify.sitespec as sitespec
SPEC_DIRECTORY = "sitespecs"
if __name__ == "__main__":
for fname in os.listdir(SPEC_DIRECTORY):
fpath = os.path.join(SPEC_DIRECTORY, fname)
test_cases = sitespec.load_testcases(fpath)
for test_case in test_cases:
resu... | Add script to generate report on scraper tests | Add script to generate report on scraper tests
| Python | agpl-3.0 | asm-products/saulify-web,asm-products/saulify-web,asm-products/saulify-web | ---
+++
@@ -0,0 +1,15 @@
+import os
+import json
+
+import saulify.sitespec as sitespec
+
+SPEC_DIRECTORY = "sitespecs"
+
+
+if __name__ == "__main__":
+ for fname in os.listdir(SPEC_DIRECTORY):
+ fpath = os.path.join(SPEC_DIRECTORY, fname)
+ test_cases = sitespec.load_testcases(fpath)
+ for t... | |
b8259551a8d147e676cc7fe34fd511a38861f294 | Week01/Problem04/cyu_04.py | Week01/Problem04/cyu_04.py | #!/usr/bin/env python3
"""This script is written by Chuanping Yu, on Jul 24, 2017,
for the Assignment#1 in IDEaS workshop"""
#Problem 4
S = 0
A = 0
B = 0
for a in range(100, 1000):
for b in range(100, 1000):
num = a*b
if str(num) == str(num)[::-1] and S < num:
S = num
A = a... | Add Chuanping Yu's solutions to Problem04 | Add Chuanping Yu's solutions to Problem04 | Python | bsd-3-clause | GT-IDEaS/SkillsWorkshop2017,GT-IDEaS/SkillsWorkshop2017,GT-IDEaS/SkillsWorkshop2017 | ---
+++
@@ -0,0 +1,17 @@
+#!/usr/bin/env python3
+
+"""This script is written by Chuanping Yu, on Jul 24, 2017,
+for the Assignment#1 in IDEaS workshop"""
+
+#Problem 4
+S = 0
+A = 0
+B = 0
+for a in range(100, 1000):
+ for b in range(100, 1000):
+ num = a*b
+ if str(num) == str(num)[::-1] and S < nu... | |
b6e8a75077d4b1667861d307d352828f3a3fbd60 | stoic/log.py | stoic/log.py | import logging
import datetime
class Iso8601Formatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
record_time = datetime.datetime.utcfromtimestamp(record.created)
return record_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
| Add formatter for outputting iso8601 dates | Add formatter for outputting iso8601 dates
| Python | apache-2.0 | NegativeMjark/stoic | ---
+++
@@ -0,0 +1,7 @@
+import logging
+import datetime
+
+class Iso8601Formatter(logging.Formatter):
+ def formatTime(self, record, datefmt=None):
+ record_time = datetime.datetime.utcfromtimestamp(record.created)
+ return record_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ") | |
51cad1634ed9f6b8e40264f027a3a891db45e729 | benchmarks/expand2_sage.py | benchmarks/expand2_sage.py | from timeit import default_timer as clock
from sage.all import var
var("x y z w")
e = (x+y+z+w)**15
f = e*(e+w)
print f
t1 = clock()
g = f.expand()
t2 = clock()
print "Total time:", t2-t1, "s"
| Add the expand2 benchmark using Sage | Add the expand2 benchmark using Sage
| Python | mit | symengine/symengine.py,bjodah/symengine.py,bjodah/symengine.py,symengine/symengine.py,bjodah/symengine.py,symengine/symengine.py | ---
+++
@@ -0,0 +1,10 @@
+from timeit import default_timer as clock
+from sage.all import var
+var("x y z w")
+e = (x+y+z+w)**15
+f = e*(e+w)
+print f
+t1 = clock()
+g = f.expand()
+t2 = clock()
+print "Total time:", t2-t1, "s" | |
4b6e1b2426efa4f96dc1120718b4acbfbcdbee98 | numba/tests/test_caching.py | numba/tests/test_caching.py | from __future__ import print_function, absolute_import, division
import sys
import os
import multiprocessing as mp
import traceback
from numba import njit
from .support import (
TestCase,
temp_directory,
override_env_config,
captured_stdout,
captured_stderr,
)
def constant_unicode_cache():
c... | Add test for unicode cache | Add test for unicode cache
| Python | bsd-2-clause | jriehl/numba,IntelLabs/numba,jriehl/numba,cpcloud/numba,IntelLabs/numba,gmarkall/numba,IntelLabs/numba,gmarkall/numba,jriehl/numba,sklam/numba,sklam/numba,seibert/numba,numba/numba,stuartarchibald/numba,seibert/numba,cpcloud/numba,stonebig/numba,seibert/numba,cpcloud/numba,gmarkall/numba,numba/numba,gmarkall/numba,stua... | ---
+++
@@ -0,0 +1,97 @@
+from __future__ import print_function, absolute_import, division
+
+import sys
+import os
+import multiprocessing as mp
+import traceback
+
+from numba import njit
+from .support import (
+ TestCase,
+ temp_directory,
+ override_env_config,
+ captured_stdout,
+ captured_stderr... | |
6a89500514073906df88216048ea0afe1c817e33 | tests/test_brann_bronzebeard.py | tests/test_brann_bronzebeard.py | from utils import *
BRANN_BRONZEBEARD = "LOE_077"
def _prepare_game():
game = prepare_game()
brann = game.player1.give(BRANN_BRONZEBEARD)
brann.play()
game.end_turn(); game.end_turn()
game.player1.discard_hand()
return game, brann
def test_brann_abusive_sergeant():
game, brann = _prepare_game()
abusive ... | Add some tests for Brann Bronzebeard | Add some tests for Brann Bronzebeard
| Python | agpl-3.0 | Ragowit/fireplace,Ragowit/fireplace,NightKev/fireplace,amw2104/fireplace,smallnamespace/fireplace,amw2104/fireplace,smallnamespace/fireplace,beheh/fireplace,jleclanche/fireplace | ---
+++
@@ -0,0 +1,43 @@
+from utils import *
+
+
+BRANN_BRONZEBEARD = "LOE_077"
+
+
+def _prepare_game():
+ game = prepare_game()
+ brann = game.player1.give(BRANN_BRONZEBEARD)
+ brann.play()
+ game.end_turn(); game.end_turn()
+
+ game.player1.discard_hand()
+
+ return game, brann
+
+
+def test_brann_abusive_sergean... | |
ea4b0cece818a3d615fa116936f7067bb9c13832 | tests/test_spatial_relations.py | tests/test_spatial_relations.py |
## Imports
import numpy as np
import matplotlib.pyplot as plt
from pySpatialTools.Retrieve import GridSpatialDisc, CircRetriever
from pySpatialTools.Spatial_Relations.region_spatial_relations import regions_relation_points
## Paramters
n = 10000
ngx, ngy = 100, 100
## Artificial distribution in space
locs = np.rando... | Test for spatial relations between regions. | Test for spatial relations between regions.
| Python | mit | tgquintela/pySpatialTools,tgquintela/pySpatialTools | ---
+++
@@ -0,0 +1,40 @@
+
+## Imports
+import numpy as np
+import matplotlib.pyplot as plt
+from pySpatialTools.Retrieve import GridSpatialDisc, CircRetriever
+from pySpatialTools.Spatial_Relations.region_spatial_relations import regions_relation_points
+
+## Paramters
+n = 10000
+ngx, ngy = 100, 100
+
+## Artificia... | |
89ed35bf6215ba2fa71640eb6d5117f3a5fe5018 | stix2matcher/test/test_comparison_exprs.py | stix2matcher/test/test_comparison_exprs.py | import pytest
from stix2matcher.matcher import match
_observations = [
{
"type": "observed-data",
"number_observed": 1,
"first_observed": "2004-11-26T11:42:29Z",
"objects": {
"0": {
"type": u"person",
"name": u"alice",
"a... | Add some tests for comparison expressions: and, or, and order of operations. | Add some tests for comparison expressions: and, or, and order
of operations.
| Python | bsd-3-clause | chisholm/cti-pattern-matcher,oasis-open/cti-pattern-matcher | ---
+++
@@ -0,0 +1,45 @@
+import pytest
+
+from stix2matcher.matcher import match
+
+
+_observations = [
+ {
+ "type": "observed-data",
+ "number_observed": 1,
+ "first_observed": "2004-11-26T11:42:29Z",
+ "objects": {
+ "0": {
+ "type": u"person",
+ ... | |
c7ba3c4340c73ef5765bc883b500dc5188d43189 | android/runtime/v8/tools/genRequireIndex.py | android/runtime/v8/tools/genRequireIndex.py | #! /usr/bin/env python
# Generates an index file used by require
# to test if a file exists in the assets folder.
# Usage: genRequireIndex.py <rootDirectory> <outputFile>
# rootDirectory = path to the directory being indexed
# (Should be path to the app's assets folder)
# outputFile = path where ... | Add script to generate file index for Require. | Add script to generate file index for Require.
| Python | apache-2.0 | ashcoding/titanium_mobile,KoketsoMabuela92/titanium_mobile,taoger/titanium_mobile,csg-coder/titanium_mobile,emilyvon/titanium_mobile,KangaCoders/titanium_mobile,perdona/titanium_mobile,linearhub/titanium_mobile,formalin14/titanium_mobile,cheekiatng/titanium_mobile,bright-sparks/titanium_mobile,pinnamur/titanium_mobile,... | ---
+++
@@ -0,0 +1,25 @@
+#! /usr/bin/env python
+
+# Generates an index file used by require
+# to test if a file exists in the assets folder.
+# Usage: genRequireIndex.py <rootDirectory> <outputFile>
+# rootDirectory = path to the directory being indexed
+# (Should be path to the app's assets fo... | |
033d46a8157146027f2fe4bc94c6e1ae6ba49f6a | tri/photo.py | tri/photo.py | #!/usr/bin/python
import re
from os import listdir, makedirs, link, walk, rename
from os.path import isdir,isfile
cam_directory = '/home/poclement/Dropbox/Camera Uploads'
file_list = listdir(cam_directory)
archive_directory = ('/home/poclement/Dropbox/Images/Archive_Camera')
for f in file_list:
m = re.search('^(... | Add Camera upload sorting script | Add Camera upload sorting script
| Python | mit | riyoth/Script,riyoth/Script | ---
+++
@@ -0,0 +1,21 @@
+#!/usr/bin/python
+import re
+from os import listdir, makedirs, link, walk, rename
+from os.path import isdir,isfile
+
+
+cam_directory = '/home/poclement/Dropbox/Camera Uploads'
+file_list = listdir(cam_directory)
+archive_directory = ('/home/poclement/Dropbox/Images/Archive_Camera')
+
+for... | |
c948e8cc3fde47fac0ed9604baba741ee961043c | projecteuler/numbertypes.py | projecteuler/numbertypes.py | def pentagonal(n):
"""Returns the n-th pentagonal number"""
return n*(3*n-1)/2
def ispentagonal(P):
"""Returns true if P is pentagonal.
ABC-formula on P(n) gives
n = (sqrt(1+24P)+1)/6
If P is pentagonal, n is an int.
1. sqrt must return a integer
2. must be divisble by 6
... | Rename number module to not crash NumPy | Rename number module to not crash NumPy
Ended up overriding a NumPy module called numbers.
| Python | mit | bsamseth/project-euler,bsamseth/project-euler | ---
+++
@@ -0,0 +1,43 @@
+def pentagonal(n):
+ """Returns the n-th pentagonal number"""
+ return n*(3*n-1)/2
+
+def ispentagonal(P):
+ """Returns true if P is pentagonal.
+ ABC-formula on P(n) gives
+ n = (sqrt(1+24P)+1)/6
+ If P is pentagonal, n is an int.
+ 1. sqrt must return a integer... | |
2284acc100e1690bc649574f0116934e7f3bd689 | py/poor-pigs.py | py/poor-pigs.py | from itertools import count
class Solution(object):
def poorPigs(self, buckets, minutesToDie, minutesToTest):
"""
:type buckets: int
:type minutesToDie: int
:type minutesToTest: int
:rtype: int
"""
t = minutesToTest / minutesToDie
for pigs in count(0):... | Add py solution for 458. Poor Pigs | Add py solution for 458. Poor Pigs
458. Poor Pigs: https://leetcode.com/problems/poor-pigs/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,13 @@
+from itertools import count
+class Solution(object):
+ def poorPigs(self, buckets, minutesToDie, minutesToTest):
+ """
+ :type buckets: int
+ :type minutesToDie: int
+ :type minutesToTest: int
+ :rtype: int
+ """
+ t = minutesToTest / minut... | |
32b242cab9d3e9a83c69c90b155920a77a318ed7 | programming/python/matplotlib/sin_and_cos_1.py | programming/python/matplotlib/sin_and_cos_1.py | # from http://www.labri.fr/perso/nrougier/teaching/matplotlib/
from pylab import*
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)
plot(X,C)
plot(X,S)
show()
| Add another, simpler, matplotlib example | Add another, simpler, matplotlib example
| Python | mit | claremacrae/raspi_code,claremacrae/raspi_code,claremacrae/raspi_code | ---
+++
@@ -0,0 +1,11 @@
+# from http://www.labri.fr/perso/nrougier/teaching/matplotlib/
+
+from pylab import*
+
+X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
+C,S = np.cos(X), np.sin(X)
+
+plot(X,C)
+plot(X,S)
+
+show() | |
838201e987ea420cdb2726477f08fc93aae295e7 | hs_core/management/commands/set_shareable.py | hs_core/management/commands/set_shareable.py | """Set the shareable bit for a resource to True or False
This is a workaround for the fact that published, unshareable i
resources can't be added to collections.
"""
from django.core.management.base import BaseCommand
from hs_core.models import BaseResource
from hs_core.hydroshare.utils import get_resource_by_sh... | Add command to set shareable bit | Add command to set shareable bit
| Python | bsd-3-clause | hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare | ---
+++
@@ -0,0 +1,60 @@
+"""Set the shareable bit for a resource to True or False
+ This is a workaround for the fact that published, unshareable i
+ resources can't be added to collections.
+"""
+
+from django.core.management.base import BaseCommand
+from hs_core.models import BaseResource
+from hs_core.hydrosh... | |
f46a162ea225d4a962977120ad3f4bdb01777cad | giftwrap/tests/test_buildspec.py | giftwrap/tests/test_buildspec.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014, John Dewey
# All Rights Reserved.
#
# 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/lic... | Add basic test coverage for build_spec | Add basic test coverage for build_spec
This asserts the basic public surface area of the module
Change-Id: I97f5f228ed55dd0d0b748a47bd88c72c55500102
| Python | apache-2.0 | j2sol/giftwrap,j2sol/giftwrap | ---
+++
@@ -0,0 +1,61 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2014, John Dewey
+# All Rights Reserved.
+#
+# 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
+#... | |
9738e06267d35adc96fa9344f752ea4ddb8f3272 | pipeline/build-clusters.py | pipeline/build-clusters.py | import MySQLdb as mdb
input_file = "phylota_184_trees.tre"
out_dir = "clusters/"
db_host = "localhost"
db_user = "root"
db_password = "reelab14"
db_database = "phylota"
### Read in a parse the tree file output from trees file
treefile = open(input_file, 'r')
raw_id = []
ids = []
for t in treefile:
tree_id = ... | Refactor from get-clusters. Changes for speed, clarity and use simplification. | Refactor from get-clusters.
Changes for speed, clarity and use simplification.
| Python | bsd-3-clause | lcoghill/phyloboost,lcoghill/phyloboost,lcoghill/phyloboost | ---
+++
@@ -0,0 +1,54 @@
+import MySQLdb as mdb
+
+
+
+input_file = "phylota_184_trees.tre"
+out_dir = "clusters/"
+db_host = "localhost"
+db_user = "root"
+db_password = "reelab14"
+db_database = "phylota"
+
+
+
+### Read in a parse the tree file output from trees file
+
+treefile = open(input_file, 'r')
+raw_id = [... | |
ce542e0bd75a8f93d1be69be6d4c2ad3f05e85db | cybox/test/objects/win_network_share_test.py | cybox/test/objects/win_network_share_test.py | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import unittest
from mixbox.vendor.six import u
from cybox.objects.win_network_share_object import WinNetworkShare
from cybox.test.objects import ObjectTestCase
class TestWinNetworkShare(ObjectTestCase, unittest... | Add tests for WinNetworkShare object. | Add tests for WinNetworkShare object.
| Python | bsd-3-clause | CybOXProject/python-cybox | ---
+++
@@ -0,0 +1,34 @@
+# Copyright (c) 2015, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from mixbox.vendor.six import u
+
+from cybox.objects.win_network_share_object import WinNetworkShare
+from cybox.test.objects import ObjectTestCase
+
+
+class TestW... | |
3602699e1eb45e96ce6227ed6739dab49207b4bf | etc/gen-test-dump.py | etc/gen-test-dump.py | #!/usr/bin/env python
import random
WORLDS = [None] * 8 + ['world', 'world_nether', 'creative', 'hardcore']
REGIONS = [None] * 20 + ['Region%d' % i for i in range(10)]
NUM_PLAYERS = 100
NUM_PERMISSIONS_PER_PLAYER = 50
NUM_GROUPS = (3, 13, 23, 31, 41)
NUM_PERMISSIONS_PER_GROUP = 50
NUM_PLAYERS_PER_GROUP = 50
P... | Add Python script to generate (huge) test dumps. | Add Python script to generate (huge) test dumps.
| Python | apache-2.0 | MineYourMind/zPermissions,MineYourMind/zPermissions,MrWisski/zPermissions,MrWisski/zPermissions | ---
+++
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+
+import random
+
+
+WORLDS = [None] * 8 + ['world', 'world_nether', 'creative', 'hardcore']
+
+REGIONS = [None] * 20 + ['Region%d' % i for i in range(10)]
+
+NUM_PLAYERS = 100
+
+NUM_PERMISSIONS_PER_PLAYER = 50
+
+NUM_GROUPS = (3, 13, 23, 31, 41)
+
+NUM_PERMISSIONS_PE... | |
ec4296bf19f85502f947d278ce58c27e7179a1fc | random_particle_movement.py | random_particle_movement.py | import math
import pygame
import random
pygame.init()
Pi = math.pi
#-- SCREEN CHARACTERISTICS ------------------------->>>
background_color = (255,255,255)
(width, height) = (300, 200)
#-- PARTICLE DEFINITION ---------------------------->>>
class Particle:
def __init__(self, (x, y), radius):
self.x = x
... | Add module where particles randomly disperse | Add module where particles randomly disperse
| Python | mit | withtwoemms/pygame-explorations | ---
+++
@@ -0,0 +1,73 @@
+import math
+import pygame
+import random
+
+
+pygame.init()
+Pi = math.pi
+
+#-- SCREEN CHARACTERISTICS ------------------------->>>
+background_color = (255,255,255)
+(width, height) = (300, 200)
+
+#-- PARTICLE DEFINITION ---------------------------->>>
+class Particle:
+ def __init__(... | |
447fba372fd7e438edd6119c5e59342958f9ec8d | genome_designer/debug/transactions_debug.py | genome_designer/debug/transactions_debug.py | """
Experimenting with Django transactions.
"""
import random
# Since this script is intended to be used from the terminal, setup the
# environment first so that django and model imports work.
from util import setup_django_env
setup_django_env()
from django.contrib.auth.models import User
from django.db import trans... | Save code for debugging transactions. | Save code for debugging transactions.
| Python | mit | woodymit/millstone,churchlab/millstone,woodymit/millstone,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone_accidental_source | ---
+++
@@ -0,0 +1,55 @@
+"""
+Experimenting with Django transactions.
+"""
+
+import random
+
+# Since this script is intended to be used from the terminal, setup the
+# environment first so that django and model imports work.
+from util import setup_django_env
+setup_django_env()
+
+from django.contrib.auth.models ... | |
a206807606130d9eb1d55b9b54ec03b3fa3f1816 | test/integrationtests/skills/single_test.py | test/integrationtests/skills/single_test.py | # Copyright 2017 Mycroft AI Inc.
#
# 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 writin... | Add simple script for running a single skill | Add simple script for running a single skill
Based on the skill_developers_testrunner.py, takes the path to a skill
as argument and runs any tests for that skill.
| Python | apache-2.0 | MycroftAI/mycroft-core,linuxipho/mycroft-core,forslund/mycroft-core,Dark5ide/mycroft-core,forslund/mycroft-core,MycroftAI/mycroft-core,Dark5ide/mycroft-core,linuxipho/mycroft-core | ---
+++
@@ -0,0 +1,93 @@
+# Copyright 2017 Mycroft AI Inc.
+#
+# 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 a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.