commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
417e76de84f067a90fdcda93ee82d63cc7e56c7b
Add downloader.py
steamplog/downloader.py
steamplog/downloader.py
from __future__ import print_function import sys import json import urllib2 class Downloader(object): '''Download data via Steam-API''' def __init__(self, api_key): self.API = api_key def download_stats(self, steam_id): '''Download owned games from Steam Web API''' URL = ['https:/...
Python
0
f9b8a92359e15883c5ee7b4dbc259001d59e379d
introduce bnip classes
BrainNetworksInPython/scripts/classes.py
BrainNetworksInPython/scripts/classes.py
import numpy as np import networkx as nx import pandas as pd import make_graphs as mkg import graph_measures as gm def cascader(dict1, dict2, name): return {key: value.update({name: dict2[key]}) for key, value in dict1.items()} class BrainNetwork(nx.classes.graph.Graph): def __init__(self, ...
Python
0
cd9da9cf624a80acaebe92e075760ff8c2dbb7b1
Add test_first_audit_catchup_during_ordering
plenum/test/audit_ledger/test_first_audit_catchup_during_ordering.py
plenum/test/audit_ledger/test_first_audit_catchup_during_ordering.py
import pytest from plenum.test import waits from plenum.common.constants import LEDGER_STATUS, DOMAIN_LEDGER_ID from plenum.common.messages.node_messages import MessageReq, CatchupReq from plenum.server.catchup.node_leecher_service import NodeLeecherService from plenum.test.delayers import ppDelay, pDelay, cDelay, DEF...
Python
0
af536ba048860001c2eea2ada1fb5861c9fdf578
Fix migrations, historical models to not have any properties
django_auth_policy/migrations/0002_users_nullable.py
django_auth_policy/migrations/0002_users_nullable.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings def fill_repr(apps, schema_editor): from django.contrib.auth import get_user_model User = get_user_model() LoginAttempt = apps.get_mo...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings def fill_repr(apps, schema_editor): LoginAttempt = apps.get_model("django_auth_policy", "LoginAttempt") for item in LoginAttempt.objects.a...
Python
0
cc300b1c0f6ccc4ca50b4f4d20f5f351af698cfc
Add files via upload
nthprime.py
nthprime.py
#encoding=utf8 ''' Find nth prime number ''' from math import sqrt def prime(maxn): n = 1 while n < maxn: if is_prime(n): yield n n += 1 def is_prime(n): if n == 1: return False for i in range(2, int(sqrt(n))+1): if n % i == 0: ...
Python
0
98d04ccc3549b0b7597b995b83d60ae570108b8a
Create Adafruit_HTU21D.py
Adafruit_HTU21D.py
Adafruit_HTU21D.py
#!/usr/bin/python import time from Adafruit_I2C import Adafruit_I2C # =========================================================================== # HTU21D Class # # Code only test with a Sparkfun HTU21D Sensor module on a Beaglebone Black. # It has been reported that an I2C address issue was seen on a Pi. # ========...
Python
0.000001
3b42aa408472755ecb4c63d60f8bb14f43b4e930
Write high-level code for vector-based algorithms (inner product, cross product and norm).
viennagrid-python/viennagrid/algorithms.py
viennagrid-python/viennagrid/algorithms.py
#-*- coding: utf-8 -*- import viennagrid_wrapper as _wrapper _SUPPORTED_NORMS = (1, 2, 'inf') ########################### # VECTOR-BASED ALGORITHMS # ########################### def inner_prod(point1, point2): # Try to get method 'inner_prod' from 'point1'. If it doesn't have the method, # it means it's not a car...
Python
0.000001
d0b16ba083cafc4eb8da73e56a082a4959c1ac53
Implement the training with proxy NCA loss
main_proxy_nca.py
main_proxy_nca.py
# -*- coding: utf-8 -*- """ Created on Mon Jan 09 20:49:04 2017 @author: sakurai """ import colorama import numpy as np import chainer.functions as F from sklearn.model_selection import ParameterSampler from lib.functions.n_pair_mc_loss import n_pair_mc_loss from lib.common.utils import LogUniformDistribution, load...
Python
0
596b11351ee78d715833ef0681fdc1634a425167
add show_flirt_references
viv_utils/scripts/show_flirt_references.py
viv_utils/scripts/show_flirt_references.py
import sys import gzip import logging import argparse import binascii import flirt import viv_utils import viv_utils.flirt import vivisect.const logger = logging.getLogger("get_flirt_matches") def load_flirt_signature(path): if path.endswith(".sig"): with open(path, "rb") as f: sigs = flir...
Python
0.000002
b1316b3db89fbee6e6c1ad807e2e36b8b4dd1874
Add a script to fix garbled activities
Attic/act-fixup.py
Attic/act-fixup.py
from parliament.models import * from django.db import transaction, reset_queries if True: with transaction.atomic(): print("Documents %d" % Document.objects.count()) for idx, doc in enumerate(Document.objects.all()): if idx % 1000 == 0: reset_queries() p...
Python
0.000001
ad78abc4073cb26b192629aed9e9f8e3f5d9e94a
Test for GPI newline fix; for geneontology/go-site#1681
tests/test_gpiwriter.py
tests/test_gpiwriter.py
import io from ontobio.io import entitywriter, gafgpibridge def test_header_newline(): gpi_obj = { 'id': "MGI:MGI:1918911", 'label': "0610005C13Rik", # db_object_symbol, 'full_name': "RIKEN cDNA 0610005C13 gene", # db_object_name, 'synonyms': [], 'type': ["gene"], # db_...
Python
0
4d8dbf66bdee710e5b53863a4852e80c42a2c7a2
Add a sqlserver test
tests/test_sqlserver.py
tests/test_sqlserver.py
import unittest import logging from nose.plugins.attrib import attr from checks import gethostname from tests.common import get_check logging.basicConfig() """ Run the following on your local SQL Server: CREATE LOGIN datadog WITH PASSWORD = '340$Uuxwp7Mcxo7Khy'; CREATE USER datadog FOR LOGIN datadog; GRANT SELECT o...
Python
0.000105
b70b51d1c43a344a3c408f3da30c6477b311241e
Create __init__.py
acitool/jsondata/Mpod/__init__.py
acitool/jsondata/Mpod/__init__.py
Python
0.000429
9ec45d8b44a63bcd2652de30191b2bf0caf72ab8
Add tests for backrefs
tests/aggregate/test_backrefs.py
tests/aggregate/test_backrefs.py
import sqlalchemy as sa from sqlalchemy_utils.aggregates import aggregated from tests import TestCase class TestAggregateValueGenerationForSimpleModelPaths(TestCase): def create_models(self): class Thread(self.Base): __tablename__ = 'thread' id = sa.Column(sa.Integer, primary_key=T...
Python
0
f45f00401daa8446982477cd8ba26c661e577508
Add dictionary.en.py
dictionary.en.py
dictionary.en.py
#!/usr/bin/env python3 import argparse import csv import os import random from collections import defaultdict import numpy as np from gensim.models.word2vec import Word2Vec try: from sklearn.model_selection import train_test_split except ImportError: from sklearn.cross_validation import train_test_split par...
Python
0.999101
72e2a92522702af998dc599e3370346e22097603
Update threadedcomments/management/commands/migrate_threaded_comments.py
threadedcomments/management/commands/migrate_threaded_comments.py
threadedcomments/management/commands/migrate_threaded_comments.py
from django.core.management.base import NoArgsCommand from django.contrib.sites.models import Site from django.db import transaction, connection from django.conf import settings from threadedcomments.models import ThreadedComment USER_SQL = """ SELECT id, content_type_id, object_id, parent_id, use...
from django.core.management.base import NoArgsCommand from django.contrib.sites.models import Site from django.db import transaction, connection from django.conf import settings from threadedcomments.models import ThreadedComment USER_SQL = """ SELECT id, content_type_id, object_id, parent_id, use...
Python
0.000002
8bf521bf26af93f13043ee6e0d70070d49f76f68
Implement the cipher map problem.
Home/cipherMap.py
Home/cipherMap.py
import operator def checkio(arr): index = convertMapToTuples(arr[0]) cube = convertCubeToList(arr[1]) output = '' dimension = len(arr[0]) for i in range(0, 4): index.sort(key=operator.itemgetter(0, 1)) for idx in index: output = '{0}{1}'.format(output, cube[idx[0]][idx[1...
Python
0.00037
e583d977c7089f21841890b7eb50c824db153202
Test for unicode characters in grammars.
tests/functional/test_unicode.py
tests/functional/test_unicode.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from textx.metamodel import metamodel_from_str def test_unicode_grammar_from_string(): """ Test grammar with unicode char given in grammar string. """ grammar = """ First: 'first' a = Second ; Second: ...
Python
0
17e7859f7e361ebea5d9df5170b1083af83ca320
combine search via keyword and inputfile
LookupAppName4.py
LookupAppName4.py
## ## Look up application name via package name ## ## 0. Searching app name other metadata by package name ## ex:python LookUPAppName 0 packageName.txt output.csv ## The input file contains app package names which are separated by \n ## com.asus.email ## com.asus.todo ## com.asus.launcher ## ## 1. Searching popular app...
Python
0
558788056cc89bbb5d1ec35a622f56b0c2cc472b
Define two new functions pull_probes_by_cropseason_field() and pull_probes_by_period(). These functions query the UGA database and pull relevant probe summary data into the WaterHistory table for the specified perior or CropSeason + Field.
irrigator_pro/uga/pull_probes.py
irrigator_pro/uga/pull_probes.py
from django.test import TestCase from farms.models import * from uga.models import * from datetime import date, datetime, time, timedelta from django.db.models import Count from django.utils import timezone # for make_aware, get_default_timezone from uga.aggregates import * field = Field.o...
Python
0.999996
8117b3bee367afea107f7ef4b2003006e0ea857e
Create anteater.py
anteater.py
anteater.py
#!/usr/bin/python # -*- coding: utf-8 -*- ########################################### # 27.11.2012 | word scraper bot wsb.py # # by PirateSecurity # http://piratesec.de # ########################################### import mechanize import cookielib import urllib2 from bs4 import BeautifulSoup import re import sys ...
Python
0.000005
8085c141505cb9f2c3a70efe902d6020ad93d38b
Add wnidFile2urlFile
put_wnidFile_get_urlFile.py
put_wnidFile_get_urlFile.py
import os from random import shuffle from psutil import virtual_memory import time def main(): # 未避免記憶體塞暴,每隔 1024*256 強制清空一次 lists max_lines = 1024*256 # 紀錄開始時間 startTime = time.time() shuffle_data = True # 打亂順序 # 查看urls資料夾里有沒有可能的url_file urls_dirPath = os.path.join("urls") urls_dirLi...
Python
0.999557
f2c47ccf852e1a2b2a68f4d7ac1e72409ddfad3e
Create scratch.py
scratch.py
scratch.py
import os import urllib DOWNLOADS_DIR = '/python-downloader/downloaded' # For every line in the file for url in open('urls.txt'): # Split on the rightmost / and take everything on the right side of that name = url.rsplit('/', 1)[-1] # Combine the name and the downloads directory to get the local filename...
Python
0.000002
8e3b2b6103a591dae2b99d7e219722e0992dae65
Add CatagoryMgr
CatagoryManager.py
CatagoryManager.py
from DbHelper import DbHelper class CatagoryManager(object): TABLE_NAME = "cactagory" FIELD_TITLE = "title" FIELD_COUNT = "count" def __init__(self): self.db = DbHelper() sql = "CREATE TABLE IF NOT EXISTS `" + self.TABLE_NAME + "` (" \ + self.FIELD_TITLE + " TEXT NOT NUL...
Python
0.000003
dcc64e9fd8bb3cb407959a30a2054fc180596bae
Add Pandas integration unit tests
tests/test_pandas_integration.py
tests/test_pandas_integration.py
from unittest import TestCase import numpy as np import pandas as pd import numpy.testing as npt from nimble import Events class TestAsPandasCondition(TestCase): def setUp(self): conditional_series = pd.Series([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) condition = (conditional_series > 0) sel...
Python
0
1696ca33e644d3cb1138d7ee4c48239b7a757cfd
Add the first script to try a led light
python_scripts/gpio_test.py
python_scripts/gpio_test.py
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(7,GPIO.OUT) for x in range(0,10): GPIO.output(7,True) time.sleep(1) GPIO.output(7,False) time.sleep(1) GPIO.cleanup()
Python
0.000001
5c091ea20a531692c676f9d4e0f450c0e642f740
Create module for uptime retrieval
Modules/Uptime.py
Modules/Uptime.py
from collections import OrderedDict from ModuleInterface import ModuleInterface from IRCResponse import IRCResponse, ResponseType import datetime class Module(ModuleInterface): triggers = ["uptime"] help = "uptime -- returns the uptime for the bot" def onTrigger(self, Hubbot, message): now = date...
Python
0
e39270b69e1e8831c177bf4e5051726e6a678407
Add wsgi python script [ci skip]
app/wsgi.py
app/wsgi.py
import os import sys root = os.path.dirname(os.path.realpath(__file__ + '/..')) # activate the virtual env activate_this = root + '/venv/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) sys.path.insert(0, root) # set the environment variable to production os.environ['FLASK_ENV']="PRODUCTI...
Python
0
b3865b173d9f29e3fd3b8c98f76029ec1f2e6829
Add Pure Storage Protection Groups module (#26356)
lib/ansible/modules/storage/purestorage/purefa_pg.py
lib/ansible/modules/storage/purestorage/purefa_pg.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Simon Dodsley (simon@purestorage.com) # # This file is part of Ansible # # Ansible 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...
Python
0
655bf4b4159e70b4a99185a1735ac63c3ee951dc
Add script to filter result by result type.
analysis/filter-by-result-type.py
analysis/filter-by-result-type.py
#!/usr/bin/env python import argparse import os import logging import pprint import sys import yaml # HACK _file = os.path.abspath(__file__) _dir = os.path.dirname(os.path.dirname(_file)) sys.path.insert(0, _dir) from BoogieRunner.ResultType import ResultType def main(args): resultTypes = [ r.name for r in list(R...
Python
0
983a89d7b400ec71806311cfe6a576d85dd59958
Create distance.py
abstractions/sensor/distance/distance.py
abstractions/sensor/distance/distance.py
# This code has to be added to __init__.py in folder .../devices/sensor class Distance(): def __family__(self): return "Distance" def __getMillimeter__(self): raise NotImplementedError @api("Distance", 0) @request("GET", "sensor/distance/*") @response(contentType=M_JSON) def...
Python
0.001409
bf93b3b4c8965e31e5b9b8ebdbf3f1b1d258e15e
Add a new script to simplify profiling of cvs2svn.py. Document in the script how to use kcachegrind to view the results.
tools/cvs2svn/profile-cvs2svn.py
tools/cvs2svn/profile-cvs2svn.py
#!/usr/bin/env python # # Use this script to profile cvs2svn.py using Python's hotshot profiler. # # The profile data is stored in cvs2svn.hotshot. To view the data using # hotshot, run the following in python: # # import hotshot.stats # stats = hotshot.stats.load('cvs2svn.hotshot') # stats.strip_dirs(...
Python
0.000009
61f06365254c57ced68beb83714164186164d939
add solutin for LRU Cache
src/LRUCache.py
src/LRUCache.py
class LRUCache: class ListNode: def __init__(self, val): self.val = val self.next = None self.prev = None # @param capacity, an integer def __init__(self, capacity): self.capacity = capacity self.size = 0 self.cache = {} self.hea...
Python
0
3a0fdcf51e1db8abab900a6cc1b4596d0dc4b054
automate fab process
automata.py
automata.py
import pexpect import getpass version = raw_input('Version: ') secret = getpass.getpass('Enter Passphrase: ') github_username = 'ianjuma' clean = pexpect.spawn('fab clean') clean.expect('Passphrase for private key:') clean.send(secret) deploy = pexpect.spawn('fab deploy:%s' %(version,)) deploy.expect('Passphrase for...
Python
0.000818
5ea95763c541b30a4b3f9ef5dbfa201b24ae5293
Create get_gg_list_result.py
get_gg_list_result.py
get_gg_list_result.py
import time from splinter import Browser def splinter(url,browser): #login 126 email websize browser.visit(url) #wait web element loading time.sleep(5) #fill in account and password browser.find_by_id('idInput').fill('xxxxxx') browser.find_by_id('pwdInput').fill('xxxxx') #click the butt...
Python
0.000003
3095142aa814e51e8fcde4d53633a93a54a7574f
Index main label reference
migrations/versions/e679554261b2_main_label_index.py
migrations/versions/e679554261b2_main_label_index.py
"""Main label index Revision ID: e679554261b2 Revises: e2be4ab896d3 Create Date: 2019-05-09 18:55:24.472216 """ # revision identifiers, used by Alembic. revision = 'e679554261b2' down_revision = 'e2be4ab896d3' from alembic import op import sqlalchemy as sa # NOQA def upgrade(): op.create_index(op.f('ix_label...
Python
0
ff51c695b516ea7e16518779c66ebd827b4f6230
Clean up Encode
python/pyphantomjs/encoding.py
python/pyphantomjs/encoding.py
''' This file is part of the PyPhantomJS project. Copyright (C) 2011 James Roe <roejames12@hotmail.com> 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 ...
''' This file is part of the PyPhantomJS project. Copyright (C) 2011 James Roe <roejames12@hotmail.com> 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 ...
Python
0.951529
815d758f74e01bc7a460e211ffb9cb81fedb9726
add 0002
Jaccorot/0002/0002.py
Jaccorot/0002/0002.py
#!/usr/local/bin/python #coding=utf-8 #第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。 import uuid import MySQLdb def create_code(num, length): #生成”num“个激活码,每个激活码含有”length“位 result = [] while True: uuid_id = uuid.uuid1() temp = str(uuid_id).replace('-', '')[:length] if temp not...
Python
0.999998
715be73c6fc5f3e5d151a0534309d097c73f1963
Fix listsinceblock.py
qa/rpc-tests/listsinceblock.py
qa/rpc-tests/listsinceblock.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal c...
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal c...
Python
0.000014
f015f18d1d4c495cb0b909b93e51d97f00301d59
Set the id of the person, not the roll call item
pupa/importers/votes.py
pupa/importers/votes.py
from pupa.models import Vote from .utils import (people_by_jurisdiction_and_name, orgs_by_jurisdiction_and_name, bills_by_jurisdiction_and_name) from .base import BaseImporter class VoteImporter(BaseImporter): _type = 'vote' _model_class = Vote def __init__(self, j...
from pupa.models import Vote from .utils import (people_by_jurisdiction_and_name, orgs_by_jurisdiction_and_name, bills_by_jurisdiction_and_name) from .base import BaseImporter class VoteImporter(BaseImporter): _type = 'vote' _model_class = Vote def __init__(self, j...
Python
0.000012
c3e8a9a60410ca4494038ba9f3a774b960a8a29e
Create quiz3.py
Laboratorios/quiz3.py
Laboratorios/quiz3.py
segundos = 0 while chance < 6: mints_seg = int (("ingrese el tiempo en segundos:")) chance +=1 if mints_seg / 60 segundos =60 time_seg%60 print (segundos)
Python
0.000002
0a0e7fbb684dd38f4704c28359969493a088fd0f
add future cons.
tushare/futures/domestic_cons.py
tushare/futures/domestic_cons.py
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' Created on 2017年06月04日 @author: debugo @contact: me@debugo.com ''' import re import datetime CFFEX_DAILY_URL = "http://www.cffex.com.cn/fzjy/mrhq/%s/%s/%s_1.csv" SHFE_DAILY_URL = 'http://www.shfe.com.cn/data/dailydata/kx/kx%s.dat' SHFE_VWAP_URL = 'http://www.shfe.com.c...
Python
0.000001
71a6d0a032896f4ef2e9a4cda541d142f2c48171
Add unittests for environment handler.
typhon/tests/test_environment.py
typhon/tests/test_environment.py
# -*- coding: utf-8 -*- """Testing the environment/configuration handler. """ import os from copy import copy import pytest from typhon import environment class TestEnvironment: """Testing the environment handler.""" def setup_method(self): """Run all test methods with an empty environment.""" ...
Python
0
d84a0b0d50fb4d01b2a2354d5317afd181f1053c
Add Random Forest Regression in Python
Regression/RandomForestRegression/regularRandomForestRegression.py
Regression/RandomForestRegression/regularRandomForestRegression.py
# -*- coding: utf-8 -*- """Random Forest Regression for machine learning. Random forest algorithm is a supervised classification algorithm. As the name suggest, this algorithm creates the forest with a number of decision trees. In general, the more trees in the forest the more robust the forest looks like. In the sam...
Python
0.000002
8bdab0460cf280a63538e8c56650a90109cda283
add PermMissingElem.py - working
PermMissinElem.py
PermMissinElem.py
def solution(A): euler = (len(A) + 1) * (len(A) + 2) / 2 return euler - sum(A)
Python
0
8ea82371d69b2f0cdc3f7c9bdd20e59e47eca621
add bookworm src
src/bookworm.py
src/bookworm.py
import csv import nltk import pandas as pd import spacy from nltk.tokenize import word_tokenize import string def load_book(bookPath, lower=True): ''' Reads in a novel from a .txt file, and returns it in (optionally lowercased) string form Parameters ---------- bookPath : string (required) ...
Python
0.000215
8f60b540e44fd13787c11303d81f570861c74bcf
make M5_PATH a real search path
configs/common/SysPaths.py
configs/common/SysPaths.py
# Copyright (c) 2006 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list ...
# Copyright (c) 2006 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list ...
Python
0.000858
32d12ae035d1c8cebd3a163f9e35c538628e5bc7
Add test_message.py
tests/test_message.py
tests/test_message.py
#!/usr/bin/env python3 # # Copyright 2016 Red Hat, Inc. # # Authors: # Fam Zheng <famz@redhat.com> # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. import sys import os import time import datetime from patchewtest import PatchewTestCase, main c...
Python
0
a965c542e8a2ea4bb74e522eae34161d8a6c3efa
Add minimal product test
tests/test_product.py
tests/test_product.py
# -*- coding: utf-8 -*- import unittest import os from context import epages class TestProduct(unittest.TestCase): client = None product_service = None product_id = None @classmethod def setUpClass(cls): host = os.environ['EPAGES_HOST'] shop = os.environ['EPAGES_SHOP'] t...
Python
0.000069
cf8ff340597d29431eaed8265a67205a1b021ee7
add host_evacuate task
rock/tasks/host_evacuate.py
rock/tasks/host_evacuate.py
from flow_utils import BaseTask from actions import NovaAction from server_evacuate import ServerEvacuateTask import logging class HostEvacuateTask(BaseTask,NovaAction): def execute(self, host): n_client = self._get_client() evacuated_host = host evacuable_servers = n_client.servers.list...
Python
0.000002
ceb3c0535f2701d595d440552d60da876d7cd0b8
Move some functions from 'model.utils' to 'core.xrf_utils'
pyxrf/core/xrf_utils.py
pyxrf/core/xrf_utils.py
import xraylib def parse_compound_formula(compound_formula): r""" Parses the chemical formula of a compound and returns the dictionary, which contains element name, atomic number, number of atoms and mass fraction in the compound. Parameters ---------- compound_formula: str chemi...
Python
0
2a6ec396512c435413f6e3848d1448af839fa9a6
Add unittests for FindQuery
tests/test_storage.py
tests/test_storage.py
import time from graphite_api.storage import FindQuery from . import TestCase class StorageTestCase(TestCase): def test_find_query(self): end = int(time.time()) start = end - 3600 query = FindQuery('collectd', None, None) self.assertEqual(repr(query), '<FindQuery: collectd from ...
Python
0
e4396938425bc27fc730d580a6cd4ee6e3fd09e9
Remove v1.0 and v1.1 API from version info.
quantum/api/versions.py
quantum/api/versions.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Citrix Systems. # 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...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Citrix Systems. # 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...
Python
0.000001
5db291b8a745f8dc640e7cdc7a274535abcc63af
Create rPiEinkQR.py
rPiEinkQR.py
rPiEinkQR.py
import os from PIL import Image from epyper.displayCOGProcess import Display from epyper.displayController import DisplayController # code to create QR code of good size for eink screen # qrencode -o qrcode.png -s 7 -l L -v 1 -m 1 "TestThree003" QRname = "qrencode -o qrcode.png -s 7 -l L -v 1 -m 1 \"" + "TestThree04"...
Python
0.000001
dff76b6518b1de1be56def7469180d841a9e6121
Create __init__.py
Tools/__init__.py
Tools/__init__.py
# -*- coding: utf-8 -*-
Python
0.000429
a152c7c48baa0f1c82e7d84bebbee674eb4f2761
Add command to queue expired tiles
tilequeue/commands.py
tilequeue/commands.py
from tilequeue.queues import make_sqs_queue from tilequeue.tile import explode_with_parents from tilequeue.tile import parse_expired_coord_string import argparse import os def add_aws_cred_options(arg_parser): arg_parser.add_argument('--aws_access_key_id') arg_parser.add_argument('--aws_secret_access_key') ...
Python
0.000001
707781ac58318af002cc1e75d8c31839d4e66e77
add module to support search result export
arches/app/utils/geos_to_pyshp.py
arches/app/utils/geos_to_pyshp.py
from django.contrib.gis.geos import MultiPoint from django.contrib.gis.geos import MultiLineString from django.contrib.gis.geos import MultiPolygon def convert_geom(geos_geom): if geos_geom.geom_type == 'Point': multi_geom = MultiPoint(geos_geom) shp_geom = [[c for c in multi_geom.coords]] if geos_geom...
Python
0
8e7a2e9192dadbcfd02acd10bcd7e05357af32e8
Add a loader for doctests to the unittest suite
tests/test_doctest.py
tests/test_doctest.py
# coding: utf-8 """Test doctest contained tests in every file of the module. """ import doctest import importlib import os import pkgutil import sys import types import warnings import tempfile try: from unittest import mock except ImportError: import mock import six import fs import fs.opener.parse from fs....
Python
0
3e0903ba2f74d5f73241d1ffc5056f2a77c709e0
Add a simple test for SetupPrometheusEndpointOnPortRange
tests/test_exports.py
tests/test_exports.py
#!/usr/bin/env python from django_prometheus.exports import SetupPrometheusEndpointOnPortRange import unittest class ExportTest(unittest.TestCase): def testPortRange(self): port_range = [8000, 8001] SetupPrometheusEndpointOnPortRange(port_range) SetupPrometheusEndpointOnPortRange(port_rang...
Python
0.000001
a4ce015943da37335114aa8b384f2ee7371f6446
Test in app-factory.
tests/test_factory.py
tests/test_factory.py
from flask import Flask from flask_sslify import SSLify from pytest import fixture class AppFactoryContext(object): def __init__(self): self.sslify = SSLify() self.app = None self.appctx = None def __enter__(self): self.app = self.create_app() self.appctx = self.app.a...
Python
0
a866b7e2de7e76e8bfb3b1feb22d7692afa5111d
Add test exposing stale promise job store cache (connected to #817)
src/toil/test/src/promisesTest.py
src/toil/test/src/promisesTest.py
# Copyright (C) 2015 UCSC Computational Genomics Lab # # 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 o...
Python
0
e99807f81dea6bac82f373a210af0c4f26b61334
test - Test for exception on syntax error
tests/test_request.py
tests/test_request.py
import pytest import overpy class TestQuery(object): def test_syntax_error(self): with pytest.raises(overpy.exception.OverpassBadRequest): api = overpy.Overpass() # Missing ; after way(1) api.query(( "way(1)" "out body;" ))
Python
0
69c5015a1a9dc3233530d691d20befa529f7c880
Create lookupAndStoreTweets.py utility.
app/utils/insert/lookupAndStoreTweets.py
app/utils/insert/lookupAndStoreTweets.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Lookup and Store Tweets utility. """ import argparse import os import sys # Allow imports to be done when executing this file directly. appDir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardi...
Python
0
bb2644fc14dd92cf54c6a22da6fe3a66f89535e6
Create VNSautoRotator.py
VNSautoRotator.py
VNSautoRotator.py
import numpy as np import sys, os import nrrd if (len(sys.argv) < 2): print 'Error: missing arguments!' print 'e.g. python VNSautoRotator.py imageIn.nrrd [ImageOut.nrrd]' print 'rotate RPI to LPS orientation for CMTK (as it doesn't like RPI)' else: print 'Processing %s...'% (str(sys.argv[1])) data1...
Python
0
16b73476daedaf1b111e900c0db947dcdab1c9a6
Add zits crawler
comics/crawler/crawlers/zits.py
comics/crawler/crawlers/zits.py
from comics.crawler.utils.lxmlparser import LxmlParser from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Zits' language = 'en' url = 'http://www.arcamax.com/zits' start_date = '1997-07-01' history_capable_days = 14...
Python
0
9b0d6239bf73dce4cc981f13dd16d3c5f46b40b3
Create dominick.py
dominick.py
dominick.py
Python
0
5ffdaf778157d112c26b96020408f80ec3820e02
Create __init__.py
crispy/actions/__init__.py
crispy/actions/__init__.py
from crispy.actions.core import *
Python
0.000429
fb9915a481e3161325eb5200db2232e6e34b2acc
Add support for Jawbone
services/jawbone.py
services/jawbone.py
from oauthlib.common import add_params_to_uri import foauth.providers class Jawbone(foauth.providers.OAuth2): # General info about the provider provider_url = 'https://jawbone.com/' docs_url = 'https://jawbone.com/up/developer/endpoints' category = 'Fitness' # URLs to interact with the API au...
Python
0
4f50891c1a7d918010dbcecd640bb4b83f7bd2a3
ADD taobao login
socialoauth/sites/taobao.py
socialoauth/sites/taobao.py
# -*- coding: utf-8 -*- from socialoauth.sites.base import OAuth2 class TaoBao(OAuth2): AUTHORIZE_URL = 'https://oauth.taobao.com/authorize' ACCESS_TOKEN_URL = 'https://oauth.taobao.com/token' TAOBAO_API_URL = 'https://eco.taobao.com/router/rest' def build_api_url(self, url): return sel...
Python
0
20eb83e4e8e0391c9efaca7f30a80220f9a14e9a
Add codelists management tools
maediprojects/query/codelists.py
maediprojects/query/codelists.py
from maediprojects import db, models import datetime def create_code(data): codelistcode = models.CodelistCode() for attr, val in data.items(): setattr(codelistcode, attr, val) db.session.add(codelistcode) db.session.commit() return codelistcode def update_attr(data): codelistcode...
Python
0.000001
3b74b2c0c8f06cd7262cd9dd9093a82038a23d59
Create saxparser.py
saxparser.py
saxparser.py
#!/usr/bin/python import sys import xml.sax import io import MySQLdb class MyHandler(xml.sax.ContentHandler): def __init__(self): xml.sax.ContentHandler.__init__(self) self.db = MySQLdb.connect(host="localhost", user="root", passwd="trowel", db="registerdb2011") self.cursor = self.db.curso...
Python
0.000002
c4578461b82dbe0f94439e6823669af536ae3f09
add index on _id_document field
apps/archive_history/service.py
apps/archive_history/service.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import loggi...
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import loggi...
Python
0.000002
1c810e9026f2d2c7ce3722d89a0cd7d333904e0f
add ipdb.py for easier debugging
examples/ipdb.py
examples/ipdb.py
""" This module provides a quick n dirty way to get a debug ipython shell. 2 ways to achieve that: 1. call set_trace() will immediately stop your program at that position 2. import ipdb will overwrite sys.excepthook with ipdb.info. This will provide the ipython shell """ import sys from IPython.core.debugger impor...
Python
0.000001
1e3011f728dc522ba82abf3526dfb50c9d874558
Create invertJulesRT_new.py
chapter4/Minimising/invertJulesRT_new.py
chapter4/Minimising/invertJulesRT_new.py
#!/usr/bin/env python import sys import os from copy import copy import numpy as np import matplotlib.pyplot as plt import scipy.optimize as opt from runJulesRTStruct import runJulesRTStruct class julesRTData(): def __init__(self): self.lai=float() self.leafT=float() self.leafR=float() self.soilR...
Python
0.000002
da4436ec5ec3c982e42e9f85749ac8c8cf8b8a94
add codegen submodule
altair/codegen.py
altair/codegen.py
""" Object for generating Python code calls """ class CodeGen(object): def __init__(self, name, args=None, kwargs=None, methods=None): self.name = name self.args = (args or []) self.kwargs = (kwargs or {}) self.methods = (methods or []) def to_str(self, tablevel=0, tabsize=4): ...
Python
0.000001
9d20d1f87f509ce51fde5c51460ff0b17c051ca1
Create pytest_setup.py
utils/pytest_setup.py
utils/pytest_setup.py
pip install -U pytest-xdist pip install -U parameterized pip install -U pytest-flake8 pip install -U pytest-html
Python
0.000007
4c3a53c0dde389f7294ff17117352a15a9efb94b
Add Strategy for generating types deterministically
speccer/strategy.py
speccer/strategy.py
# strategy.py - Strategies for producing arguments to model commands # author: Ben Simner import string import itertools import functools import abc def generate(typ, depth, guard=None): '''Generate all results for some type 'typ' to depth 'depth' Checking partials against 'guard' function ''' s...
Python
0.000003
7039e4f25d8eecdf2d5d2b4a4a769e05c5075222
Fix description of 'api_read_full_member' permission
bluebottle/members/migrations/0020_auto_20171031_1048.py
bluebottle/members/migrations/0020_auto_20171031_1048.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2017-10-31 09:48 from __future__ import unicode_literals from django.db import migrations def rename_full_member_permission(apps, schema_editor): Permission = apps.get_model('auth', 'Permission') perm = Permission.objects.get(codename='api_read_full_me...
Python
0.000052
4b4e9bc8f9605519b12d4da25dc6822baa629d2e
Add test_core
unit_tests/test_core.py
unit_tests/test_core.py
from lcapy import * import unittest import sympy as sym s = sym.var('s') class LcapyTester(unittest.TestCase): """Unit tests for lcapy """ def test_sExpr(self): """Lcapy: check sExpr """ a = sExpr('(s+2)/(s-2)') self.assertEqual(a.N, sExpr('s+2'), "N incorrect.") ...
Python
0.000001
30be74075e761f932a10ea0806a08991b8fd9cb4
Add script to list nodes without an external ID
code/python/find-nodes-without-external-id.py
code/python/find-nodes-without-external-id.py
#!/usr/bin/env python import httplib import urllib import json import ssl import argparse import re parser = argparse.ArgumentParser(description='Find any node that does not have an external ID set.') parser.add_argument('--target-url', required=True, help='URL for the UpGuard instance. This should be the hostname on...
Python
0
f12af379ec31b8c14bf871768c558c81bad95301
Add grains for the cloud metadata server
salt/grains/metadata.py
salt/grains/metadata.py
# -*- coding: utf-8 -*- ''' Grains from cloud metadata servers at 169.254.169.254 .. versionadded:: Nitrogen :depends: requests ''' from __future__ import absolute_import # Import python libs import os import socket # Import salt libs import salt.utils.http as http # metadata server information IP = '169.254.169....
Python
0
101189c319c2d0fadc97fd1077a87c11ab159a12
add a new test folder.
Test/new_module.py
Test/new_module.py
#!/usr/bin/env python3 # # Copyright (c) 2016 Zhixian MA <zxma_sjtu@qq.com> # MIT license """ A test script to learn the grammar and code tyle of python, and try to make interesting docstrings. """ import os import sys import argparse import logging import numpy as np from astropy.io import fits import fg21sim from...
Python
0
6183347fc0f0309bf2c700f75b5b51f7cdbda1b4
Create Detect_Faces.py
src/Detect_Faces.py
src/Detect_Faces.py
__author__ = 'Guggi' import urllib2 import urllib import unirest import json from poster.encode import multipart_encode from poster.streaminghttp import register_openers from PIL import Image, ImageDraw, ImageFont register_openers() api_key = "YOUR_API_KEY" #you need to exchange the YOUR_API_KEY with your own API ke...
Python
0
0f66e2cdcf653ea772a726ef2a5be0d12eeb1372
add converter for Nifti volumes (anything Nibabel can read)
volume_to_raw_chunks.py
volume_to_raw_chunks.py
#! /usr/bin/env python3 # # Copyright (c) 2016, 2017, Forschungszentrum Juelich GmbH # Author: Yann Leprince <y.leprince@fz-juelich.de> # # This software is made available under the MIT licence, see LICENCE.txt. import gzip import json import os import os.path import sys import numpy as np import nibabel import nibab...
Python
0
3d624b5693a753ee8ecdd6f979eaa3d17736dca7
Create Syllabifier.py
cltk/corpus/middle_english/Syllabifier.py
cltk/corpus/middle_english/Syllabifier.py
""" Sonority hierarchy for Middle English """ Syllabifier = { 'a': 1, 'æ': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'y': 1, 'm': 2, 'n': 2, 'p': 3, 'b': 3, 'd': 3, 'g': 3, 't': 3, 'k': 3, 'ð': 3, 'c': 4, 'f': 4, 's': 4, 'h': 4, 'v': 4, '...
Python
0.000001
bace8f65e696211db5a6ffa2cefc70d2e061b950
Add Support for /r/greentext
greentext/app.py
greentext/app.py
#encoding:utf-8 from utils import get_url, weighted_random_subreddit from utils import SupplyResult # Subreddit that will be a source of content subreddit = weighted_random_subreddit({ 'greentext': 1.0, # If we want get content from several subreddits # please provide here 'subreddit': probability # ...
Python
0
b1af12dfc111c6550c166d00fdabf7fa707bfc1b
Create main.py
challenge_0/python/wost/main.py
challenge_0/python/wost/main.py
''' Written in Python 3.6 ''' def main(text): print(f"Hello world, additional text: {text}") if __name__ == "__main__": main(input("What would you like to say?"))
Python
0.000001
3d762fd7993d6b02ef6ae94da5cf1264cbe4363c
Create settings.py
settings.py
settings.py
""" Описание возможных значений: False - нет, True - да () - кортеж, заполняется элементами через запятую '' - строка, само содержимое пишется между кавычками """ # Данные для авторизации бота # Кортеж из одного элемента - токен группы # Кортеж из 2х элементов - логин/ пароль пользователя # Если в кортеже 1 элемент - ...
Python
0.000001
14aba0695514866439164f48fe1f66390719431f
Add selcet_gamma.py (authored by Amnon)
scripts/select_gamma.py
scripts/select_gamma.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Fri Oct 18 10:13:48 2013 @author: amnon ### 80 char max please Look at all the gammaproteobacteria and select candidate contamination sequence OTUs output: a list of sorted gammaproteobacteria (or other) otuids, according to mean frequency """ import...
Python
0
83fe6892c5b061f5fbba64c9f870f30c80b1a12a
create word bigram matrix
dsl/features/word_level.py
dsl/features/word_level.py
import logging from os import path from argparse import ArgumentParser from featurize import Tokenizer, BigramModel def parse_args(): p = ArgumentParser() p.add_argument('--train', type=str) p.add_argument('--test', type=str) p.add_argument('--raw-matrix-dir', type=str) p.add_argument('--workdir',...
Python
0.999995
f6a5d10a068f79c3ffa20ea9913523549b129b3d
Add tests for all standard commands
dodo_commands/framework/test/test_commands.py
dodo_commands/framework/test/test_commands.py
"""Tests for all standard commands.""" import os import shutil import ruamel.yaml class TestConfigIO: # noqa @classmethod def _load_config(cls, config_filename): with open(config_filename) as f: return ruamel.yaml.round_trip_load(f.read()) @classmethod def _write_config(cls, conf...
Python
0.000003
fec8de91954230b44b717f4b3d5a3a774c108fdf
Create monitor.py
assets/monitor.py
assets/monitor.py
#!/usr/bin/env python import sqlite3 import os import time import glob # global variables speriod=(15*60)-1 dbname='/var/www/templog.db' # store the temperature in the database def log_temperature(temp): conn=sqlite3.connect(dbname) curs=conn.cursor() curs.execute("INSERT INTO temps values(datetime(...
Python
0.000001
81b178677a3c217f62be85bf16964a1f0717930f
fix #1
commons_util/os_utils/memory.py
commons_util/os_utils/memory.py
__author__ = 'Danyang'
Python
0.000002
cd1ed470e319c6aa5d2ed5206d6fb6fba63876ee
add k-fold splitter
splitter.py
splitter.py
""" Stuff which splits dataset into train and test sets. """ class KFoldSplitter(object): """Splitter that splits a table into k groups of (almost) equal size. Before using this splitter, make sure the table to split has a `group_id` column. Sample usage: >>> splitter.split('query') >>> while spli...
Python
0.000002
6119f7998d918d3b38f129b7afd720f9a35e35c1
Add script for fetching metadata from audio file
audio-metadata.py
audio-metadata.py
#! /usr/bin/env python import os import sys import re import tempfile def getVideoDetails(filepath): tmpf = tempfile.NamedTemporaryFile() os.system("ffmpe...
Python
0
21df69e2b2be4d59b5c8257d7efbf27a75eeb8dd
Add priming_output example
examples/priming_output.py
examples/priming_output.py
#!/usr/bin/env python3 """Test priming output buffer. See http://www.portaudio.com/docs/proposals/020-AllowCallbackToPrimeStream.html Note that this is only supported in some of the host APIs. """ import sounddevice as sd def callback(indata, outdata, frames, time, status): outdata.fill(0) if status.primin...
Python
0.00023
98398398f590c3a98733193fc0ea45a1948edd0e
Add example to compare layers in a char-rnn task.
examples/recurrent-text.py
examples/recurrent-text.py
#!/usr/bin/env python import climate import matplotlib.pyplot as plt import numpy as np import theanets import utils climate.enable_default_logging() COLORS = ['#d62728', '#1f77b4', '#2ca02c', '#9467bd', '#ff7f0e', '#e377c2', '#8c564b', '#bcbd22', '#7f7f7f', '#17becf'] URL = 'http://www.gutenberg.org/cac...
Python
0
f41dc1eb966da1505d4dedd00034debf79774807
add tests
smalltalk_like/tests.py
smalltalk_like/tests.py
from obj_model import Class, Instance, TYPE, OBJECT def test_creation(): test_attribute() test_subclass() test_callmethod() def test_attribute(): # Python Code class A(object): pass obj = A() obj.a = 1 assert obj.a == 1 obj.b = 2 assert obj.b == 2 obj.a = 3 ...
Python
0
6c9cf71064cf8a0c47147efeb742b2d66caa1c47
add stub models file
corehq/apps/toggle_ui/models.py
corehq/apps/toggle_ui/models.py
# Stub models file from couchdbkit.ext.django.schema import Document class _(Document): pass
Python
0
01c8d16df94ce558593b29974e30aa96679c6862
add stylize.py for feed-forward mode
stylize.py
stylize.py
""" Copyright 2016-present Tony Peng Load a trained feed-forward model to stylize an image. """ import nets import numpy as np import tensorflow as tf import utils import time MODEL_PATH = 'models/trained/Udnie' CONTENT_IMAGE_PATH = 'runs/Udnie/content_small.jpg' OUTPUT_IMAGE_PATH = 'runs/Udnie/styled4.jpg' content...
Python
0