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 |
|---|---|---|---|---|---|---|---|---|---|---|
263cd80a16f44e900d939322e3e6e1ce0cea31b7 | elements/swift-proxy/check_mk_checks/swift_proxy_healthcheck.py | elements/swift-proxy/check_mk_checks/swift_proxy_healthcheck.py | #!/usr/bin/python
# 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
# dis... | Add check_mk swift proxy diagnostic | Add check_mk swift proxy diagnostic
Added a check_mk script that runs healthcheck to ensure that a
proxy node is up and running with proxy services. This diag is
also check_mk compliant (ie. the output matches check_mk desired
format).
Have not added thecheck_mk-agent element to element-deps file as
even though it is... | Python | apache-2.0 | rdo-management/tripleo-image-elements,radez/tripleo-image-elements,radez/tripleo-image-elements,rdo-management/tripleo-image-elements,openstack/tripleo-image-elements,openstack/tripleo-image-elements | ---
+++
@@ -0,0 +1,65 @@
+#!/usr/bin/python
+# 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 a... | |
d34dad32170e53f49e14611f5bfbfcb4eb7b8d4d | extra/create_rand_host.py | extra/create_rand_host.py | import requests
import json
import random
import uuid
login="test"
password="P@ssword"
with open("dict", 'r', encoding="latin-1") as words :
a = words.readlines()
headers = {
'Content-type': 'application/json',
'Accept': 'application/json'
}
def gen_ip():
a = random.randint(1, 254)
b = rando... | Add script to generate fake data | Add script to generate fake data
| Python | mit | H0neyBadger/cmdb,H0neyBadger/cmdb | ---
+++
@@ -0,0 +1,77 @@
+import requests
+import json
+import random
+import uuid
+
+login="test"
+password="P@ssword"
+
+with open("dict", 'r', encoding="latin-1") as words :
+ a = words.readlines()
+
+headers = {
+ 'Content-type': 'application/json',
+ 'Accept': 'application/json'
+}
+
+def gen_ip():
... | |
0f2ef5a0eae40a24e50c10187606aa884faff728 | TrailingString.py | TrailingString.py | # Trailing String
#
# https://www.codeeval.com/open_challenges/32/
#
# Challenge Description: There are two strings: A and B. Print 1 if string B
# occurs at the end of string A. Otherwise, print 0.
import sys
def is_trailing_string(x, y):
return x[-len(y):] == y
if __name__ == '__main__':
input_f... | Solve the Trailing String challenge | Solve the Trailing String challenge
| Python | mit | TommyN94/CodeEvalSolutions,TommyN94/CodeEvalSolutions | ---
+++
@@ -0,0 +1,21 @@
+# Trailing String
+#
+# https://www.codeeval.com/open_challenges/32/
+#
+# Challenge Description: There are two strings: A and B. Print 1 if string B
+# occurs at the end of string A. Otherwise, print 0.
+import sys
+
+
+def is_trailing_string(x, y):
+ return x[-len(y):] == y
+
+if... | |
2986ca3ebd7562d9cb84f33598e17b3b9627f3a2 | landlab/grid/tests/test_diagonals.py | landlab/grid/tests/test_diagonals.py | #! /usr/bin/env python
import numpy as np
from nose.tools import assert_is, assert_is_instance
from numpy.testing import assert_array_equal
from landlab.grid.diagonals import create_nodes_at_diagonal
def test_nodes_at_diagonal():
"""Test tail and head nodes of diagonals."""
diagonals = create_nodes_at_diago... | Add some unit tests for the diagonals. | Add some unit tests for the diagonals.
| Python | mit | amandersillinois/landlab,landlab/landlab,cmshobe/landlab,cmshobe/landlab,cmshobe/landlab,landlab/landlab,amandersillinois/landlab,landlab/landlab | ---
+++
@@ -0,0 +1,37 @@
+#! /usr/bin/env python
+import numpy as np
+
+from nose.tools import assert_is, assert_is_instance
+from numpy.testing import assert_array_equal
+
+from landlab.grid.diagonals import create_nodes_at_diagonal
+
+
+def test_nodes_at_diagonal():
+ """Test tail and head nodes of diagonals."""... | |
9f2d4c6052089706f9398be3234eb1fc63de95bf | tests/test_comparisons.py | tests/test_comparisons.py | """
Test ChatterBot's statement comparison algorithms.
"""
from unittest import TestCase, SkipTest
from chatterbot.conversation import Statement
from chatterbot import comparisons
class LevenshteinDistanceTestCase(TestCase):
def test_levenshtein_distance_statement_false(self):
"""
Falsy values s... | Add a few statement comparison tests | Add a few statement comparison tests
| Python | bsd-3-clause | Gustavo6046/ChatterBot,davizucon/ChatterBot,vkosuri/ChatterBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,gunthercox/ChatterBot,Reinaesaya/OUIRL-ChatBot | ---
+++
@@ -0,0 +1,76 @@
+"""
+Test ChatterBot's statement comparison algorithms.
+"""
+
+from unittest import TestCase, SkipTest
+from chatterbot.conversation import Statement
+from chatterbot import comparisons
+
+
+class LevenshteinDistanceTestCase(TestCase):
+
+ def test_levenshtein_distance_statement_false(se... | |
145d90259715e826ac88f86715e5a7215f3800ac | app/jobs/create_civic_vcf.py | app/jobs/create_civic_vcf.py | class CreateCivicVcf < ActiveJob::Base
def perform
system("python3 #{script_path} #{vcf_path}")
self.class.set(wait_until: Date.tomorrow.midnight).perform_later
end
def script_path
File.join(Rails.root, 'misc_scripts', 'create_civic_vcf.py')
end
private
def civicpy_cache_file_location
File... | Add job to create CIViC VCF | Add job to create CIViC VCF
| Python | mit | genome/civic-server,genome/civic-server,genome/civic-server,genome/civic-server,genome/civic-server | ---
+++
@@ -0,0 +1,15 @@
+class CreateCivicVcf < ActiveJob::Base
+ def perform
+ system("python3 #{script_path} #{vcf_path}")
+ self.class.set(wait_until: Date.tomorrow.midnight).perform_later
+ end
+
+ def script_path
+ File.join(Rails.root, 'misc_scripts', 'create_civic_vcf.py')
+ end
+
+ private
+ d... | |
8fac2cf0cb4d7b530670797ef1c2731238dfa655 | frappe/patches/v12_0/delete_duplicate_indexes.py | frappe/patches/v12_0/delete_duplicate_indexes.py | import frappe
# This patch deletes all the duplicate indexes created for same column
# The patch only checks for indexes with UNIQUE constraints
def execute():
all_tables = frappe.db.get_tables()
final_deletion_map = frappe._dict()
for table in all_tables:
indexes_to_keep_map = frappe._dict()
indexes_to_dele... | Add patch to delete duplicate issues | fix: Add patch to delete duplicate issues
| Python | mit | yashodhank/frappe,vjFaLk/frappe,StrellaGroup/frappe,frappe/frappe,StrellaGroup/frappe,adityahase/frappe,mhbu50/frappe,saurabh6790/frappe,StrellaGroup/frappe,vjFaLk/frappe,almeidapaulopt/frappe,frappe/frappe,almeidapaulopt/frappe,saurabh6790/frappe,yashodhank/frappe,saurabh6790/frappe,yashodhank/frappe,yashodhank/frappe... | ---
+++
@@ -0,0 +1,42 @@
+import frappe
+
+# This patch deletes all the duplicate indexes created for same column
+# The patch only checks for indexes with UNIQUE constraints
+
+def execute():
+ all_tables = frappe.db.get_tables()
+
+ final_deletion_map = frappe._dict()
+
+ for table in all_tables:
+ indexes_to_keep... | |
cb26f56c47e8125f9ac09ddfcd952fc42a9c3669 | quickly/families/migrations/0002_familymember_name.py | quickly/families/migrations/0002_familymember_name.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-05-17 16:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('families', '0001_initial'),
]
operations = [
migrations.AddField(
... | Add name to family member | Add name to family member
| Python | mit | wearespindle/quickly.press,wearespindle/quickly.press,wearespindle/quickly.press | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.2 on 2017-05-17 16:49
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('families', '0001_initial'),
+ ]
+
+ operations =... | |
fee9c862334bfd290a2b9bd1e07b93badfb66ae5 | letsencrypt-postfix/TestPostfixConfigGenerator.py | letsencrypt-postfix/TestPostfixConfigGenerator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import logging
import unittest
import Config
import PostfixConfigGenerator as pcg
logger = logging.getLogger(_... | Add failing test for get_all_names. | Add failing test for get_all_names.
| Python | apache-2.0 | letsencrypt/letsencrypt,lmcro/letsencrypt,stweil/letsencrypt,lmcro/letsencrypt,letsencrypt/letsencrypt,stweil/letsencrypt | ---
+++
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+from __future__ import unicode_literals
+
+import io
+import logging
+import unittest
+
+import Config
+import PostfixConfigGenera... | |
4d531a4ae2036785dffbb67d96fe013c7ca44784 | localtv/management/commands/send_welcome_email.py | localtv/management/commands/send_welcome_email.py | # Copyright 2011 - Participatory Culture Foundation
#
# This file is part of Miro Community.
#
# Miro Community is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at ... | Add management command to send welcome email | Add management command to send welcome email
| Python | agpl-3.0 | pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity | ---
+++
@@ -0,0 +1,54 @@
+# Copyright 2011 - Participatory Culture Foundation
+#
+# This file is part of Miro Community.
+#
+# Miro Community is free software: you can redistribute it and/or modify it
+# under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either... | |
518dd9401b41fc02c815ee6e0ca3b6b113d87f43 | mica/stats/tests/test_guide_stats.py | mica/stats/tests/test_guide_stats.py | import tempfile
import os
from .. import guide_stats
def test_calc_stats():
guide_stats.calc_stats(17210)
def test_make_gui_stats():
"""
Save the guide stats for one obsid into a newly-created table
"""
# Get a temporary file, but then delete it, because _save_acq_stats will only
# make a n... | Add a test that makes a new guide stats database | Add a test that makes a new guide stats database
| Python | bsd-3-clause | sot/mica,sot/mica | ---
+++
@@ -0,0 +1,24 @@
+import tempfile
+import os
+
+from .. import guide_stats
+
+
+def test_calc_stats():
+ guide_stats.calc_stats(17210)
+
+
+def test_make_gui_stats():
+ """
+ Save the guide stats for one obsid into a newly-created table
+ """
+ # Get a temporary file, but then delete it, becaus... | |
0f5de6aeae62337797993697307335276fd1d11a | python/005_smallest_multiple/smallest_multiple.py | python/005_smallest_multiple/smallest_multiple.py | from collections import Counter
from functools import reduce
from operator import mul
from typing import Generator
_range = tuple(range(2, 21))
def _factor_generator(number: int) -> Generator:
while number % 2 == 0:
number = number / 2
yield 2
cursor = 3
while cursor <= number:
if... | Add solution to problme 5 | Add solution to problme 5
| Python | bsd-3-clause | gidj/euler,gidj/euler | ---
+++
@@ -0,0 +1,28 @@
+from collections import Counter
+from functools import reduce
+from operator import mul
+from typing import Generator
+
+_range = tuple(range(2, 21))
+
+
+def _factor_generator(number: int) -> Generator:
+ while number % 2 == 0:
+ number = number / 2
+ yield 2
+ cursor = ... | |
4b125b0d6f1c3710499be585b08ecf70663415c3 | work/migrations/0002_auto_20170810_1630.py | work/migrations/0002_auto_20170810_1630.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-08-10 14:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0001_initial'),
]
operations = [
migrations.AlterField(
... | Set post stat on draft by default | Set post stat on draft by default
| Python | mit | oktomus/website,oktomus/website,oktomus/website | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.2 on 2017-08-10 14:30
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('work', '0001_initial'),
+ ]
+
+ operations = [
+... | |
1d6c17e5adc3df4de86636ef77fc0a406bf065e9 | scrapi/harvesters/dryad.py | scrapi/harvesters/dryad.py | '''
Harvester for Dryad for the SHARE project
Example API call: http://www.datadryad.org/oai/request?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class DryadHarvester(OAIHarvester):
short_name = 'dryad'
long_name = 'Dryad Data Reposi... | '''
Harvester for Dryad for the SHARE project
Example API call: http://www.datadryad.org/oai/request?verb=ListRecords&metadataPrefix=oai_dc
'''
from __future__ import unicode_literals
from lxml import etree
import logging
from scrapi.base import OAIHarvester
logger = logging.getLogger(__name__)
class DryadHarvest... | Add custom normaluze function that will not get non existant items | Add custom normaluze function that will not get non existant items
| Python | apache-2.0 | icereval/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,mehanig/scrapi,alexgarciac/scrapi,erinspace/scrapi,felliott/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,ostwald/scrapi,fabianvf/scrapi,jeffreyliu3230/scrapi,mehanig/scrapi | ---
+++
@@ -3,9 +3,14 @@
Example API call: http://www.datadryad.org/oai/request?verb=ListRecords&metadataPrefix=oai_dc
'''
+from __future__ import unicode_literals
-from __future__ import unicode_literals
+from lxml import etree
+import logging
+
from scrapi.base import OAIHarvester
+
+logger = logging.getLogg... |
339438e97f91958b1fc0cb1c2d85b3c6d97a1efa | lib/allosmod/config/__init__.py | lib/allosmod/config/__init__.py | # Dummy config; should not be installed. This is here simply so that the
# test suite works.
import os
datadir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'..', '..', '..', 'data')
local_scratch='/tmp'
global_scratch='/scrapp'
| Add dummy config file so that tests work. | Add dummy config file so that tests work.
| Python | lgpl-2.1 | salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib | ---
+++
@@ -0,0 +1,9 @@
+# Dummy config; should not be installed. This is here simply so that the
+# test suite works.
+
+import os
+
+datadir = os.path.join(os.path.abspath(os.path.dirname(__file__)),
+ '..', '..', '..', 'data')
+local_scratch='/tmp'
+global_scratch='/scrapp' | |
60c99b91cede21a509030f276684bb2ff706ec3c | wdom/tests/test_window.py | wdom/tests/test_window.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from time import sleep
from unittest.mock import MagicMock
from wdom.document import get_document
from wdom.server import _tornado
from wdom.server.handler import event_handler
from wdom.testing import TestCase
from wdom.window import customElements
class TestWindow(Te... | Add test for window module | Add test for window module
| Python | mit | miyakogi/wdom,miyakogi/wdom,miyakogi/wdom | ---
+++
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+from time import sleep
+from unittest.mock import MagicMock
+
+from wdom.document import get_document
+from wdom.server import _tornado
+from wdom.server.handler import event_handler
+from wdom.testing import TestCase
+from wdom.window impor... | |
00b35fc6373ec290d92b4b6aa71972b1f9d94105 | test/python3_regression.py | test/python3_regression.py | from __future__ import absolute_import, division, print_function
import os
def find_new_python3_incompatible_code(module_under_test):
'''
Check source code to see if any files violate Python 3 syntax that
previously did not. Example call:
def test_find_python3_violations():
import xia2
impo... | Add Jenkins Python3 monster to dials, but don't enable it here yet. | Add Jenkins Python3 monster to dials, but don't enable it here yet.
| Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | ---
+++
@@ -0,0 +1,63 @@
+from __future__ import absolute_import, division, print_function
+
+import os
+
+def find_new_python3_incompatible_code(module_under_test):
+ '''
+ Check source code to see if any files violate Python 3 syntax that
+ previously did not. Example call:
+
+ def test_find_python3_viola... | |
49b8df3387e6839bc2e0025ec8d2454ab61654a2 | dataactbroker/helpers/pandas_helper.py | dataactbroker/helpers/pandas_helper.py | import pandas as pd
from dataactcore.interfaces.db import GlobalDB
def check_dataframe_diff(new_data, model, id_col, sort_cols, lambda_funcs=None):
""" Checks if 2 dataframes (the new data and the existing data for a model) are different.
Args:
new_data: dataframe containing the new data to ... | Create a helper to check for differences in dataframes | Create a helper to check for differences in dataframes
| Python | cc0-1.0 | fedspendingtransparency/data-act-broker-backend,fedspendingtransparency/data-act-broker-backend | ---
+++
@@ -0,0 +1,54 @@
+import pandas as pd
+
+from dataactcore.interfaces.db import GlobalDB
+
+
+def check_dataframe_diff(new_data, model, id_col, sort_cols, lambda_funcs=None):
+ """ Checks if 2 dataframes (the new data and the existing data for a model) are different.
+
+ Args:
+ new_data: ... | |
0d1ce8eaf0329ab6efb6e1bbbb0edca2e78ce649 | python/qidoc/test/test_qidoc_list.py | python/qidoc/test/test_qidoc_list.py | ## Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved.
## Use of this source code is governed by a BSD-style license that can be
## found in the COPYING file.
def test_simple(qidoc_action, record_messages):
qidoc_action.add_test_project("world")
qidoc_action.add_test_project("libworld")
qidoc_... | Add a test for `qidoc list` | Add a test for `qidoc list`
Change-Id: I0fcd9fa17c2d69c5d90ec61eca872ca9a23f92b3
Reviewed-on: http://gerrit.aldebaran.lan/62795
Tested-by: gerrit
Reviewed-by: vbarbaresi <371b46c96c99af52f4f920034e4fcb63ece5bdb5@aldebaran-robotics.com>
| Python | bsd-3-clause | aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild | ---
+++
@@ -0,0 +1,10 @@
+## Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved.
+## Use of this source code is governed by a BSD-style license that can be
+## found in the COPYING file.
+
+def test_simple(qidoc_action, record_messages):
+ qidoc_action.add_test_project("world")
+ qidoc_action.add_t... | |
88dd94982afa76c3e450c9b186fa8054979779d3 | InformationScripting/test/scripts/countChanges.py | InformationScripting/test/scripts/countChanges.py | # script $<"<changes>" | "<countChanges>" | "<heatmap>">$
# assume single input
input = inputs[0]
commits = input.take("commit")
nodeCounts = {}
for commit in commits:
sha1 = commit.commit
for change in input.take(sha1):
key = getattr(change, sha1)
nodeCounts[key] = nodeCounts.get(key, 0) + 1
... | Add a script to count changes per node. | Add a script to count changes per node.
This makes it possible to show a heatmap of recently changed nodes.
| Python | bsd-3-clause | Vaishal-shah/Envision,Vaishal-shah/Envision,mgalbier/Envision,Vaishal-shah/Envision,mgalbier/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,mgalbier/Envision,dimitar-asenov/Envision,mgalbier/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,... | ---
+++
@@ -0,0 +1,17 @@
+# script $<"<changes>" | "<countChanges>" | "<heatmap>">$
+
+# assume single input
+input = inputs[0]
+commits = input.take("commit")
+nodeCounts = {}
+for commit in commits:
+ sha1 = commit.commit
+ for change in input.take(sha1):
+ key = getattr(change, sha1)
+ nodeCoun... | |
52fbd3f92454c103a484c03ae6cbea63dc1329ce | cinder/tests/tempest/api/volume/test_volume_unicode.py | cinder/tests/tempest/api/volume/test_volume_unicode.py | # -*- coding: utf-8 -*-
# Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#... | Add Unicode volume name test | tempest: Add Unicode volume name test
Create and view a volume with Unicode characters
in the name.
Change-Id: I0c49814a98921d9743f74a6fc0b0b0044473c398
| Python | apache-2.0 | Datera/cinder,bswartz/cinder,cloudbase/cinder,bswartz/cinder,phenoxim/cinder,Nexenta/cinder,eharney/cinder,eharney/cinder,mahak/cinder,Nexenta/cinder,Hybrid-Cloud/cinder,ge0rgi/cinder,j-griffith/cinder,openstack/cinder,NetApp/cinder,phenoxim/cinder,j-griffith/cinder,Datera/cinder,openstack/cinder,Hybrid-Cloud/cinder,Ne... | ---
+++
@@ -0,0 +1,59 @@
+# -*- coding: utf-8 -*-
+# Copyright 2016 Red Hat, Inc.
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://w... | |
1263bf8dd374afe04735948e767bb31813d99077 | test/on_yubikey/cli_piv/test_read_write_object.py | test/on_yubikey/cli_piv/test_read_write_object.py | import os
import unittest
from ..framework import cli_test_suite
from ykman.piv import OBJ
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class ReadWriteObject(unittest.TestCase):
def setUp(cls):
ykman_cli('piv', 'reset', '-f')
pass
... | Add test of PIV read/write object cycle | Add test of PIV read/write object cycle
| Python | bsd-2-clause | Yubico/yubikey-manager,Yubico/yubikey-manager | ---
+++
@@ -0,0 +1,41 @@
+import os
+import unittest
+
+from ..framework import cli_test_suite
+from ykman.piv import OBJ
+from .util import DEFAULT_MANAGEMENT_KEY
+
+
+@cli_test_suite
+def additional_tests(ykman_cli):
+ class ReadWriteObject(unittest.TestCase):
+
+ def setUp(cls):
+ ykman_cli('p... | |
e419ae979fc59af758c5fe93bde7add47dcf21df | UM/Settings/ProfileWriter.py | UM/Settings/ProfileWriter.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.PluginObject import PluginObject
## Base class for profile writer plugins.
#
# This class defines a write() function to write profiles to files with.
class ProfileWriter(PluginObject):
## Initialises the... | Add base class for profile writer plugins | Add base class for profile writer plugins
This class defines the write() function to write profiles with, that all profile writer plugins should implement.
Contributes to issue CURA-34.
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -0,0 +1,24 @@
+# Copyright (c) 2015 Ultimaker B.V.
+# Uranium is released under the terms of the AGPLv3 or higher.
+
+from UM.PluginObject import PluginObject
+
+## Base class for profile writer plugins.
+#
+# This class defines a write() function to write profiles to files with.
+class ProfileWriter(Pl... | |
a61d86d235d3968898911596df594f93fe96d7e5 | Sketches/MPS/Synchronous.py | Sketches/MPS/Synchronous.py | #!/usr/bin/python
import Axon
import time
from Kamaelia.Chassis.Pipeline import Pipeline
class MySender(Axon.Component.component):
def main(self):
while 1:
yield 1
sent = False
print "-----------------------------------------------------------------------"
w... | Test suite used for testing the Component level API for fixed box sizes | Test suite used for testing the Component level API for fixed box sizes
Michael
| 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,61 @@
+#!/usr/bin/python
+
+import Axon
+import time
+from Kamaelia.Chassis.Pipeline import Pipeline
+
+class MySender(Axon.Component.component):
+ def main(self):
+ while 1:
+ yield 1
+ sent = False
+ print "-----------------------------------------------... | |
1663cb8557de85b1f3ccf5822fa01758e679ccd7 | TestScript/multi_client.py | TestScript/multi_client.py | # -*- coding: utf-8 -*-
__author__ = 'sm9'
import asyncore, socket
import string, random
import struct, time
HOST = '192.168.0.11'
PORT = 9001
PKT_CS_LOGIN = 1
PKT_SC_LOGIN = 2
PKT_CS_CHAT = 3
PKT_SC_CHAT = 4
def str_generator(size=128, chars=string.ascii_uppercase + string.digits):
return... | Test script for the stress test | *added: Test script for the stress test | Python | mit | zrma/EasyGameServer,zeliard/EasyGameServer,zeliard/EasyGameServer,zrma/EasyGameServer,Lt-Red/EasyGameServer,Lt-Red/EasyGameServer | ---
+++
@@ -0,0 +1,100 @@
+# -*- coding: utf-8 -*-
+__author__ = 'sm9'
+
+import asyncore, socket
+import string, random
+import struct, time
+
+HOST = '192.168.0.11'
+PORT = 9001
+
+
+PKT_CS_LOGIN = 1
+PKT_SC_LOGIN = 2
+PKT_CS_CHAT = 3
+PKT_SC_CHAT = 4
+
+
+def str_generator(size=128, chars=string.ascii_uppercase ... | |
3a3f529498522dada5e6af6765cd537f47d368d8 | Tools/compiler/stacktest.py | Tools/compiler/stacktest.py | import compiler
import dis
import types
def extract_code_objects(co):
l = [co]
for const in co.co_consts:
if type(const) == types.CodeType:
l.append(const)
return l
def compare(a, b):
if not (a.co_name == "?" or a.co_name.startswith('<lambda')):
assert a.co_name == b.co_nam... | Test utility to look for bad stacksize calculations. | Test utility to look for bad stacksize calculations.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -0,0 +1,43 @@
+import compiler
+import dis
+import types
+
+def extract_code_objects(co):
+ l = [co]
+ for const in co.co_consts:
+ if type(const) == types.CodeType:
+ l.append(const)
+ return l
+
+def compare(a, b):
+ if not (a.co_name == "?" or a.co_name.startswith('<lambda'... | |
63709e388ed86892e9771b86daad4a9ec3c0bd44 | ibei/__init__.py | ibei/__init__.py | # -*- coding: utf-8 -*-
"""
Base Library (:mod:`ibei`)
==========================
.. currentmodule:: ibei
"""
from .version import __version__
from .uibei import uibei
from .sqsolarcell import SQSolarcell
from .devossolarcell import DeVosSolarcell
| # -*- coding: utf-8 -*-
"""
Base Library (:mod:`ibei`)
==========================
.. currentmodule:: ibei
"""
from .version import __version__
from .uibei import uibei
| Remove import of specific models | Remove import of specific models
| Python | mit | jrsmith3/ibei | ---
+++
@@ -8,5 +8,3 @@
from .version import __version__
from .uibei import uibei
-from .sqsolarcell import SQSolarcell
-from .devossolarcell import DeVosSolarcell |
3ef6a9d7d40dd66c89fd3e5c309ad76b5d4e836c | heat/tests/test_fault_middleware.py | heat/tests/test_fault_middleware.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | Add unittests for faultwrap middleware | Add unittests for faultwrap middleware
Partially implements bp exception-formatting
Change-Id: Ib57ce625775e222e5b42b22c10687bce7b63d26d
| Python | apache-2.0 | miguelgrinberg/heat,JioCloud/heat,takeshineshiro/heat,pshchelo/heat,jasondunsmore/heat,dragorosson/heat,rh-s/heat,maestro-hybrid-cloud/heat,pratikmallya/heat,miguelgrinberg/heat,rickerc/heat_audit,NeCTAR-RC/heat,cwolferh/heat-scratch,cryptickp/heat,openstack/heat,steveb/heat,gonzolino/heat,rh-s/heat,citrix-openstack-bu... | ---
+++
@@ -0,0 +1,65 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# 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
+#... | |
5a2e3da28fa2471d97b5d0e1b3cae76602dc9c79 | snippets/list_holidays.py | snippets/list_holidays.py | import pandas as pd
from datetime import date
import holidays
def process_holidays(df):
year = df['year']
user_date = date(year, df['month'], df['day'])
hd = holidays.US(years=year)
for holiday_date, name in hd.iteritems():
days = (holiday_date - user_date).days
# Get the real data for... | Create small script to compute distance to some US holidays | Create small script to compute distance to some US holidays
| Python | mit | davidgasquez/kaggle-airbnb | ---
+++
@@ -0,0 +1,27 @@
+import pandas as pd
+from datetime import date
+import holidays
+
+def process_holidays(df):
+ year = df['year']
+ user_date = date(year, df['month'], df['day'])
+ hd = holidays.US(years=year)
+ for holiday_date, name in hd.iteritems():
+ days = (holiday_date - user_date).... | |
e6c79dc248d51b38da2d6fa0e92468176b0b21bc | migrations/versions/1010_remove_unused_fields.py | migrations/versions/1010_remove_unused_fields.py | """Remove unused fields
Revision ID: 1010
Revises: 1000
Create Date: 2017-10-04 15:14:48.532073
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '1010'
down_revision = '1000'
def upgrade():
op.drop_column('contact... | Remove unused fields from model and drop columns from db | Remove unused fields from model and drop columns from db
| Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api | ---
+++
@@ -0,0 +1,31 @@
+"""Remove unused fields
+
+Revision ID: 1010
+Revises: 1000
+Create Date: 2017-10-04 15:14:48.532073
+
+"""
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+
+# revision identifiers, used by Alembic.
+revision = '1010'
+down_revision = '1000'
+
... | |
14a1e5fb2afe9c372646ce26a9b2b92c517067b3 | minecraft-server/minecraftforge_spider.py | minecraft-server/minecraftforge_spider.py | # -*- coding: utf-8 -*-
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.selector import Selector
import re
class Forge(scrapy.Item):
versions = scrapy.Field()
latest = scrapy.Field()
class ForgeVersions(scrapy.Item):
i... | Add initial version of forge download scraper | Add initial version of forge download scraper
| Python | apache-2.0 | jbeda/itzg-dockerfiles,zerocoolys/dockerfiles-1,sekka1/dockerfiles,zerocoolys/dockerfiles-1,jbeda/itzg-dockerfiles,jbeda/itzg-dockerfiles,ajthemacboy/dockerfiles,itzg/dockerfiles,sekka1/dockerfiles,sekka1/dockerfiles,zerocoolys/dockerfiles-1 | ---
+++
@@ -0,0 +1,68 @@
+# -*- coding: utf-8 -*-
+import scrapy
+from scrapy.contrib.spiders import CrawlSpider, Rule
+from scrapy.contrib.linkextractors import LinkExtractor
+from scrapy.selector import Selector
+
+import re
+
+class Forge(scrapy.Item):
+ versions = scrapy.Field()
+ latest = scrapy.Field()
+
... | |
027aa7152e3873c3bfa96c04e4d2ea0b6c345020 | snippet/example/python/sqlalchemy-orm-example.py | snippet/example/python/sqlalchemy-orm-example.py | # encoding: utf8
from __future__ import print_function
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, prima... | Add the usage example of sqlalchemy ORM. | Add the usage example of sqlalchemy ORM.
| Python | mit | xgfone/snippet,xgfone/snippet,xgfone/snippet,xgfone/snippet,xgfone/snippet,xgfone/snippet,xgfone/snippet | ---
+++
@@ -0,0 +1,49 @@
+# encoding: utf8
+from __future__ import print_function
+
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy import create_engine, Column, Integer, String
+from sqlalchemy.ext.declarative import declarative_base
+
+Base = declarative_base()
+
+
+class User(Base):
+ __tablename__ = ... | |
c58a30b5b410595b76aebc8db7025a49b231b75b | scripts/most_recent.py | scripts/most_recent.py | from datetime import datetime
from optparse import OptionParser
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
if __name__ == '__main__':
usage = "%prog <USERNAME> <WEB SERVER>"
parser = OptionParser(usage=usage)
opts,args = parser.parse_args()
if len(args) != 2:
parser.e... | Add script to print time of most recent gobble. | Add script to print time of most recent gobble.
| Python | agpl-3.0 | foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm | ---
+++
@@ -0,0 +1,22 @@
+from datetime import datetime
+from optparse import OptionParser
+from urllib2 import urlopen
+
+from BeautifulSoup import BeautifulSoup
+
+
+if __name__ == '__main__':
+ usage = "%prog <USERNAME> <WEB SERVER>"
+ parser = OptionParser(usage=usage)
+ opts,args = parser.parse_args()
+... | |
febfaffb2bdbb9529cbb7df004b62ae8a2a07ad0 | tests/test_jeffress_big.py | tests/test_jeffress_big.py | """
In this test we create a bigger Jeffress model.
- It consists of 180 output neurons.
- The axonal delay between the input neurons and the inter-layer neurons are sampled from 0ms to 100ms.
- We create the same spiketrain with 50 ms difference between the two input neurons.
One can see that the better the weigh... | Add example, Jeffress net with 180 neurons | Add example, Jeffress net with 180 neurons
| Python | bsd-2-clause | timqian/neurons,johannesmik/neurons | ---
+++
@@ -0,0 +1,54 @@
+"""
+In this test we create a bigger Jeffress model.
+
+ - It consists of 180 output neurons.
+ - The axonal delay between the input neurons and the inter-layer neurons are sampled from 0ms to 100ms.
+ - We create the same spiketrain with 50 ms difference between the two input neurons.
+
+On... | |
2a51077d78b7b30a1ca751595b6872b9532b070c | zthread/refactor/rename.py | zthread/refactor/rename.py | #!/usr/bin/env python
import re,glob,os,sys
def rename(dir_path, search_pattern):
for file_path in glob.iglob(os.path.join(dir_path, search_pattern)):
title, ext = os.path.splitext(os.path.basename(file_path))
res = "_".join([s.group(0).lower() for s in
re.finditer(r"[A-Z][a-z]+", tit... | Add a script to help to refactor source code. | Add a script to help to refactor source code.
| Python | mit | YanShenChun/cppthread,YanShenChun/cppthread,YanShenChun/cppthread | ---
+++
@@ -0,0 +1,27 @@
+#!/usr/bin/env python
+
+import re,glob,os,sys
+
+def rename(dir_path, search_pattern):
+ for file_path in glob.iglob(os.path.join(dir_path, search_pattern)):
+ title, ext = os.path.splitext(os.path.basename(file_path))
+ res = "_".join([s.group(0).lower() for s in
+ ... | |
52ca0942faaa52138805f966cb0b242009516a06 | py/coin-change.py | py/coin-change.py | class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
min_count = [0] * (amount + 1)
for c in coins:
if c <= amount:
min_count[c] = 1
for i in xrange(min(co... | Add py solution for 322. Coin Change | Add py solution for 322. Coin Change
322. Coin Change: https://leetcode.com/problems/coin-change/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,25 @@
+class Solution(object):
+ def coinChange(self, coins, amount):
+ """
+ :type coins: List[int]
+ :type amount: int
+ :rtype: int
+ """
+ min_count = [0] * (amount + 1)
+ for c in coins:
+ if c <= amount:
+ min_count... | |
8ddda76d25fd2572eccd24353d2347242af063fa | benchexec/tools/cbmc-path.py | benchexec/tools/cbmc-path.py | """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2018 Dirk Beyer
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
ht... | Add tool-info module for CBMC Path | Add tool-info module for CBMC Path
This module inherits from CBMC's tool-info module, except that it
returns "CBMC Path" as the tool name. The --paths switch is specified in
the wrapper script `cbmc`, which invokes `cbmc-binary`.
| Python | apache-2.0 | dbeyer/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,dbeyer/benchexec,sosy-lab/benchexec | ---
+++
@@ -0,0 +1,30 @@
+"""
+BenchExec is a framework for reliable benchmarking.
+This file is part of BenchExec.
+Copyright (C) 2007-2018 Dirk Beyer
+All rights reserved.
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obt... | |
8aaa76b3adb7f7c661eba8d1f4c50e8b0f03fee4 | s3_to_azure/move_files.py | s3_to_azure/move_files.py | import sys
import time
from azure.storage import BlobService
from azure import WindowsAzureMissingResourceError
from CREDENTIALS import account_name, account_key
db = BlobService(account_name=account_name, account_key=account_key)
###
bucket = 'crawl-data'
in_progress = set()
#
existing = set([x.name for x in db.list... | Add a script that moves files to Azure storage using Copy Blob API | Add a script that moves files to Azure storage using Copy Blob API
| Python | mit | Smerity/cc-quick-scripts,Smerity/cc-quick-scripts | ---
+++
@@ -0,0 +1,38 @@
+import sys
+import time
+from azure.storage import BlobService
+from azure import WindowsAzureMissingResourceError
+
+from CREDENTIALS import account_name, account_key
+db = BlobService(account_name=account_name, account_key=account_key)
+
+###
+bucket = 'crawl-data'
+in_progress = set()
+#
... | |
c3ec949a888896cc2457c391f797c504538bcf51 | junction/tickets/management/commands/fill_data.py | junction/tickets/management/commands/fill_data.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
import optparse
# Third Party Stuff
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
# Junction Stuff
from junction.tickets.models import Ticket
class Comman... | Add management command to fill data for given ticket nums | Add management command to fill data for given ticket nums
`fill_data` management command takes input file which has a list of
ticket numbers and outputs a csv with all details of given ticket numbers
| Python | mit | nava45/junction,nava45/junction,ChillarAnand/junction,pythonindia/junction,pythonindia/junction,pythonindia/junction,pythonindia/junction,ChillarAnand/junction,ChillarAnand/junction,nava45/junction,nava45/junction,ChillarAnand/junction | ---
+++
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, print_function, unicode_literals
+
+import os
+import optparse
+
+# Third Party Stuff
+from django.core.management.base import BaseCommand, CommandError
+from django.db import transaction
+
+# Junction Stuff
+from junction.tick... | |
e86c87f4d97677f18522321ca06f79373722a610 | senlin/tests/middleware/test_trust_middleware.py | senlin/tests/middleware/test_trust_middleware.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 unde... | Add test case for Trust Middleware | Add test case for Trust Middleware
This patch adds a test case for Trust Middleware in order to verify its correctness.
Change-Id: I26a65d8ac617e3011dc2be104138e9d177c98c80
Closes-Bug: #1469947
| Python | apache-2.0 | stackforge/senlin,openstack/senlin,Alzon/senlin,openstack/senlin,tengqm/senlin-container,openstack/senlin,tengqm/senlin-container,Alzon/senlin,stackforge/senlin | ---
+++
@@ -0,0 +1,64 @@
+# 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 wr... | |
ddbda12b1cb83886b8edab6e50bdde8a6a2d2672 | compass/tests/test_views.py | compass/tests/test_views.py | from django.test import TestCase, Client
from ..models import Category, Book
class CompassTest(TestCase):
@classmethod
def setUpClass(cls):
cls.client = Client()
super(CompassTest, cls).setUpClass()
def test_can_view_search_page(self):
response = self.client.get('/')
self... | Test views return response for searched query | Test views return response for searched query
| Python | mit | andela-osule/bookworm,andela-osule/bookworm | ---
+++
@@ -0,0 +1,63 @@
+from django.test import TestCase, Client
+from ..models import Category, Book
+
+
+
+class CompassTest(TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.client = Client()
+ super(CompassTest, cls).setUpClass()
+
+ def test_can_view_search_page(self):
+ resp... | |
e6bfcede8cb01fa38a5401315422a13d28983182 | tests/test_agent.py | tests/test_agent.py | import json
import pytest
import zmq
from zephyrus.addresses import Participants
from zephyrus.agent import Agent
from zephyrus.message import Message
from zephyrus.tester import TesterMessenger as ZTesterMessenger
@pytest.fixture
def DummyAgent():
class Dummy(Agent):
def act(self, perceived):
... | Add tests to agent module. Just sunny day case for now | Add tests to agent module. Just sunny day case for now
| Python | mit | wairton/zephyrus-mas | ---
+++
@@ -0,0 +1,63 @@
+import json
+
+import pytest
+import zmq
+
+from zephyrus.addresses import Participants
+from zephyrus.agent import Agent
+from zephyrus.message import Message
+from zephyrus.tester import TesterMessenger as ZTesterMessenger
+
+
+@pytest.fixture
+def DummyAgent():
+ class Dummy(Agent):
+ ... | |
797599802c4702d4a4452aafa276ceedd829e27f | tests/test_tools.py | tests/test_tools.py | from windpowerlib.tools import smallest_difference
import collections
class TestTools:
@classmethod
def setup_class(self):
self.return_tuple = collections.namedtuple('selected_values',
['closest_value',
... | Add test module for tools module | Add test module for tools module
| Python | mit | wind-python/windpowerlib | ---
+++
@@ -0,0 +1,28 @@
+from windpowerlib.tools import smallest_difference
+import collections
+
+
+class TestTools:
+
+ @classmethod
+ def setup_class(self):
+ self.return_tuple = collections.namedtuple('selected_values',
+ ['closest_value',
+ ... | |
2d557b68fd9b7e0e900215afeb5185e466907a49 | cyhdfs3/tests/test_avro.py | cyhdfs3/tests/test_avro.py | import posixpath
import subprocess
import numpy as np
import pandas as pd
import pandas.util.testing as pdt
import cyavro
from utils import *
avroschema = """ {"type": "record",
"name": "from_bytes_test",
"fields":[
{"name": "id", "type": "int"},
{"name": "name", "type": "string"}
]
}
"""
def test_avro_mov... | Add test for reading and writing avro bytes to hdfs | Add test for reading and writing avro bytes to hdfs
| Python | apache-2.0 | danielfrg/libhdfs3.py,danielfrg/libhdfs3.py,danielfrg/cyhdfs3,danielfrg/cyhdfs3 | ---
+++
@@ -0,0 +1,81 @@
+import posixpath
+import subprocess
+
+import numpy as np
+import pandas as pd
+import pandas.util.testing as pdt
+
+import cyavro
+
+from utils import *
+
+
+avroschema = """ {"type": "record",
+"name": "from_bytes_test",
+"fields":[
+ {"name": "id", "type": "int"},
+ {"name": "name", "... | |
5b619029441261659bf0f326f784e5322a952096 | coursera-crypto-i/w4/pbdkf2_hmac_sha256.py | coursera-crypto-i/w4/pbdkf2_hmac_sha256.py | import binascii, hashlib, hmac, os, time
def scramble_with_kdf(passw, salt, iters):
return hashlib.pbkdf2_hmac('sha256', passw, salt, iters, 32)
def scramble_with_sha256(passw, salt, iters):
passw = salt + passw
for i in range(iters):
passw = hashlib.sha256(passw).digest()
return passw
def sc... | Add timing test of password scrambling with pbkdf2, sha-256 and hmac(sha-256) | Add timing test of password scrambling with pbkdf2, sha-256 and hmac(sha-256)
| Python | mit | reider-roque/crypto-challenges | ---
+++
@@ -0,0 +1,37 @@
+import binascii, hashlib, hmac, os, time
+
+def scramble_with_kdf(passw, salt, iters):
+ return hashlib.pbkdf2_hmac('sha256', passw, salt, iters, 32)
+
+def scramble_with_sha256(passw, salt, iters):
+ passw = salt + passw
+ for i in range(iters):
+ passw = hashlib.sha256(pass... | |
a8f152e9a6a2db98305ee84dfb5b3be3cee91a84 | us_ignite/apps/management/commands/app_import.py | us_ignite/apps/management/commands/app_import.py | import requests
from django.core.management.base import BaseCommand, CommandError
from us_ignite.apps import importer
class Command(BaseCommand):
help = 'Import the given JSON file.'
def handle(self, url, *args, **options):
response = requests.get(url)
if not response.status_code == 200:
... | Implement importer as a management command. | Implement importer as a management command.
Heroku has limitations on the ammount of time that a request
should take.
By using a management command the application can workaround
the time it takes to perform the import.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -0,0 +1,17 @@
+import requests
+
+from django.core.management.base import BaseCommand, CommandError
+
+from us_ignite.apps import importer
+
+
+class Command(BaseCommand):
+ help = 'Import the given JSON file.'
+
+ def handle(self, url, *args, **options):
+ response = requests.get(url)
+ ... | |
3ed70bcc0c699744fd4dc3259ca2f0b6ee7e5d6a | swampdragon/pubsub_providers/redis_sub_provider.py | swampdragon/pubsub_providers/redis_sub_provider.py | import json
import tornadoredis.pubsub
import tornadoredis
from .base_provider import BaseProvider
from .redis_settings import get_redis_host, get_redis_port, get_redis_db
class RedisSubProvider(BaseProvider):
def __init__(self):
self._subscriber = tornadoredis.pubsub.SockJSSubscriber(tornadoredis.Client(... | import json
import tornadoredis.pubsub
import tornadoredis
from .base_provider import BaseProvider
from .redis_settings import get_redis_host, get_redis_port, get_redis_db, get_redis_password
class RedisSubProvider(BaseProvider):
def __init__(self):
self._subscriber = tornadoredis.pubsub.SockJSSubscriber(... | Add auth step to baseprovider for Redis connection pools | Add auth step to baseprovider for Redis connection pools
| Python | bsd-3-clause | denizs/swampdragon,jonashagstedt/swampdragon,jonashagstedt/swampdragon,denizs/swampdragon,denizs/swampdragon,jonashagstedt/swampdragon | ---
+++
@@ -2,7 +2,7 @@
import tornadoredis.pubsub
import tornadoredis
from .base_provider import BaseProvider
-from .redis_settings import get_redis_host, get_redis_port, get_redis_db
+from .redis_settings import get_redis_host, get_redis_port, get_redis_db, get_redis_password
class RedisSubProvider(BaseProv... |
0a74878997b2df53b1e482a61a36c6e9f35b248a | examples/uevents.py | examples/uevents.py | import time
from examples.common import print_devices
import blivet
from blivet.events.manager import event_manager
from blivet.util import set_up_logging
def print_changes(event, changes):
print("***", event)
for change in changes:
print("***", change)
print("***")
print()
set_up_logging(c... | Add an example of event monitoring. | Add an example of event monitoring.
| Python | lgpl-2.1 | rvykydal/blivet,AdamWill/blivet,jkonecny12/blivet,rhinstaller/blivet,jkonecny12/blivet,rhinstaller/blivet,rvykydal/blivet,AdamWill/blivet,vpodzime/blivet,vojtechtrefny/blivet,vpodzime/blivet,vojtechtrefny/blivet | ---
+++
@@ -0,0 +1,26 @@
+import time
+
+from examples.common import print_devices
+
+import blivet
+from blivet.events.manager import event_manager
+from blivet.util import set_up_logging
+
+
+def print_changes(event, changes):
+ print("***", event)
+ for change in changes:
+ print("***", change)
+ p... | |
49b916ce00d919a73ddc8923f62e0b4c6115b608 | src/coranking_test.py | src/coranking_test.py | import unittest
import nose.tools
from sklearn import manifold, datasets
from mia.coranking import trustworthiness, continuity, LCMC, coranking_matrix
from mia.utils import *
class CorankingTest(unittest.TestCase):
def setUp(self):
self._high_data, color \
= datasets.samples_generator.make_s... | Add test to source folder. | Add test to source folder.
| Python | mit | samueljackson92/coranking | ---
+++
@@ -0,0 +1,44 @@
+import unittest
+import nose.tools
+from sklearn import manifold, datasets
+
+from mia.coranking import trustworthiness, continuity, LCMC, coranking_matrix
+from mia.utils import *
+
+
+class CorankingTest(unittest.TestCase):
+
+ def setUp(self):
+ self._high_data, color \
+ ... | |
9c4cb69b60b7d91a5ed07f2871174e276db80071 | loadcontent.py | loadcontent.py | from os import listdir, path
basedir = '../../website.content/'
for app in listdir(basedir):
module = __import__(app,{},{},fromlist=['load'])
if 'loaddir' in dir(module.load):
module.load.loaddir(path.join(basedir, app), clear=True)
elif 'loadfile' in dir(module.load):
module.load.clear()
... | Load content from a given directory. | Load content from a given directory.
Currently, the directory is hard-coded.
| Python | agpl-3.0 | luispedro/django-gitcms,luispedro/django-gitcms | ---
+++
@@ -0,0 +1,11 @@
+from os import listdir, path
+basedir = '../../website.content/'
+for app in listdir(basedir):
+ module = __import__(app,{},{},fromlist=['load'])
+ if 'loaddir' in dir(module.load):
+ module.load.loaddir(path.join(basedir, app), clear=True)
+ elif 'loadfile' in dir(module.loa... | |
cd0e3ec8359eeec31ad383310c2bab4588dc095a | IcedID_Downloader/ztrak_downloader_strings_ida.py | IcedID_Downloader/ztrak_downloader_strings_ida.py | def gen_key(k):
return(((k << 0x1d) | (k >> 3)) & 0xffffffff)
#Unpacked of 32a683ac11d966d73fedf4e249573022891ac902086167e4d20b18be28bd2c1d
for addr in XrefsTo(0x40233e, flags=0):
addr = addr.frm
#print(hex(addr))
addr = idc.PrevHead(addr)
while GetMnem(addr) != "push":
addr = idc.PrevHead(addr)
prin... | Add IcedID downloader ida string decoding | Add IcedID downloader ida string decoding
| Python | mit | sysopfb/Malware_Scripts | ---
+++
@@ -0,0 +1,65 @@
+def gen_key(k):
+ return(((k << 0x1d) | (k >> 3)) & 0xffffffff)
+
+#Unpacked of 32a683ac11d966d73fedf4e249573022891ac902086167e4d20b18be28bd2c1d
+for addr in XrefsTo(0x40233e, flags=0):
+ addr = addr.frm
+ #print(hex(addr))
+ addr = idc.PrevHead(addr)
+ while GetMnem(addr) != "push":
+ addr... | |
c4b83a909eb7149ac3da33b90e912d1275a8dc16 | tests/compiler/test_access_compilation.py | tests/compiler/test_access_compilation.py | from tests.compiler import compile_local, A_ID, LST_ID, SELF_ID, VAL1_ID
from thinglang.compiler.opcodes import OpcodePushLocal, OpcodePushIndexImmediate, OpcodePushIndex, OpcodePushMember
def test_local_list_immediate_index():
assert compile_local('lst[123]') == [OpcodePushLocal(LST_ID), OpcodePushIndexImmediate... | Add tests for indexed access compilation | Add tests for indexed access compilation
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -0,0 +1,12 @@
+from tests.compiler import compile_local, A_ID, LST_ID, SELF_ID, VAL1_ID
+from thinglang.compiler.opcodes import OpcodePushLocal, OpcodePushIndexImmediate, OpcodePushIndex, OpcodePushMember
+
+
+def test_local_list_immediate_index():
+ assert compile_local('lst[123]') == [OpcodePushLocal(... | |
ca109b6cd0f7ce5818abdf413abcac51fc5f8b0d | odl/contrib/param_opt/test/test_param_opt.py | odl/contrib/param_opt/test/test_param_opt.py | import pytest
import odl
import odl.contrib.fom
import odl.contrib.param_opt
from odl.util.testutils import simple_fixture
space = simple_fixture('space',
[odl.rn(3),
odl.uniform_discr([0, 0], [1, 1], [9, 11]),
odl.uniform_discr(0, 1, 10)])
def te... | Add initial test for the optimal_parameters function. | TST: Add initial test for the optimal_parameters function.
| Python | mpl-2.0 | odlgroup/odl,kohr-h/odl,odlgroup/odl,kohr-h/odl | ---
+++
@@ -0,0 +1,29 @@
+import pytest
+import odl
+import odl.contrib.fom
+import odl.contrib.param_opt
+from odl.util.testutils import simple_fixture
+
+space = simple_fixture('space',
+ [odl.rn(3),
+ odl.uniform_discr([0, 0], [1, 1], [9, 11]),
+ ... | |
9ade5a79e74281f8503c798b06f6b568122b0594 | addons/zotero/migrations/0005_auto_20180216_0849.py | addons/zotero/migrations/0005_auto_20180216_0849.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-02-16 14:49
from __future__ import unicode_literals
from bulk_update.helper import bulk_update
from django.db import migrations
def reverse_func(state, schema):
print 'Starting reverse zotero library migration'
modify_node_settings(state, None)
... | Add data migration for existing zotero user and node settings models - "personal" library is the only library that was previously available, but now group libraries are accessible. | Add data migration for existing zotero user and node settings models - "personal" library is the only library that was previously available, but now group libraries are accessible.
| Python | apache-2.0 | chennan47/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,icereval/osf.io,erinspace/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,icereval/osf.io,felliott/osf.io,erinspace/osf.io,sloria/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,mfraezz/osf.io,m... | ---
+++
@@ -0,0 +1,68 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.9 on 2018-02-16 14:49
+from __future__ import unicode_literals
+
+from bulk_update.helper import bulk_update
+from django.db import migrations
+
+def reverse_func(state, schema):
+ print 'Starting reverse zotero library migration'
+ m... | |
7578cef2d5006af632b45ce6b279d54253db3b5b | pi_approach/Libraries/serverxclient.py | pi_approach/Libraries/serverxclient.py | # Server and Client Abstraction Library
import socket
HOST = "userinterface.local"
PORT = 12345
class Server(object):
"""A server-serving class"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def setup_server(self):
try:
Server.s.bind((HOST,PORT))
print "Bind success"
except socket.error:
... | Add abstracted server and client library | Add abstracted server and client library
| Python | mit | the-raspberry-pi-guy/lidar | ---
+++
@@ -0,0 +1,47 @@
+# Server and Client Abstraction Library
+
+import socket
+
+HOST = "userinterface.local"
+PORT = 12345
+
+class Server(object):
+ """A server-serving class"""
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+
+ def setup_server(self):
+ try:
+ Server.s.bind((HOST,PORT))
+ print... | |
a9efd01f22a4fe311b97bb6ef4f14e3abe1a5dc1 | analysis/sort-by.py | analysis/sort-by.py | #!/usr/bin/env python
"""
Sort a result list by a particular top level key.
The key must have a total order (e.g. strings, ints, floats)
"""
import argparse
import os
import logging
import pprint
import sys
import yaml
from br_util import FinalResultType, classifyResult
# HACK
_brPath = os.path.dirname(os.path.dirname... | Add script to sort results. This is useful for sorting by the "total_time" key. | Add script to sort results. This is useful for sorting by the
"total_time" key.
| Python | bsd-3-clause | symbooglix/boogie-runner,symbooglix/boogie-runner | ---
+++
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+"""
+Sort a result list by a particular top level key.
+The key must have a total order (e.g. strings, ints, floats)
+"""
+import argparse
+import os
+import logging
+import pprint
+import sys
+import yaml
+from br_util import FinalResultType, classifyResult
+
+# HACK
... | |
2ad3cb462469a2d4f3f457e1e520979871410d20 | tests/test/xie/graphics/shape.py | tests/test/xie/graphics/shape.py | import unittest
import copy
from xie.graphics.shape import Pane
class PaneTestCase(unittest.TestCase):
def setUp(self):
self.generateTestData()
def tearDown(self):
pass
def generateTestData(self):
self.pane_1=Pane(38, 32, 101, 50)
self.pane_2=Pane(22, 50, 122, 89)
self.pane_3=Pane(5, 20, 31, 32)
self... | Add test cases for Pane. | Add test cases for Pane.
| Python | apache-2.0 | xrloong/Xie | ---
+++
@@ -0,0 +1,42 @@
+import unittest
+import copy
+
+from xie.graphics.shape import Pane
+
+class PaneTestCase(unittest.TestCase):
+ def setUp(self):
+ self.generateTestData()
+
+ def tearDown(self):
+ pass
+
+ def generateTestData(self):
+ self.pane_1=Pane(38, 32, 101, 50)
+ self.pane_2=Pane(22, 50, 122, 89... | |
efdb0a8c8857ca04614108769e898cc409615b18 | functions.py | functions.py | import numpy as np
from key import Key
def remove_duplicates(values):
output = []
seen = []
for value in values:
if not np.any([np.all(value == x) for x in seen]):
output.append(value)
seen.append(value)
return output
def key_proliferation(input_keys):
dt = np.dtype... | Develop key_proliferate function to create new keys. | Develop key_proliferate function to create new keys.
| Python | apache-2.0 | paulsbrookes/subcipher | ---
+++
@@ -0,0 +1,22 @@
+import numpy as np
+from key import Key
+
+def remove_duplicates(values):
+ output = []
+ seen = []
+ for value in values:
+ if not np.any([np.all(value == x) for x in seen]):
+ output.append(value)
+ seen.append(value)
+ return output
+
+def key_prol... | |
ba388774ac7326efae78cfc69768985e71c988f4 | test/test_ev3_battery_percentage.py | test/test_ev3_battery_percentage.py | import ev3.ev3dev
import unittest
from util import get_input
class TestI2CS(unittest.TestCase):
def test_battery(self):
print(ev3.ev3dev.get_battery_percentage())
if __name__ == '__main__':
unittest.main()
| Move get_battery_percentage to module method Add test | Move get_battery_percentage to module method
Add test
| Python | apache-2.0 | MaxNoe/python-ev3,topikachu/python-ev3,topikachu/python-ev3,evz/python-ev3,MaxNoe/python-ev3,evz/python-ev3 | ---
+++
@@ -0,0 +1,11 @@
+import ev3.ev3dev
+import unittest
+from util import get_input
+
+
+class TestI2CS(unittest.TestCase):
+
+ def test_battery(self):
+ print(ev3.ev3dev.get_battery_percentage())
+if __name__ == '__main__':
+ unittest.main() | |
dc1b04727f21038c815119b522ad276ceb01de41 | tests/test_issue_types.py | tests/test_issue_types.py | from taiga.requestmaker import RequestMaker, RequestMakerException
from taiga.models.base import InstanceResource, ListResource
from taiga.models.models import IssueType, IssueTypes
from taiga import TaigaAPI
import taiga.exceptions
import json
import requests
import unittest
from mock import patch
from .tools import c... | Add tests for issue types | Add tests for issue types
| Python | mit | jespino/python-taiga,nephila/python-taiga,bameda/python-taiga,mlq/python-taiga,bameda/python-taiga,erikw/python-taiga,erikw/python-taiga,mlq/python-taiga,jespino/python-taiga | ---
+++
@@ -0,0 +1,24 @@
+from taiga.requestmaker import RequestMaker, RequestMakerException
+from taiga.models.base import InstanceResource, ListResource
+from taiga.models.models import IssueType, IssueTypes
+from taiga import TaigaAPI
+import taiga.exceptions
+import json
+import requests
+import unittest
+from mo... | |
16b6c70884f870461cd3fa7d18daf61faa5c25d0 | selfdrive/car/tests/test_car_params.py | selfdrive/car/tests/test_car_params.py | #!/usr/bin/env python3
import unittest
from selfdrive.car.fingerprints import all_known_cars
from selfdrive.car.car_helpers import interfaces
from selfdrive.car.fingerprints import _FINGERPRINTS as FINGERPRINTS
class TestCarParam(unittest.TestCase):
def test_creating_car_params(self):
all_cars = all_known_cars(... | Add test that gets all the car params | Add test that gets all the car params
| Python | mit | commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot | ---
+++
@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+import unittest
+from selfdrive.car.fingerprints import all_known_cars
+from selfdrive.car.car_helpers import interfaces
+from selfdrive.car.fingerprints import _FINGERPRINTS as FINGERPRINTS
+
+
+class TestCarParam(unittest.TestCase):
+ def test_creating_car_params(s... | |
2e208d7458a91f08a75bcee39a1cb9134565b857 | DeepAlignmentNetwork/ImageDemo.py | DeepAlignmentNetwork/ImageDemo.py | from FaceAlignment import FaceAlignment
import numpy as np
import cv2
import utils
model = FaceAlignment(112, 112, 1, 1, True)
model.loadNetwork("../data/DAN-Menpo-tracking.npz")
cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_alt.xml")
color_img = cv2.imread("../data/jk.jpg")
if len(color_img.shape... | Add a sample code for still images | Add a sample code for still images
| Python | mit | MarekKowalski/DeepAlignmentNetwork | ---
+++
@@ -0,0 +1,46 @@
+from FaceAlignment import FaceAlignment
+import numpy as np
+import cv2
+import utils
+
+model = FaceAlignment(112, 112, 1, 1, True)
+model.loadNetwork("../data/DAN-Menpo-tracking.npz")
+
+cascade = cv2.CascadeClassifier("../data/haarcascade_frontalface_alt.xml")
+
+color_img = cv2.imread(".... | |
164b386d97929816eaecbebe7a47164202acad8f | website/profile_run.py | website/profile_run.py | #!/usr/bin/env python3
from werkzeug.contrib.profiler import ProfilerMiddleware
from app import app
app.config['PROFILE'] = True
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
app.run(debug = True)
| Add a script for profiling the app | Add a script for profiling the app
| Python | lgpl-2.1 | reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualisat... | ---
+++
@@ -0,0 +1,7 @@
+#!/usr/bin/env python3
+from werkzeug.contrib.profiler import ProfilerMiddleware
+from app import app
+
+app.config['PROFILE'] = True
+app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])
+app.run(debug = True) | |
d1a9fc8e3e64e3eb4187f7db7c0176f05d68ccef | smaug/tests/fullstack/test_protectables.py | smaug/tests/fullstack/test_protectables.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 ... | Add fullstack tests of the resource protectables RESTAPI | Add fullstack tests of the resource protectables RESTAPI
Change-Id: Ibe660a07311544f82246e82538b565847488040b
Closes-Bug: #1578888
| Python | apache-2.0 | openstack/smaug,openstack/smaug | ---
+++
@@ -0,0 +1,51 @@
+# 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... | |
61d9f394f186b754580c11c40932754072194f72 | playlist_updates.py | playlist_updates.py | #! /usr/bin/env python
import os
import sys
import httplib2
from apiclient.discovery import build # pylint: disable=import-error
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser
from oauth2client.tools import run_flow
# The CLIENT... | Add boilerplate to access youtube api | Add boilerplate to access youtube api
| Python | unlicense | ipwnponies/youtube-sort-playlist,ipwnponies/youtube-sort-playlist | ---
+++
@@ -0,0 +1,75 @@
+#! /usr/bin/env python
+import os
+import sys
+
+import httplib2
+from apiclient.discovery import build # pylint: disable=import-error
+from oauth2client.client import flow_from_clientsecrets
+from oauth2client.file import Storage
+from oauth2client.tools import argparser
+from oauth2client... | |
67b1e01382b718bc8facbdb48e0c88f716e5a247 | tests/integration/test_smoke.py | tests/integration/test_smoke.py | """Smoke tests to verify basic communication to all AWS services."""
import botocore.session
from nose.tools import assert_equals
REGION = 'us-east-1'
SMOKE_TESTS = {
'autoscaling': {'DescribeAccountLimits': {},
'DescribeAdjustmentTypes': {}},
'cloudformation': {'DescribeStacks': {},
... | Add integ smoke tests to verify basic service calls | Add integ smoke tests to verify basic service calls
Verify we can make a successful servie call to each supported
service (except support).
The point of these tests to verify nothing's majorly broken. This
will make a Describe/List call to a service and verify we get a
200 response back.
| Python | apache-2.0 | pplu/botocore,boto/botocore | ---
+++
@@ -0,0 +1,65 @@
+"""Smoke tests to verify basic communication to all AWS services."""
+import botocore.session
+
+from nose.tools import assert_equals
+
+
+REGION = 'us-east-1'
+SMOKE_TESTS = {
+ 'autoscaling': {'DescribeAccountLimits': {},
+ 'DescribeAdjustmentTypes': {}},
+ 'cloudformation'... | |
d5b366c317e8fefaede6ae34cf25a67b5db1df28 | core/migrations/0009_auto_20200825_0800.py | core/migrations/0009_auto_20200825_0800.py | # Generated by Django 2.2.14 on 2020-08-25 08:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0008_board_private'),
]
operations = [
migrations.AlterField(
model_name='pin',
name='referer',
... | Add migrations for url and referer length | Feature: Add migrations for url and referer length
| Python | bsd-2-clause | pinry/pinry,pinry/pinry,pinry/pinry,pinry/pinry | ---
+++
@@ -0,0 +1,23 @@
+# Generated by Django 2.2.14 on 2020-08-25 08:00
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('core', '0008_board_private'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='pin'... | |
d2bedbc07192a703f00a04e1fb262048da890f3d | example/roles/bsd_role.py | example/roles/bsd_role.py | from pyinfra.modules import server, pkg
# OpenBSD packages?
pkg.packages(
['py-pip', 'git'],
sudo=True,
op='core_packages' # this and above binds these three operations to run as one
)
# add_pkg does not automatically do this
server.shell(
'ln -sf /usr/local/bin/pip2.7 /usr/local/bin/pip',
sudo=T... | Add role to example deploy. | Add role to example deploy.
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra | ---
+++
@@ -0,0 +1,15 @@
+from pyinfra.modules import server, pkg
+
+
+# OpenBSD packages?
+pkg.packages(
+ ['py-pip', 'git'],
+ sudo=True,
+ op='core_packages' # this and above binds these three operations to run as one
+)
+
+# add_pkg does not automatically do this
+server.shell(
+ 'ln -sf /usr/local/bi... | |
aba72a7172dc0760441bd9a8bb9fef4a2c38c70b | Lib/test/test_pep263.py | Lib/test/test_pep263.py | #! -*- coding: koi8-r -*-
assert u"".encode("utf-8") == '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
| Test whether a Cyrillic text correctly appears in a Unicode literal. | Test whether a Cyrillic text correctly appears in a Unicode literal.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -0,0 +1,2 @@
+#! -*- coding: koi8-r -*-
+assert u"".encode("utf-8") == '\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' | |
44c7cb73a309a02e907ab6d4ded5957e62ec39e3 | lib/analyzer/pipe_server.py | lib/analyzer/pipe_server.py | '''Wraps a process to make it act as a pipe server. Takes care of supressing
console windows under Windows and other housekeeping.
'''
from subprocess import Popen
from subprocess import PIPE
import threading
from Dart import PluginLogger
from Dart.lib.plat import supress_window
from Dart.lib.path import pushd
_log... | Add PipeServer class to manage a pipe server process | WIP: Add PipeServer class to manage a pipe server process
| Python | bsd-3-clause | guillermooo-forks/dart-sublime-bundle,guillermooo/dart-sublime-bundle,guillermooo-forks/dart-sublime-bundle,guillermooo/dart-sublime-bundle,guillermooo/dart-sublime-bundle,guillermooo/dart-sublime-bundle,guillermooo-forks/dart-sublime-bundle,guillermooo-forks/dart-sublime-bundle | ---
+++
@@ -0,0 +1,56 @@
+'''Wraps a process to make it act as a pipe server. Takes care of supressing
+console windows under Windows and other housekeeping.
+'''
+
+from subprocess import Popen
+from subprocess import PIPE
+import threading
+
+from Dart import PluginLogger
+from Dart.lib.plat import supress_window
+... | |
5b7697661c90e27ce36e6eae3b854470862f4191 | tensorflow_io/image/python/ops/image_dataset_ops.py | tensorflow_io/image/python/ops/image_dataset_ops.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Add python wrapper for WebP image format support | Add python wrapper for WebP image format support
Signed-off-by: Yong Tang <765086fe2e0c1f980161f127fec596800f327f62@outlook.com>
| Python | apache-2.0 | tensorflow/io,tensorflow/io,tensorflow/io,tensorflow/io,tensorflow/io,tensorflow/io,tensorflow/io | ---
+++
@@ -0,0 +1,59 @@
+# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-... | |
dadeb85fdbe6a4fed129cbeffbc305b36cef36c4 | {{cookiecutter.repo_name}}/tests/test_cli.py | {{cookiecutter.repo_name}}/tests/test_cli.py | import pytest
from click.testing import CliRunner
from cli import main
@pytest.fixture
def runner():
return CliRunner()
@pytest.fixture(params=['fr', 'en', 'tlh'])
def lang(request):
return request.param
@pytest.fixture(params=['-l', '--language'])
def cli_param(request):
return request.param
@pyte... | Implement test for the cli | Implement test for the cli
| Python | mit | hackebrot/cookiedozer,hackebrot/cookiedozer | ---
+++
@@ -0,0 +1,36 @@
+import pytest
+from click.testing import CliRunner
+
+from cli import main
+
+
+@pytest.fixture
+def runner():
+ return CliRunner()
+
+
+@pytest.fixture(params=['fr', 'en', 'tlh'])
+def lang(request):
+ return request.param
+
+
+@pytest.fixture(params=['-l', '--language'])
+def cli_par... | |
6af695bdceaabdd4144def6a11f930e9d02a2d5c | src/assistant_library_with_local_commands_demo.py | src/assistant_library_with_local_commands_demo.py | #!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | Add a demo to showcase how to handle local commands with Assistant Library. | Add a demo to showcase how to handle local commands with Assistant Library.
| Python | apache-2.0 | google/aiyprojects-raspbian,t1m0thyj/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,t1m0thyj/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian | ---
+++
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+# Copyright 2017 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+#... | |
a81d8aef2462bce852f52b551eb067659973978f | rethinkdb/setup-rethinkdb.py | rethinkdb/setup-rethinkdb.py | #!/usr/bin/env python
import rethinkdb as r
conn = r.connect()
r.db_create('muzhack').run(conn)
r.db('muzhack').table_create('users').run(conn)
r.db('muzhack').table_create('projects').run(conn)
| Add script for setting up rethinkdb | Add script for setting up rethinkdb
| Python | mit | muzhack/muzhack,muzhack/musitechhub,muzhack/musitechhub,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack,muzhack/muzhack,muzhack/musitechhub | ---
+++
@@ -0,0 +1,7 @@
+#!/usr/bin/env python
+import rethinkdb as r
+
+conn = r.connect()
+r.db_create('muzhack').run(conn)
+r.db('muzhack').table_create('users').run(conn)
+r.db('muzhack').table_create('projects').run(conn) | |
153983a933cd708cffbfde84a69930b33f747ca1 | zephyr/management/commands/set_unread_to_pointer.py | zephyr/management/commands/set_unread_to_pointer.py | from optparse import make_option
import logging
from django.core.management.base import BaseCommand
from zephyr.lib.actions import do_deactivate, user_sessions
from zephyr.lib import utils
from zephyr.models import UserMessage, UserProfile
from django.db import transaction, models
class Command(BaseCommand):
he... | Add a manage.py command to add read flags up to the current pointer | Add a manage.py command to add read flags up to the current pointer
This is required because our migration is going to go in two phases.
When we do the database migration (on pushing to master), we update
all messages at that point. But prod doesn't know about the new
flags field, so any new messages sent on prod will... | Python | apache-2.0 | zorojean/zulip,developerfm/zulip,ikasumiwt/zulip,yocome/zulip,codeKonami/zulip,ipernet/zulip,PaulPetring/zulip,brockwhittaker/zulip,christi3k/zulip,bastianh/zulip,johnny9/zulip,ufosky-server/zulip,vabs22/zulip,Drooids/zulip,stamhe/zulip,Juanvulcano/zulip,RobotCaleb/zulip,TigorC/zulip,joshisa/zulip,Frouk/zulip,peiwei/zu... | ---
+++
@@ -0,0 +1,73 @@
+from optparse import make_option
+import logging
+
+from django.core.management.base import BaseCommand
+
+from zephyr.lib.actions import do_deactivate, user_sessions
+from zephyr.lib import utils
+from zephyr.models import UserMessage, UserProfile
+from django.db import transaction, models
... | |
fa470267fff5107e1c4e258e66c677291972c558 | scripts/build_sbt_image.py | scripts/build_sbt_image.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Build a Docker image for one of our sbt applications.
Usage:
build_sbt_image.py --project=<PROJECT> [--version=<VERSION>] [--env=<BUILD_ENV>]
build_sbt_image.py -h | --help
Options:
-h --help Show this screen.
--project=<PROJECT> Name... | Add a script for building the sbt images | Add a script for building the sbt images
| Python | mit | wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api | ---
+++
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+# -*- encoding: utf-8 -*-
+"""
+Build a Docker image for one of our sbt applications.
+
+Usage:
+ build_sbt_image.py --project=<PROJECT> [--version=<VERSION>] [--env=<BUILD_ENV>]
+ build_sbt_image.py -h | --help
+
+Options:
+ -h --help Show this scr... | |
828521e71b2afd93f53b13222fbdfaf9e855d442 | scripts/comment_scraper.py | scripts/comment_scraper.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import praw
# Connect to Reddit
# ----------------------------
user_agent = "Quick comment thread scraper by /u/mediaarts"
r = praw.Reddit(user_agent = user_agent)
# Get comment thread and populate dict
# ----------------------------
submission_id = "1p1j6c"
submissio... | Add scratch Reddit comment scraper | Add scratch Reddit comment scraper
| Python | mit | PsyBorgs/redditanalyser,PsyBorgs/redditanalyser | ---
+++
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import praw
+
+# Connect to Reddit
+# ----------------------------
+
+user_agent = "Quick comment thread scraper by /u/mediaarts"
+r = praw.Reddit(user_agent = user_agent)
+
+
+# Get comment thread and populate dict
+# -----------------------... | |
34299b315cc02044050181ffe73b09042bb19a0a | evewspace/API/default_settings.py | evewspace/API/default_settings.py | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option... | Add default settings module for API | Add default settings module for API
| Python | apache-2.0 | evewspace/eve-wspace,nyrocron/eve-wspace,Maarten28/eve-wspace,nyrocron/eve-wspace,Zumochi/eve-wspace,Maarten28/eve-wspace,Maarten28/eve-wspace,acdervis/eve-wspace,hybrid1969/eve-wspace,hybrid1969/eve-wspace,marbindrakon/eve-wspace,Unsettled/eve-wspace,mmalyska/eve-wspace,Maarten28/eve-wspace,marbindrakon/eve-wspace,gpa... | ---
+++
@@ -0,0 +1,28 @@
+# Eve W-Space
+# Copyright (C) 2013 Andrew Austin and other contributors
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the... | |
49046745e9000281c4cf225836ad988b04a59517 | judge/migrations/0112_language_extensions.py | judge/migrations/0112_language_extensions.py | from django.db import migrations
def update_language_extensions(apps, schema_editor):
Language = apps.get_model('judge', 'Language')
extension_mapping = {
'ADA': 'adb',
'AWK': 'awk',
'BASH': 'sh',
'BF': 'c',
'C': 'c',
'C11': 'c',
'CBL': 'cbl',
'... | Add migration to update Language extensions | Add migration to update Language extensions
| Python | agpl-3.0 | DMOJ/site,DMOJ/site,DMOJ/site,DMOJ/site | ---
+++
@@ -0,0 +1,92 @@
+from django.db import migrations
+
+
+def update_language_extensions(apps, schema_editor):
+ Language = apps.get_model('judge', 'Language')
+
+ extension_mapping = {
+ 'ADA': 'adb',
+ 'AWK': 'awk',
+ 'BASH': 'sh',
+ 'BF': 'c',
+ 'C': 'c',
+ 'C1... | |
d6e6c5caa26469b101333df5a901a94f3fe532f3 | tests/test_classbasedview.py | tests/test_classbasedview.py | import asyncio
import pytest
from aiohttp import web
from aiohttp.web_urldispatcher import View
from unittest import mock
def test_ctor():
request = mock.Mock()
view = View(request)
assert view.request is request
@pytest.mark.run_loop
def test_render_ok():
resp = web.Response(text='OK')
class ... | Add tests for class based views | Add tests for class based views
| Python | apache-2.0 | jashandeep-sohi/aiohttp,rutsky/aiohttp,decentfox/aiohttp,alex-eri/aiohttp-1,arthurdarcet/aiohttp,juliatem/aiohttp,esaezgil/aiohttp,pfreixes/aiohttp,mind1master/aiohttp,z2v/aiohttp,KeepSafe/aiohttp,mind1master/aiohttp,decentfox/aiohttp,mind1master/aiohttp,elastic-coders/aiohttp,rutsky/aiohttp,jettify/aiohttp,pfreixes/ai... | ---
+++
@@ -0,0 +1,57 @@
+import asyncio
+import pytest
+
+from aiohttp import web
+from aiohttp.web_urldispatcher import View
+from unittest import mock
+
+
+def test_ctor():
+ request = mock.Mock()
+ view = View(request)
+ assert view.request is request
+
+
+@pytest.mark.run_loop
+def test_render_ok():
+ ... | |
082bdc7c12074f7df3d0a308b00f0d512ae98a16 | lib/tarSupport.py | lib/tarSupport.py | import os
import sys
import tarfile
import cStringIO
class GlideinTar:
"""
potential exception needs to be caught by calling routine
"""
def __init__(self):
self.strings = {}
self.files = []
def add_file(self, filename, arc_dirname):
if os.path.exists(filename):
... | Add the ability to create Tar files | Add the ability to create Tar files
| Python | bsd-3-clause | bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS | ---
+++
@@ -0,0 +1,50 @@
+import os
+import sys
+import tarfile
+import cStringIO
+
+class GlideinTar:
+ """
+ potential exception needs to be caught by calling routine
+ """
+ def __init__(self):
+ self.strings = {}
+ self.files = []
+
+ def add_file(self, filename, arc_dirname):
+ ... | |
011c1701813c3107433d261581189c57e3b3302f | megalist_dataflow/utils/group_by_execution_dofn.py | megalist_dataflow/utils/group_by_execution_dofn.py | # Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Create DoFn to group and batch data based on Execution equality | Create DoFn to group and batch data based on Execution equality
| Python | apache-2.0 | google/megalista,google/megalista | ---
+++
@@ -0,0 +1,47 @@
+# Copyright 2020 Google LLC
+#
+# 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
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by appl... | |
10c7d2f33d34e5a158795701b2d9bc71bbb1c120 | integration_tests/samples/rtm_v2/rtm_v2_proxy_app.py | integration_tests/samples/rtm_v2/rtm_v2_proxy_app.py | # ------------------
# Only for running this script here
import sys
from os.path import dirname
sys.path.insert(1, f"{dirname(__file__)}/../../..")
# ------------------
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s.%(msecs)03d %(levelname)s %(filename)s (%(lineno)s): %(message)... | Add RTM v2 client example too | Add RTM v2 client example too
| Python | mit | slackapi/python-slackclient,slackapi/python-slackclient,slackhq/python-slackclient,slackapi/python-slackclient | ---
+++
@@ -0,0 +1,46 @@
+# ------------------
+# Only for running this script here
+import sys
+from os.path import dirname
+
+sys.path.insert(1, f"{dirname(__file__)}/../../..")
+# ------------------
+
+import logging
+
+logging.basicConfig(
+ level=logging.DEBUG,
+ format="%(asctime)s.%(msecs)03d %(levelname... | |
5367b40e7dec274cb36df6e5dfdd53fca986345b | scripts/annotate-true-allele-freqs.py | scripts/annotate-true-allele-freqs.py | from cyvcf2 import VCF, Writer
def subclone_vaf(gt):
"""Calculate subclone allele frequency"""
if np.all(gt[:2] == [1, 1]):
return 1.0
elif np.all(gt[:2] == [0, 1]) or np.all(gt[:2] == [1, 0]):
return 0.5
else:
return 0.0
# Reader
vcf_in = VCF(snakemake.input.vcf)
# Setup su... | Add script to annotate allele frequencies. | Add script to annotate allele frequencies.
| Python | mit | PROSIC/prosic-evaluation,PROSIC/prosic-evaluation | ---
+++
@@ -0,0 +1,41 @@
+from cyvcf2 import VCF, Writer
+
+
+def subclone_vaf(gt):
+ """Calculate subclone allele frequency"""
+ if np.all(gt[:2] == [1, 1]):
+ return 1.0
+ elif np.all(gt[:2] == [0, 1]) or np.all(gt[:2] == [1, 0]):
+ return 0.5
+ else:
+ return 0.0
+
+
+# Reader
+vcf... | |
cf7fd8a8ba0943303dd5baaee831e7070460c0a0 | lowfat/management/commands/addactivities.py | lowfat/management/commands/addactivities.py | import pandas as pd
from django.core.management.base import BaseCommand
from lowfat.models import Fund
class Command(BaseCommand):
help = "Add activities"
def add_arguments(self, parser):
parser.add_argument('csv', nargs='?', default='activities.csv')
# pylint: disable=too-many-branches,too-man... | Add script to import activities | Add script to import activities
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | ---
+++
@@ -0,0 +1,41 @@
+import pandas as pd
+
+from django.core.management.base import BaseCommand
+
+from lowfat.models import Fund
+
+class Command(BaseCommand):
+ help = "Add activities"
+
+ def add_arguments(self, parser):
+ parser.add_argument('csv', nargs='?', default='activities.csv')
+
+ # p... | |
5a641395fb336313f091d28ffb17625df836d2a3 | create_admin.py | create_admin.py | from getpass import getpass
from md5 import md5
from redis import Redis
def main():
database = Redis()
database.set("user:admin:password", md5(getpass()).hexdigest())
database.delete("user:admin:profiles")
database.rpush("user:admin:profiles", "admin")
if __name__ == "__main__":
main()
| Create script that helps to create an admin user. | Create script that helps to create an admin user.
| Python | mit | Computiva/carbono,Computiva/carbono,Computiva/carbono,Computiva/carbono | ---
+++
@@ -0,0 +1,13 @@
+from getpass import getpass
+from md5 import md5
+
+from redis import Redis
+
+def main():
+ database = Redis()
+ database.set("user:admin:password", md5(getpass()).hexdigest())
+ database.delete("user:admin:profiles")
+ database.rpush("user:admin:profiles", "admin")
+
+if __name... | |
1867707bd33bb4908e63f82f3d975fcf5d9e829a | plc-upo-alarm.py | plc-upo-alarm.py | import shlex
import sys
import re
from subprocess import Popen, PIPE
def extractMacAddress(ampStatLine):
macAddr = None
items = ampStatLine.split( " " )
for index in range(len(items)):
if (items[index] == "MAC") and ((index+1) < len(items)):
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1... | Read ampstat -m -i <device> and print out the mac addresses on the powerline network | Read ampstat -m -i <device> and print out the mac addresses on the powerline network
| Python | mit | alanbertadev/plc_upo_alarm | ---
+++
@@ -0,0 +1,34 @@
+import shlex
+import sys
+import re
+from subprocess import Popen, PIPE
+
+def extractMacAddress(ampStatLine):
+ macAddr = None
+ items = ampStatLine.split( " " )
+ for index in range(len(items)):
+ if (items[index] == "MAC") and ((index+1) < len(items)):
+ if re.m... | |
000ceb19945af56a0196654fa2f4e924aaa1f4ae | publications_bootstrap/migrations/0003_db_index.py | publications_bootstrap/migrations/0003_db_index.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-06-30 09:41
from __future__ import unicode_literals
from django.db import migrations, models
import echoices.fields
import publications_bootstrap.fields
import publications_bootstrap.models.publication
class Migration(migrations.Migration):
dependenci... | Add new migrations with db indexes | Add new migrations with db indexes
| Python | mit | mbourqui/django-publications-bootstrap,mbourqui/django-publications-bootstrap,mbourqui/django-publications-bootstrap | ---
+++
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.7 on 2017-06-30 09:41
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import echoices.fields
+import publications_bootstrap.fields
+import publications_bootstrap.models.publication
+
+
+class Migration(... | |
10df3cd5e4c8517652efdb8381155253aa6a8157 | osfclient/tests/test_cli.py | osfclient/tests/test_cli.py | from unittest.mock import call
from unittest.mock import Mock
from unittest.mock import patch
from osfclient import cli
@patch('osfclient.cli.os.path.exists', return_value=True)
@patch('osfclient.cli.configparser.ConfigParser')
def test_config_file(MockConfigParser, os_path_exists):
MockConfigParser().__getitem_... | Add test for file based configuration | Add test for file based configuration
| Python | bsd-3-clause | betatim/osf-cli,betatim/osf-cli | ---
+++
@@ -0,0 +1,62 @@
+from unittest.mock import call
+from unittest.mock import Mock
+from unittest.mock import patch
+
+from osfclient import cli
+
+
+@patch('osfclient.cli.os.path.exists', return_value=True)
+@patch('osfclient.cli.configparser.ConfigParser')
+def test_config_file(MockConfigParser, os_path_exist... | |
0a8ca89881c08c78816c47e5b54aa7f78fdb8cc0 | src/servers/urls.py | src/servers/urls.py | ''' Servers URL Configuration
'''
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="servers"),
url(r'^(?P<slug>.+)/', views.server, name="server"),
]
| Create URL routes to the two server app views | Create URL routes to the two server app views
| Python | mit | Jonpro03/Minecrunch_Web,Jonpro03/Minecrunch_Web,Jonpro03/Minecrunch_Web | ---
+++
@@ -0,0 +1,10 @@
+''' Servers URL Configuration
+'''
+
+from django.conf.urls import url
+from . import views
+
+urlpatterns = [
+ url(r'^$', views.index, name="servers"),
+ url(r'^(?P<slug>.+)/', views.server, name="server"),
+] | |
b96d62fb4797360e17bd7ffa2a22f9a89977605a | excerises/src/II/q6.py | excerises/src/II/q6.py | D = {'a': 0, 'b': 1, 'c': 2}
# Attempting to access a key that does not exist
# will result in a KeyError Exception
try:
D['d']
except KeyError as err:
print('KeyError for', err)
# Assign to a non-existing key (will create entry)
D['d'] = 'spam'
print(D)
# For Lists cannot assign to a non-existing index
L = ['a... | Add Q6 for Section II | Add Q6 for Section II
| Python | bsd-3-clause | skellykiernan/pylearn,skellykiernan/pylearn | ---
+++
@@ -0,0 +1,16 @@
+D = {'a': 0, 'b': 1, 'c': 2}
+# Attempting to access a key that does not exist
+# will result in a KeyError Exception
+try:
+ D['d']
+except KeyError as err:
+ print('KeyError for', err)
+# Assign to a non-existing key (will create entry)
+D['d'] = 'spam'
+print(D)
+# For Lists cannot ... | |
ac9d87bf486f8062d1c2d8122e2dc5660546a22f | menpofit/clm/expert/base.py | menpofit/clm/expert/base.py | import numpy as np
from menpofit.math.correlationfilter import mccf, imccf
# TODO: document me!
class IncrementalCorrelationFilterThinWrapper(object):
r"""
"""
def __init__(self, cf_callable=mccf, icf_callable=imccf):
self.cf_callable = cf_callable
self.icf_callable = icf_callable
def... | Add dummy wrapper for correlation filters | Add dummy wrapper for correlation filters
| Python | bsd-3-clause | grigorisg9gr/menpofit,yuxiang-zhou/menpofit,yuxiang-zhou/menpofit,grigorisg9gr/menpofit | ---
+++
@@ -0,0 +1,28 @@
+import numpy as np
+from menpofit.math.correlationfilter import mccf, imccf
+
+
+# TODO: document me!
+class IncrementalCorrelationFilterThinWrapper(object):
+ r"""
+ """
+ def __init__(self, cf_callable=mccf, icf_callable=imccf):
+ self.cf_callable = cf_callable
+ sel... | |
eef6382ffbe5a9d69747fe98819af446c7aea661 | temba/msgs/migrations/0065_external_id_partial_index.py | temba/msgs/migrations/0065_external_id_partial_index.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('msgs', '0064_auto_20160908_1340'),
]
operations = [
migrations.RunSQL(
"CREATE INDEX msgs_msg_external_id_where_... | Add partial index for non-null external ids | Add partial index for non-null external ids
| Python | agpl-3.0 | tsotetsi/textily-web,pulilab/rapidpro,tsotetsi/textily-web,tsotetsi/textily-web,pulilab/rapidpro,pulilab/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,pulilab/rapidpro,tsotetsi/textily-web | ---
+++
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('msgs', '0064_auto_20160908_1340'),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ ... | |
b08e7fd64da5342508807420e5c9aa6c3686a68e | scripts/analytics/institutions.py | scripts/analytics/institutions.py | from modularodm import Q
from website.app import init_app
from website.models import User, Node, Institution
def get_institutions():
institutions = Institution.find(Q('_id', 'ne', None))
return institutions
def get_user_count_by_institutions():
institutions = get_institutions()
user_counts = []
... | Add basic script without the ability to send the data anywhere | Add basic script without the ability to send the data anywhere
| Python | apache-2.0 | Johnetordoff/osf.io,hmoco/osf.io,laurenrevere/osf.io,mattclark/osf.io,baylee-d/osf.io,icereval/osf.io,laurenrevere/osf.io,sloria/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,binoculars/osf.io,caseyrollins/osf.io,alexschiller/osf.io,acshi/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,crcresearch/osf.io,felliott... | ---
+++
@@ -0,0 +1,43 @@
+from modularodm import Q
+
+from website.app import init_app
+from website.models import User, Node, Institution
+
+
+def get_institutions():
+ institutions = Institution.find(Q('_id', 'ne', None))
+ return institutions
+
+
+def get_user_count_by_institutions():
+ institutions = get... | |
f79465a56f45aaa74593bf0176015dabd5845b25 | src/lovelace/management/commands/send_mass_email.py | src/lovelace/management/commands/send_mass_email.py | import sys
import json
import requests
from bs4 import BeautifulSoup
from django.core.management.base import BaseCommand, CommandError
from users.models import UserProfile
from lovelace.settings import MAILGUN_API_URL, MAILGUN_API_KEY, LOVELACE_FROM_EMAIL
class Command(BaseCommand):
help = "Send a mass email to ... | Send mass email Django command | Send mass email Django command
| Python | mit | project-lovelace/lovelace-website,project-lovelace/lovelace-website,project-lovelace/lovelace-website | ---
+++
@@ -0,0 +1,66 @@
+import sys
+import json
+import requests
+
+from bs4 import BeautifulSoup
+from django.core.management.base import BaseCommand, CommandError
+
+from users.models import UserProfile
+from lovelace.settings import MAILGUN_API_URL, MAILGUN_API_KEY, LOVELACE_FROM_EMAIL
+
+class Command(BaseComma... | |
cb991585c786d1c899da85a2abdf58cc9725d44a | prototypes/converters/autovasp_converter.py | prototypes/converters/autovasp_converter.py | import os
import json
import sys
from tqdm import tqdm
from parsers.utils import find_files
from parsers.ase_parser import parse_ase
from validator import Validator
# This is the converter for
# Arguments:
# input_path (string): The file or directory where the data resides. This should not be hard-coded in the func... | Complete converter for VASP prototype | Complete converter for VASP prototype
Prototyping autoconverter for VASP files. Does not yet handle URIs
outside of data.materialsdatafacility.org.
| Python | apache-2.0 | materials-data-facility/forge | ---
+++
@@ -0,0 +1,79 @@
+import os
+import json
+import sys
+from tqdm import tqdm
+from parsers.utils import find_files
+from parsers.ase_parser import parse_ase
+from validator import Validator
+
+
+# This is the converter for
+# Arguments:
+# input_path (string): The file or directory where the data resides. Th... | |
ccf986954bfc4a5e56ed608aefbb416bf7acab3c | tests/test_sso/test_bitbucket_id_creation.py | tests/test_sso/test_bitbucket_id_creation.py | from urllib.parse import urlparse
from django.urls import reverse
from tests.utils import BaseViewTest
class BitbucketIdentityTest(BaseViewTest):
def test_wrong_provider_raises_404(self):
auth_path = reverse('sso:create_identity', kwargs={'provider': 'undefined'})
resp = self.client.get(auth_pat... | Add bitbucket identity creation tests | Add bitbucket identity creation tests
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -0,0 +1,29 @@
+from urllib.parse import urlparse
+
+from django.urls import reverse
+
+from tests.utils import BaseViewTest
+
+
+class BitbucketIdentityTest(BaseViewTest):
+ def test_wrong_provider_raises_404(self):
+ auth_path = reverse('sso:create_identity', kwargs={'provider': 'undefined'})
+ ... | |
5519ccdeceffa72bd1822e2d6d42f9215ea7229e | mzalendo/core/management/commands/core_import_keynan_boundaries_2013.py | mzalendo/core/management/commands/core_import_keynan_boundaries_2013.py | # This script imports the boundaries for the 2013 Kenyan election into
# MapIt - it uses the generic mapit_import script.
import json
import os
import sys
import urllib
from tempfile import NamedTemporaryFile
from optparse import make_option
from django.core.management import call_command
from django.core.managemen... | Add a command that imports the 2013 election boundaries | Add a command that imports the 2013 election boundaries
This uses the generic mapit_import script via
django.core.management.call_command.
| Python | agpl-3.0 | patricmutwiri/pombola,geoffkilpin/pombola,ken-muturi/pombola,geoffkilpin/pombola,hzj123/56th,hzj123/56th,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,hzj123/56th,mysociety/pombola,hzj123/56th,patricmutwiri/pombola,hzj123/56th,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pomb... | ---
+++
@@ -0,0 +1,58 @@
+# This script imports the boundaries for the 2013 Kenyan election into
+# MapIt - it uses the generic mapit_import script.
+
+import json
+import os
+import sys
+import urllib
+
+from tempfile import NamedTemporaryFile
+
+from optparse import make_option
+
+from django.core.management import... | |
d6020572b9882a26939c71cb5d6ea795f0ef2d44 | tests/test_spans.py | tests/test_spans.py | import unittest
import datetime
import hiro
from sifr.span import Minute, Year, Month, Day, Hour
class SpanTests(unittest.TestCase):
def test_minute(self):
with hiro.Timeline().freeze(datetime.datetime(2012, 12, 12)):
now = datetime.datetime.now()
span = Minute(now, ["single"])
... | Add basic tests for spans | Add basic tests for spans
| Python | mit | alisaifee/sifr,alisaifee/sifr | ---
+++
@@ -0,0 +1,36 @@
+import unittest
+import datetime
+import hiro
+from sifr.span import Minute, Year, Month, Day, Hour
+
+
+class SpanTests(unittest.TestCase):
+ def test_minute(self):
+ with hiro.Timeline().freeze(datetime.datetime(2012, 12, 12)):
+ now = datetime.datetime.now()
+ ... | |
c7621caf782e44c76d2477813726ea35de00d49c | tests/test_store.py | tests/test_store.py | # pylint: disable=C0103,C0111,W0703
import unittest
from bumblebee.store import Store
class TestStore(unittest.TestCase):
def setUp(self):
self.store = Store()
self.anyKey = "some-key"
self.anyValue = "some-value"
self.unsetKey = "invalid-key"
def test_set_value(self):
... | Add unit tests for the store class | [tests] Add unit tests for the store class
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | ---
+++
@@ -0,0 +1,26 @@
+# pylint: disable=C0103,C0111,W0703
+
+import unittest
+
+from bumblebee.store import Store
+
+class TestStore(unittest.TestCase):
+ def setUp(self):
+ self.store = Store()
+ self.anyKey = "some-key"
+ self.anyValue = "some-value"
+ self.unsetKey = "invalid-key... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.