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 |
|---|---|---|---|---|---|---|---|---|---|---|
7a0bb642a4dccd3b6ada7cace0583aed54caedec | tests/test_settings.py | tests/test_settings.py | import os
import unittest
from swf.settings import from_env
AWS_ENV_KEYS = (
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_DEFAULT_REGION",
)
class TestSettings(unittest.TestCase):
def setUp(self):
self.oldies = {}
for key in AWS_ENV_KEYS:
self.oldies[key] = os.enviro... | Add some tests to demonstrate current behaviour | Add some tests to demonstrate current behaviour
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow | ---
+++
@@ -0,0 +1,47 @@
+import os
+import unittest
+
+from swf.settings import from_env
+
+AWS_ENV_KEYS = (
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_DEFAULT_REGION",
+)
+
+class TestSettings(unittest.TestCase):
+ def setUp(self):
+ self.oldies = {}
+ for key in AWS_ENV_KEYS... | |
df17568e00d1b0adbd327d58918d71b3bf195ced | py/valid-triangle-number.py | py/valid-triangle-number.py | from collections import Counter
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = filter(None, nums)
if not nums:
return 0
c = Counter(nums)
N = max(nums)
buckets = [0] * (N + 1... | Add py solution for 611. Valid Triangle Number | Add py solution for 611. Valid Triangle Number
611. Valid Triangle Number: https://leetcode.com/problems/valid-triangle-number/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,29 @@
+from collections import Counter
+class Solution(object):
+ def triangleNumber(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ nums = filter(None, nums)
+ if not nums:
+ return 0
+ c = Counter(nums)
+ N = m... | |
35ad1b2bc237ea0a5783750d5980040f9cbdec92 | source/sql/alembic/versions/56c1c7a19078_add_visible_parameter.py | source/sql/alembic/versions/56c1c7a19078_add_visible_parameter.py | """add visible parameter
Revision ID: 56c1c7a19078
Revises: 46168c7abc89
Create Date: 2018-11-13 15:33:38.146755
"""
# revision identifiers, used by Alembic.
revision = '56c1c7a19078'
down_revision = '46168c7abc89'
from alembic import op
import sqlalchemy as sa
import geoalchemy2 as ga
from sqlalchemy.dialects impo... | Add visible parameter (Bool) in georef.way Bdd | Add visible parameter (Bool) in georef.way Bdd
| Python | agpl-3.0 | xlqian/navitia,Tisseo/navitia,kinnou02/navitia,patochectp/navitia,Tisseo/navitia,pbougue/navitia,xlqian/navitia,CanalTP/navitia,xlqian/navitia,CanalTP/navitia,CanalTP/navitia,Tisseo/navitia,CanalTP/navitia,Tisseo/navitia,kinnou02/navitia,Tisseo/navitia,CanalTP/navitia,pbougue/navitia,patochectp/navitia,xlqian/navitia,k... | ---
+++
@@ -0,0 +1,24 @@
+"""add visible parameter
+
+Revision ID: 56c1c7a19078
+Revises: 46168c7abc89
+Create Date: 2018-11-13 15:33:38.146755
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '56c1c7a19078'
+down_revision = '46168c7abc89'
+
+from alembic import op
+import sqlalchemy as sa
+import geoal... | |
5e2ebfe1d45a542f7f8b480e855890140cfbc1fb | samples/vmc/networks_nsxt/hello_world.py | samples/vmc/networks_nsxt/hello_world.py | #!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2019. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS... | Add networks_nsxt dir, simple example | Add networks_nsxt dir, simple example
Define a directory for NSX-T sample code. Add a basic
example that shows how to authenticate to VMC/NSX-T and
make a simple read call.
Signed-Off-By: Gordon Good <357c6cd042c65e38a52fc9cc40c47924d92a9c54@vmware.com>
| Python | mit | tianhao64/vsphere-automation-sdk-python,tianhao64/vsphere-automation-sdk-python | ---
+++
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+
+"""
+* *******************************************************
+* Copyright (c) VMware, Inc. 2019. All Rights Reserved.
+* SPDX-License-Identifier: MIT
+* *******************************************************
+*
+* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS... | |
dd1e7b06c4fbb31da91a14a57d98b4910eb4a351 | candidates/tests/helpers.py | candidates/tests/helpers.py | from __future__ import print_function
import difflib
import pprint
import sys
def p(*args):
"""A helper for printing to stderr"""
print(file=sys.stderr, *args)
def equal_arg(arg1, arg2):
"""Return True if the args are equal, False otherwise
If the arguments aren't equal under ==, return True, other... | Add equal_call_args for helpful diffs of args | Add equal_call_args for helpful diffs of args
This is particularly useful because mock's assert_called_with produces
really unhelpful output if the the expectation doesn't match.
| Python | agpl-3.0 | neavouli/yournextrepresentative,neavouli/yournextrepresentative,mhl/yournextmp-popit,neavouli/yournextrepresentative,datamade/yournextmp-popit,openstate/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mhl/yournextmp-popit,neavouli/yournextrepresentative,... | ---
+++
@@ -0,0 +1,48 @@
+from __future__ import print_function
+
+import difflib
+import pprint
+
+import sys
+
+def p(*args):
+ """A helper for printing to stderr"""
+ print(file=sys.stderr, *args)
+
+def equal_arg(arg1, arg2):
+ """Return True if the args are equal, False otherwise
+
+ If the arguments... | |
02f69a304a0e55a8f3164b7b1fbafbf0ba7f07b4 | pyboard/GPIO_interrupt_updater.py | pyboard/GPIO_interrupt_updater.py | from pyb import UART
from pyb import ExtInt
from pyb import Pin
from micropyGPS import MicropyGPS
# Global Flag to Start GPS data Processing
new_data = False
# Callback Function
def pps_callback(line):
print("Updated GPS Object...")
global new_data # Use Global to trigger update
new_data = True
print('... | Add external interrupt updater example | Add external interrupt updater example
| Python | mit | inmcm/micropyGPS | ---
+++
@@ -0,0 +1,47 @@
+from pyb import UART
+from pyb import ExtInt
+from pyb import Pin
+from micropyGPS import MicropyGPS
+
+# Global Flag to Start GPS data Processing
+new_data = False
+
+
+# Callback Function
+def pps_callback(line):
+ print("Updated GPS Object...")
+ global new_data # Use Global to tri... | |
aea73dc4d5484fa8999348d4291978289ca02fe0 | ods/spiders/ecfin_spider.py | ods/spiders/ecfin_spider.py | import urlparse
from ods.items import OdsSheet, DatasetItem, DistributionItem
from ods.spiders import OdsSpider
def flat_text(sel):
"""Return the flat text contained in a selector."""
return " ".join(s.strip() for s in sel.xpath("text()").extract())
class EcfinSurveysSpider(OdsSpider):
name = "ecfin-sur... | Add example spider for DG ECFIN | Add example spider for DG ECFIN
| Python | apache-2.0 | tenforce/ods-scraper,tenforce/ods-scraper | ---
+++
@@ -0,0 +1,33 @@
+import urlparse
+
+from ods.items import OdsSheet, DatasetItem, DistributionItem
+from ods.spiders import OdsSpider
+
+def flat_text(sel):
+ """Return the flat text contained in a selector."""
+ return " ".join(s.strip() for s in sel.xpath("text()").extract())
+
+class EcfinSurveysSpid... | |
d655a1c3e27e637e0970b9fed71875eb63f36a12 | tools/cr/cr/actions/gyp.py | tools/cr/cr/actions/gyp.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to add gyp support to cr."""
import cr
import os
GYP_DEFINE_PREFIX = 'GYP_DEF_'
class GypPrepareOut(cr.PrepareOut):
"""A prepare action that... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A module to add gyp support to cr."""
import cr
import os
GYP_DEFINE_PREFIX = 'GYP_DEF_'
class GypPrepareOut(cr.PrepareOut):
"""A prepare action that... | Fix typo GYP_DEF_target_arch v GPP_DEF_target_arch | Fix typo GYP_DEF_target_arch v GPP_DEF_target_arch
BUG=
Review URL: https://codereview.chromium.org/218623005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@260590 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,Just-D/chromium-1,bright-sparks/chromium-spacewalk,jaruba/chromium.src,ltilve/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,chuan9/... | ---
+++
@@ -15,7 +15,7 @@
ENABLED = cr.Config.From(
GYP_GENERATORS='ninja',
GYP_GENERATOR_FLAGS='output_dir={CR_OUT_BASE} config={CR_BUILDTYPE}',
- GPP_DEF_target_arch='{CR_ENVSETUP_ARCH}',
+ GYP_DEF_target_arch='{CR_ENVSETUP_ARCH}',
)
def Prepare(self): |
01f66f87c52f4ac974876dde9c9fc505193eb16d | verify_all.py | verify_all.py | # Apache License 2.0
import sys
import os
import glob
import verify
class VerifyAll:
def verify_file(self, file, log):
class ErrorCounter:
def __init__(self):
self.count = 0
def error_handler(self, label, msg):
self.count += 1
retur... | Add script to verify all files. | Add script to verify all files.
| Python | apache-2.0 | kryptine/ghilbert,raphlinus/ghilbert,raphlinus/ghilbert,raphlinus/ghilbert,kryptine/ghilbert,raphlinus/ghilbert | ---
+++
@@ -0,0 +1,57 @@
+# Apache License 2.0
+
+import sys
+import os
+import glob
+
+import verify
+
+class VerifyAll:
+
+ def verify_file(self, file, log):
+ class ErrorCounter:
+ def __init__(self):
+ self.count = 0
+ def error_handler(self, label, msg):
+ ... | |
5dd02067e2529a5988dec3dda6f5c14e50bfa890 | tests/overrides_test.py | tests/overrides_test.py | import unittest
from gi.repository import BlockDev
class OverridesTestCase(unittest.TestCase):
def test_error_proxy(self):
"""Verify that the error proxy works as expected"""
# calls via the error proxy has to be done as
# e.g. BlockDev.swap.swapon() instead of BlockDev.swap_swapon(), sinc... | Add the first small test for the ErrorProxy | Add the first small test for the ErrorProxy
Others should follow later, but let's start with this most simple one that
verifies the very basic functionality.
| Python | lgpl-2.1 | vpodzime/libblockdev,atodorov/libblockdev,vpodzime/libblockdev,vpodzime/libblockdev,atodorov/libblockdev,atodorov/libblockdev,rhinstaller/libblockdev,rhinstaller/libblockdev,rhinstaller/libblockdev | ---
+++
@@ -0,0 +1,32 @@
+import unittest
+from gi.repository import BlockDev
+
+class OverridesTestCase(unittest.TestCase):
+ def test_error_proxy(self):
+ """Verify that the error proxy works as expected"""
+
+ # calls via the error proxy has to be done as
+ # e.g. BlockDev.swap.swapon() ins... | |
3c47e583d82911967103f13148f6ece78ded09bb | python/ql/test/library-tests/frameworks/aiohttp/app_conf_test.py | python/ql/test/library-tests/frameworks/aiohttp/app_conf_test.py | """
This file is a test of an extra data-flow step that we want to have for
aiohttp.web.Application
We don't really have an established way to test extra data-flow steps in external
libraries right now, so for now I've just used our normal taint-flow testing ¯\_(ツ)_/¯
see https://docs.aiohttp.org/en/stable/web_advanc... | Add test for missing data-flow step in aiohttp.web | Python: Add test for missing data-flow step in aiohttp.web
| Python | mit | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | ---
+++
@@ -0,0 +1,48 @@
+"""
+This file is a test of an extra data-flow step that we want to have for
+aiohttp.web.Application
+
+We don't really have an established way to test extra data-flow steps in external
+libraries right now, so for now I've just used our normal taint-flow testing ¯\_(ツ)_/¯
+
+see https://do... | |
c6a5b1b54eeb15c173a59d42a2cb7dbfac81b982 | Sketches/JL/IRC/plainPython/parser.py | Sketches/JL/IRC/plainPython/parser.py | #! /usr/bin/env python
def parseRpl(segment):
after_number = segment.find('</a>')
number = segment[after_number-3:after_number]
at_name = segment.find('</td><td class="t">') + len('</td><td class="t">')
after_name = segment.find('</td>', at_name)
if segment[at_name:at_name + 7] == '<a href':
... | Copy of the script used to make the reference IRC numeric_replies file | Copy of the script used to make the reference IRC numeric_replies file | Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia | ---
+++
@@ -0,0 +1,47 @@
+#! /usr/bin/env python
+
+def parseRpl(segment):
+ after_number = segment.find('</a>')
+ number = segment[after_number-3:after_number]
+
+ at_name = segment.find('</td><td class="t">') + len('</td><td class="t">')
+ after_name = segment.find('</td>', at_name)
+ if segment[... | |
8d31f3b6a573759546e7dbc694d9f63647b0cc43 | photutils/segmentation/tests/test_finder.py | photutils/segmentation/tests/test_finder.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the finder module.
"""
from astropy.convolution import Gaussian2DKernel, convolve
from astropy.stats import gaussian_fwhm_to_sigma
import pytest
from ..finder import SourceFinder
from ...datasets import make_100gaussians_image
from ...utils... | Add unit tests for SourceFinder | Add unit tests for SourceFinder
| Python | bsd-3-clause | astropy/photutils,larrybradley/photutils | ---
+++
@@ -0,0 +1,38 @@
+# Licensed under a 3-clause BSD style license - see LICENSE.rst
+"""
+Tests for the finder module.
+"""
+
+from astropy.convolution import Gaussian2DKernel, convolve
+from astropy.stats import gaussian_fwhm_to_sigma
+import pytest
+
+from ..finder import SourceFinder
+from ...datasets import... | |
1753d0b8d04f479ee52673a58863bdc01d3a1df6 | runners/tests/test_models.py | runners/tests/test_models.py | from django.test import TestCase
from runners.models import RunnerVersion, Runner
class TestRunnerVersions(TestCase):
def setUp(self):
self.runner = Runner.objects.create(name='wine')
def test_versions_are_ordered_correctly(self):
RunnerVersion.objects.create(runner=self.runner, version='1.9.... | Add tests for version sorting | Add tests for version sorting
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website | ---
+++
@@ -0,0 +1,24 @@
+from django.test import TestCase
+from runners.models import RunnerVersion, Runner
+
+
+class TestRunnerVersions(TestCase):
+ def setUp(self):
+ self.runner = Runner.objects.create(name='wine')
+
+ def test_versions_are_ordered_correctly(self):
+ RunnerVersion.objects.cre... | |
fc586c2571328f1591bb396b9e9e7dcb0730b610 | src/core/migrations/0049_fix_review_accept_acknowledgement_url.py | src/core/migrations/0049_fix_review_accept_acknowledgement_url.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-12-17 10:48
from __future__ import unicode_literals
import re
from django.db import migrations
FROM_RE = re.compile("{{ ?do_review_url ?}}")
TO = "{{ review_url }}"
def replace_setting_urls(apps, schema_editor):
SettingValueTranslation = apps.get_mod... | Fix wrong URL name in review_accept_acknowledgement | Fix wrong URL name in review_accept_acknowledgement
| Python | agpl-3.0 | BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway | ---
+++
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.29 on 2020-12-17 10:48
+from __future__ import unicode_literals
+import re
+
+from django.db import migrations
+
+FROM_RE = re.compile("{{ ?do_review_url ?}}")
+TO = "{{ review_url }}"
+
+
+def replace_setting_urls(apps, schema_editor):
+ ... | |
8ef2fce934e38e135898b707a1491edf56d675ac | salt/client/raet/__init__.py | salt/client/raet/__init__.py | # -*- coding: utf-8 -*-
'''
The client libs to communicate with the salt master when running raet
'''
# Import python libs
import os
import time
import logging
# Import Salt libs
from salt.transport.road.raet import stacking
from salt.transport.road.raet import yarding
import salt.config
import salt.client
import sal... | Add raet LocalClient - just starting | Add raet LocalClient - just starting
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+'''
+The client libs to communicate with the salt master when running raet
+'''
+
+# Import python libs
+import os
+import time
+import logging
+
+# Import Salt libs
+from salt.transport.road.raet import stacking
+from salt.transport.road.raet import yarding
+import ... | |
468d5cc051d01f4440d6f4e5f85bad771994f8de | project/velkoja/management/commands/check_nordea_overdue.py | project/velkoja/management/commands/check_nordea_overdue.py | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from velkoja.nordeachecker import NordeaOverdueInvoicesHandler
class Command(BaseCommand):
help = 'Check overdue Nordea payments and send emails about them'
def add_arguments(self, parser):
pass
def handle(... | Add management command to run the checks | Add management command to run the checks
| Python | mit | HelsinkiHacklab/asylum,rambo/asylum,rambo/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum | ---
+++
@@ -0,0 +1,17 @@
+# -*- coding: utf-8 -*-
+from django.core.management.base import BaseCommand, CommandError
+from velkoja.nordeachecker import NordeaOverdueInvoicesHandler
+
+
+class Command(BaseCommand):
+ help = 'Check overdue Nordea payments and send emails about them'
+
+ def add_arguments(self, pa... | |
8f15649c42b858cef4df3cbd16fb3d207df3aaef | script/upload-test-images.py | script/upload-test-images.py | import girder_client
import os
import sys
def main():
# Use the API key to authenticate.
key = os.environ.get("GIRDER_API_KEY")
if key is None:
print >>sys.stderr, "Environment variable GIRDER_API_KEY is blank. Cannot upload images."
return 1
gc = girder_client.GirderClient(host="data... | Add script to upload images to Girder | Add script to upload images to Girder
| Python | apache-2.0 | Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela | ---
+++
@@ -0,0 +1,42 @@
+import girder_client
+import os
+import sys
+
+
+def main():
+ # Use the API key to authenticate.
+ key = os.environ.get("GIRDER_API_KEY")
+ if key is None:
+ print >>sys.stderr, "Environment variable GIRDER_API_KEY is blank. Cannot upload images."
+ return 1
+
+ gc... | |
91b3e6f4a53330b27941497e10542b99ed27b94c | python/partition-dataset.py | python/partition-dataset.py |
import pandas as pd
import operator
df = pd.read_csv('../datasets/movielens-synthesized/ratings-synthesized-1m.csv')
counts = {}
user_ratings = df.groupby('user')
for k, df in user_ratings:
# do something with group
counts[k] = df['user'].count()
print "num users", len(counts)
sorted_x = sorted(counts.it... | Add script to partition movielens dataset into a more dense selection. | WIP: Add script to partition movielens dataset into a more dense selection.
| Python | mit | ntnu-smartmedia/goldfish,monsendag/goldfish,ntnu-smartmedia/goldfish,monsendag/goldfish,ntnu-smartmedia/goldfish,monsendag/goldfish | ---
+++
@@ -0,0 +1,26 @@
+
+import pandas as pd
+import operator
+df = pd.read_csv('../datasets/movielens-synthesized/ratings-synthesized-1m.csv')
+
+
+counts = {}
+user_ratings = df.groupby('user')
+
+
+for k, df in user_ratings:
+ # do something with group
+ counts[k] = df['user'].count()
+
+print "num users"... | |
c7dc0a027d587f3c194c29f85f4a75db9bc2a44c | tests/rules_tests/grammarManipulation_tests/GetTest.py | tests/rules_tests/grammarManipulation_tests/GetTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule as _R, Grammar
from rules_tests.grammar import *
class GetTest(TestCase):
def __init__(self, *args):
super().__init__(*args)
... | Add tests of rule's get methods | Add tests of rule's get methods
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+"""
+:Author Patrik Valkovic
+:Created 23.06.2017 16:39
+:Licence GNUv3
+Part of grammpy
+
+"""
+
+from unittest import main, TestCase
+
+from grammpy import Rule as _R, Grammar
+from rules_tests.grammar import *
+
+
+class GetTest(TestCase):
+ def __init__(self, *a... | |
ad7c3675f4e6f6b1e083f1308307498bff285e89 | director/projects/migrations/0004_auto_20180723_1708.py | director/projects/migrations/0004_auto_20180723_1708.py | # Generated by Django 2.0.7 on 2018-07-23 17:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0003_auto_20180723_0245'),
]
operations = [
migrations.AlterUniqueTogether(
name='filesprojectfile',
unique_toge... | Add migration for altering unique_together | Add migration for altering unique_together
| Python | apache-2.0 | stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub | ---
+++
@@ -0,0 +1,17 @@
+# Generated by Django 2.0.7 on 2018-07-23 17:08
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('projects', '0003_auto_20180723_0245'),
+ ]
+
+ operations = [
+ migrations.AlterUniqueTogether(
+ name='f... | |
b9ce512cb88cb5fddb4561d2edaaf20c715c5d94 | tests/rules_tests/clearAfterNonTermRemove/WithEpsilonTest.py | tests/rules_tests/clearAfterNonTermRemove/WithEpsilonTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 19.08.2017 17:05
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import *
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class Rules(Rule):
rules = [
([A], [B, C]),
([A... | Add test of rule with epsilon | Add test of rule with epsilon
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+"""
+:Author Patrik Valkovic
+:Created 19.08.2017 17:05
+:Licence GNUv3
+Part of grammpy
+
+"""
+
+from unittest import TestCase, main
+from grammpy import *
+
+class A(Nonterminal): pass
+class B(Nonterminal): pass
+class C(Nonterminal): pass
+class Rules(Rule):
+ ... | |
3883775d12769a25a0bea5017741c53af14e20ab | sites/sandbox/apps/offers.py | sites/sandbox/apps/offers.py | from oscar.apps.offer import models
class ChangesOwnerName(models.Benefit):
class Meta:
proxy = True
def apply(self, basket, condition, offer=None):
condition.consume_items(basket, ())
return models.PostOrderAction(
"You will have your name changed to Barry!")
def ap... | from oscar.apps.offer import models
class ChangesOwnerName(models.Benefit):
class Meta:
proxy = True
def apply(self, basket, condition, offer=None):
condition.consume_items(offer, basket, ())
return models.PostOrderAction(
"You will have your name changed to Barry!")
... | Correct consume_items call for sandbox offer | Correct consume_items call for sandbox offer
| Python | bsd-3-clause | faratro/django-oscar,jmt4/django-oscar,elliotthill/django-oscar,lijoantony/django-oscar,QLGu/django-oscar,dongguangming/django-oscar,pasqualguerrero/django-oscar,nickpack/django-oscar,anentropic/django-oscar,WillisXChen/django-oscar,pdonadeo/django-oscar,spartonia/django-oscar,binarydud/django-oscar,binarydud/django-os... | ---
+++
@@ -7,7 +7,7 @@
proxy = True
def apply(self, basket, condition, offer=None):
- condition.consume_items(basket, ())
+ condition.consume_items(offer, basket, ())
return models.PostOrderAction(
"You will have your name changed to Barry!")
|
3d3ec162988ae93a3abd95ae32d855d6f3169fe5 | src/collectors/UPSCollector/UPSCollector.py | src/collectors/UPSCollector/UPSCollector.py | from diamond import *
import diamond.collector
import subprocess
class UPSCollector(diamond.collector.Collector):
"""
This class collects data from NUT, a UPS interface for linux.
Requires: nut/upsc to be installed, configured and running.
"""
def get_default_config(self):
"""
Re... | Add a collector to collect from 'NUT', the UPS daemon for Linux. | Add a collector to collect from 'NUT', the UPS daemon for Linux.
| Python | mit | EzyInsights/Diamond,stuartbfox/Diamond,jumping/Diamond,TAKEALOT/Diamond,jumping/Diamond,tuenti/Diamond,Ssawa/Diamond,krbaker/Diamond,acquia/Diamond,datafiniti/Diamond,stuartbfox/Diamond,TAKEALOT/Diamond,EzyInsights/Diamond,zoidbergwill/Diamond,Basis/Diamond,hvnsweeting/Diamond,works-mobile/Diamond,dcsquared13/Diamond,c... | ---
+++
@@ -0,0 +1,42 @@
+from diamond import *
+import diamond.collector
+
+import subprocess
+
+class UPSCollector(diamond.collector.Collector):
+ """
+ This class collects data from NUT, a UPS interface for linux.
+
+ Requires: nut/upsc to be installed, configured and running.
+ """
+
+ def get_defa... | |
115e280a00bbd64a97315c27c183756b2220790a | scripts/Reader_RDM6300.py | scripts/Reader_RDM6300.py | """
Support for the RDM6300 serial RFID module
1.) Connect the RDM6300 module
------------------------------
Connect the RDM6300 module to the serial GPIO pins 14 and 15.
2.) Enable GPIO serial port
---------------------------
Edit the /boot/config.txt (sudo nano /boot/config.txt) and add the following line:
enab... | Support for the RDM6300 serial RFID module | Support for the RDM6300 serial RFID module
Support for the RDM6300 serial RFID module
1.) Connect the RDM6300 module
------------------------------
Connect the RDM6300 module to the serial GPIO pins 14 and 15.
2.) Enable GPIO serial port
---------------------------
Edit the /boot/config.txt (sudo nano /boot/... | Python | mit | MiczFlor/RPi-Jukebox-RFID,MiczFlor/RPi-Jukebox-RFID,MiczFlor/RPi-Jukebox-RFID,MiczFlor/RPi-Jukebox-RFID,MiczFlor/RPi-Jukebox-RFID | ---
+++
@@ -0,0 +1,44 @@
+"""
+Support for the RDM6300 serial RFID module
+
+1.) Connect the RDM6300 module
+------------------------------
+Connect the RDM6300 module to the serial GPIO pins 14 and 15.
+
+2.) Enable GPIO serial port
+---------------------------
+Edit the /boot/config.txt (sudo nano /boot/config.txt)... | |
e382e25f47533fad12583e5a7e1213381a92751b | CsvToSepaDD.py | CsvToSepaDD.py | #!/usr/bin/env python
import argparse
import pprint
DEFAULT_CONFIG_FILE_NAME = 'CsvToSepaDD.config'
DEFAULT_CURRENCY = 'EUR'
def csvToSepa(args):
'''
[TODO] Converts the SEPA direct debit data from a given CSV file to SEPA XML
'''
pass
def createConfig(args):
'''Interactively creates a con... | Add a first draft for the user interface | Add a first draft for the user interface
| Python | bsd-3-clause | mfiedler/CsvToSepaDD | ---
+++
@@ -0,0 +1,67 @@
+#!/usr/bin/env python
+
+import argparse
+import pprint
+
+
+DEFAULT_CONFIG_FILE_NAME = 'CsvToSepaDD.config'
+DEFAULT_CURRENCY = 'EUR'
+
+
+
+def csvToSepa(args):
+ '''
+ [TODO] Converts the SEPA direct debit data from a given CSV file to SEPA XML
+ '''
+ pass
+
+
+
+
+def create... | |
573878b5609fb6badae40e4a1bdef944b9d340dc | tools/telemetry/telemetry/core/platform/profiler/android_screen_recorder_profiler.py | tools/telemetry/telemetry/core/platform/profiler/android_screen_recorder_profiler.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core import util
from telemetry.core.backends.chrome import android_browser_finder
from telemetry.core.platform i... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
from telemetry.core import util
from telemetry.core.backends.chrome import android_browser_finder
from telemetry.core.platform i... | Fix screen recording with multiple connected devices | telemetry: Fix screen recording with multiple connected devices
Make it possible to use the Android screen recording profiler with
multiple connected devices. Only the screen on the device that is
actually running the telemetry test will get recorded.
BUG=331435
TEST=tools/perf/run_benchmark smoothness.key_mobile_sit... | Python | bsd-3-clause | markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromi... | ---
+++
@@ -18,8 +18,11 @@
self._output_path = output_path + '.mp4'
self._recorder = subprocess.Popen(
[os.path.join(util.GetChromiumSrcDir(), 'build', 'android',
- 'screenshot.py'), '--video', '--file',
- self._output_path], stdin=subprocess.PIPE, stdout=subprocess.PIP... |
301169a141b56a1a74b0c668e2b33083d593acdd | app/models/baseModel.py | app/models/baseModel.py | from app import db
class BaseModel(db.Model):
''' A model detailing the base properties to be inherited '''
__abstract__ = True
id = db.Column(db.Integer, primary_key=True)
date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
date_modified = db.Column(
db.DateTime, de... | Add Base Model This model is to be used by other model classes to inherit some traits | Add Base Model
This model is to be used by other model classes to inherit some traits
| Python | mit | Elbertbiggs360/buckelist-api | ---
+++
@@ -0,0 +1,29 @@
+from app import db
+
+
+class BaseModel(db.Model):
+ ''' A model detailing the base properties to be inherited '''
+ __abstract__ = True
+ id = db.Column(db.Integer, primary_key=True)
+ date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
+ date_modified ... | |
cf3c624d5f5224c22f018c683dfc12bdc7b2a348 | rename_file.py | rename_file.py | import sublime
import sublime_plugin
import os
import functools
class RenameFileCommand(sublime_plugin.WindowCommand):
def run(self, paths):
if paths[0] == "$file":
paths[0] = self.window.active_view().file_name()
branch, leaf = os.path.split(paths[0])
v = self.window.show_inpu... | Add Initial version of plugin. | Add Initial version of plugin.
| Python | mit | ishu3101/RenameFile | ---
+++
@@ -0,0 +1,31 @@
+import sublime
+import sublime_plugin
+import os
+import functools
+
+
+class RenameFileCommand(sublime_plugin.WindowCommand):
+ def run(self, paths):
+ if paths[0] == "$file":
+ paths[0] = self.window.active_view().file_name()
+ branch, leaf = os.path.split(paths... | |
219b600773f6bf93b2fc61edc837fa3e1af086dd | tools/let2def.py | tools/let2def.py | #!/usr/bin/env python3
#
# Usage: let2def.py prog.fut
#
# Replaces top-level 'let's with 'def'.
from subprocess import check_output
import sys
import re
import os
prog = sys.argv[1]
out = check_output(["futhark", "defs", prog]).decode('utf-8')
funlocs = set()
for line in out.split('\n'):
m = re.match('value [^ ]... | Add tool for converting "let" to "def". | Add tool for converting "let" to "def".
| Python | isc | HIPERFIT/futhark,HIPERFIT/futhark,diku-dk/futhark,HIPERFIT/futhark,diku-dk/futhark,diku-dk/futhark,diku-dk/futhark,diku-dk/futhark | ---
+++
@@ -0,0 +1,42 @@
+#!/usr/bin/env python3
+#
+# Usage: let2def.py prog.fut
+#
+# Replaces top-level 'let's with 'def'.
+
+from subprocess import check_output
+import sys
+import re
+import os
+
+prog = sys.argv[1]
+out = check_output(["futhark", "defs", prog]).decode('utf-8')
+
+funlocs = set()
+for line in ou... | |
a3a70348fb8eed7e63f68ea67246bf85c4eb0097 | sal/urls.py | sal/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^login/$', 'django.contrib.auth... | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^login/$', 'django.contrib.auth... | Update password functions for Django 1.8 | Update password functions for Django 1.8
| Python | apache-2.0 | chasetb/sal,chasetb/sal,macjustice/sal,sheagcraig/sal,erikng/sal,erikng/sal,chasetb/sal,salopensource/sal,macjustice/sal,salopensource/sal,macjustice/sal,sheagcraig/sal,erikng/sal,salopensource/sal,chasetb/sal,sheagcraig/sal,macjustice/sal,erikng/sal,sheagcraig/sal,salopensource/sal | ---
+++
@@ -10,8 +10,8 @@
# Examples:
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', 'django.contrib.auth.views.logout_then_login'),
- url(r'^changepassword/$', 'django.contrib.auth.views.password_change'),
- url(r'^changepassword/done/$', 'django.contrib.auth.views.passwo... |
c535c2d4bfd231b5999b3a974b24a91a76325300 | utils/metrics.py | utils/metrics.py | """Metrics to compute the model performance."""
import numpy as np
def dcg_score(y_true, y_pred, k=5):
"""Discounted Cumulative Gain (DCG) at rank K.
Parameters
----------
y_true : 1d array-like, shape = [n_samples]
Ground truth (correct) labels.
y_pred : 2d array-like, shape = [n_sample... | Add functions to measure performance | Add functions to measure performance
| Python | mit | davidgasquez/kaggle-airbnb | ---
+++
@@ -0,0 +1,69 @@
+"""Metrics to compute the model performance."""
+
+import numpy as np
+
+
+def dcg_score(y_true, y_pred, k=5):
+ """Discounted Cumulative Gain (DCG) at rank K.
+
+ Parameters
+ ----------
+ y_true : 1d array-like, shape = [n_samples]
+ Ground truth (correct) labels.
+ y... | |
b390a4381d7c495f1fad91248194799f3325c3d5 | billjobs/serializers.py | billjobs/serializers.py | from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
| Add serializer for User model | Add serializer for User model
| Python | mit | ioO/billjobs | ---
+++
@@ -0,0 +1,9 @@
+from django.contrib.auth.models import User, Group
+from rest_framework import serializers
+
+
+class UserSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = User
+ fields = ('url', 'username', 'email', 'groups')
+ | |
db863be10cca5d43e37cace88fd2a500f6ee96f8 | rest_framework/authtoken/admin.py | rest_framework/authtoken/admin.py | from django.contrib import admin
from .models import Token
class TokenAdmin(admin.ModelAdmin):
list_display = ('key', 'user', 'created')
fields = ('user',)
ordering = ('-created',)
admin.site.register(Token, TokenAdmin)
| Add an ModelAdmin for easy management of Tokens | Add an ModelAdmin for easy management of Tokens
| Python | bsd-2-clause | simudream/django-rest-framework,xiaotangyuan/django-rest-framework,xiaotangyuan/django-rest-framework,wangpanjun/django-rest-framework,arpheno/django-rest-framework,antonyc/django-rest-framework,raphaelmerx/django-rest-framework,mgaitan/django-rest-framework,d0ugal/django-rest-framework,davesque/django-rest-framework,b... | ---
+++
@@ -0,0 +1,11 @@
+from django.contrib import admin
+from .models import Token
+
+
+class TokenAdmin(admin.ModelAdmin):
+ list_display = ('key', 'user', 'created')
+ fields = ('user',)
+ ordering = ('-created',)
+
+
+admin.site.register(Token, TokenAdmin) | |
7bf0ba89a74b555555e43c0a38780d8f5fe69fcf | host/greatfet/boards/one.py | host/greatfet/boards/one.py | #
# Copyright (c) 2016 Kyle J. Temkin <kyle@ktemkin.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this li... | Rename Azalea to GreatFET One | Rename Azalea to GreatFET One
| Python | bsd-3-clause | dominicgs/GreatFET-experimental,dominicgs/GreatFET-experimental,dominicgs/GreatFET-experimental,greatscottgadgets/greatfet,greatscottgadgets/greatfet,greatscottgadgets/greatfet,greatscottgadgets/greatfet | ---
+++
@@ -0,0 +1,57 @@
+#
+# Copyright (c) 2016 Kyle J. Temkin <kyle@ktemkin.com>
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the a... | |
530d1d75872df47a1dbd90b2b6cfd5ebac0fe4c8 | badgecheck/server/app.py | badgecheck/server/app.py | from flask import Flask, redirect, render_template, request
import json
import six
from badgecheck.verifier import verify
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024 # 4mb file upload limit
@app.route("/")
def home():
return render_template('index.html')
@app.route("/results", m... | from flask import Flask, redirect, render_template, request
import json
import six
from badgecheck.verifier import verify
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024 # 4mb file upload limit
def request_wants_json():
best = request.accept_mimetypes.best_match(['application/json', '... | Establish basic JSON API capability. | Establish basic JSON API capability.
| Python | apache-2.0 | concentricsky/badgecheck,openbadges/badgecheck,IMSGlobal/openbadges-validator-core,IMSGlobal/openbadges-validator-core,concentricsky/badgecheck,openbadges/badgecheck | ---
+++
@@ -9,9 +9,19 @@
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024 # 4mb file upload limit
+def request_wants_json():
+ best = request.accept_mimetypes.best_match(['application/json', 'text/html'])
+ return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['... |
82140baa69ff88c329ad500224d6dfa605867536 | tests/smtp.py | tests/smtp.py | import smtplib
import sys
from email import mime
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
msg = mime.multipart.MIMEMultipart()
msg['Subject'] = 'Test email'
msg['From'] = sys.argv[1]
msg['To'] = sys.argv[2]
msg.preamble = 'Test email'
s = smtplib.SMTP('localhost')
s.set_d... | Add a very simple test script for sending mails | Add a very simple test script for sending mails
| Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io | ---
+++
@@ -0,0 +1,17 @@
+import smtplib
+import sys
+from email import mime
+
+from email.mime.image import MIMEImage
+from email.mime.multipart import MIMEMultipart
+
+msg = mime.multipart.MIMEMultipart()
+msg['Subject'] = 'Test email'
+msg['From'] = sys.argv[1]
+msg['To'] = sys.argv[2]
+msg.preamble = 'Test email'... | |
5ae10de8c33b3388c0e593187be9fb62ac1f2c2c | django/setup.py | django/setup.py | import subprocess
import sys
import setup_util
import os
from os.path import expanduser
home = expanduser("~")
def start(args):
setup_util.replace_text("django/hello/hello/settings.py", "HOST': '.*'", "HOST': '" + args.database_host + "'")
setup_util.replace_text("django/hello/hello/settings.py", "\/home\/ubuntu"... | import subprocess
import sys
import setup_util
import os
from os.path import expanduser
home = expanduser("~")
def start(args):
setup_util.replace_text("django/hello/hello/settings.py", "HOST': '.*'", "HOST': '" + args.database_host + "'")
setup_util.replace_text("django/hello/hello/settings.py", "\/home\/ubuntu"... | Use more gunicorn threads when pooling database connector isn't available. | Use more gunicorn threads when pooling database connector isn't available.
When using postgres with meinheld, the best you can do so far (as far as I know) is up the number of threads. | Python | bsd-3-clause | jetty-project/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,testn/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,grob/FrameworkBenchmarks... | ---
+++
@@ -9,6 +9,10 @@
def start(args):
setup_util.replace_text("django/hello/hello/settings.py", "HOST': '.*'", "HOST': '" + args.database_host + "'")
setup_util.replace_text("django/hello/hello/settings.py", "\/home\/ubuntu", home)
+ # because pooling doesn't work with meinheld, it's necessary to create ... |
53fbe6bed16fb4cddb0ffb533b8d1632ed209c5c | corehq/motech/fhir/tests/test_smart_metadata_endpoints.py | corehq/motech/fhir/tests/test_smart_metadata_endpoints.py | import json
from django.test import TestCase
from django.test.client import Client
from django.urls import reverse
from corehq.motech.fhir.models import build_capability_statement
from corehq.util.test_utils import flag_enabled
from corehq.util.view_utils import absolute_reverse
class TestConfigurationView(TestCase... | Add smart metadata endpoint tests | Add smart metadata endpoint tests
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,64 @@
+import json
+
+from django.test import TestCase
+from django.test.client import Client
+from django.urls import reverse
+
+from corehq.motech.fhir.models import build_capability_statement
+from corehq.util.test_utils import flag_enabled
+from corehq.util.view_utils import absolute_reverse
+
... | |
93eb8e085854996e28982fad67915810328f8dc8 | examples/adjacency_list.py | examples/adjacency_list.py | from collections import deque
from peewee import *
db = SqliteDatabase(':memory:')
class TreeNode(Model):
parent = ForeignKeyField('self', backref='children', null=True)
name = TextField()
class Meta:
database = db
def __str__(self):
return 'name=%s' % self.name
def dump(self,... | Add adjacency list example. Compare to SQA's. | Add adjacency list example. Compare to SQA's.
[skip ci]
| Python | mit | coleifer/peewee,coleifer/peewee,coleifer/peewee | ---
+++
@@ -0,0 +1,54 @@
+from collections import deque
+from peewee import *
+
+
+db = SqliteDatabase(':memory:')
+
+
+class TreeNode(Model):
+ parent = ForeignKeyField('self', backref='children', null=True)
+ name = TextField()
+
+ class Meta:
+ database = db
+
+ def __str__(self):
+ retur... | |
bd928bc44bc5a357fea6d2184549f33ea244f744 | manoseimas/mps_v2/migrations/0007_auto_20150605_0930.py | manoseimas/mps_v2/migrations/0007_auto_20150605_0930.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mps_v2', '0006_auto_20150604_1500'),
]
operations = [
migrations.AlterField(
model_name='parliamentmember',
... | Add related name to MP <-> group relationship. | Add related name to MP <-> group relationship.
| Python | agpl-3.0 | ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt | ---
+++
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('mps_v2', '0006_auto_20150604_1500'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ ... | |
45e714e69495f7bc3d93ce88e7a4e0a7bba4b39a | migrations/versions/0233_updated_first_class_dates.py | migrations/versions/0233_updated_first_class_dates.py | """empty message
Revision ID: 0233_updated_first_class_dates
Revises: 0230_noti_postage_constraint_3
"""
revision = '0233_updated_first_class_dates'
down_revision = '0230_noti_postage_constraint_3'
from datetime import datetime
from alembic import op
from sqlalchemy.sql import text
START_DATE = datetime(2018, 8, ... | Update first class letter rate start dates | Update first class letter rate start dates
We want to bring the start dates for first class letter rates forward by
a month so that we don't see billing errors when sending first class letters now.
(The feature will still go live at the planned time - this is to let us test things
beforehand.)
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -0,0 +1,30 @@
+"""empty message
+
+Revision ID: 0233_updated_first_class_dates
+Revises: 0230_noti_postage_constraint_3
+
+"""
+
+revision = '0233_updated_first_class_dates'
+down_revision = '0230_noti_postage_constraint_3'
+
+from datetime import datetime
+from alembic import op
+from sqlalchemy.sql impor... | |
734333e1bdcbe6077b38e471000746d4566a39cb | temba/msgs/migrations/0087_populate_broadcast_send_all.py | temba/msgs/migrations/0087_populate_broadcast_send_all.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-06 17:33
from __future__ import unicode_literals
from django.db import migrations
from temba.utils import chunk_list
def do_populate_send_all(Broadcast):
broadcast_ids = Broadcast.objects.all().values_list('id', flat=True)
for chunk in chunk_li... | Add data migrations to populate broadcast send all field | Add data migrations to populate broadcast send all field
| Python | agpl-3.0 | pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro,pulilab/rapidpro | ---
+++
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.6 on 2017-04-06 17:33
+from __future__ import unicode_literals
+
+from django.db import migrations
+from temba.utils import chunk_list
+
+
+def do_populate_send_all(Broadcast):
+ broadcast_ids = Broadcast.objects.all().values_list('id', ... | |
64a59a2c9014e57039af1f8362bbf3fcba19aa42 | teami18n/teami18n/management/commands/import_country_data.py | teami18n/teami18n/management/commands/import_country_data.py | from datetime import date
from django.core.management import BaseCommand
import wbpy
from teami18n.models import Country
class Command(BaseCommand):
help = 'Import Country Data'
def handle(self, *args, **options):
def get_population(country_code):
current_date = date.today()
... | Add command to import countries population | Add command to import countries population
| Python | mit | team-i18n/hackaway,team-i18n/hackaway,team-i18n/hackaway | ---
+++
@@ -0,0 +1,32 @@
+from datetime import date
+
+from django.core.management import BaseCommand
+
+import wbpy
+
+from teami18n.models import Country
+
+
+class Command(BaseCommand):
+ help = 'Import Country Data'
+
+ def handle(self, *args, **options):
+
+ def get_population(country_code):
+ ... | |
e4612e9c7cb61906a2f32a6a227f9ecec3a73957 | bin/escape_key.py | bin/escape_key.py | #!/usr/bin/env python
#
# Change caps lock to escape on built in keyboards
#
# https://github.com/tekezo/Seil/issues/68#issuecomment-229260237
# Must be run with sudo, SIP must be disabled, requires restart
#
from xml.etree import ElementTree
import argparse
import os
import subprocess
# Find this product and the ven... | Add script for changing caps lock to escape | Add script for changing caps lock to escape
| Python | mit | keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles,keith/dotfiles | ---
+++
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+#
+# Change caps lock to escape on built in keyboards
+#
+# https://github.com/tekezo/Seil/issues/68#issuecomment-229260237
+# Must be run with sudo, SIP must be disabled, requires restart
+#
+
+from xml.etree import ElementTree
+import argparse
+import os
+import subp... | |
4284afb497dae4923a856785d17b4b6d145fc48a | virtualfish/test/test_addpath.py | virtualfish/test/test_addpath.py | import sys
def test_addpath(vf):
venv = f"{vf.homedir}/.virtualenvs/test"
vf.run("vf new test")
vf.run("vf activate test")
vf.run(f"mkdir {venv}/testpath")
vf.run(f"vf addpath {venv}/testpath")
out, _ = vf.run(f"{venv}/bin/python -c 'import sys; print(sys.path)'")
assert ".virtualenvs/test... | Add test for `vf addpath <path>` | Add test for `vf addpath <path>`
| Python | mit | adambrenecki/virtualfish,adambrenecki/virtualfish | ---
+++
@@ -0,0 +1,11 @@
+import sys
+
+
+def test_addpath(vf):
+ venv = f"{vf.homedir}/.virtualenvs/test"
+ vf.run("vf new test")
+ vf.run("vf activate test")
+ vf.run(f"mkdir {venv}/testpath")
+ vf.run(f"vf addpath {venv}/testpath")
+ out, _ = vf.run(f"{venv}/bin/python -c 'import sys; print(sys.p... | |
bcb03670ac1a561899f98c22635092dc5be11770 | tests/test_permissions.py | tests/test_permissions.py | import nose
import angr
import logging
l = logging.getLogger("angr_tests")
import os
test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
private_test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries-private/'))
def test_nx():
... | Add simple testcase for page permissions | Add simple testcase for page permissions
| Python | bsd-2-clause | iamahuman/angr,tyb0807/angr,axt/angr,f-prettyland/angr,angr/angr,tyb0807/angr,angr/angr,axt/angr,schieb/angr,f-prettyland/angr,chubbymaggie/angr,haylesr/angr,schieb/angr,chubbymaggie/angr,iamahuman/angr,angr/angr,iamahuman/angr,tyb0807/angr,axt/angr,schieb/angr,chubbymaggie/angr,f-prettyland/angr,haylesr/angr | ---
+++
@@ -0,0 +1,39 @@
+import nose
+import angr
+
+import logging
+l = logging.getLogger("angr_tests")
+
+import os
+test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries/tests'))
+private_test_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../b... | |
f4a28ea7d513dc3a52758966fcc2682e23b05b4c | lp-build-juju-snap.py | lp-build-juju-snap.py | #! /usr/bin/python
import os
import time
from datetime import datetime
from launchpadlib.launchpad import Launchpad
# basic data
arches = ['amd64', 'arm64', 'ppc64el']
series = 'xenial'
# basic paths
home = os.getenv("HOME")
workdir = os.path.join(home, "juju-daily-snap")
# we need to store credentials once for cr... | Add existin lp build juju snap script | Add existin lp build juju snap script
| Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | ---
+++
@@ -0,0 +1,84 @@
+#! /usr/bin/python
+
+import os
+import time
+
+from datetime import datetime
+from launchpadlib.launchpad import Launchpad
+
+# basic data
+arches = ['amd64', 'arm64', 'ppc64el']
+series = 'xenial'
+
+# basic paths
+home = os.getenv("HOME")
+workdir = os.path.join(home, "juju-daily-snap")
+... | |
97e6f41ba5eef2a5c2f5dc0d25b7556ccc95351f | nodeconductor/logging/migrations/0002_alter_alert_severity_field.py | nodeconductor/logging/migrations/0002_alter_alert_severity_field.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('logging', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='alert',
name='severit... | Add migration for alert severity field (nc-553) | Add migration for alert severity field (nc-553)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('logging', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ mod... | |
2337f61b9da2368dd7847e8f8f727e96cd1150b3 | cw_controller.py | cw_controller.py | import restapi
# Class for /company/companies
import connectpyse
class CWController(restapi.Client):
def __init__(self):
self.module_url = ''
super().__init__('{}/{}'.format(connectpyse.API_URL, self.module_url))
def get_companies(self, user_params={}):
json_results = sel... | Add controller super class draft via upload | Add controller super class draft via upload | Python | mit | joshuamsmith/ConnectPyse | ---
+++
@@ -0,0 +1,39 @@
+import restapi
+# Class for /company/companies
+import connectpyse
+
+
+class CWController(restapi.Client):
+
+ def __init__(self):
+ self.module_url = ''
+ super().__init__('{}/{}'.format(connectpyse.API_URL, self.module_url))
+
+ def get_companies(self, user_params={}):... | |
4a41397aefcee66d5d4d06b44f94d1337a154d98 | ynr/apps/popolo/migrations/0035_attach_memberships_to_posts.py | ynr/apps/popolo/migrations/0035_attach_memberships_to_posts.py | # Generated by Django 2.2.9 on 2020-01-27 21:19
from django.db import migrations
def attach_memberships_to_posts(apps, schema_editor):
Membership = apps.get_model("popolo", "Membership")
for membership in Membership.objects.all():
if membership.post != membership.ballot.post:
membership.p... | Set all membership.post objects to membership.ballot.post | Set all membership.post objects to membership.ballot.post
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -0,0 +1,22 @@
+# Generated by Django 2.2.9 on 2020-01-27 21:19
+
+from django.db import migrations
+
+
+def attach_memberships_to_posts(apps, schema_editor):
+ Membership = apps.get_model("popolo", "Membership")
+ for membership in Membership.objects.all():
+ if membership.post != membership.b... | |
2a4b9c1b7628ab7088c01f6590b31d1c8c9a5958 | Classification/trump_plot.py | Classification/trump_plot.py |
import sys, os
foo_dir = os.path.dirname(os.path.join(os.getcwd(), __file__))
sys.path.append(os.path.normpath(os.path.join(foo_dir, '../DataGathering', '..')))
sys.path.append(os.path.normpath(os.path.join(foo_dir, '../Classification', '..')))
sys.path.append(os.path.normpath(os.path.join(foo_dir, '../TextCleaning', ... | Add script to plot insights from Trump’s tweets | Add script to plot insights from Trump’s tweets
| Python | mit | steinnp/Big-Data-Final | ---
+++
@@ -0,0 +1,81 @@
+
+import sys, os
+foo_dir = os.path.dirname(os.path.join(os.getcwd(), __file__))
+sys.path.append(os.path.normpath(os.path.join(foo_dir, '../DataGathering', '..')))
+sys.path.append(os.path.normpath(os.path.join(foo_dir, '../Classification', '..')))
+sys.path.append(os.path.normpath(os.path.... | |
2f83109cf85d74ecd5da5a849cc165e723f8e5fd | CreateObject.py | CreateObject.py | for key, value in request.data.iteritems():
if value is None:
print key
if getattr(ExistingBooking, key) is not None:
value = getattr(ExistingBooking, key)
print 'VALUE::',value
setattr(Bookingupdate, key, value)
Bookingupdate.save()
| Create Python objects using getattr and setattr | Create Python objects using getattr and setattr
This can be used for django models with copious fields | Python | mit | gladsonvm/snippets | ---
+++
@@ -0,0 +1,8 @@
+for key, value in request.data.iteritems():
+ if value is None:
+ print key
+ if getattr(ExistingBooking, key) is not None:
+ value = getattr(ExistingBooking, key)
+ print 'VALUE::',value
+ setattr(Bookingupdate, key, value)
+Bookingupdate.save() | |
4630a1410f4a31865a7293eae67c7f10e06fba67 | annocfg.py | annocfg.py |
class AnnotatedCFG(object):
def __init__(self):
pass
def should_take_exit(self, addr_from, addr_to):
return False
def should_execute_statement(self, addr):
return False
def get_run(self, addr):
return None
def get_whitelisted_statement(self, addr):
return []
| Add the skeleton of AnnotatedCFG class. | Add the skeleton of AnnotatedCFG class.
| Python | bsd-2-clause | zhuyue1314/angr,cureHsu/angr,tyb0807/angr,iamahuman/angr,iamahuman/angr,mingderwang/angr,haylesr/angr,GuardianRG/angr,lowks/angr,axt/angr,chubbymaggie/angr,avain/angr,fjferrer/angr,avain/angr,angr/angr,terry2012/angr,angr/angr,f-prettyland/angr,iamahuman/angr,f-prettyland/angr,lowks/angr,xurantju/angr,cureHsu/angr,chub... | ---
+++
@@ -0,0 +1,16 @@
+
+class AnnotatedCFG(object):
+ def __init__(self):
+ pass
+
+ def should_take_exit(self, addr_from, addr_to):
+ return False
+
+ def should_execute_statement(self, addr):
+ return False
+
+ def get_run(self, addr):
+ return None
+
+ def get_whitelisted_statement(self, addr):
+ return [... | |
d6fb3be1566649718255601923b6ca137aeb855c | tools/experimental_create.py | tools/experimental_create.py | #!/usr/bin/python
import eventlet
from eventlet.green import socket
import libssh2
import time
import os
import random
import base64
import uuid
import M2Crypto
from novaclient.v1_1 import client
def instance_start(instance_name, image_name, flavor_name):
"""
Method to start an instance
"""
def _null_... | Add code that shows how to create an instance | Add code that shows how to create an instance
This creates an instance with a keypair, and saves the private key to
/tmp/private_key.
Then:
ssh -i /tmp/private_key 10.0.0.x where x is the IP address
Signed-off-by: Steven Dake <8638f3fce5db0278cfbc239bd581dfc00c29ec9d@redhat.com>
| Python | apache-2.0 | pshchelo/heat,rickerc/heat_audit,steveb/heat,pshchelo/heat,dragorosson/heat,noironetworks/heat,sdake/heat-jeos,steveb/heat,dragorosson/heat,JioCloud/heat,jasondunsmore/heat,noironetworks/heat,cryptickp/heat,dims/heat,gonzolino/heat,cwolferh/heat-scratch,dims/heat,srznew/heat,Triv90/Heat,srznew/heat,varunarya10/heat,rh-... | ---
+++
@@ -0,0 +1,63 @@
+#!/usr/bin/python
+
+import eventlet
+from eventlet.green import socket
+import libssh2
+import time
+import os
+import random
+import base64
+import uuid
+import M2Crypto
+from novaclient.v1_1 import client
+
+def instance_start(instance_name, image_name, flavor_name):
+ """
+ Method ... | |
2287d84e2a89fd938ae299f69164602880c611df | openprescribing/frontend/management/commands/load_development_data.py | openprescribing/frontend/management/commands/load_development_data.py | from django.core.management import call_command
from django.core.management.base import BaseCommand
from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable
class Command(BaseCommand):
help = 'Loads sample data intended for use in local development'
def handle(self, *args, **options):
... | Add command to load data for local development | Add command to load data for local development
At present this just loads a bunch of test fixtures (those recommended
by @inglep) but there's obviously scope for doing something else in
future. The main thing is that there's a single command to run which
does all this and we can update what that command actually does ... | Python | mit | annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing | ---
+++
@@ -0,0 +1,15 @@
+from django.core.management import call_command
+from django.core.management.base import BaseCommand
+
+from frontend.tests.test_api_spending import TestAPISpendingViewsPPUTable
+
+
+class Command(BaseCommand):
+
+ help = 'Loads sample data intended for use in local development'
+
+ de... | |
0eb4c06a818ceaac94be9e1992aed7394ebaca30 | sara_flexbe_states/src/sara_flexbe_states/Wonderland_Entity_Exist.py | sara_flexbe_states/src/sara_flexbe_states/Wonderland_Entity_Exist.py | #!/usr/bin/env python
# encoding=utf8
from flexbe_core import EventState, Logger
import json
class Wonderland_Entity_Exist(EventState):
'''
Read the 3D position of an entity in a json string
># json_text string command to read
<= ok return when at least one entity exist
<= empty return wh... | Add a state for infor if an entity exist. | Add a state for infor if an entity exist.
| Python | bsd-3-clause | WalkingMachine/sara_behaviors,WalkingMachine/sara_behaviors | ---
+++
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+# encoding=utf8
+
+from flexbe_core import EventState, Logger
+import json
+
+
+class Wonderland_Entity_Exist(EventState):
+ '''
+ Read the 3D position of an entity in a json string
+
+ ># json_text string command to read
+
+ <= ok return when at least on... | |
731e7c5e4595fb2dc5e27b8811ac6d2d61cb8a60 | language/Python/17-昆明-土豆/practice_buddle_sort.py | language/Python/17-昆明-土豆/practice_buddle_sort.py | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import time
L1 = [i for i in range(1000000)]
print("List Length:", len(L1))
t1 = time.time()
for j in range(0, len(L1) - 1):
if L1[j] > L1[j + 1]:
L1[j], L1[j + 1] = L1[j + 1], L1[j]
else:
pass
print('Sorted List:', L1)
t2 = time.time()
print("T... | Add some files written by PatrickY. | Add some files written by PatrickY.
| Python | mit | LinFengYnu/2017YNU,LinFengYnu/2017YNU,LinFengYnu/2017YNU,LinFengYnu/2017YNU,LinFengYnu/2017YNU | ---
+++
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# -*- encoding: utf-8 -*-
+
+import time
+
+L1 = [i for i in range(1000000)]
+print("List Length:", len(L1))
+t1 = time.time()
+for j in range(0, len(L1) - 1):
+ if L1[j] > L1[j + 1]:
+ L1[j], L1[j + 1] = L1[j + 1], L1[j]
+ else:
+ pass
+print('Sor... | |
3558fa2b35e02704c1556081a069b24e07e8d5a6 | alembic/versions/8f5b2066cbac_add_self_referential_image_reference.py | alembic/versions/8f5b2066cbac_add_self_referential_image_reference.py | """Add self-referential image reference
Revision ID: 8f5b2066cbac
Revises: 698cc06661d6
Create Date: 2016-03-20 19:35:31.321144
"""
# revision identifiers, used by Alembic.
revision = '8f5b2066cbac'
down_revision = '698cc06661d6'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
... | Add DB migration for self-referential image id .. that works on sqlalchemy | Add DB migration for self-referential image id .. that works on sqlalchemy
| Python | mit | matslindh/kimochi,matslindh/kimochi | ---
+++
@@ -0,0 +1,52 @@
+"""Add self-referential image reference
+
+Revision ID: 8f5b2066cbac
+Revises: 698cc06661d6
+Create Date: 2016-03-20 19:35:31.321144
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '8f5b2066cbac'
+down_revision = '698cc06661d6'
+branch_labels = None
+depends_on = None
+
+from ... | |
5a866e5141e42a212b13ec98233cc4ec88ad04bf | videos/tests/test_models.py | videos/tests/test_models.py | from django.test import TestCase
from .. import models
class TestVideo(TestCase):
def test_fields(self):
expected_fields = (
'id',
'title',
'slug',
'preview',
'length',
'recorded',
'created',
# Incoming
... | Test fields of core models | Test fields of core models
| Python | bsd-2-clause | incuna/incuna-videos,incuna/incuna-videos | ---
+++
@@ -0,0 +1,37 @@
+from django.test import TestCase
+
+from .. import models
+
+
+class TestVideo(TestCase):
+ def test_fields(self):
+ expected_fields = (
+ 'id',
+
+ 'title',
+ 'slug',
+ 'preview',
+ 'length',
+ 'recorded',
+ ... | |
61560b843db83d5542d4924a3e3caf06ed00711f | python/ecep/portal/migrations/0009_auto_20151022_1556.py | python/ecep/portal/migrations/0009_auto_20151022_1556.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def clear_enrollment_info(apps, schema_editor):
"""
Get rid of all that dumb crap.
"""
Location = apps.get_model('portal', 'Location')
for loc in Location.objects.all():
loc.enrollmen... | Add migration to perform bulk data operation removing garbage enrollment info | Add migration to perform bulk data operation removing garbage enrollment info
| Python | mit | smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning | ---
+++
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+def clear_enrollment_info(apps, schema_editor):
+ """
+ Get rid of all that dumb crap.
+ """
+ Location = apps.get_model('portal', 'Location')
+
+ for loc in Locat... | |
f5201902da06f7152e61027a640bc949b0fc5085 | download_vgg19.py | download_vgg19.py | """Downloads the pretrained VGG model."""
import argparse
import os
from fuel.downloaders.base import default_downloader
URL = ('https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/'
'vgg19_normalized.pkl')
def main():
default_downloader(os.getcwd(), [URL], [None])
if __name__ == "__main__":
... | Add download script for VGG19 | Add download script for VGG19
| Python | mit | vdumoulin/discgen | ---
+++
@@ -0,0 +1,19 @@
+"""Downloads the pretrained VGG model."""
+import argparse
+import os
+
+from fuel.downloaders.base import default_downloader
+
+URL = ('https://s3.amazonaws.com/lasagne/recipes/pretrained/imagenet/'
+ 'vgg19_normalized.pkl')
+
+
+def main():
+ default_downloader(os.getcwd(), [URL],... | |
1218887b10e39672e356fabbe8b9772d41d316c9 | haystackbrowser/forms.py | haystackbrowser/forms.py | from django import forms
from haystack.forms import ModelSearchForm
class PreSelectedModelSearchForm(ModelSearchForm):
def __init__(self, *args, **kwargs):
super(PreSelectedModelSearchForm, self).__init__(*args, **kwargs)
self.fields['models'].initial = (choice[0] for choice in self.fields['models'... | Create a form subclass with all models pre-ticked. | Create a form subclass with all models pre-ticked.
| Python | bsd-2-clause | vmarkovtsev/django-haystackbrowser,vmarkovtsev/django-haystackbrowser,jannon/django-haystackbrowser,jannon/django-haystackbrowser,vmarkovtsev/django-haystackbrowser,jannon/django-haystackbrowser | ---
+++
@@ -0,0 +1,7 @@
+from django import forms
+from haystack.forms import ModelSearchForm
+
+class PreSelectedModelSearchForm(ModelSearchForm):
+ def __init__(self, *args, **kwargs):
+ super(PreSelectedModelSearchForm, self).__init__(*args, **kwargs)
+ self.fields['models'].initial = (choice[0] f... | |
81e85f8d89a90be7444e39bd2d5dedf49d299922 | robot_localisation/main.py | robot_localisation/main.py | """
This module contains the logic to run the simulation.
"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import argparse
from robot_localisation.grid import *
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Robot localisation with HMM')
parser.... | Add basic argparse of rows and columns | Add basic argparse of rows and columns
| Python | mit | AxelTLarsson/robot-localisation | ---
+++
@@ -0,0 +1,25 @@
+"""
+This module contains the logic to run the simulation.
+"""
+import sys
+import os
+sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
+import argparse
+from robot_localisation.grid import *
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Ro... | |
1557372d65872c0cfdb206ae784dd425fe503ad2 | coffer/coffer.py | coffer/coffer.py | """
Secure storage container for treasures
"""
class Coffer(object):
"""
Secure storage container for treasures
Treasures must be removed to be modified and re-added to be
stored again.
"""
def __init__(self, path, *args, **kwargs):
"""
Creates a new coffer
"""
... | Add skeleton code for Coffer class | Add skeleton code for Coffer class
| Python | mit | robobrobro/coffer,robobrobro/coffer | ---
+++
@@ -0,0 +1,39 @@
+"""
+Secure storage container for treasures
+"""
+
+class Coffer(object):
+ """
+ Secure storage container for treasures
+
+ Treasures must be removed to be modified and re-added to be
+ stored again.
+ """
+
+ def __init__(self, path, *args, **kwargs):
+ """
+ ... | |
c4abca82c9e1a11ee92878c99e30853116f07c4c | changelogs/custom/pypi/synapse.py | changelogs/custom/pypi/synapse.py |
def get_urls(releases, **kwargs):
# Pypi has a old bugtracker_url which points to a separate repo which causes invalid
# changelogs to be generated by this tool.
ret = {'https://raw.githubusercontent.com/vertexproject/synapse/master/CHANGELOG.md'}
return ret, set()
| Add a custom get_urls for the Synapse package. | Add a custom get_urls for the Synapse package.
| Python | mit | pyupio/changelogs | ---
+++
@@ -0,0 +1,6 @@
+
+def get_urls(releases, **kwargs):
+ # Pypi has a old bugtracker_url which points to a separate repo which causes invalid
+ # changelogs to be generated by this tool.
+ ret = {'https://raw.githubusercontent.com/vertexproject/synapse/master/CHANGELOG.md'}
+ return ret, set() | |
2380e5074426f1c0006eaef1c08c9f213c834458 | lab/11/template_11_c.py | lab/11/template_11_c.py | from tkinter import *
class Kalkulator():
def __init__(self, master):
self.master = master
# TODO: Set title window menjadi "Kalkulator Sederhana" di bawah ini.
# TODO: Buatlah Label, Entry, Button,
# dan komponen-komponen lain yang dibutuhkan.
def tambah(self):
# TODO... | Add lab 11 template for class C | Add lab 11 template for class C
| Python | mit | giovanism/TarungLab,laymonage/TarungLab | ---
+++
@@ -0,0 +1,31 @@
+from tkinter import *
+
+class Kalkulator():
+ def __init__(self, master):
+ self.master = master
+ # TODO: Set title window menjadi "Kalkulator Sederhana" di bawah ini.
+
+ # TODO: Buatlah Label, Entry, Button,
+ # dan komponen-komponen lain yang dibutuhkan.
+... | |
85e855e19d05d4e7c273abc50dfce40c3277182b | hydrachain/tests/test_sim_joins.py | hydrachain/tests/test_sim_joins.py | import pytest
from hydrachain.consensus.simulation import Network, assert_heightdistance
# run this test with `tox -- -rx -k test_late_joins`
@pytest.mark.xfail
@pytest.mark.parametrize('validators', range(3, 10))
@pytest.mark.parametrize('late', range(1, 3))
@pytest.mark.parametrize('delay', [2])
def test_late_joins... | Add test for late-join scenario | Add test for late-join scenario
This adds a parametrized test for variations of
num_validators, late-joiners, late-join-delays.
Currently it fails for
- num_validators > 3 && late-joiners = 1 && delay = 2
- num_validators [7, 9] && late-joiners = 2 && delay = 2
| Python | mit | HydraChain/hydrachain,wangkangda/hydrachain,HydraChain/hydrachain,wangkangda/hydrachain | ---
+++
@@ -0,0 +1,27 @@
+import pytest
+from hydrachain.consensus.simulation import Network, assert_heightdistance
+
+
+# run this test with `tox -- -rx -k test_late_joins`
+@pytest.mark.xfail
+@pytest.mark.parametrize('validators', range(3, 10))
+@pytest.mark.parametrize('late', range(1, 3))
+@pytest.mark.parametri... | |
79313c3ec73591498170de911ea58bc33cf6cf05 | collection_pipelines/std.py | collection_pipelines/std.py | """Standard pipeline processors."""
from collection_pipelines.core import CollectionPipelineOutput
class value(CollectionPipelineOutput):
"""Output processor that returns pipeline items."""
def __init__(self):
self.retval = []
def process(self, item):
"""Appends the item to results list... | Add output processor that returns the collected items | Add output processor that returns the collected items
| Python | mit | povilasb/pycollection-pipelines | ---
+++
@@ -0,0 +1,25 @@
+"""Standard pipeline processors."""
+
+from collection_pipelines.core import CollectionPipelineOutput
+
+
+class value(CollectionPipelineOutput):
+ """Output processor that returns pipeline items."""
+
+ def __init__(self):
+ self.retval = []
+
+ def process(self, item):
+ ... | |
0df317159243b29d714e8b28c55439bf6af49fd3 | scripts/python/framework.py | scripts/python/framework.py | #
# IAS Basic device framework.
#
# Author: Joeri Hermans
#
import sys
import socket
import struct
# Global members, which are required for the communication
# with the remote IAS controller.
gDeviceIdentifier = sys.argv[1]
gControllerAddress = sys.argv[2]
gControllerPort = int(sys.argv[3])
gSocket = s... | Add basic Python script for devices. | Add basic Python script for devices.
| Python | apache-2.0 | JoeriHermans/Intelligent-Automation-System,JoeriHermans/Intelligent-Automation-System,JoeriHermans/Intelligent-Automation-System,JoeriHermans/Intelligent-Automation-System | ---
+++
@@ -0,0 +1,73 @@
+#
+# IAS Basic device framework.
+#
+# Author: Joeri Hermans
+#
+
+import sys
+import socket
+import struct
+
+# Global members, which are required for the communication
+# with the remote IAS controller.
+gDeviceIdentifier = sys.argv[1]
+gControllerAddress = sys.argv[2]
+gControllerPort = i... | |
58c49557574bcbb66c824bbf743fdfbb354e7a03 | h2o-py/tests/testdir_algos/naivebayes/pyunit_irisNB_cv.py | h2o-py/tests/testdir_algos/naivebayes/pyunit_irisNB_cv.py | from __future__ import print_function
from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.naive_bayes import H2ONaiveBayesEstimator
def nb_iris():
print("Importing iris_wheader.csv data...\n")
iris = h2o.upload_file(pyunit_utils.loc... | Add PyUnit for Naive Bayes (cross)validation. | PUBDEV-2769: Add PyUnit for Naive Bayes (cross)validation.
| Python | apache-2.0 | mathemage/h2o-3,h2oai/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,jangorecki/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,spennihana/h2o-3,jangorecki/h2o-3,spennihana/h2o-3,mathemage/h2o-3,spennihana/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,YzPaul3/h2o-3,michalkurka/h2o-3,h2... | ---
+++
@@ -0,0 +1,42 @@
+from __future__ import print_function
+from builtins import range
+import sys
+sys.path.insert(1,"../../../")
+import h2o
+from tests import pyunit_utils
+from h2o.estimators.naive_bayes import H2ONaiveBayesEstimator
+
+
+
+def nb_iris():
+
+
+ print("Importing iris_wheader.csv data...\n")
... | |
2f69ff34e9d0aa9ea4119e01222a1b0fc6161b39 | ubuntu-cloud.py | ubuntu-cloud.py | #!/usr/bin/env python
from __future__ import print_function
import os
import requests
# TODO(bc): provide these via config and/or argparse
MIRROR_PATH = '/mnt/mirror.os02/ubuntu-cloud'
RELEASE_LIST = ['trusty',
'utopic']
ARCH_LIST = ['amd64']
LABEL_LIST = ['release']
ITEM_LIST = ['disk1.img']
UPSTREA... | Add POC script to mirror Ubuntu cloud images | Add POC script to mirror Ubuntu cloud images
| Python | mit | briancline/mirror-scripts,briancline/mirror-scripts | ---
+++
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+from __future__ import print_function
+import os
+import requests
+
+
+# TODO(bc): provide these via config and/or argparse
+MIRROR_PATH = '/mnt/mirror.os02/ubuntu-cloud'
+RELEASE_LIST = ['trusty',
+ 'utopic']
+ARCH_LIST = ['amd64']
+LABEL_LIST = ['relea... | |
6afa2a817387d24751b62845113e6f4de01025ba | code/tests/test_smoothing.py | code/tests/test_smoothing.py | """
Tests functions in smoothing.py
Run with:
nosetests test_smoothing.py
"""
# Test method .smooth()
smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5)
smooth3 = subtest_runtest1.smooth(2, 0.25)
assert [smooth1.max(), smooth1.shape, smooth1.sum()] == [0, (3, 3, 3), 0]
assert [smooth2.ma... | Add seperate test function for smoothing | Add seperate test function for smoothing
| Python | bsd-3-clause | berkeley-stat159/project-delta | ---
+++
@@ -0,0 +1,14 @@
+"""
+Tests functions in smoothing.py
+Run with:
+ nosetests test_smoothing.py
+"""
+
+# Test method .smooth()
+smooth1, smooth2 = subtest_runtest1.smooth(0), subtest_runtest1.smooth(1, 5)
+smooth3 = subtest_runtest1.smooth(2, 0.25)
+assert [smooth1.max(), smooth1.shape, smooth1.sum()] ==... | |
981427d1efb4f3887fa1110e9a3ba8b6dd8910e0 | json_parser/profiling.py | json_parser/profiling.py | from timeit import timeit
TEST1 = """
load_string(r'{ "one": { "two": [{ "three": { "four": null }}, false ], "five": 5 }}')
"""
TEST2 = """
load_string_faster(r'{ "one": { "two": [{ "three": { "four": null }}, false ], "five": 5 }}')
"""
TEST3 = """
json.loads(r'{ "one": { "two": [{ "three": { "four": null }}, f... | Add timing comparisons to JSON parser. | Add timing comparisons to JSON parser.
| Python | mit | py-in-the-sky/challenges,py-in-the-sky/challenges,py-in-the-sky/challenges | ---
+++
@@ -0,0 +1,28 @@
+from timeit import timeit
+
+
+TEST1 = """
+load_string(r'{ "one": { "two": [{ "three": { "four": null }}, false ], "five": 5 }}')
+"""
+
+
+TEST2 = """
+load_string_faster(r'{ "one": { "two": [{ "three": { "four": null }}, false ], "five": 5 }}')
+"""
+
+
+TEST3 = """
+json.loads(r'{ "one":... | |
e7e9c0c624e53f34b6b77f8de99cbcc5cda4f3fa | triangular_matrix.py | triangular_matrix.py | import pandas as pd
import numpy as np
import itertools
import argparse
parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
parser.add_argument('-t', '--triangular-matrix', required=True, help='An npz file containing co-segregation frequencies to conv... | Add script to turn triangular matrices into squares | Add script to turn triangular matrices into squares
| Python | apache-2.0 | pombo-lab/gamtools,pombo-lab/gamtools | ---
+++
@@ -0,0 +1,40 @@
+import pandas as pd
+import numpy as np
+import itertools
+import argparse
+
+parser = argparse.ArgumentParser(description='Calculate coverage over different window sizes for a list of bam files.')
+parser.add_argument('-t', '--triangular-matrix', required=True, help='An npz file containing ... | |
a581253c6daee875855ac1677717eb1cf464e704 | froide/publicbody/migrations/0021_proposedpublicbody.py | froide/publicbody/migrations/0021_proposedpublicbody.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-19 10:35
from __future__ import unicode_literals
from django.db import migrations
import froide.publicbody.models
class Migration(migrations.Migration):
dependencies = [
('publicbody', '0020_foilaw_requires_signature'),
]
operatio... | Add proposed publicbody proxy model migration | Add proposed publicbody proxy model migration | Python | mit | fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide | ---
+++
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.14 on 2018-07-19 10:35
+from __future__ import unicode_literals
+
+from django.db import migrations
+import froide.publicbody.models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('publicbody', '0020_foilaw_re... | |
dc4939b981f508c966c02580ab45091f05265140 | contrib/nic_file_fixcase.py | contrib/nic_file_fixcase.py | #!/bin/python
# coding: utf-8
import sys
import lglass.nic
import lglass.object
old_db = lglass.nic.FileDatabase(sys.argv[1], case_insensitive=False)
new_db = lglass.nic.FileDatabase(sys.argv[1], case_insensitive=True)
for obj in old_db.find():
old_db.delete(obj)
new_db.save(obj)
| Add script to fix case in file databases | Add script to fix case in file databases
| Python | mit | fritz0705/lglass | ---
+++
@@ -0,0 +1,15 @@
+#!/bin/python
+# coding: utf-8
+
+import sys
+
+import lglass.nic
+import lglass.object
+
+old_db = lglass.nic.FileDatabase(sys.argv[1], case_insensitive=False)
+new_db = lglass.nic.FileDatabase(sys.argv[1], case_insensitive=True)
+
+for obj in old_db.find():
+ old_db.delete(obj)
+ new... | |
debf6402b30606aae07828e5f4cd92d3fcb3834d | fetch_configs/devtools-internal.py | fetch_configs/devtools-internal.py | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import config_util # pylint: disable=import-error
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=no... | Add a fetch config for devtools (internal). | Add a fetch config for devtools (internal).
This change has precedent, c.f. 04d16a561 for infra_internal.
R=yangguo
Bug: None
Change-Id: I089b114bcfe110ad138284bb71802cfc5d7f157d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/3782488
Reviewed-by: Yang Guo <1cf0af8245a3a17a632a2c... | Python | bsd-3-clause | CoherentLabs/depot_tools,CoherentLabs/depot_tools | ---
+++
@@ -0,0 +1,44 @@
+# Copyright 2019 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import sys
+
+import config_util # pylint: disable=import-error
+
+
+# This class doesn't need an __init__ method, so we dis... | |
b4f1f1398772d26c8eb20a80c4df76b601e406dd | st2api/tests/unit/controllers/v1/test_service_registry.py | st2api/tests/unit/controllers/v1/test_service_registry.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Add test cases for new service registry related API endpoint. | Add test cases for new service registry related API endpoint.
| Python | apache-2.0 | nzlosh/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2 | ---
+++
@@ -0,0 +1,79 @@
+# Licensed to the StackStorm, Inc ('StackStorm') under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (th... | |
99c3b830efac69db667ba0b97b5b77c93bca0774 | candidates/management/commands/candidates_remove_bogus_dates.py | candidates/management/commands/candidates_remove_bogus_dates.py | import sys
from candidates.popit import PopItApiMixin, popit_unwrap_pagination
from candidates.update import fix_dates
from django.core.management.base import BaseCommand
from slumber.exceptions import HttpClientError
def strip_bogus_fields(data, bogus_field_keys):
for key in bogus_field_keys:
if key i... | Add a command to remove some bogus data key / value pairs | Add a command to remove some bogus data key / value pairs
| Python | agpl-3.0 | mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,... | ---
+++
@@ -0,0 +1,60 @@
+import sys
+
+from candidates.popit import PopItApiMixin, popit_unwrap_pagination
+from candidates.update import fix_dates
+
+from django.core.management.base import BaseCommand
+
+from slumber.exceptions import HttpClientError
+
+
+def strip_bogus_fields(data, bogus_field_keys):
+ for ke... | |
782fc597ab79acb3cbd0d9dffb4ed77cc561d894 | gimlet/tests/test_session.py | gimlet/tests/test_session.py | from unittest import TestCase
from webob import Request
from gimlet.factories import session_factory_factory
class TestSession(TestCase):
def _make_session(self, secret='secret', **options):
request = Request.blank('/')
return session_factory_factory(secret, **options)(request)
def test_se... | Add unit tests for Session | Add unit tests for Session
| Python | mit | storborg/gimlet | ---
+++
@@ -0,0 +1,39 @@
+from unittest import TestCase
+
+from webob import Request
+
+from gimlet.factories import session_factory_factory
+
+
+class TestSession(TestCase):
+
+ def _make_session(self, secret='secret', **options):
+ request = Request.blank('/')
+ return session_factory_factory(secre... | |
220497316492ea2153cb86e54d2c92606f5ab4cb | epochTime.py | epochTime.py |
from datetime import datetime
import time;
#t = time.mktime(time.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S"));
with open('Hashes-17.csv') as data:
for lines in data:
#print lines
splitLines=lines.split(',')
print splitLines[2]
temp='"'+splitLines[2]+'"'
#print tem... | Convert human readable time to epoch. | Convert human readable time to epoch.
Time utility | Python | mit | inimitableharish/bitsandpieces | ---
+++
@@ -0,0 +1,18 @@
+
+from datetime import datetime
+
+import time;
+#t = time.mktime(time.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S"));
+
+with open('Hashes-17.csv') as data:
+ for lines in data:
+ #print lines
+ splitLines=lines.split(',')
+ print splitLines[2]
+ temp='... | |
b465435a8aa3be325875a41d196288349b59359f | src/mmw/apps/modeling/migrations/0024_fix_gwlfe_gis_data.py | src/mmw/apps/modeling/migrations/0024_fix_gwlfe_gis_data.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def fix_gis_data_serialization(apps, schema_editor):
"""
Release 1.20.0 introduced a change which let the project "gis_data"
field get updated by modifications on a scenario. This effectively
meant that ... | Reset models affected by modification bug | Reset models affected by modification bug
Resets the possibly affected multi-year model results by removing the
calculated GIS parts, forcing a recomputation when accessed again.
| Python | apache-2.0 | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed | ---
+++
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+def fix_gis_data_serialization(apps, schema_editor):
+ """
+ Release 1.20.0 introduced a change which let the project "gis_data"
+ field get updated by modifications on a scenar... | |
7df2ef1e850cefd5fcbd62d1dd27bae1bef975a1 | skimage/io/tests/test_image.py | skimage/io/tests/test_image.py | from skimage.io import Image
from numpy.testing import assert_equal, assert_array_equal
def test_tags():
f = Image([1, 2, 3], foo='bar', sigma='delta')
g = Image([3, 2, 1], sun='moon')
h = Image([1, 1, 1])
assert_equal(f.tags['foo'], 'bar')
assert_array_equal((g + 2).tags['sun'], 'moon')
asse... | Add tests for image tags. | Add tests for image tags.
| Python | bsd-3-clause | pratapvardhan/scikit-image,emon10005/scikit-image,SamHames/scikit-image,chintak/scikit-image,michaelpacer/scikit-image,oew1v07/scikit-image,michaelaye/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,ofgulban/scikit-image,Midafi/scikit-image,newville/scikit-image,warmspringwinds/scikit-... | ---
+++
@@ -0,0 +1,17 @@
+from skimage.io import Image
+
+from numpy.testing import assert_equal, assert_array_equal
+
+def test_tags():
+ f = Image([1, 2, 3], foo='bar', sigma='delta')
+ g = Image([3, 2, 1], sun='moon')
+ h = Image([1, 1, 1])
+
+ assert_equal(f.tags['foo'], 'bar')
+ assert_array_equal... | |
2fc2a07e219a60fb62edadeed00220c4b922061f | src/nodeconductor_saltstack/migrations/0003_add_error_message.py | src/nodeconductor_saltstack/migrations/0003_add_error_message.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('nodeconductor_saltstack', '0002_paid_resources'),
]
operations = [
migrations.AddField(
model_name='saltstackser... | Add migration for error_message field (NC-909) | Add migration for error_message field (NC-909)
| Python | mit | opennode/nodeconductor-saltstack | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('nodeconductor_saltstack', '0002_paid_resources'),
+ ]
+
+ operations = [
+ migrations.AddFi... | |
abbca8065b92cd652c2d4ddab46ab4bf574e5ccf | decimaltobinary.py | decimaltobinary.py | from stack import Stack
def convertToBinary(value):
remainder = Stack()
while value > 0:
rem = value % 2
remainder.push(rem)
value = value // 2
binary = ''
while not remainder.isEmpty():
binary = binary + str(remainder.pop())
return binary
def myconvertTobinary(value):
remainder = Sta... | Add python script to convert decimal value to binary | Add python script to convert decimal value to binary
| Python | mit | prabhugs/scripts,prabhugs/scripts | ---
+++
@@ -0,0 +1,33 @@
+from stack import Stack
+
+def convertToBinary(value):
+ remainder = Stack()
+
+ while value > 0:
+ rem = value % 2
+ remainder.push(rem)
+ value = value // 2
+
+ binary = ''
+ while not remainder.isEmpty():
+ binary = binary + str(remainder.pop())
+
+ return binary
+
+def... | |
d0ea82dd5a4f36ec374357276093e1a91d85e54f | examples/basics/visuals/bezier.py | examples/basics/visuals/bezier.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -------------------------------------------------------------------------... | Add an example how to draw Bezier curves. | Add an example how to draw Bezier curves.
The vispy.geometry.curves module provides several helper
functions to generate the right vertices for a nice curved
line.
| Python | bsd-3-clause | sbtlaarzc/vispy,QuLogic/vispy,drufat/vispy,kkuunnddaannkk/vispy,dchilds7/Deysha-Star-Formation,dchilds7/Deysha-Star-Formation,jay3sh/vispy,jdreaver/vispy,RebeccaWPerry/vispy,RebeccaWPerry/vispy,srinathv/vispy,julienr/vispy,inclement/vispy,Eric89GXL/vispy,bollu/vispy,QuLogic/vispy,jay3sh/vispy,QuLogic/vispy,srinathv/vis... | ---
+++
@@ -0,0 +1,78 @@
+# -*- coding: utf-8 -*-
+# -----------------------------------------------------------------------------
+# Copyright (c) 2015, Vispy Development Team. All Rights Reserved.
+# Distributed under the (new) BSD License. See LICENSE.txt for more info.
+# -----------------------------------------... | |
b639aebe9689b09e879cefa3a4ff2d6bc2f1c5f1 | sandbox/load_modules.py | sandbox/load_modules.py | import os
import glob
position = p.copy()
for module_name in position.b.split():
fileNode = position.insertAsLastChild()
fileNode.h = '@clean {0}.py'.format(module_name)
c.redraw_now()
"""
DependencyNodeUI
ComputeNodeUI
RandomUI
ExpressionUI
BoxUI
ReferenceUI
BackdropUI
DotUI
SubGraphUI
SwitchUI
ContextVari... | Load modules under a package directory | Load modules under a package directory | Python | mit | satishgoda/leo-editor-tutorial | ---
+++
@@ -0,0 +1,27 @@
+import os
+import glob
+
+position = p.copy()
+
+for module_name in position.b.split():
+ fileNode = position.insertAsLastChild()
+ fileNode.h = '@clean {0}.py'.format(module_name)
+
+c.redraw_now()
+
+"""
+DependencyNodeUI
+ComputeNodeUI
+RandomUI
+ExpressionUI
+BoxUI
+ReferenceUI
+Ba... | |
ec62e6784b69ecc47106529d27b8fc6dc1ab215f | imaginary/test/test_idea.py | imaginary/test/test_idea.py |
"""
Some basic unit tests for L{imaginary.idea} (but many tests for this code are in
other modules instead).
"""
from twisted.trial.unittest import TestCase
from epsilon.structlike import record
from imaginary.idea import Idea, Link, Path
class Named(record('name')):
pass
class PathTests(TestCase):
"""
... | Add a test for Path.__repr__ | Add a test for Path.__repr__ | Python | mit | glyph/imaginary,twisted/imaginary | ---
+++
@@ -0,0 +1,34 @@
+
+"""
+Some basic unit tests for L{imaginary.idea} (but many tests for this code are in
+other modules instead).
+"""
+
+from twisted.trial.unittest import TestCase
+
+from epsilon.structlike import record
+
+from imaginary.idea import Idea, Link, Path
+
+
+class Named(record('name')):
+ ... | |
5af7dcb774cb52ffe09822d788d7beebd34a6ef6 | watcher.py | watcher.py | import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class ScriptModifiedHandler(PatternMatchingEventHandler):
patterns = ['*.py']
def __init__(self):
super(ScriptModifiedHandler, self).__init__()
# you can add some init code here
def proc... | Add watchdog that monitors scripts editing | Add watchdog that monitors scripts editing | Python | mit | duboviy/misc | ---
+++
@@ -0,0 +1,41 @@
+import time
+from watchdog.observers import Observer
+from watchdog.events import PatternMatchingEventHandler
+
+
+class ScriptModifiedHandler(PatternMatchingEventHandler):
+ patterns = ['*.py']
+
+ def __init__(self):
+ super(ScriptModifiedHandler, self).__init__()
+ # you can... | |
4b9ee24e05b0ac73c7ca9fa17d50d11b1c8a95df | test/5232/fileinto_test.py | test/5232/fileinto_test.py | import sys
sys.path.append('./')
import unittest
import checksieve
class TestFileinto(unittest.TestCase):
def test_fileinto_with_flags(self):
sieve = '''
require ["fileinto", "imap4flags"];
fileinto :flags "\\\\Seen" "Mailbox";
'''
self.assertFalse(checksieve.parse_str... | Add failing tests for fileinto command with :flags option | Add failing tests for fileinto command with :flags option
| Python | mit | dburkart/check-sieve,dburkart/check-sieve,dburkart/check-sieve,dburkart/mail-sieve-verifier,dburkart/mail-sieve-verifier | ---
+++
@@ -0,0 +1,47 @@
+import sys
+sys.path.append('./')
+
+import unittest
+import checksieve
+
+class TestFileinto(unittest.TestCase):
+
+ def test_fileinto_with_flags(self):
+ sieve = '''
+ require ["fileinto", "imap4flags"];
+ fileinto :flags "\\\\Seen" "Mailbox";
+ '''
+ ... | |
ee057041b9be696173ab900ca6f44f72785777dd | VehicleDetectionTracking/car_notcar.py | VehicleDetectionTracking/car_notcar.py | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import os
#from skimage.feature import hog
#from skimage import color, exposure
# images are divided up into vehicles and non-vehicles
os.chdir('./objects')
# Define a function to return some characteristics of ... | Add scripts which define a function to return some characteristics of the dataset | feat: Add scripts which define a function to return some characteristics of the dataset
| Python | mit | aguijarro/SelfDrivingCar | ---
+++
@@ -0,0 +1,63 @@
+import matplotlib.image as mpimg
+import matplotlib.pyplot as plt
+import numpy as np
+import cv2
+import glob
+import os
+#from skimage.feature import hog
+#from skimage import color, exposure
+# images are divided up into vehicles and non-vehicles
+
+os.chdir('./objects')
+
+# Define a fun... | |
de999808e8d4996ca1a06a2e484dac3acc0d3fe5 | vandali/urls.py | vandali/urls.py | from django.conf.urls import patterns, url
from vandali import views
urlpatterns = patterns(
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^portfolio/$', views.portfolio, name='portfolio'),
url(r'^contact/$', views.blog, name='blog'),
url(r'^blog/$', vie... | Set routes for home, about, portfolio, contact, blog | Set routes for home, about, portfolio, contact, blog
| Python | bsd-2-clause | aldnav/vandali,aldnav/vandali | ---
+++
@@ -0,0 +1,11 @@
+from django.conf.urls import patterns, url
+
+from vandali import views
+
+urlpatterns = patterns(
+ url(r'^$', views.index, name='index'),
+ url(r'^about/$', views.about, name='about'),
+ url(r'^portfolio/$', views.portfolio, name='portfolio'),
+ url(r'^contact/$', views.blog, n... | |
6b8a569c4196f79b06619f392faf008fb63d0909 | votingrecord.py | votingrecord.py | import collections
import prettytable
import yaml
import library
"""Generate governance repo voting record."""
def print_voting_record(change_ids, repo):
headers = ["Subject", "Link"]
names = collections.defaultdict(dict) # {name: {number:vote, },}
total_votes = collections.defaultdict(int) # {name: ... | Add script to generate voting record for governance repo | Add script to generate voting record for governance repo
The OpenStack TC now votes via gerrit, so we can easily track voting
records.
| Python | apache-2.0 | jogo/gerrit-fun | ---
+++
@@ -0,0 +1,57 @@
+import collections
+
+import prettytable
+import yaml
+
+import library
+
+"""Generate governance repo voting record."""
+
+
+def print_voting_record(change_ids, repo):
+ headers = ["Subject", "Link"]
+ names = collections.defaultdict(dict) # {name: {number:vote, },}
+ total_votes ... | |
0db77c23b81f92b16464733404b4966d7a584f46 | sklearn/tests/test_kernel_ridge.py | sklearn/tests/test_kernel_ridge.py | import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import Ridge
from sklearn.kernel_ridge import KernelRidge
from sklearn.utils.testing import assert_array_almost_equal
X, y = make_classification(n_classes=2, random_state=0)
Y = np.array([y, y]).T
def test_kernel_ridge()... | TEST Added tests for KernelRidge based on @mblondel's code in lightning | TEST Added tests for KernelRidge based on @mblondel's code in lightning
| Python | bsd-3-clause | ky822/scikit-learn,IshankGulati/scikit-learn,ElDeveloper/scikit-learn,robin-lai/scikit-learn,nvoron23/scikit-learn,466152112/scikit-learn,loli/semisupervisedforests,sumspr/scikit-learn,pypot/scikit-learn,Sentient07/scikit-learn,jereze/scikit-learn,MohammedWasim/scikit-learn,kevin-intel/scikit-learn,ishanic/scikit-learn... | ---
+++
@@ -0,0 +1,42 @@
+import numpy as np
+
+from sklearn.datasets import make_classification
+from sklearn.linear_model import Ridge
+from sklearn.kernel_ridge import KernelRidge
+
+from sklearn.utils.testing import assert_array_almost_equal
+
+
+X, y = make_classification(n_classes=2, random_state=0)
+Y = np.arr... | |
7ea36b3c1f6d0cdca6b4bcb46cb765f983295b4e | v3/test_federation.py | v3/test_federation.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
# distributed under t... | Add CRUD operations for Identity Providers. | Add CRUD operations for Identity Providers.
Add relevant methods for adding, updating, listing, getting, and deleting
Identity Provider objects.
Change-Id: Ib77781b507d2c06c368a1877eb716ec7fe2d88e4
Implements: blueprint federation-crud-operations
| Python | apache-2.0 | varunarya10/keystonemiddleware | ---
+++
@@ -0,0 +1,86 @@
+# 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 writi... | |
4d2f90d0671c5425fde6da3165c19340a39a4942 | test/test_report_mapping.py | test/test_report_mapping.py | # Import -----------------------------------------------------------------------
import os
from sequana.report_mapping import MappingReport
from sequana import bedtools
from . import data
pathdata = data.__path__[0]
# Test -------------------------------------------------------------------------
def test_report():
... | Add test for report mapping | Add test for report mapping
| Python | bsd-3-clause | sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana | ---
+++
@@ -0,0 +1,18 @@
+# Import -----------------------------------------------------------------------
+
+import os
+from sequana.report_mapping import MappingReport
+from sequana import bedtools
+from . import data
+pathdata = data.__path__[0]
+
+# Test -----------------------------------------------------------... | |
cce53a80c34978b9dec96cb77897970ff9cb9d65 | dataactcore/migrations/versions/d35ecdfc1da7_add_indexing_to_duns_table.py | dataactcore/migrations/versions/d35ecdfc1da7_add_indexing_to_duns_table.py | """add indexing to DUNS table
Revision ID: d35ecdfc1da7
Revises: 4b1ee78268fb
Create Date: 2017-08-31 12:03:16.395760
"""
# revision identifiers, used by Alembic.
revision = 'd35ecdfc1da7'
down_revision = '4b1ee78268fb'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgr... | Add migration for DUNS indexing | Add migration for DUNS indexing
| Python | cc0-1.0 | fedspendingtransparency/data-act-broker-backend,fedspendingtransparency/data-act-broker-backend | ---
+++
@@ -0,0 +1,44 @@
+"""add indexing to DUNS table
+
+Revision ID: d35ecdfc1da7
+Revises: 4b1ee78268fb
+Create Date: 2017-08-31 12:03:16.395760
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = 'd35ecdfc1da7'
+down_revision = '4b1ee78268fb'
+branch_labels = None
+depends_on = None
+
+from alembic im... | |
6b27d719afcaa2beba35c012e365c95bf0e5fbd2 | migrations/versions/6bd350cf4748_add_lab_assistant_role.py | migrations/versions/6bd350cf4748_add_lab_assistant_role.py | """Add Lab assistant role
Revision ID: 6bd350cf4748
Revises: 6504bfe5203c
Create Date: 2016-08-28 17:43:34.671050
"""
# revision identifiers, used by Alembic.
revision = '6bd350cf4748'
down_revision = '6504bfe5203c'
from alembic import op
import sqlalchemy as sa
old = ['student', 'grader', 'staff', 'instructor']
n... | Add migration for role enum | Add migration for role enum
| Python | apache-2.0 | Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok | ---
+++
@@ -0,0 +1,25 @@
+"""Add Lab assistant role
+
+Revision ID: 6bd350cf4748
+Revises: 6504bfe5203c
+Create Date: 2016-08-28 17:43:34.671050
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '6bd350cf4748'
+down_revision = '6504bfe5203c'
+
+from alembic import op
+import sqlalchemy as sa
+
+old = ['s... | |
e4f0fc2cdd209bbadffae9f3da83b0585a64143f | accelerator/migrations/0077_add_program_overview_link_field_to_a_program.py | accelerator/migrations/0077_add_program_overview_link_field_to_a_program.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-05-15 14:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0076_change_description_to_textfield'),
]
operations = [
mi... | Add migration file form program overview link | [AC-6989] Add migration file form program overview link
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.18 on 2019-05-15 14:16
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('accelerator', '0076_change_description_to_textfield')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.