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
7700e8b9a5a62fce875156482170c4fbc4cae902
Update shortcut template
swjblog/polls/views.py
swjblog/polls/views.py
from django.http import HttpResponse from django.template import loader from django.shortcuts import get_object_or_404, render # Create your views here. from .models import Question # def index(request): # latest_question_list = Question.objects.order_by('-pub_date')[:5] # template = loader.get_template('po...
from django.shortcuts import render from django.http import HttpResponse from django.template import loader # Create your views here. from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') cont...
Python
0.000001
0e780569b8d40f3b9599df4f7d4a457f23b3f54f
Make uploader work
stoneridge_uploader.py
stoneridge_uploader.py
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import glob import os import requests import stoneridge class StoneRidgeUploader(object): ""...
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import glob import os import human_curl as requests import stoneridge class StoneRidgeUploader(o...
Python
0.000035
00216fef47b24c7c4d371cb350db7305d85e7d7b
fix link to numpy func
cupy/random/__init__.py
cupy/random/__init__.py
import numpy as _numpy def bytes(length): """Returns random bytes. .. note:: This function is just a wrapper for :obj:`numpy.random.bytes`. The resulting bytes are generated on the host (NumPy), not GPU. .. seealso:: :meth:`numpy.random.bytes <numpy.random.mtrand.RandomState.byt...
import numpy as _numpy def bytes(length): """Returns random bytes. .. note:: This function is just a wrapper for :meth:`numpy.random.bytes`. The resulting bytes are generated on the host (NumPy), not GPU. .. seealso:: :meth:`numpy.random.bytes <numpy.random.mtrand.RandomState.by...
Python
0
5b1790664ad5268a1d1764b81d1fa7e8fea5aabe
Bump version number.
stormtracks/version.py
stormtracks/version.py
VERSION = (0, 5, 0, 6, 'alpha') def get_version(form='short'): if form == 'short': return '.'.join([str(v) for v in VERSION[:4]]) elif form == 'long': return '.'.join([str(v) for v in VERSION][:4]) + '-' + VERSION[4] else: raise ValueError('unrecognised form specifier: {0}'.format(...
VERSION = (0, 5, 0, 5, 'alpha') def get_version(form='short'): if form == 'short': return '.'.join([str(v) for v in VERSION[:4]]) elif form == 'long': return '.'.join([str(v) for v in VERSION][:4]) + '-' + VERSION[4] else: raise ValueError('unrecognised form specifier: {0}'.format(...
Python
0
8b84b2ae83977e091ee33ce86e30bcc7cc5c08a2
Allow apostrophe and forbid colon in thread names
chandl/util.py
chandl/util.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import sys import hashlib import unidecode import six import requests import chandl def bytes_fmt(num, suffix='B'): """ Turn a number of bytes into a more friendly representation, e.g. 2.5MiB. :param num: The number of bytes...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import sys import hashlib import unidecode import six import requests import chandl def bytes_fmt(num, suffix='B'): """ Turn a number of bytes into a more friendly representation, e.g. 2.5MiB. :param num: The number of bytes...
Python
0.000006
a82d419d17c67cfd7842cf104994b9ecbda96e94
Delete existing libnccl before installing NCCL
perfkitbenchmarker/linux_packages/nccl.py
perfkitbenchmarker/linux_packages/nccl.py
# Copyright 2018 PerfKitBenchmarker 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 appli...
# Copyright 2018 PerfKitBenchmarker 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 appli...
Python
0.000001
13ae8cf8eddba1cf40d89307ba1c52480cbac472
Bump version
async2rewrite/__init__.py
async2rewrite/__init__.py
""" Convert discord.py code using abstract syntax trees. """ __title__ = 'async2rewrite' __author__ = 'Tyler Gibbs' __version__ = '0.0.3' __copyright__ = 'Copyright 2017 TheTrain2000' __license__ = 'MIT' from .main import *
""" Convert discord.py code using abstract syntax trees. """ __title__ = 'async2rewrite' __author__ = 'Tyler Gibbs' __version__ = '0.0.2' __copyright__ = 'Copyright 2017 TheTrain2000' __license__ = 'MIT' from .main import *
Python
0
0639158e539f0f1c1a6d4dac1753179429257017
add django_pluralize template filter
source/base/helpers.py
source/base/helpers.py
import datetime import logging import os from django.conf import settings from django.template.defaultfilters import linebreaks as django_linebreaks,\ escapejs as django_escapejs, pluralize as django_pluralize from jingo import register from sorl.thumbnail import get_thumbnail logger = logging.getLogger('base.he...
import datetime import logging import os from django.conf import settings from django.template.defaultfilters import linebreaks as django_linebreaks,\ escapejs as django_escapejs from jingo import register from sorl.thumbnail import get_thumbnail logger = logging.getLogger('base.helpers') @register.filter def l...
Python
0.000001
62694c2072e3499b843372166daeead8a6335a5e
Format with Black
comics/accounts/views.py
comics/accounts/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from invitations.utils import get_invitation_model from comics.accounts.models ...
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from invitations.utils import get_invitation_model from comics.accounts.models ...
Python
0
d305e953d028b935333b86b4cffc58649b8a4652
Twitter uses OAuth1 not OAuth2, dummy
hiptweet/tasks.py
hiptweet/tasks.py
import logging import requests from flask import Blueprint, jsonify from requests_oauthlib import OAuth1Session from hiptweet import celery from hiptweet.models import HipChatGroup, HipChatRoom from celery.utils.log import get_task_logger # set up logging logger = get_task_logger(__name__) logger.setLevel(logging.INFO...
import logging import requests from flask import Blueprint, jsonify from requests_oauthlib import OAuth2Session from hiptweet import celery from hiptweet.models import HipChatGroup, HipChatRoom from celery.utils.log import get_task_logger # set up logging logger = get_task_logger(__name__) logger.setLevel(logging.INFO...
Python
0.99914
aa4be6a435222003bf5e87df5c1f8d34394592fe
add celery conf
hiren/__init__.py
hiren/__init__.py
from github.celery import app as celery_app
Python
0.999777
a871f05ba94c34b1444468c46ed7895469059653
Create member allow_origin
glarkconnector.py
glarkconnector.py
#!/usr/bin/python """Connector for the glark.io editor. """ __version__ = "0.1" import BaseHTTPServer import json import os import re import sys class ConnectorRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Request handler exposing a REST api to the underlying filesystem""" serv...
#!/usr/bin/python """Connector for the glark.io editor. """ __version__ = "0.1" import BaseHTTPServer import json import os import re import sys class ConnectorRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Request handler exposing a REST api to the underlying filesystem""" serv...
Python
0
f343c9782ac0ae02ca056385aa4c6098399d0076
Fix loop through jaydebeapi cursor because not iterable
atp_classes/TeradataDB.py
atp_classes/TeradataDB.py
import atp_classes, re, platform, os class TeradataDB: def __init__(self, host=None, port=None, username=None, password=None, database=None, auth_mech=None): config = atp_classes.Config() self.host = host or config.get_config()['database']['dataWarehouse']['host'] self.username = username...
import atp_classes, re, platform, os class TeradataDB: def __init__(self, host=None, port=None, username=None, password=None, database=None, auth_mech=None): config = atp_classes.Config() self.host = host or config.get_config()['database']['dataWarehouse']['host'] self.username = username...
Python
0.000022
e8583e6ad8c0a3d89fe4bcb063a776f1ad139447
Update spoonerism.py
pythainlp/transliterate/spoonerism.py
pythainlp/transliterate/spoonerism.py
# -*- coding: utf-8 -*- from pythainlp.transliterate import pronunciate from pythainlp import thai_consonants _list_consonants = list(thai_consonants.replace("ห", "")) def puan(word: str, show_pronunciation: bool = True) -> str: """ Thai Spoonerism This function converts Thai word to spoonerized. It...
# -*- coding: utf-8 -*- from pythainlp.transliterate import pronunciate from pythainlp import thai_consonants _list_consonants = list(thai_consonants.replace("ห", "")) def puan(word: str, show_pronunciation: bool = True) -> str: """ Thai Spoonerism This function converts Thai word to spoonerized. It...
Python
0
9abe7a776c4b0a4995a1c3a3d16f02bcba93f12e
add sin flute
audio/fourier_an_audio.py
audio/fourier_an_audio.py
#Milton Orlando Sarria #analisis espectral de sinusoides import matplotlib.pyplot as plt import numpy as np from fourierFunc import fourierAn import wav_rw as wp from scipy.signal import get_window filename1='sound/flute-A4.wav' filename2='sound/violin-B3.wav' #leer los archivos de audio fs,x1=wp.wavread(filename1) ...
#Milton Orlando Sarria #analisis espectral de sinusoides import matplotlib.pyplot as plt import numpy as np from fourierFunc import fourierAn import wav_rw as wp filename1='sound/flute-A4.wav' filename2='sound/violin-B3.wav' #leer los archivos de audio fs,x1=wp.wavread(filename1) fs,x2=wp.wavread(filename2) t=(np....
Python
0.999997
0b7f25c92a2d0798a535487aa5305a793e998214
Fix line replacement logic
homely/general.py
homely/general.py
import os from homely.engine import add from homely.utils import filereplacer def lineinfile(filename, contents, prefix=None, regex=None): filename = os.path.expanduser(filename) obj = LineInFile(filename=filename, contents=contents) if prefix is not None: obj.findprefix(prefix) elif regex is...
import os from homely.engine import add from homely.utils import filereplacer def lineinfile(filename, contents, prefix=None, regex=None): filename = os.path.expanduser(filename) obj = LineInFile(filename=filename, contents=contents) if prefix is not None: obj.findprefix(prefix) elif regex is...
Python
0.000004
53b43e51c4d073dae4f3ccad896ba1744ca1284b
Update version
auth_backends/_version.py
auth_backends/_version.py
__version__ = '0.1.2' # pragma: no cover
__version__ = '0.1.1' # pragma: no cover
Python
0
f57a2c9124da513734a8e4934b8a02903109077e
Remove hardcoded backgrount from molecule svg
girder/molecules/server/openbabel.py
girder/molecules/server/openbabel.py
from girder.api.rest import RestException from openbabel import OBMol, OBConversion import pybel import re inchi_validator = re.compile('InChI=[0-9]S?\/') # This function only validates the first part. It does not guarantee # that the entire InChI is valid. def validate_start_of_inchi(inchi): if not inchi_vali...
from girder.api.rest import RestException from openbabel import OBMol, OBConversion import pybel import re inchi_validator = re.compile('InChI=[0-9]S?\/') # This function only validates the first part. It does not guarantee # that the entire InChI is valid. def validate_start_of_inchi(inchi): if not inchi_vali...
Python
0.00027
2321ddb5f6d7731597f4f122a87041933348f064
Enable Unicode tests
gmn/src/d1_gmn/tests/test_unicode.py
gmn/src/d1_gmn/tests/test_unicode.py
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # Licensed under the Apache License, Version 2.0 ...
# -*- coding: utf-8 -*- # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2016 DataONE # # Licensed under the Apache License, Version 2.0 ...
Python
0.000001
3868a4ef30835ed1904a37318013e20f2295a8a9
Remove fantastic from COB theme
ckanext/cob/plugin.py
ckanext/cob/plugin.py
import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit def groups(): # Return a list of groups return toolkit.get_action('group_list')(data_dict={'all_fields': True}) def dataset_count(): # Return a count of all datasets result = toolkit.get_action('package_search')(data_dict={'rows': 1...
import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit def groups(): # Return a list of groups return toolkit.get_action('group_list')(data_dict={'all_fields': True}) def dataset_count(): # Return a count of all datasets result = toolkit.get_action('package_search')(data_dict={'rows': 1...
Python
0
46c1c21c0190aa95f4fede8fa1d98bbae7cf38c5
test mode defaults to true - fix for #21
ckanext/doi/config.py
ckanext/doi/config.py
#!/usr/bin/env python # encoding: utf-8 """ Created by 'bens3' on 2013-06-21. Copyright (c) 2013 'bens3'. All rights reserved. """ from pylons import config from paste.deploy.converters import asbool TEST_PREFIX = '10.5072' ENDPOINT = 'https://mds.datacite.org' TEST_ENDPOINT = 'https://test.datacite.org/mds' def g...
#!/usr/bin/env python # encoding: utf-8 """ Created by 'bens3' on 2013-06-21. Copyright (c) 2013 'bens3'. All rights reserved. """ from pylons import config from paste.deploy.converters import asbool TEST_PREFIX = '10.5072' ENDPOINT = 'https://mds.datacite.org' TEST_ENDPOINT = 'https://test.datacite.org/mds' def g...
Python
0.000001
3c1b5c425109d24eca552e60e859d7d747607492
Fix UP in TRRUST
indra/sources/trrust/processor.py
indra/sources/trrust/processor.py
from copy import deepcopy from indra.databases import hgnc_client from indra.statements import Agent, IncreaseAmount, DecreaseAmount, Evidence class TrrustProcessor(object): """Processor to extract INDRA Statements from Trrust data frame. Attributes ---------- df : pandas.DataFrame The Trrust...
from copy import deepcopy from indra.databases import hgnc_client from indra.statements import Agent, IncreaseAmount, DecreaseAmount, Evidence class TrrustProcessor(object): """Processor to extract INDRA Statements from Trrust data frame. Attributes ---------- df : pandas.DataFrame The Trrust...
Python
0.000001
bf8ab86d536570790d135f0f46c97ffb30a83535
update background_substraction.py
background_subtraction.py
background_subtraction.py
# Reference: http://docs.opencv.org/master/db/d5c/tutorial_py_bg_subtraction.html # requires opencv v3.1.0 import numpy as np import cv2 # TODO: remove hard coded file name cap = cv2.VideoCapture('videos/sample_video_2.mp4') # Here are the 3 ways of background subtraction # createBackgroundSubtractorMOG2 seems to gi...
# Reference: http://docs.opencv.org/master/db/d5c/tutorial_py_bg_subtraction.html import numpy as np import cv2 # TODO: remove hard coded file name cap = cv2.VideoCapture('videos/sample_video_2.mp4') # Here are the 3 ways of background subtraction # createBackgroundSubtractorMOG2 seems to give the best result. Need ...
Python
0.000001
1f815ad5cb7535132a60297808abfa959709ba65
Fix redirect_to_login
daiquiri/files/views.py
daiquiri/files/views.py
import logging from django.contrib.auth.views import redirect_to_login from django.core.exceptions import PermissionDenied from django.http import Http404 from django.views.generic import View from .utils import file_exists, check_file, send_file logger = logging.getLogger(__name__) class FileView(View): def ...
import logging from django.core.exceptions import PermissionDenied from django.http import Http404 from django.shortcuts import redirect from django.views.generic import View from .utils import file_exists, check_file, send_file logger = logging.getLogger(__name__) class FileView(View): def get(self, request,...
Python
0.000011
3ce5f60102d5de7367a06e7412e9e31597e40a58
revert to original hello world
click_tutorial/cli.py
click_tutorial/cli.py
import click @click.command() def cli(): click.echo("Hello, World!") if __name__ == '__main__': cli()
import click @click.argument('name') @click.command() def cli(name): click.echo("Hello, {0}!".format(name)) if __name__ == '__main__': cli()
Python
0.999999
2a1ec4c0ea1904d7ea4728c08514cf5e5fa3ca44
migrate utils tests
paramnormal/tests/test_utils.py
paramnormal/tests/test_utils.py
# -*- coding: utf-8 -*- import numpy import nose.tools as nt from numpy.random import seed import numpy.testing as nptest from paramnormal import paramnormal, utils def test_greco_deco(): d1 = paramnormal.normal._process_args(mu=1, sigma=2) d2 = paramnormal.normal._process_args(μ=1, σ=2) expected = dict...
# -*- coding: utf-8 -*- import numpy import nose.tools as nt from numpy.random import seed import numpy.testing as nptest from paramnormal import process_args def test_greco_deco(): if not process_args.PY2: d1 = process_args.normal(mu=1, sigma=2) d2 = process_args.normal(μ=1, σ=2) expect...
Python
0.000001
d44250f60e9676618170bd61f8f6bc438078ef87
Add celery settings.
base/config/production.py
base/config/production.py
" Production settings must be here. " from .core import * from os import path as op SECRET_KEY = 'SecretKeyForSessionSigning' ADMINS = frozenset([MAIL_USERNAME]) # flask.ext.collect # ----------------- COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static') # dealer DEALER_PARAMS = dict( backends=('git', ...
" Production settings must be here. " from .core import * from os import path as op SECRET_KEY = 'SecretKeyForSessionSigning' ADMINS = frozenset([MAIL_USERNAME]) # flask.ext.collect # ----------------- COLLECT_STATIC_ROOT = op.join(op.dirname(ROOTDIR), 'static') # dealer DEALER_PARAMS = dict( backends=('git', ...
Python
0
4c977a313942074cccdd6756762c5545e650cdc7
Switch to NumPy's `ndindex` in `_cdist_apply`
dask_distance/_utils.py
dask_distance/_utils.py
import functools import itertools import numpy import dask import dask.array from . import _compat from . import _pycompat def _broadcast_uv(u, v): u = _compat._asarray(u) v = _compat._asarray(v) U = u if U.ndim == 1: U = U[None] V = v if V.ndim == 1: V = V[None] if U....
import functools import itertools import numpy import dask import dask.array from . import _compat from . import _pycompat def _broadcast_uv(u, v): u = _compat._asarray(u) v = _compat._asarray(v) U = u if U.ndim == 1: U = U[None] V = v if V.ndim == 1: V = V[None] if U....
Python
0
bd712dad2709ba31be89f48f283084d5894cb378
Replace dot in archive thumbnail name by underscore
ipol_demo/modules/core/archive.py
ipol_demo/modules/core/archive.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ Helper functions for core, related to the archive module. """ import gzip import json import os import traceback from collections import OrderedDict import requests from ipolutils.utils import thumbnail def create_thumbnail(src_file): """ Create thumbnail w...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ Helper functions for core, related to the archive module. """ import gzip import json import os import traceback from collections import OrderedDict import requests from ipolutils.utils import thumbnail def create_thumbnail(src_file): """ Create thumbnail w...
Python
0
871f49eea1197af8224c601833e6e96f59697eb3
Update phishing_database.py
plugins/feeds/public/phishing_database.py
plugins/feeds/public/phishing_database.py
#!/usr/bin/env python """This class will incorporate the PhishingDatabase feed into yeti.""" from datetime import timedelta import logging from core.observables import Url from core.feed import Feed from core.errors import ObservableValidationError class PhishingDatabase(Feed): """This class will pull the Phishi...
from datetime import timedelta import logging from core.observables import Url from core.feed import Feed from core.errors import ObservableValidationError class PhishingDatabase(Feed): """ This class will pull the PhishingDatabase feed from github on a 12 hour interval. """ default_values = { 'frequ...
Python
0.000002
453e50823d3fb7a5937311e9118abbcbd5309855
Implement a bunch more rare neutral minions
fireplace/carddata/minions/neutral/rare.py
fireplace/carddata/minions/neutral/rare.py
import random from ...card import * from fireplace.enums import Race # Injured Blademaster class CS2_181(Card): def action(self): self.damage(4) # Young Priestess class EX1_004(Card): def endTurn(self): other_minions = [t for t in self.controller.field if t is not self] if other_minions: random.choice(ot...
from ...card import * # Abomination class EX1_097(Card): def deathrattle(self): for target in self.controller.getTargets(TARGET_ALL_CHARACTERS): target.damage(2) # Bloodsail Corsair class NEW1_025(Card): def action(self): weapon = self.controller.opponent.hero.weapon if self.controller.opponent.hero.weap...
Python
0.000004
730489e4f6a7f3067ad67c16512c2cbcb97f3272
stop gap on astronmical solar zenith
bin/astronomical.py
bin/astronomical.py
""" astronomical.py, Sam Murphy (2017-04-27) Astronomical calculations (e.g. solar angles) for processing satellite imagery through Google Earth Engine. """ import ee class Astronomical: pi = 3.141592653589793 degToRad = pi / 180 # degress to radians radToDeg = 180 / pi # radians to degress def sin(x):retu...
""" astronomical.py, Sam Murphy (2017-04-27) Astronomical calculations (e.g. solar angles) for processing satellite imagery through Google Earth Engine. """ import ee class Astronomical: pi = 3.141592653589793 degToRad = pi / 180 # degress to radians radToDeg = 180 / pi # radians to degress def sin(x):retu...
Python
0.000001
9e3becba368e5cc916c9af99a89e62e502d0a506
Fix syntax error in urls
greenland/urls.py
greenland/urls.py
"""greenland URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-b...
"""greenland URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-b...
Python
0.000254
0a08c933375197bd630442e4c1f27c68fb2c8d0b
Reorder some things
groupvpn-webui.py
groupvpn-webui.py
import json import math import random import re import string from flask import Flask, redirect, render_template, request, url_for import ipaddress import wtforms as w PASSWORD_CHARS = string.ascii_lowercase + string.digits PASSWORD_LENGTH = 30 class IPNetworkField(w.Field): widget = w.widgets.TextInput() d...
import json import math import random import re import string from flask import Flask, redirect, render_template, request, url_for import ipaddress import wtforms as w PASSWORD_CHARS = string.ascii_lowercase + string.digits PASSWORD_LENGTH = 30 class IPNetworkField(w.Field): widget = w.widgets.TextInput() d...
Python
0.000335
4c6c41872b9a547917d81996f5f93d628c90216d
proper print
temperature-sparkpy.py
temperature-sparkpy.py
from __future__ import print_function import sys import math from operator import add from pyspark import SparkContext def is_number(s): try: float(s) return True except ValueError: return False def mapper(line): # positive or negative sign = line[87:88] # bef...
from __future__ import print_function import sys import math from operator import add from pyspark import SparkContext def is_number(s): try: float(s) return True except ValueError: return False def mapper(line): # positive or negative sign = line[87:88] # bef...
Python
0.997763
548edcb10ef949d394388282d052da36135982d7
Add coveralls support[5].
build.py
build.py
#!/usr/bin/python import os import shutil from subprocess import call import sys import platform cur_path = os.getcwd() build_path = os.getcwd() + "/build" if platform.system() == 'Windows': build_path = os.getcwd() + "/win_build" if 'test' in sys.argv: os.chdir(build_path) r = call(["make tests"], shell=...
#!/usr/bin/python import os import shutil from subprocess import call import sys import platform cur_path = os.getcwd() build_path = os.getcwd() + "/build" if platform.system() == 'Windows': build_path = os.getcwd() + "/win_build" if 'test' in sys.argv: os.chdir(build_path) r = call(["make tests"], shell=...
Python
0
df41dcb3c8538e482bcc61f9817ce26569652b6b
build script set user data for git
build.py
build.py
# -*- coding: utf-8 -*- import os import sh from logging_service import __version__ as version GIT_USER = 'circle-ci' GIT_EMAIL = 'vitomarti@gmail.com' def open_file(path): return open(path, 'r+') def get_git(repo_path): return sh.git.bake(_cwd=repo_path) def set_user_data_git(git): git('config', '...
# -*- coding: utf-8 -*- import os import sh from logging_service import __version__ as version def open_file(path): return open(path, 'r+') def get_git(repo_path): return sh.git.bake(_cwd=repo_path) def main(): file_build = open_file('build_version') lines = file_build.readlines() build_vers...
Python
0.000001
54b8e07ac412e757fb32ebfa19b75ef8a72f6688
Print build path
build.py
build.py
#!/usr/bin/env python import sys import os from argparse import ArgumentParser from subprocess import check_call, check_output def ensure_tool(name): check_call(['which', name]) def build_and_publish(path, args): login_command = get_login_command(args) print >>sys.stderr, "Test anaconda.org login:" ...
#!/usr/bin/env python import sys import os from argparse import ArgumentParser from subprocess import check_call, check_output def ensure_tool(name): check_call(['which', name]) def build_and_publish(path, args): login_command = get_login_command(args) print >>sys.stderr, "Test anaconda.org login:" ...
Python
0.000001
00e68cff5e7d370e137383b4e0c3c774ddb4c929
update metadata
l10n_br_sale_stock/__openerp__.py
l10n_br_sale_stock/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################### # # # Copyright (C) 2013 Raphaël Valyi - Akretion # # Copyright (C) 2013 Renato Lima - Akretion ...
# -*- coding: utf-8 -*- ############################################################################### # # # Copyright (C) 2013 Raphaël Valyi - Akretion # # Copyright (C) 2013 Renato Lima - Akretion ...
Python
0.000001
3d52e82a295c7c7d6b77d81a1d2c6ac0929bb120
make sqlitecache bundable.
sqlite_cache/__init__.py
sqlite_cache/__init__.py
from __future__ import absolute_import from .core import SQLiteCache # pragma: no cover
from sqlite_cache.core import SQLiteCache # pragma: no cover
Python
0
962322fd385bcfcc670ead757190d37955ccda14
improve logging and add ros params
lg_earth/src/lg_earth/kmlalive.py
lg_earth/src/lg_earth/kmlalive.py
import subprocess import rospy import rosservice import traceback import sys class KmlAlive: def __init__(self, earth_proc): self.earth_proc = earth_proc rospy.loginfo("XXX starting KMLALIVE process") self.timeout_period = rospy.get_param(~timeout_period, 5) self.initial_timeout = ...
import subprocess import rospy import rosservice import traceback import sys class KmlAlive: def __init__(self, earth_proc): self.earth_proc = earth_proc rospy.loginfo("XXX starting KMLALIVE process") rospy.Timer(rospy.Duration(10), self.keep_alive, oneshot=True) # only restart whe...
Python
0
f672da20640b761d47d5c15d791e06fc5e25fd35
Fix Deprecation warning in Django 1.9
bootstrap3/utils.py
bootstrap3/utils.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re from django import VERSION from django.forms.widgets import flatatt from django.template import (Context, RequestContext, Template, Variable, VariableDoesNotExist) from django.template.base import (FilterExpression,...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re from django.forms.widgets import flatatt from django.template import Variable, VariableDoesNotExist, Template, Context from django.template.base import FilterExpression, kwarg_re, TemplateSyntaxError from django.template.loader import get_templ...
Python
0.000067
60690c178f3adb5a2e05e4960e3b142dbf6c1aad
update cache
cache.py
cache.py
import inspect import json as json from functools import wraps from hashlib import md5 def cache_json(func, key_prefix='', expire=0, expire_at='', redis_client=None): """key_prefix is optional. if use, it should be unique at module level within the redis db, __module__ & func_name & all arguments wo...
import json as json def cache_json(func, key_prefix='', expire=0, expire_at='', redis_client=None): """key_prefix should be unique at module level within the redis db, func name & all arguments would also be part of the key. redis_client: it's thread safe. to avoid giving `redis_client` param every t...
Python
0.000001
c40376c36312e582704b4fafbc36f4b17171394f
switch to using selectors
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by roadhump # Copyright (c) 2014 roadhump # # License: MIT # """This module exports the ESLint plugin class.""" import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLi...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by roadhump # Copyright (c) 2014 roadhump # # License: MIT # """This module exports the ESLint plugin class.""" import logging import re from SublimeLinter.lint import NodeLinter logger = logging.getLogger('SublimeLi...
Python
0.000002
d927e5dbf7820ad0e48006d9b2042b62c04bd310
Update regex
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Clifton Kaznocha # Copyright (c) 2014 Clifton Kaznocha # # License: MIT # """This module exports the Flow plugin class.""" import os from SublimeLinter.lint import Linter class Flow(Linter): """Provides an in...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Clifton Kaznocha # Copyright (c) 2014 Clifton Kaznocha # # License: MIT # """This module exports the Flow plugin class.""" import os from SublimeLinter.lint import Linter class Flow(Linter): """Provides an in...
Python
0.000002
6a9d6d30dc7ea207e2f4d8179a5ef99a95fce4e5
Fix bug in ListingGenerator with limit=None.
praw/models/listinggenerator.py
praw/models/listinggenerator.py
from .prawmodel import PRAWModel class ListingGenerator(PRAWModel): """Instances of this class generate ``RedditModels``""" def __init__(self, reddit, url, limit=100, params=None): """Initialize a ListingGenerator instance. :param reddit: An instance of :class:`.Reddit`. :param url: ...
from .prawmodel import PRAWModel class ListingGenerator(PRAWModel): """Instances of this class generate ``RedditModels``""" def __init__(self, reddit, url, limit=100, params=None): """Initialize a ListingGenerator instance. :param reddit: An instance of :class:`.Reddit`. :param url: ...
Python
0
bf7562d9f45a777163f2ac775dc9cf4afe99a930
Change 'language' to 'syntax', that is more precise terminology.
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint # License: MIT # """This module exports the JSHint plugin linter class.""" from Sub...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jshint # License: MIT # """This module exports the JSHint plugin linter class.""" from Sub...
Python
0.002004
cea40608a1efe16310c7b978fba40abcde26ced4
make flake8 happy
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Dan Flettre # Copyright (c) 2015 Dan Flettre # # License: MIT # """This module exports the Semistandard plugin class.""" from SublimeLinter.lint import NodeLinter class Semistandard(NodeLinter): """Provides a...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Dan Flettre # Copyright (c) 2015 Dan Flettre # # License: MIT # """This module exports the Semistandard plugin class.""" from SublimeLinter.lint import NodeLinter, util class Semistandard(NodeLinter): """Prov...
Python
0
9bfe8cd21931c69d79657aa275be02af21ec78f1
Simplify `cmd` property
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Bartosz Kruszczynski # Copyright (c) 2015 Bartosz Kruszczynski # # License: MIT # """This module exports the Reek plugin class.""" from SublimeLinter.lint import RubyLinter import re class Reek(RubyLinter): ""...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Bartosz Kruszczynski # Copyright (c) 2015 Bartosz Kruszczynski # # License: MIT # """This module exports the Reek plugin class.""" from SublimeLinter.lint import RubyLinter import re class Reek(RubyLinter): ""...
Python
0
d20d035516f279b00deeae9ad55d3540f02eaf33
Fix deprecation warnings
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Fred Callaway # Copyright (c) 2015 Fred Callaway # Copyright (c) 2017 FichteFoll <fichtefoll2@googlemail.com> # # License: MIT # """This module exports the Mypy plugin class.""" import logging import os import shuti...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Fred Callaway # Copyright (c) 2015 Fred Callaway # Copyright (c) 2017 FichteFoll <fichtefoll2@googlemail.com> # # License: MIT # """This module exports the Mypy plugin class.""" import logging import os import shuti...
Python
0.00011
68293b6075ead70651924761e4e3187286ad6765
Add the proper tests user/pass.
integration_tests/test_basic_page_loads.py
integration_tests/test_basic_page_loads.py
from django.contrib.auth.models import User from django.test import testcases from django.test.client import Client class Fail(testcases.TestCase): def setUp(self): super(Fail, self).setUp() u = User(username='john_doe') u.set_password('password') u.is_superuser = True u.s...
from django.contrib.auth.models import User from django.test import testcases from django.test.client import Client class Fail(testcases.TestCase): def setUp(self): super(Fail, self).setUp() u = User(username='john_doe') u.set_password('password') u.is_superuser = True u.s...
Python
0
005c684b88e6383aabe5294bfa0104ba4fb3ed40
Use the fancier tmp_file management in tests
test/ops/test_index.py
test/ops/test_index.py
""" Tests for index operations """ from unittest import TestCase import os import sys import xarray as xr import pandas as pd import numpy as np from datetime import datetime import tempfile import shutil from contextlib import contextmanager import itertools from cate.ops import index from cate.ops import subset ...
""" Tests for index operations """ from unittest import TestCase import os import xarray as xr import pandas as pd import numpy as np from datetime import datetime from cate.ops import index from cate.ops import subset def assert_dataset_equal(expected, actual): # this method is functionally equivalent to ...
Python
0
759a6994441c35400965beea19e6425b377cf4e8
add datetime_format
cloud.py
cloud.py
# coding: utf-8 import leancloud from leancloud import Engine from leancloud import LeanEngineError from app import app from logentries import LogentriesHandler import logging from qiniu import Auth from qiniu import BucketManager import requests import os import json import time engine = Engine(app) log = logg...
# coding: utf-8 import leancloud from leancloud import Engine from leancloud import LeanEngineError from app import app from logentries import LogentriesHandler import logging from qiniu import Auth from qiniu import BucketManager import requests import os import json import time engine = Engine(app) log = logg...
Python
0.002308
853dc8de1d077494c707a5ec8a6b75ac0e0628cf
Add trailing slash to URL for consistency.
cadorsfeed/views.py
cadorsfeed/views.py
from werkzeug import redirect, Response from werkzeug.exceptions import NotFound from cadorsfeed.utils import expose, url_for, db from parse import parse from fetch import fetchLatest, fetchReport @expose('/report/latest/') def latest_report(request): if 'latest' in db: latestDate = db['latest'] else:...
from werkzeug import redirect, Response from werkzeug.exceptions import NotFound from cadorsfeed.utils import expose, url_for, db from parse import parse from fetch import fetchLatest, fetchReport @expose('/report/latest') def latest_report(request): if 'latest' in db: latestDate = db['latest'] else: ...
Python
0
cb50a43435de4e3b62324d1b738f3775cabe7367
Fix reverse url in RecentChangesFeed
candidates/feeds.py
candidates/feeds.py
from __future__ import unicode_literals import re from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from django.utils.feedgenerator import Atom1Feed from django.utils.text import slugify from django.utils.translation import uget...
from __future__ import unicode_literals import re from django.contrib.sites.models import Site from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from django.utils.feedgenerator import Atom1Feed from django.utils.text import slugify from django.utils.translation import uget...
Python
0.999993
63caf1fceb94d185e73858c2b58c82bf5912b7c4
Add documentation for coding formatter
beetsplug/hook.py
beetsplug/hook.py
# This file is part of beets. # Copyright 2015, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
# This file is part of beets. # Copyright 2015, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
Python
0
847d9c4a1e88b9e00a3be082db635743866a8abd
Fix tests
catalog/__init__.py
catalog/__init__.py
from os import environ from flask import Flask from flask_sqlalchemy import SQLAlchemy DB_URL = 'postgresql:///catalog' + ('_test' if environ.get('ENV') == 'test' else '') app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) i...
from os import environ from flask import Flask from flask_wtf.csrf import CSRFProtect from flask_sqlalchemy import SQLAlchemy DB_URL = 'postgresql:///catalog' + ('_test' if environ.get('ENV') == 'test' else '') app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL app.config['SQLALCHEMY_TRACK_MODIFICA...
Python
0.000003
31fd889ec6d8851ce61085b0cbd15b86195905a8
remove unused imports
test/scripts/window.py
test/scripts/window.py
#!/usr/bin/env python """ This program is carefully crafted to exercise a number of corner-cases in Qtile. """ from __future__ import print_function import sys import time import xcffib import xcffib.xproto def configure(window): window.configure( width=100, height=100, x=0, ...
#!/usr/bin/env python """ This program is carefully crafted to exercise a number of corner-cases in Qtile. """ from __future__ import print_function import sys import time import struct import xcffib import xcffib.xproto try: from StringIO import StringIO # Python 2 except ImportError: from io import St...
Python
0.000001
7d26429acac78b2b1388a5d069d807038038bd1c
Add a folded indicator
examples/gui_integration/python_editor.py
examples/gui_integration/python_editor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # PCEF - Python/Qt Code Editing Framework # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # PCEF - Python/Qt Code Editing Framework # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, ...
Python
0.000001
147a24ea0ba9da03b3774b7993e20e785776e027
Use sys.nstates in stead of using A.shape[0]
control/passivity.py
control/passivity.py
''' Author: Mark Yeatman Date: May 15, 2022 ''' from . import statesp as ss import numpy as np import cvxopt as cvx def is_passive(sys): ''' Indicates if a linear time invarient system is passive Constructs a linear matrix inequality and a feasibility optimization such that is a solution exists, t...
''' Author: Mark Yeatman Date: May 15, 2022 ''' from . import statesp as ss import numpy as np import cvxopt as cvx def is_passive(sys): ''' Indicates if a linear time invarient system is passive Constructs a linear matrix inequality and a feasibility optimization such that is a solution exists, t...
Python
0.000008
b8e556871ff4aff9b85c67cc010814a0e6f60386
Add new constants and change existing file names.
const.py
const.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module defines constant values for the ScrambleSuit protocol. While some values can be changed, in general they should not. If you do not obey, be at least careful because the protocol could easily break. """ # Length of the HMAC used to authenticate the ticket...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module defines constant values for the ScrambleSuit protocol. While some values can be changed, in general they should not. If you do not obey, be at least careful because the protocol could easily break. """ # FIXME - Directory where long-lived information is ...
Python
0
84bcae49475d0d0ce0c14d671b363c488d93bb9f
Add skip reason
fmriprep/workflows/bold/tests/test_util.py
fmriprep/workflows/bold/tests/test_util.py
''' Testing module for fmriprep.workflows.bold.util ''' import pytest import os import numpy as np from nipype.utils.filemanip import fname_presuffix from nilearn.image import load_img from ..util import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = l...
''' Testing module for fmriprep.workflows.bold.util ''' import pytest import os import numpy as np from nipype.utils.filemanip import fname_presuffix from nilearn.image import load_img from ..util import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = l...
Python
0.000001
2a030ce151cdb6eaaa3933bd7f958edf658ab209
Make the parent directory part of the Python path for custom management commands to work.
manage.py
manage.py
#!/usr/bin/env python import os import sys sys.path.append(os.path.abspath("..")) from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory contain...
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to ...
Python
0
0feb5947af0dacc53ba624723593dd88b0b4653a
Fix shop creation
byceps/services/shop/shop/service.py
byceps/services/shop/shop/service.py
""" byceps.services.shop.shop.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import Optional from ....database import db from ....typing import PartyID from .models import Shop as DbShop from .transfer.models impo...
""" byceps.services.shop.shop.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import Optional from ....database import db from ....typing import PartyID from .models import Shop as DbShop from .transfer.models impo...
Python
0.000001
c0e903c3dab9fea0594d023ab9c049ca408bd9a4
Cover text: outlined
cover.py
cover.py
from PIL import Image, ImageDraw, ImageFont from io import BytesIO import textwrap def make_cover(title, author, width=600, height=800, fontname="Helvetica", fontsize=40, bgcolor=(120, 20, 20), textcolor=(255, 255, 255), wrapat=30): img = Image.new("RGBA", (width, height), bgcolor) draw = ImageDraw.Draw(img)...
from PIL import Image, ImageDraw, ImageFont from io import BytesIO import textwrap def make_cover(title, author, width=600, height=800, fontname="Helvetica", fontsize=40, bgcolor=(120, 20, 20), textcolor=(255, 255, 255), wrapat=30): img = Image.new("RGBA", (width, height), bgcolor) draw = ImageDraw.Draw(img)...
Python
0.999509
99bfdd1f038865a3558e212777b0a5641d87c170
Add report types to NEA.
inspectors/nea.py
inspectors/nea.py
#!/usr/bin/env python import datetime import logging import os import re from urllib.parse import urljoin from bs4 import BeautifulSoup from utils import utils, inspector # http://arts.gov/oig # Oldest report: 2005 # options: # standard since/year options for a year range to fetch from. # report_id: only bother...
#!/usr/bin/env python import datetime import logging import os import re from urllib.parse import urljoin from bs4 import BeautifulSoup from utils import utils, inspector # http://arts.gov/oig # Oldest report: 2005 # options: # standard since/year options for a year range to fetch from. # report_id: only bother...
Python
0
91a8c5312c58edff070915fc5d182b35f60ef0fa
allow for error recovery in cases where a file sync fails.
sync-dropbox-to-ftp.py
sync-dropbox-to-ftp.py
#!/usr/bin/env python3 """The initial options file should look like: { "state": { "cursor": null, "left": [] }, "options": { "ftp": { "auth": { "host": "FTP_HOST", "user": "FTP_USER", "passwd": "FTP_PASSWORD" }, "path": "FTP_DIRECTORY_NAME" }, "dropbox": { "auth": { "access_token": "...
#!/usr/bin/env python3 """The initial options file should look like: { "state": { "cursor": null }, "options": { "ftp": { "auth": { "host": "FTP_HOST", "user": "FTP_USER", "passwd": "FTP_PASSWORD" }, "path": "FTP_DIRECTORY_NAME" }, "dropbox": { "auth": { "access_token": "ACCESS_TOKEN...
Python
0
5f15ad2da19cc3872b5e6fbbaa5db8b902cef720
Revert "we don't want this commit"
manage.py
manage.py
#!/usr/bin/env python """ Usage: manage.py {lms|cms} [--settings env] ... Run django management commands. Because edx-platform contains multiple django projects, the first argument specifies which project to run (cms [Studio] or lms [Learning Management System]). By default, those systems run in with a settings file ...
#!/usr/bin/env python """ Usage: manage.py {lms|cms} [--settings env] ... Run django management commands. Because edx-platform contains multiple django projects, the first argument specifies which project to run (cms [Studio] or lms [Learning Management System]). By default, those systems run in with a settings file ...
Python
0
8c233868e82a6828d21574b0d488699c1c7b1443
Update test_ValueType.py
cairis/cairis/test/test_ValueType.py
cairis/cairis/test/test_ValueType.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
Python
0.000001
278c7817120370c22cad2e56471e7d1673312e3e
Use functools.wraps rather than manually setting __name__
curry.py
curry.py
from functools import wraps from inspect import signature, isclass import sys import unittest def get_arg_count(fun): if isclass(fun): return len(signature(fun.__call__).parameters) else: return len(signature(fun).parameters) def curry(fun): arg_count = get_arg_count(fun) @wraps...
from inspect import signature, isclass import sys import unittest def get_arg_count(fun): if isclass(fun): return len(signature(fun.__call__).parameters) else: return len(signature(fun).parameters) def curry(fun): arg_count = get_arg_count(fun) def curried(*old_args, **old_kwargs): ...
Python
0
7cac8f8ba591315d68e223503c4e93f976c8d89d
Set default race and class without extra database queries
characters/views.py
characters/views.py
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/ind...
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/ind...
Python
0
daabf57935c9bec91ee4ce0bcd4713790fe928ea
use celery
daily.py
daily.py
from totalimpactwebapp.user import User from totalimpactwebapp import db import datetime import tasks """ requires these env vars be set in this environment: DATABASE_URL """ def page_query(q): offset = 0 while True: r = False for elem in q.limit(100).offset(offset): r = True ...
from totalimpactwebapp.user import User from totalimpactwebapp import db import datetime import tasks """ requires these env vars be set in this environment: DATABASE_URL """ def page_query(q): offset = 0 while True: r = False for elem in q.limit(100).offset(offset): r = True ...
Python
0.000618
a2cc8a5e6009bda68edf85a432d9a8ec002e99a1
Fix #80
adapter/__init__.py
adapter/__init__.py
import sys PY2 = sys.version_info[0] == 2 if PY2: is_string = lambda v: isinstance(v, basestring) # python2-based LLDB accepts utf8-encoded ascii strings only. to_lldb_str = lambda s: s.encode('utf8', 'backslashreplace') if isinstance(s, unicode) else s from_lldb_str = lambda s: s.decode('utf8', 'repla...
import sys PY2 = sys.version_info[0] == 2 if PY2: is_string = lambda v: isinstance(v, basestring) to_lldb_str = lambda s: s.encode('utf8', 'backslashreplace') from_lldb_str = lambda s: s.decode('utf8', 'replace') xrange = xrange else: is_string = lambda v: isinstance(v, str) to_lldb_str = str ...
Python
0.000001
2930d355421ed3804d5c675fad20c82f27066d7e
Support numpy 1.9
chainer/functions/array/broadcast.py
chainer/functions/array/broadcast.py
import six from chainer import cuda from chainer import function from chainer.utils import type_check def _backward_one(x, g): if g is None: xp = cuda.get_array_module(x) return xp.zeros_like(x) if g.ndim != x.ndim: g = g.sum(axis=tuple(range(g.ndim - x.ndim))) # An input var...
import six from chainer import cuda from chainer import function from chainer.utils import type_check def _backward_one(x, g): if g is None: xp = cuda.get_array_module(x) return xp.zeros_like(x) if g.ndim != x.ndim: g = g.sum(axis=tuple(range(g.ndim - x.ndim))) # An input var...
Python
0.00004
dc50a4ec058f9893e87a069bc64e4715ecfa0bea
Add initial status code assertion
haas_rest_test/plugins/assertions.py
haas_rest_test/plugins/assertions.py
# -*- coding: utf-8 -*- # Copyright (c) 2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals from jsonschema.exceptions import ValidationEr...
# -*- coding: utf-8 -*- # Copyright (c) 2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals class StatusCodeAssertion(object): _sche...
Python
0.000004
b9ea36d80ec256988a772e621eb91481cff5e464
Bump version to 0.3
cicoclient/shell.py
cicoclient/shell.py
# Copyright 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 # # Unless required by applicable...
# Copyright 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 # # Unless required by applicable...
Python
0
561de1d124289058eafde34547e8fc773c3e9793
Rename strips to d_strips
board.py
board.py
import direction_strips as ds_m from pente_exceptions import * from defines import * class Board(): def __init__(self, size, clone_it=False): self.size = size if not clone_it: self.set_to_empty() def set_to_empty(self): self.d_strips = [] self.d_strips.append(ds_m....
import direction_strips as ds_m from pente_exceptions import * from defines import * class Board(): def __init__(self, size, clone_it=False): self.size = size if not clone_it: self.set_to_empty() def set_to_empty(self): self.strips = [] # TODO Rename to d_strips se...
Python
0.999681
62e9510fe2fbe3186c7c817a5c287322a65b1dc9
Fix linearPotential import to new package structure
galpy/potential/IsothermalDiskPotential.py
galpy/potential/IsothermalDiskPotential.py
############################################################################### # IsothermalDiskPotential.py: class that implements the one-dimensional # self-gravitating isothermal disk ############################################################################### import numpy from .li...
############################################################################### # IsothermalDiskPotential.py: class that implements the one-dimensional # self-gravitating isothermal disk ############################################################################### import numpy from gal...
Python
0.000022
1e012f6fc25e2be5bc55b7cae9f04a3a33ac86e5
use static url for ckeditor media serving
ckeditor/widgets.py
ckeditor/widgets.py
from django import forms from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.html import conditional_escape from django.utils.encoding import force_unicode from django.utils impo...
from django import forms from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.html import conditional_escape from django.utils.encoding import force_unicode from django.utils impo...
Python
0
b927fe276af848b6c9a4653e04421a739e63037c
remove unused import
test/test_graphprot.py
test/test_graphprot.py
from scripttest import TestFileEnvironment import re # from filecmp import cmp bindir = "graphprot/" script = "graphprot_seqmodel" # test file environment datadir = "test/" testdir = "test/testenv_graphprot_seqmodel/" # directories relative to test file environment bindir_rel = "../../" + bindir datadir_rel = "../../"...
from scripttest import TestFileEnvironment import re import os # from filecmp import cmp bindir = "graphprot/" script = "graphprot_seqmodel" # test file environment datadir = "test/" testdir = "test/testenv_graphprot_seqmodel/" # directories relative to test file environment bindir_rel = "../../" + bindir datadir_rel ...
Python
0.000001
c04bd5e52b4a516e31f98231cc6ccb7853040d2b
fix bad middleware arg
corehq/middleware.py
corehq/middleware.py
import logging import os import datetime from django.conf import settings try: import psutil except ImportError: psutil = None # this isn't OR specific, but we like it to be included OPENROSA_ACCEPT_LANGUAGE = "HTTP_ACCEPT_LANGUAGE" OPENROSA_VERSION_HEADER = "HTTP_X_OPENROSA_VERSION" OPENROSA_DATE_HEADER = "...
import logging import os import datetime from django.conf import settings try: import psutil except ImportError: psutil = None # this isn't OR specific, but we like it to be included OPENROSA_ACCEPT_LANGUAGE = "HTTP_ACCEPT_LANGUAGE" OPENROSA_VERSION_HEADER = "HTTP_X_OPENROSA_VERSION" OPENROSA_DATE_HEADER = "...
Python
0.000169
56f24e52f961da414f0610e6bd815812b4a14ef6
Update utils.py
classifier/utils.py
classifier/utils.py
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
Python
0.000001
c28112624b3c735c610f756a6bff1497e9516c64
Revise naive alg to more intuitive one: separate checking index and value
alg_find_peak_1D.py
alg_find_peak_1D.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function def find_peak_naive(arr): """Find peak by naive iteration. Time complexity: O(n). """ for i in range(len(arr)): if i == 0: if arr[i] > arr[i + 1]: return ar...
from __future__ import absolute_import from __future__ import division from __future__ import print_function def find_peak_naive(arr): """Find peak by naive iteration. Time complexity: O(n). """ for i in range(len(arr)): if i == 0 and arr[i] > arr[i + 1]: return arr[i] eli...
Python
0.000016
8a44ec213272536d59d16118e2a13c533299242e
fix missing = in SystemCSerializer
hwt/serializer/systemC/serializer.py
hwt/serializer/systemC/serializer.py
from jinja2.environment import Environment from jinja2.loaders import PackageLoader from hwt.hdlObjects.types.enum import Enum from hwt.hdlObjects.types.enumVal import EnumVal from hwt.serializer.generic.serializer import GenericSerializer from hwt.serializer.serializerClases.nameScope import LangueKeyword from hwt.se...
from jinja2.environment import Environment from jinja2.loaders import PackageLoader from hwt.hdlObjects.types.enum import Enum from hwt.hdlObjects.types.enumVal import EnumVal from hwt.serializer.generic.serializer import GenericSerializer from hwt.serializer.serializerClases.nameScope import LangueKeyword from hwt.se...
Python
0.001621
dbec204b242ab643de162046ba73dca32043c6c2
Implement __getattr__ to reduce code
space-age/space_age.py
space-age/space_age.py
class SpaceAge(object): YEARS = {"on_earth": 1, "on_mercury": 0.2408467, "on_venus": 0.61519726, "on_mars": 1.8808158, "on_jupiter": 11.862615, "on_saturn": 29.447498, "on_uranus": 84.016846, "on_neptune": 164.79132} def...
class SpaceAge(object): def __init__(self, seconds): self.seconds = seconds @property def years(self): return self.seconds/31557600 def on_earth(self): return round(self.years, 2) def on_mercury(self): return round(self.years/0.2408467, 2) def on_venus(self): ...
Python
0.99731
a28bb36aeb887d11b9cf8391e03264a81b40b84a
add base entity construct
sparc/entity/entity.py
sparc/entity/entity.py
from BTrees.OOBTree import OOBTree from zope.annotation.interfaces import IAnnotations from zope.annotation.interfaces import IAnnotatable from zope.annotation.interfaces import IAttributeAnnotatable from zope.component import adapts from zope.component.factory import Factory from zope.interface import implements from ...
from BTrees.OOBTree import OOBTree from zope.annotation.interfaces import IAnnotations from zope.annotation.interfaces import IAnnotatable from zope.annotation.interfaces import IAttributeAnnotatable from zope.component import adapts from zope.component.factory import Factory from zope.interface import implements from ...
Python
0.000001
2732ac448d6a31678629324dc47f89a33ecd261b
Manage service choicefield display in inline form
billjobs/admin.py
billjobs/admin.py
from django import forms from django.db.models import Q from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from .models import Bill, BillLine, Se...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from .models import Bill, BillLine, Service, UserProfile class BillLineInline(admin.TabularIn...
Python
0
8b275ccb96b8fe3c2c3919e11f08e988219a1e14
Add the process PID in the logs
src/diamond/utils/log.py
src/diamond/utils/log.py
# coding=utf-8 import logging import logging.config import sys import os class DebugFormatter(logging.Formatter): def __init__(self, fmt=None): if fmt is None: fmt = ('%(created)s\t' + '[%(processName)s:%(process)d:%(levelname)s]\t' + '%(message)s') ...
# coding=utf-8 import logging import logging.config import sys import os class DebugFormatter(logging.Formatter): def __init__(self, fmt=None): if fmt is None: fmt = '%(created)s\t[%(processName)s:%(levelname)s]\t%(message)s' self.fmt_default = fmt self.fmt_prefix = fmt.repla...
Python
0.000001
d2917cb2131b9b08fa6457b195606fcc0220eef1
Fix X509 construcor
ctypescrypto/x509.py
ctypescrypto/x509.py
from ctypes import c_void_p from ctypescrypto.bio import Membio from ctypescrypto.pkey import PKey from ctypescrypto.oid import Oid from ctypescrypto.exception import LibCryptoError from ctypescrypto import libcrypto class X509Error(LibCryptoError): pass class X509Name: def __init__(self,ptr): self.ptr=ptr def ...
from ctypes import c_void_p from ctypescrypto.bio import Membio from ctypescrypto.pkey import PKey from ctypescrypto.oid import Oid from ctypescrypto.exception import LibCryptoError from ctypescrypto import libcrypto class X509Error(LibCryptoError): pass class X509Name: def __init__(self,ptr): self.ptr=ptr def ...
Python
0.000018
419db3c559d836d6ba77c758212a55051e6c8fab
Add FIXME for module as function arg
test_obj_dict_tools.py
test_obj_dict_tools.py
from obj_dict_tools import * from nose.tools import raises @dict_fields(['name', 'size']) class Simple: def __init__(self, name=None, size=None): self.name = name self.size = size @dict_fields(['first', 'second']) class Pair: def __init__(self, first=None, second=None): self.first ...
from obj_dict_tools import * from nose.tools import raises @dict_fields(['name', 'size']) class Simple: def __init__(self, name=None, size=None): self.name = name self.size = size @dict_fields(['first', 'second']) class Pair: def __init__(self, first=None, second=None): self.first ...
Python
0
b6f57d8aaeff8f85c89c381b972113810a468412
use lat, lon
models.py
models.py
from random import choice, randint import urllib2, json from pushbullet import PushBullet from os import environ ''' Checks if the current login attempt is a security threat or not. Performs the required action in each case ''' def is_safe(form, ip, geocoded_ip, mandrill): ip = ip latitude = form.get...
from random import choice, randint import urllib2, json from pushbullet import PushBullet from os import environ ''' Checks if the current login attempt is a security threat or not. Performs the required action in each case ''' def is_safe(form, ip, geocoded_ip, mandrill): ip = ip latitude = form.get...
Python
0.000137
4ffef0e45bf6581d3ec0ce67836fc106cf5e689f
complete rough draft of client script
client/heartbeat.py
client/heartbeat.py
# Heartbeat Client for SPARCS Services # Version 0.0.1 - 2016-09-18 import json import psutil import pprint import time import requests NETWORK_REPORT = False SERVICE_NAME = '' SERVICE_KEY = '' API_ENDPOINT = 'https://' # get cpu info # - user, system, idle (1 sec) def get_cpu(): cpu = psutil.cpu_times_percen...
# Heartbeat Client for SPARCS Services # Version 0.0.1 - 2016-09-18 import json import psutil import time import requests SERVICE_NAME = '' SERVICE_KEY = '' API_ENDPOINT = 'https://' # get cpu info # - user, system, idle (3 sec) def get_cpu(): pass # get memory info # - virtual (total, available, used) # - ...
Python
0
a0f96b2b25d309c8934ffe9a197f3d66c9097b52
replace phone to email for privacy
models.py
models.py
from app import db from datetime import datetime class Profile(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) gender = db.Column(db.String(1)) age = db.Column(db.Integer()) email = db.Column(db.String(50), unique=True) description = db.Colu...
from app import db from datetime import datetime class Profile(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) gender = db.Column(db.String(1)) age = db.Column(db.Integer()) description = db.Column(db.String(300)) date = db.Column(db.DateTim...
Python
0.000189
9c8bde1e57ad2e70c7b3b9188bff9b90e85434e6
Send email and push
models.py
models.py
from random import choice, randint import urllib2, json from pushbullet import PushBullet from os import environ ''' Checks if the current login attempt is a security threat or not. Performs the required action in each case ''' def is_safe(form, ip, mandrill): ip = ip latitude = form.get('latitude', ...
from random import choice import urllib2, json from pushbullet import PushBullet ''' Checks if the current login attempt is a security threat or not. Performs the required action in each case ''' def is_safe(form, ip, mandrill): ip = ip geo = form.get('geo', None) os = form.get('os', None)...
Python
0
ea8cbcaf41f01a46390882fbc99e6e14d70a49d1
Create an API auth token for every newly created user
src/mmw/apps/user/models.py
src/mmw/apps/user/models.py
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL...
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.db import models class ItsiUserManager(models.Manager): def create_itsi_user(self, user, itsi_id): itsi_user = self.create(user=user, itsi_id=itsi_id) return itsi_user class ItsiUser(models.Model): user = models....
Python
0
8a304e7c09a2e6a01454d686a882a8e139be7a3d
make async dbus call, return result in deferred method
dbus-tools/dbus-send.py
dbus-tools/dbus-send.py
############################################################################### # Copyright 2012 Intel Corporation. # # 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...
############################################################################### # Copyright 2012 Intel Corporation. # # 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
1bbfce6c64debb9f9377d1a912604f32ace9dca5
Update runsegment.py
bin/runsegment.py
bin/runsegment.py
#!/usr/bin/python import os import numpy as np import shutil import common from segment import normalizefile, segmentfile def runAll(args): print('\n\n\nYou have requested to normalize and segment bincounts files') print('\tWARNING:') print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CAN...
#!/usr/bin/python import os import numpy as np import shutil import common from segment import normalizefile, segmentfile def runAll(args): print('\n\n\nYou have requested to normalize and segment bincounts files') print('\tWARNING:') print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CAN...
Python
0.000001
4f27b87b9ee600c7c1c05ae9fece549b9c18e2a4
Create default instance in middleware if not found.
speeches/middleware.py
speeches/middleware.py
from instances.models import Instance class InstanceMiddleware: """This middleware sets request.instance to the default Instance for all requests. This can be changed/overridden if you use SayIt in a way that uses multiple instances.""" def process_request(self, request): request.instance, _ = ...
from instances.models import Instance class InstanceMiddleware: """This middleware sets request.instance to the default Instance for all requests. This can be changed/overridden if you use SayIt in a way that uses multiple instances.""" def process_request(self, request): request.instance = Ins...
Python
0
cb54c04049050d853f874e92c83061aad911a19a
Update qotd-parser.py
intelmq/bots/parsers/shadowserver/qotd-parser.py
intelmq/bots/parsers/shadowserver/qotd-parser.py
import csv import StringIO from intelmq.lib.bot import Bot, sys from intelmq.lib.event import Event from intelmq.bots import utils class ShadowServerQotdParserBot(Bot): def process(self): report = self.receive_message() if report: report = report.strip() columns = { ...
import csv import StringIO from intelmq.lib.bot import Bot, sys from intelmq.lib.event import Event from intelmq.bots import utils class ShadowServerQotdParserBot(Bot): def process(self): report = self.receive_message() if report: report = report.strip() columns = { ...
Python
0.000001
2980c30a8de6cbdf5d22bb269c16f8c5ad499ba8
Fix build output (dots on one line)
build.py
build.py
import re import argparse from utils import build_docker_image def main(): parser = argparse.ArgumentParser() parser.add_argument('--nocache', action='store_true', default=False) args = parser.parse_args() content = '' stream = build_docker_image(nocache=args.nocache) for item in stream: ...
import argparse from utils import build_docker_image def main(): parser = argparse.ArgumentParser() parser.add_argument('--nocache', action='store_true', default=False) args = parser.parse_args() for item in build_docker_image(nocache=args.nocache): print item.values()[0] if __name__ == '__m...
Python
0